blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
16515e3d4a9db2dd60b0d32557c9490e1bace854
40416cef809fa0a88afef5b5e8f7a04e16abbc20
/Zenitka/Object.cpp
7ef43fe327dea540170fdc08c8348ddb98a782a5
[]
no_license
GetRight23/AntiaircraftGun
111989db7923935ee8f57515206997bea46f7412
a5dbdde925efbce5bcac859e4cd45796615e7d1a
refs/heads/master
2020-04-01T21:29:44.232549
2018-10-18T17:13:42
2018-10-18T17:13:42
153,659,046
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include "Object.h" Object::Object() : x(0), y(0), w(0), h(0), startX(0), startY(0) { sprite.setPosition(x, y); } Object::Object(float x, float y, float sx, float sy, float w, float h, sf::Texture& texture) : x(x), y(y), w(w), h(h), startX(sx), startY(sy) { setTexture(texture); sprite.setPosition(x, y); } Object::~Object() { } void Object::setTexture(sf::Texture& texture) { sprite.setTexture(texture); sprite.setTextureRect(sf::IntRect(static_cast<int>(startX), static_cast<int>(startY), static_cast<int>(w), static_cast<int>(h))); sprite.setOrigin(w / 2.0f, h / 2.0f); }
[ "ivasilich23@gmail.com" ]
ivasilich23@gmail.com
54c32181fda033b69bfb9d00cbb6c132331694be
7067fef998a194e5f0997a1def3b7326947c0b54
/Common/AEAliasList.cp
2d269ba086014c0f8ced177a2f513209947129eb
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
quicksilver/OnMyCommand-qsplugin
3c8a0017603e809c11a50c2c4c3c5cea0d368bd7
14bd6c31c1210013db2c73fee249bdbf9b08a7ea
refs/heads/main
2022-06-02T09:53:48.389877
2011-07-26T09:40:46
2011-07-26T09:40:46
1,885,847
1
1
null
null
null
null
WINDOWS-1252
C++
false
false
5,786
cp
//************************************************************************************** // Filename: AEAliasList.cp // Part of Contextual Menu Workshop by Abracode Inc. // http://free.abracode.com/cmworkshop/ // Copyright © 2002-2003 Abracode, Inc. All rights reserved. // // Description: Lightweight list of alias objects stored in AEDescList // Main design features: // - the acutal list can be owned by this object or not // (there are many cases when we do not want this object to destroy the list) // - designed not to throw exceptions // - the list is 1-based // - no attempt is made to eliminate duplicates (ie pointing to the same objects) // //************************************************************************************** // Revision History: // Monday, August 12, 2002 - Original //************************************************************************************** #include "AEAliasList.h" #include "StAEDesc.h" #include "CMUtils.h" AEAliasList::AEAliasList(void) { mList.descriptorType = typeNull; mList.dataHandle = NULL; OSErr err = ::AECreateList( NULL, 0, false, &mList ); if(err == noErr) { mOwnList = true; } //what can I do about the error here? //I do nothing, hoping that mList.dataHandle will be null if error occured } AEAliasList::AEAliasList(const AEDescList *inList, Boolean inTakeOwnership, Boolean inCopyList /*= false*/) { mList.descriptorType = typeNull; mList.dataHandle = NULL; mOwnList = false; if(inCopyList) { CopyList( inList );//if you copy list, you always take ownership of it. inTakeOwnership is ignored } else { if(inTakeOwnership) { AdoptList( inList );//take ownership without copying } else if(inList != NULL) { mList = *inList;//just assign it } } } AEAliasList::~AEAliasList(void) { DisposeOfList(); } SInt32 AEAliasList::GetCount() const { if( mList.dataHandle == NULL ) return 0; SInt32 theCount = 0; if( ::AECountItems( &mList, &theCount) == noErr ) return theCount; return 0; } //add item to the end of the list OSErr AEAliasList::AddItem(const FSRef *inRef) { if( inRef == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inRef, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //add item to the end of the list OSErr AEAliasList::AddItem(const FSSpec *inFSSpec) { if( inFSSpec == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inFSSpec, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //add item to the end of the list OSErr AEAliasList::AddItem(const AliasHandle inAliasH) { if( inAliasH == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inAliasH, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //remember: 1-based indexes OSErr AEAliasList::FetchItemAt(SInt32 inIndex, FSSpec &outSpec) const { if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; AEKeyword theKeyword; OSErr err = ::AEGetNthDesc(&mList, inIndex, typeWildCard, &theKeyword, objDesc); if (err == noErr) { err = CMUtils::GetFSSpec(objDesc, outSpec); } return err; } //remember: 1-based indexes OSErr AEAliasList::FetchItemAt(SInt32 inIndex, FSRef &outRef) const { if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; AEKeyword theKeyword; OSErr err = ::AEGetNthDesc(&mList, inIndex, typeWildCard, &theKeyword, objDesc); if (err == noErr) { err = CMUtils::GetFSRef(objDesc, outRef); } return err; } //remember: 1-based indexes OSErr AEAliasList::RemoveItemAt(SInt32 inIndex) { if( mList.dataHandle == NULL ) return nilHandleErr; return ::AEDeleteItem( &mList, inIndex); } OSErr AEAliasList::RemoveAllItems() { if( mList.dataHandle == NULL ) return nilHandleErr; OSErr err = noErr; SInt32 theCount = GetCount(); for(SInt32 i = 1; i<= theCount; i++) { err = ::AEDeleteItem( &mList, i); if(err != noErr) break; } return err; } OSErr AEAliasList::CopyList(const AEDescList *inList) { if( inList == NULL ) return nilHandleErr; if( inList->dataHandle == NULL ) return nilHandleErr; if( mOwnList && (inList->dataHandle == mList.dataHandle) ) {//self assignment case - when we own the list, there is no need to copy it return noErr; } AEDescList newList = {typeNull, NULL}; OSErr err = ::AEDuplicateDesc( inList, &newList); if( err == noErr ) { DisposeOfList();//it is now safe to destroy our previous data mList = newList; mOwnList = true; } return err; } //take ownership of the list OSErr AEAliasList::AdoptList(const AEDescList *inList) { if( inList == NULL ) return nilHandleErr; //check for self assignment, disposing of our data and then assigning it would be catastrophic if( inList->dataHandle == mList.dataHandle ) {//take ownership of it if we are not owning it yet mOwnList = true; return noErr;//we own it, there is need to reassign } DisposeOfList();//destroy our previous data mList = *inList; mOwnList = true; return noErr; } //releses ownership of the list //but does keep its data AEDescList AEAliasList::DisownList() { mOwnList = false; return mList; } //disposes of the list only when we own it //or forgets its data if we do not own it void AEAliasList::DisposeOfList() { if( mOwnList ) { if( mList.dataHandle != NULL ) { ::AEDisposeDesc( &mList ); } } mList.descriptorType = typeNull; mList.dataHandle = NULL; //mOwnList = false;//it does not matter if we own an empty list or not }
[ "jnj@57e2f9b5-c12c-0410-8e95-a1ee7272c91a" ]
jnj@57e2f9b5-c12c-0410-8e95-a1ee7272c91a
206266d760d85b3d69f71d7a58e7a6ffa70a554a
2849e23dd5f004e9656c01507461b34ce47098f5
/src/MEDebug.cpp
7ac8f56761394c845c4585ce4b8c6784e7873088
[]
no_license
FrozenArcher/MakeEngine
a671556bc0fbf95b5ac911ab34994c6c8c183467
1d6a5e51ac3a81d399142af90f07eb0f6455fd84
refs/heads/master
2023-05-12T14:33:27.290970
2021-06-06T13:55:14
2021-06-06T13:55:14
374,047,309
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
// // Created by fracher on 2021/6/5. // #include "METime.h" #include "MEBaseTypes.h" #include <iostream> using std::cout, std::endl; namespace MakeEngine { void Log(const MEString& message) { cout << "[Log] " << GetTimeNowStr() << message << endl << endl; } void LogTest(const MEString& name, bool result) { cout << "[Test] " << GetTimeNowStr() << "Running test: " << name << "\nresult: " << (result ? "passed" : "failed") << endl << endl; } }
[ "yhy242989105@hotmail.com" ]
yhy242989105@hotmail.com
fba0d412ca1e6fd44ff29a3503e8ba8f66567a21
afda9a6e85ac236d5dbf80fa388360efe0038341
/src/common/sysinfo.cc
ad05f06694549a6c53d9e97a6cb5d79ebb2ec180
[]
no_license
sybila/NewBioDiVinE
73d2a19812df28dc217213f60f87050efcb69cb2
e046a64b2345b739bcfa64317986f78be9ad0ca3
refs/heads/master
2020-04-25T17:38:59.935101
2014-12-10T01:44:17
2014-12-10T01:44:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,446
cc
#include "common/sysinfo.hh" // {{{ vminfo vminfo_t::vminfo_t(){ pid = getpid(); snprintf (filename,sizeof filename, "/proc/%d/status", pid); vmsize=vmlck=vmrss=vmdata=vmstk=vmexe=vmlib=0; statm=false; char line[1000]; // now detect the number of lines to be skipped FILE *statusfile; lineskip = 0; if ((statusfile = fopen (filename,"r")) != NULL) { vmsize=0; while (vmsize==0) { fscanf (statusfile,"VmSize:%d kB\nVmLck:%d kB\nVmRSS:%d kB\nVmData:%d kB\n\ VmStk:%d kB\nVmExe:%d kB\nVmLib:%d kB\n" ,&vmsize,&vmlck,&vmrss,&vmdata,&vmstk,&vmexe,&vmlib); fgets(line, sizeof line, statusfile); lineskip++; } lineskip--; fclose(statusfile); } } vminfo_t::~vminfo_t() { } void vminfo_t::print() { scan(); using namespace std; cout <<"VM: "; cout <<"size="<<vmsize<<" "; cout <<"rss="<<vmrss<<" "; if (!statm) { cout <<"lck="<<vmlck<<" "; cout <<"data="<<vmdata<<" "; cout <<"stk="<<vmstk<<" "; cout <<"exe="<<vmexe<<" "; cout <<"lib="<<vmlib<<" "; } cout <<endl; } void vminfo_t::scan() { #if defined(__linux__) char line[1000]; FILE *statusfile; if ((statusfile = fopen (filename,"r")) == NULL) { return; } for (int i=0; i<lineskip; i++) { fgets (line, sizeof line, statusfile); } fscanf (statusfile,"VmSize:%d kB\nVmLck:%d kB\nVmRSS:%d kB\nVmData:%d kB\n\ VmStk:%d kB\nVmExe:%d kB\nVmLib:%d kB\n" ,&vmsize,&vmlck,&vmrss,&vmdata,&vmstk,&vmexe,&vmlib); fclose(statusfile); #elif defined(__APPLE__) task_t task = MACH_PORT_NULL; if (task_for_pid (current_task(), pid, &task) != KERN_SUCCESS) { perror ("task_for_pid"); return; } struct task_basic_info task_basic_info; mach_msg_type_number_t task_basic_info_count = TASK_BASIC_INFO_COUNT; task_info(task, TASK_BASIC_INFO, (task_info_t)&task_basic_info, &task_basic_info_count); vmrss = task_basic_info.resident_size / 1024UL; unsigned long int vmsize_bytes = task_basic_info.virtual_size; if (vmsize_bytes > SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) vmsize_bytes -= SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE; vmsize = vmsize_bytes / 1024UL; #else // getrusage() stats are neither properly supported on Linux nor OSX // (2007-07-13) struct rusage rusage; if (getrusage (RUSAGE_SELF, &rusage) == -1) { perror ("getrusage"); return; } vmrss = rusage.ru_maxrss; // vmsize = ? vmdata = rusage.ru_idrss; //? vmstk = rusage.ru_isrss; //? vmexe = rusage.ru_ixrss; //? #endif } int vminfo_t::getvmsize() { scan(); return vmsize; } int vminfo_t::getvmdata() { scan(); return vmdata; } int vminfo_t::getvmrss() { scan(); return vmrss; } // }}} // {{{ timeinfo timeinfo_t::timeinfo_t() { settimeout(0,0); reset(); } timeinfo_t::timeinfo_t(double time) { settimeout(time); reset(); } timeinfo_t::timeinfo_t(long sec, long msec) { settimeout(sec,msec); reset(); } void timeinfo_t::settimeout(long sec,long msec) { tv_usec = 1000*msec; tv_sec = sec + (tv_usec/1000000); tv_usec %= 1000000; } void timeinfo_t::settimeout(double time) { tv_usec = static_cast<long>(1000000*time)%1000000; tv_sec = static_cast<long>(time); } void timeinfo_t::reset() { gettimeofday(&stored,0); stored.tv_usec += tv_usec; stored.tv_sec += tv_sec + (stored.tv_usec/1000000); stored.tv_usec %= 1000000; } bool timeinfo_t::testtimeout() { timeval current; gettimeofday(&current,0); if (stored.tv_sec < current.tv_sec || (stored.tv_sec == current.tv_sec && stored.tv_usec <= current.tv_usec)) { return true; } return false; } #if !defined(ORIG_TIMEOUT) bool timeinfo_t::testtimeout(timeval& current) { // same as above, but caller supplies current time to compare if (stored.tv_sec < current.tv_sec || (stored.tv_sec == current.tv_sec && stored.tv_usec <= current.tv_usec)) { return true; } return false; } #endif /* !ORIG_TIMEOUT */ void timeinfo_t::print_time(long sec,long microsec) { using namespace std; cout <<sec+microsec/1000000<<"."; if (microsec<10) cout <<"0"; if (microsec<100) cout <<"0"; if (microsec<1000) cout <<"0"; if (microsec<10000) cout <<"0"; if (microsec<100000) cout <<"0"; cout<<microsec; } void timeinfo_t::print() { timeval current; gettimeofday(&current,0); long micro = 1000000 + current.tv_usec - (stored.tv_usec - tv_usec); long sec = current.tv_sec - 1 - (stored.tv_sec - tv_sec) ; sec += micro/1000000; micro %= 1000000; print_time(sec,micro); } double timeinfo_t::gettime() { timeval current; gettimeofday(&current,0); long micro = 1000000 + current.tv_usec - (stored.tv_usec - tv_usec); long sec = current.tv_sec - 1 - (stored.tv_sec - tv_sec) ; sec += micro/1000000; micro %= 1000000; return (sec+(micro/1000000.0)); } // }}} // {{{ timeprofiler timeprofiler_t::timeprofiler_t(int n) { timevalues.resize(n); for (int i=0; i<n; i++) { timevalues[i].tv_sec=0; timevalues[i].tv_usec=0; } focus=0; gettimeofday(&lasttick,0); firsttick = lasttick; }; void timeprofiler_t::profile_off() { profile_on(0); } void timeprofiler_t::profile_on(int n) { timeval tick; gettimeofday(&tick,0); timevalues[focus].tv_sec += tick.tv_sec - lasttick.tv_sec; timevalues[focus].tv_usec += tick.tv_usec - lasttick.tv_usec; if (timevalues[focus].tv_usec>1000000) { timevalues[focus].tv_sec += timevalues[focus].tv_usec/1000000; timevalues[focus].tv_usec %= 1000000; } lasttick.tv_sec = tick.tv_sec; lasttick.tv_usec = tick.tv_usec; focus=n; } long timeprofiler_t::get_time_on(int n) { timevalues[n].tv_sec += timevalues[n].tv_usec/1000000; timevalues[n].tv_usec = timevalues[n].tv_usec%1000000; return static_cast<long> (1000*(timevalues[n].tv_sec+timevalues[n].tv_usec/1000000.0)); } long timeprofiler_t::get_global_time() { timeval tick; gettimeofday(&tick,0); long micro = 1000000 + tick.tv_usec - firsttick.tv_usec; long sec = tick.tv_sec - 1 - firsttick.tv_sec; sec += micro/1000000; micro %= 1000000; return static_cast<long>(1000*(sec+micro/1000000.0)); } // }}} // {{{ loadinfo int loadinfo_t::getload() { double result; getloadavg(&result,1); return static_cast<int>(100*result); } // }}}
[ "325073@mail.muni.cz" ]
325073@mail.muni.cz
f16c6c59f0ef239c683bb4ce01099c6ce1508b2c
03a44baca9e6ed95705432d96ba059f16e62a662
/OtherTrains/2019南昌网预/I.cpp
d1fd0439c7549f2692a89bb651e2ca2bd5b56185
[]
no_license
ytz12345/2019_ICPC_Trainings
5c6e113afb8e910dd91c8340ff43af00a701c7c7
cf0ce781675a7dbc454fd999693239e235fbbe87
refs/heads/master
2020-05-14T08:29:19.671739
2020-04-03T03:21:30
2020-04-03T03:21:30
181,722,314
0
0
null
null
null
null
UTF-8
C++
false
false
1,941
cpp
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, m, k; int a[N], b[N]; struct node { int x, y, v, id; }c[N * 5], c0[N * 5]; int id, ans[N]; inline void clr(int i) { if (i > n || !b[i]) return; b[i] = 0, c[++ k] = (node){i, a[i], -1, 0}; } inline void check(int i) { if (i > n || a[i] == a[i - 1]) return; b[i] = 1, c[++ k] = (node){i, a[i], 1, 0}; } template <int N>struct bit { int c[N]; bit() {memset (c, 0, sizeof c);} int lb(int x) {return x & (-x);} void add(int i, int x) {while (i < N) c[i] += x, i += lb(i);} int ask(int i) {int res = 0; while (i > 0) res += c[i], i -= lb(i); return res;} }; void solve(int l, int r) { static bit <N> t; if (l >= r) return; int sum = 0, mid = l + r >> 1; for (int i = l; i <= mid; i ++) if (c[i].id == 0) c0[++ sum] = c[i]; for (int i = mid + 1; i <= r; i ++) if (c[i].id != 0) c0[++ sum] = c[i]; sort (c0 + 1, c0 + sum + 1, [&](node a, node b) { if (a.x != b.x) return a.x < b.x; if (a.y != b.y) return a.y < b.y; return a.id < b.id; }); for (int i = 1; i <= sum; i ++) if (c0[i].id == 0) t.add(c0[i].y, c0[i].v); else ans[c0[i].id] += t.ask(c0[i].y) * c0[i].v; for (int i = 1; i <= sum; i ++) if (c0[i].id == 0) t.add(c0[i].y, -c0[i].v); solve(l, mid), solve(mid + 1, r); } int main() { ios::sync_with_stdio(false); cin >> n >> m; for (int i = 1; i <= n; i ++) cin >> a[i], check(i); for (int op, l, r, x, y, i = 1; i <= m; i ++) { cin >> op >> l >> r; if (op == 1) { if (a[l] == r) continue; clr(l), clr(l + 1); a[l] = r, check(l), check(l + 1); } else { cin >> x >> y; ans[++ id] = (!b[l]) & (x <= a[l] && a[l] <= y); c[++ k] = (node){r, y, 1, id}; c[++ k] = (node){l - 1, y, -1, id}; c[++ k] = (node){r, x - 1, -1, id}; c[++ k] = (node){l - 1, x - 1, 1, id}; } } solve(1, k); for (int i = 1; i <= id; i ++) printf("%d\n", ans[i]); return 0; }
[ "1217783313@qq.com" ]
1217783313@qq.com
44178a6fee9bdb535d9e63f90a306f6546a8e1a5
3cb02d8bfd827beaff8f5d284bfeee2099c173e6
/2019年北京师范大学校赛/预赛/f.cpp
94704dc96969e9b443198522ee8c7ee853e647ec
[]
no_license
yyhaos/Competitions
8a88ddfa0606e884c88f17ef391ffdd1ba32bf0f
d291be1327e895883b423eeebad943893f27e66e
refs/heads/master
2021-06-12T13:14:22.354538
2020-08-18T05:24:24
2020-08-18T05:24:24
128,635,106
3
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
//Problem Web:http://39.97.97.11/problem.php?cid=1003&pid=5 #include<bits/stdc++.h> #include<ext/rope> #include<iostream> #include<stack> #include<vector> #include<queue> #include<stdio.h> #include<string.h> using namespace std; #define ll long long #define lowbit(x) (x&-x) #define rep(i,x,y) for(ll i=x;i<=y;i++) #define crep(i,x,y) for(ll i=x;i>=y;i--) #define gcd(x,y) __gcd(x,y) #define mem(x,y) memset(x,y,sizeof(x)) #define pr pair #define mp make_pair #define use_t 1 const double PI=acos(-1.0); const double eps=1e-8; const ll INF = 100000000; const ll maxn=1000; const ll q=1e9+7; ll ksm(ll a,ll b) { ll ans=1LL; while(b>0) { if(b&1LL) ans=ans*a%q; a=a*a%q; b/=2LL; } return ans; } ll used[100005]; ll t,n,m; map <string, int> na; int main () { #ifdef yyhao freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif #ifdef use_t ll ii=1; cin>>t; for(ii=1;ii<=t;ii++) { #endif // use_t mem(used,0); na.clear(); ll th=1; ll ans=0; queue<int > qu; cin>>n; string ty,name; while(n--) { cin>>ty>>name; if(na[name]==0) { na[name]=th++; } if(ty[0]=='i') qu.push(na[name]); else { if(!qu.empty() && qu.front() == na[name]) { ans++; qu.pop(); while(!qu.empty() && used[qu.front()] == 1) qu.pop(); } used[na[name]]=1; } } cout<<ans<<endl; #ifdef use_t } #endif // use_t return 0; }
[ "35396510+yyhaos@users.noreply.github.com" ]
35396510+yyhaos@users.noreply.github.com
94d70b1edcb31935530a03bd584b03f359eca7f6
ab558d94f12fd5aac98beb5d917ebfeb12714c1f
/BigBang/include/layers/sigmoid_layer.h
c7f18fafb6dc5ac8e757b71eb48c0f339a3a58af
[ "Apache-2.0" ]
permissive
1icas/BigBang
d3fed782f26e5a840f561cd9f91e339f48a2d8be
c7492e201fe63cb9acc4690b38175abe30720fbd
refs/heads/master
2021-09-06T10:25:28.032614
2018-02-05T14:29:30
2018-02-05T14:29:30
107,073,492
1
1
null
null
null
null
UTF-8
C++
false
false
965
h
#ifndef SIGMOID_LAYER_H #define SIGMOID_LAYER_H #include "activation_func_layer.h" #include "layer_type_macro.h" #include "../tensor.h" namespace BigBang { template<typename dtype> class SigmoidLayer : public ActivationFuncLayer<dtype> { public: SigmoidLayer(const LayerParameter& params):ActivationFuncLayer(params){} virtual ~SigmoidLayer() {} virtual inline const char* Type() const override { return SIGMOID_LAYER_TYPE; } protected: virtual void Forward_CPU(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void Backward_CPU(const Tensor<dtype>* top, Tensor<dtype>* bottom) override; virtual void Forward_GPU(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void Backward_GPU(const Tensor<dtype>* top, Tensor<dtype>* bottom) override; virtual void Prepare(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void reshape(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; }; } #endif
[ "30893898@qq.com" ]
30893898@qq.com
96e59239be46f2486bb30f743c69515e2c7c70c9
88a60552472e8ded90108edbc54556ac4b56e0a5
/TcpProxySession.cpp
a6686a5edfd48a8ae1a7a4b13d1862388a6173b4
[]
no_license
aaronriekenberg/asioproxy
1f4354e68134a0ae63c87e274fa087af3d6626bb
840714fa44e3afb567e18c6c71a64dd96b76c96c
refs/heads/master
2021-01-18T19:19:27.024393
2013-09-01T11:27:01
2013-09-01T11:27:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,086
cpp
#include "BoostSystemUtil.h" #include "Log.h" #include "TcpProxySession.h" #include "ProxyOptions.h" namespace asioproxy { TcpProxySession::SharedPtr TcpProxySession::create( boost::asio::io_service& ioService) { return SharedPtr(new TcpProxySession(ioService)); } TcpProxySession::~TcpProxySession() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::~TcpProxySession " << this; } terminate(); } boost::asio::ip::tcp::socket& TcpProxySession::getClientSocket() { return m_clientSocket; } void TcpProxySession::handleClientSocketAccepted() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "handleClientSocketAccepted"; } if (ProxyOptions::getInstance().isNoDelay()) { boost::asio::ip::tcp::no_delay noDelayOption(true); m_clientSocket.set_option(noDelayOption); } std::stringstream clientToProxySS; clientToProxySS << m_clientSocket.remote_endpoint() << " -> " << m_clientSocket.local_endpoint(); m_clientToProxyString = clientToProxySS.str(); Log::getInfoInstance() << "connected client to proxy " << m_clientToProxyString; const ProxyOptions::AddressAndPort& remoteAddressPort = ProxyOptions::getInstance().getRemoteAddressPort(); Log::getInfoInstance() << "begin resolving " << std::get<0>(remoteAddressPort) << ":" << std::get<1>(remoteAddressPort); boost::asio::ip::tcp::resolver::query query(std::get<0>(remoteAddressPort), std::get<1>(remoteAddressPort)); auto sharedThis = shared_from_this(); m_resolver.async_resolve(query, [=] (const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { sharedThis->handleRemoteEndpointResolved(error, iterator); }); } TcpProxySession::TcpProxySession(boost::asio::io_service& ioService) : m_clientSocket(ioService), m_resolver(ioService), m_remoteSocket( ioService), m_connectTimeoutTimer(ioService) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::TcpProxySession " << this; } } void TcpProxySession::terminate() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::terminate"; } if ((!m_clientSocketClosed) && (!m_writingToClientSocket)) { m_clientSocket.close(); m_clientSocketClosed = true; if (!m_clientToProxyString.empty()) { Log::getInfoInstance() << "disconnect client to proxy " << m_clientToProxyString; } } if ((!m_remoteSocketClosed) && (!m_writingToRemoteSocket)) { m_remoteSocket.close(); m_remoteSocketClosed = true; if (!m_proxyToRemoteString.empty()) { Log::getInfoInstance() << "disconnect proxy to remote " << m_proxyToRemoteString; } } m_connectTimeoutTimer.cancel(); } void TcpProxySession::handleRemoteEndpointResolved( const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "handleRemoteEndpointResolved"; } if (error) { const ProxyOptions::AddressAndPort& remoteAddressPort = ProxyOptions::getInstance().getRemoteAddressPort(); Log::getInfoInstance() << "failed to resolve " << std::get<0>(remoteAddressPort) << ":" << std::get<1>(remoteAddressPort); terminate(); } else { boost::asio::ip::tcp::endpoint remoteEndpoint = *iterator; Log::getInfoInstance() << "begin connect to remote " << remoteEndpoint; auto sharedThis = shared_from_this(); m_remoteSocket.async_connect(remoteEndpoint, [=] (const boost::system::error_code& error) { sharedThis->handleConnectFinished(error); }); m_connectTimeoutTimer.expires_from_now( ProxyOptions::getInstance().getConnectTimeout()); m_connectTimeoutTimer.async_wait( [=] (const boost::system::error_code& error) { sharedThis->handleConnectTimeout(); }); } } void TcpProxySession::handleConnectTimeout() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleConnectTimeout"; } m_connectTimeoutTimerPopped = true; if (!m_connectToRemoteFinished) { Log::getInfoInstance() << "connect timeout"; terminate(); } } void TcpProxySession::handleConnectFinished( const boost::system::error_code& error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleConnectFinished"; } m_connectToRemoteFinished = true; if (m_connectTimeoutTimerPopped) { terminate(); } else if (error) { Log::getInfoInstance() << "error connecting to remote endpoint: " << BoostSystemUtil::buildErrorCodeString(error); terminate(); } else { m_connectTimeoutTimer.cancel(); // allocate buffers const size_t bufferSize = ProxyOptions::getInstance().getBufferSize(); m_dataFromClientBuffer.resize(bufferSize, 0); m_dataFromRemoteBuffer.resize(bufferSize, 0); if (ProxyOptions::getInstance().isNoDelay()) { boost::asio::ip::tcp::no_delay noDelayOption(true); m_remoteSocket.set_option(noDelayOption); } std::stringstream proxyToRemoteSS; proxyToRemoteSS << m_remoteSocket.local_endpoint() << " -> " << m_remoteSocket.remote_endpoint(); m_proxyToRemoteString = proxyToRemoteSS.str(); Log::getInfoInstance() << "connected proxy to remote " << m_proxyToRemoteString; asyncReadFromClient(); asyncReadFromRemote(); } } void TcpProxySession::asyncReadFromClient() { auto sharedThis = shared_from_this(); m_clientSocket.async_read_some(boost::asio::buffer(m_dataFromClientBuffer), [=] (const boost::system::error_code& error, size_t bytesTransferred) { sharedThis->handleClientRead(error, bytesTransferred); }); } void TcpProxySession::asyncReadFromRemote() { auto sharedThis = shared_from_this(); m_remoteSocket.async_read_some(boost::asio::buffer(m_dataFromRemoteBuffer), [=] (const boost::system::error_code& error, size_t bytesTransferred) { sharedThis->handleRemoteRead(error, bytesTransferred); }); } void TcpProxySession::handleClientRead(const boost::system::error_code& error, size_t bytesRead) { if (m_remoteSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleClientRead error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { m_writingToRemoteSocket = true; auto sharedThis = shared_from_this(); boost::asio::async_write(m_remoteSocket, boost::asio::buffer(m_dataFromClientBuffer, bytesRead), [=] (const boost::system::error_code& error, size_t bytesWritten) { sharedThis->handleRemoteWriteFinished(error); }); } } void TcpProxySession::handleRemoteRead(const boost::system::error_code& error, size_t bytesRead) { if (m_clientSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleRemoteRead error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { m_writingToClientSocket = true; auto sharedThis = shared_from_this(); boost::asio::async_write(m_clientSocket, boost::asio::buffer(m_dataFromRemoteBuffer, bytesRead), [=] (const boost::system::error_code& error, size_t bytesWritten) { sharedThis->handleClientWriteFinished(error); }); } } void TcpProxySession::handleRemoteWriteFinished( const boost::system::error_code& error) { m_writingToRemoteSocket = false; if (m_clientSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleRemoteWriteFinished error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { asyncReadFromClient(); } } void TcpProxySession::handleClientWriteFinished( const boost::system::error_code& error) { m_writingToClientSocket = false; if (m_remoteSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleClientWriteFinished error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { asyncReadFromRemote(); } } }
[ "aaron.riekenberg@gmail.com" ]
aaron.riekenberg@gmail.com
6a4c0e75bb10ec54a35b1a850ee4a3a66e7e4153
ebe0cffadf5d04495905bbc75fbfd8acee832f6b
/Cameras/HomefrontTheRevolution/InjectableGenericCameraSystem/CameraManipulator.h
3dcf5679cc8f3c370c7a2f1b1bd48e603aa50d77
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
FransBouma/InjectableGenericCameraSystem
f123f31c676879561fc3a3e2d03579adf2c1f7cf
bdd9e237cef6caba38b946b18c36713f69ab09b9
refs/heads/master
2023-08-24T19:17:59.563669
2023-04-27T18:59:08
2023-04-27T18:59:08
75,194,811
718
278
BSD-2-Clause
2020-09-23T19:12:50
2016-11-30T14:30:36
C++
UTF-8
C++
false
false
2,202
h
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2017, Frans Bouma // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "stdafx.h" using namespace DirectX; namespace IGCS::GameSpecific::CameraManipulator { void writeNewCameraValuesToGameData(XMFLOAT3 newCoords, XMVECTOR newLookQuaternion); void restoreOriginalCameraValues(); void cacheOriginalCameraValues(); void setTimeStopValue(byte newValue); void setSupersamplingFactor(LPBYTE hostImageAddress, float newValue); XMFLOAT3 getCurrentCameraCoords(); void resetFoV(); void changeFoV(float amount); bool isCameraFound(); void displayCameraStructAddress(); }
[ "frans@sd.nl" ]
frans@sd.nl
5b50b6919d95fd52d34821005006f0623bfef1a7
a7a369fe4a73b2ee8a043b1ff15ed56ee1b1d292
/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp
4ac5d1de4a014911d74052fb5f4b8a41be0f7607
[]
no_license
cooler-SAI/ServerMythCore
de720f8143f14fb0e36c2b7291def52f660d9e1a
bd99985adca0698b7419094726bdbce13c18740c
refs/heads/master
2020-04-04T21:27:04.974080
2015-06-22T14:06:42
2015-06-22T14:06:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,187
cpp
/* * Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2013 Myth Project <http://mythprojectnetwork.blogspot.com/> * * Myth Project's source is based on the Trinity Project source, you can find the * link to that easily in Trinity Copyrights. Myth Project is a private community. * To get access, you either have to donate or pass a developer test. * You may not share Myth Project's sources! For personal use only. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "InstanceScript.h" #include "eye_of_eternity.h" class instance_eye_of_eternity : public InstanceMapScript { public: instance_eye_of_eternity() : InstanceMapScript("instance_eye_of_eternity", 616) { } InstanceScript* GetInstanceScript(InstanceMap* pMap) const { return new instance_eye_of_eternity_InstanceMapScript(pMap); } struct instance_eye_of_eternity_InstanceMapScript : public InstanceScript { instance_eye_of_eternity_InstanceMapScript(Map* pMap) : InstanceScript(pMap) { SetBossNumber(MAX_ENCOUNTER); vortexTriggers.clear(); portalTriggers.clear(); malygosGUID = 0; lastPortalGUID = 0; platformGUID = 0; exitPortalGUID = 0; }; bool SetBossState(uint32 type, EncounterState state) { if(!InstanceScript::SetBossState(type, state)) return false; if(type == DATA_MALYGOS_EVENT) { if(state == FAIL) { for(std::list<uint64>::const_iterator itr_trigger = portalTriggers.begin(); itr_trigger != portalTriggers.end(); ++itr_trigger) { if(Creature* trigger = instance->GetCreature(*itr_trigger)) { // just in case trigger->RemoveAllAuras(); trigger->AI()->Reset(); } } SpawnGameObject(GO_FOCUSING_IRIS, focusingIrisPosition); SpawnGameObject(GO_EXIT_PORTAL, exitPortalPosition); if(GameObject* platform = instance->GetGameObject(platformGUID)) platform->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); } else if(state == DONE) { if(Creature* malygos = instance->GetCreature(malygosGUID)) malygos->SummonCreature(NPC_ALEXSTRASZA, 829.0679f, 1244.77f, 279.7453f, 2.32f); SpawnGameObject(GO_EXIT_PORTAL, exitPortalPosition); // we make the platform appear again because at the moment we don't support looting using a vehicle if(GameObject* platform = instance->GetGameObject(platformGUID)) platform->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); if(GameObject* chest = instance->GetGameObject(chestGUID)) chest->SetRespawnTime(7*DAY); } } return true; } // There is no other way afaik... void SpawnGameObject(uint32 entry, Position& pos) { GameObject* pGo = new GameObject; if(!pGo->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT),entry, instance, PHASEMASK_NORMAL, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), 0, 0, 0, 0, 120, GO_STATE_READY)) { delete pGo; return; } instance->Add(pGo); } void OnGameObjectCreate(GameObject* pGo) { switch(pGo->GetEntry()) { case GO_NEXUS_RAID_PLATFORM: platformGUID = pGo->GetGUID(); break; case GO_FOCUSING_IRIS: pGo->GetPosition(&focusingIrisPosition); break; case GO_EXIT_PORTAL: exitPortalGUID = pGo->GetGUID(); pGo->GetPosition(&exitPortalPosition); break; case GO_ALEXSTRASZA_S_GIFT: case GO_ALEXSTRASZA_S_GIFT_2: chestGUID = pGo->GetGUID(); break; } } void OnCreatureCreate(Creature* pCreature) { switch(pCreature->GetEntry()) { case NPC_VORTEX_TRIGGER: vortexTriggers.push_back(pCreature->GetGUID()); break; case NPC_MALYGOS: malygosGUID = pCreature->GetGUID(); break; case NPC_PORTAL_TRIGGER: portalTriggers.push_back(pCreature->GetGUID()); break; } } void ProcessEvent(WorldObject* pWO, uint32 eventId) { if(eventId == EVENT_FOCUSING_IRIS) { if(GameObject* go = pWO->ToGameObject()) go->Delete(); // this is not the best way. if(Creature* malygos = instance->GetCreature(malygosGUID)) malygos->GetMotionMaster()->MovePoint(4, 770.10f, 1275.33f, 267.23f); // MOVE_INIT_PHASE_ONE if(GameObject* exitPortal = instance->GetGameObject(exitPortalGUID)) exitPortal->Delete(); } } void VortexHandling() { if(Creature* malygos = instance->GetCreature(malygosGUID)) { std::list<HostileReference*> m_threatlist = malygos->getThreatManager().getThreatList(); for(std::list<uint64>::const_iterator itr_vortex = vortexTriggers.begin(); itr_vortex != vortexTriggers.end(); ++itr_vortex) { if(m_threatlist.empty()) return; uint8 counter = 0; if(Creature* pTrigger_Creature = instance->GetCreature(*itr_vortex)) { // each trigger have to cast the spell to 5 players. for(std::list<HostileReference*>::const_iterator itr = m_threatlist.begin(); itr!= m_threatlist.end(); ++itr) { if(counter >= 5) break; if(Unit* pTarget = (*itr)->getTarget()) { Player* pPlayer = pTarget->ToPlayer(); if(!pPlayer || pPlayer->isGameMaster() || pPlayer->HasAura(SPELL_VORTEX_4)) continue; pPlayer->CastSpell(pTrigger_Creature, SPELL_VORTEX_4, true); counter++; } } } } } } void PowerSparksHandling() { bool next = (lastPortalGUID == portalTriggers.back() || !lastPortalGUID ? true : false); for(std::list<uint64>::const_iterator itr_trigger = portalTriggers.begin(); itr_trigger != portalTriggers.end(); ++itr_trigger) { if(next) { if(Creature* trigger = instance->GetCreature(*itr_trigger)) { lastPortalGUID = trigger->GetGUID(); trigger->CastSpell(trigger, SPELL_PORTAL_OPENED, true); return; } } if(*itr_trigger == lastPortalGUID) next = true; } } void SetData(uint32 data, uint32 /*value*/) { switch(data) { case DATA_VORTEX_HANDLING: VortexHandling(); break; case DATA_POWER_SPARKS_HANDLING: PowerSparksHandling(); break; } } uint64 GetData64(uint32 data) { switch(data) { case DATA_TRIGGER: return vortexTriggers.front(); case DATA_MALYGOS: return malygosGUID; case DATA_PLATFORM: return platformGUID; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "E E " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(const char* str) { if(!str) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(str); char dataHead1, dataHead2; std::istringstream loadStream(str); loadStream >> dataHead1 >> dataHead2; if(dataHead1 == 'E' && dataHead2 == 'E') { for(uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if(tmpState == IN_PROGRESS || tmpState > SPECIAL) tmpState = NOT_STARTED; SetBossState(i, EncounterState(tmpState)); } } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } private: std::list<uint64> vortexTriggers; std::list<uint64> portalTriggers; uint64 malygosGUID; uint64 lastPortalGUID; uint64 platformGUID; uint64 exitPortalGUID; uint64 chestGUID; Position focusingIrisPosition; Position exitPortalPosition; }; }; void AddSC_instance_eye_of_eternity() { new instance_eye_of_eternity(); }
[ "humbertohuanuco@gmail.com" ]
humbertohuanuco@gmail.com
700d117c9f7e07e5d11aaa33b419ee6cddd99f62
d1bb6fd4b439da85af74321e3391413640fb92f0
/Homework1Q1S2/Homework1Q1S2/Rational.cpp
de3a6b4f857e753fea0a93455e268271a3d7f266
[]
no_license
YosefSchoen/ObjectOrientedProgramming
dc6138501285509cb25cff111f2b18e79753764a
f0a36c7bf3fe461ccdabf010905a40c30c41eac4
refs/heads/master
2020-07-30T21:35:49.839185
2019-09-23T13:45:03
2019-09-23T13:45:03
210,356,549
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include "Rational.h"; #include <iostream> using namespace std; Rational::Rational(int top, int bottom) { numerator = top; denominator = bottom; } void Rational::setNumerator(int top) { numerator = top; } void Rational::setDenominator(int bottom) { denominator = bottom; } int Rational::getNumerator() { return numerator; } int Rational::getDenominator() { return denominator; } void Rational::print() { cout << numerator << "/" << denominator << endl; } bool Rational::equal(Rational second) { if (numerator * second.getDenominator() == denominator * second.getNumerator()) { return true; } else { return false; } } int Rational::reduce() { if (numerator == denominator) { return 1; } else { for (int i = 2; i <= numerator; i++) { if ((numerator % i == 0) && (denominator % i == 0)) { numerator = numerator / i; denominator = denominator / i; } } } return 0; }
[ "josephaschoen@gmail.com" ]
josephaschoen@gmail.com
d8de2c0b726c8e620b526bbaac0ade97c8ced5e8
e043290612c380ca10290badb2574da006b9dea9
/services/ui/ws/window_server_test_base.cc
bee909e989bd4522396c49f7036700ec598eadc9
[ "BSD-3-Clause" ]
permissive
jeffsseely/chromium
28667a243607baf02c74ccf4cc94a1b36ed2a42b
5c0ead04050ee0787ef0d9af45efc3c740571465
refs/heads/master
2023-03-17T04:31:14.131666
2017-01-24T18:15:39
2017-01-24T18:15:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,278
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/ws/window_server_test_base.h" #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_registry.h" #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_host_mus.h" #include "ui/display/display.h" #include "ui/display/display_list.h" #include "ui/wm/core/capture_controller.h" namespace ui { namespace { base::RunLoop* current_run_loop = nullptr; void TimeoutRunLoop(const base::Closure& timeout_task, bool* timeout) { CHECK(current_run_loop); *timeout = true; timeout_task.Run(); } } // namespace WindowServerTestBase::WindowServerTestBase() {} WindowServerTestBase::~WindowServerTestBase() {} // static bool WindowServerTestBase::DoRunLoopWithTimeout() { if (current_run_loop != nullptr) return false; bool timeout = false; base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&TimeoutRunLoop, run_loop.QuitClosure(), &timeout), TestTimeouts::action_timeout()); current_run_loop = &run_loop; current_run_loop->Run(); current_run_loop = nullptr; return !timeout; } // static bool WindowServerTestBase::QuitRunLoop() { if (!current_run_loop) return false; current_run_loop->Quit(); current_run_loop = nullptr; return true; } void WindowServerTestBase::DeleteWindowTreeClient( aura::WindowTreeClient* client) { for (auto iter = window_tree_clients_.begin(); iter != window_tree_clients_.end(); ++iter) { if (iter->get() == client) { window_tree_clients_.erase(iter); return; } } NOTREACHED(); } std::unique_ptr<aura::WindowTreeClient> WindowServerTestBase::ReleaseMostRecentClient() { if (window_tree_clients_.empty()) return nullptr; std::unique_ptr<aura::WindowTreeClient> result = std::move(window_tree_clients_.back()); window_tree_clients_.pop_back(); return result; } void WindowServerTestBase::SetUp() { WindowServerServiceTestBase::SetUp(); env_ = aura::Env::CreateInstance(aura::Env::Mode::MUS); display::Screen::SetScreenInstance(&screen_); std::unique_ptr<aura::WindowTreeClient> window_manager_window_tree_client = base::MakeUnique<aura::WindowTreeClient>(connector(), this, this); window_manager_window_tree_client->ConnectAsWindowManager(); window_manager_ = window_manager_window_tree_client.get(); window_tree_clients_.push_back(std::move(window_manager_window_tree_client)); // Connecting as the WindowManager results in OnWmNewDisplay() being called // with the display (and root). Wait for it to be called so we have display // and root window information (otherwise we can't really do anything). ASSERT_TRUE(DoRunLoopWithTimeout()); } void WindowServerTestBase::TearDown() { // WindowTreeHost depends on WindowTreeClient. window_tree_hosts_.clear(); window_tree_clients_.clear(); env_.reset(); display::Screen::SetScreenInstance(nullptr); WindowServerServiceTestBase::TearDown(); } bool WindowServerTestBase::OnConnect( const service_manager::Identity& remote_identity, service_manager::InterfaceRegistry* registry) { registry->AddInterface<mojom::WindowTreeClient>(this); return true; } void WindowServerTestBase::OnEmbed( std::unique_ptr<aura::WindowTreeHostMus> window_tree_host) { EXPECT_TRUE(QuitRunLoop()); window_tree_hosts_.push_back(std::move(window_tree_host)); } void WindowServerTestBase::OnLostConnection(aura::WindowTreeClient* client) { window_tree_client_lost_connection_ = true; DeleteWindowTreeClient(client); } void WindowServerTestBase::OnEmbedRootDestroyed( aura::WindowTreeHostMus* window_tree_host) { if (!DeleteWindowTreeHost(window_tree_host)) { // Assume a subclass called Embed() and wants us to destroy it. delete window_tree_host; } } void WindowServerTestBase::OnPointerEventObserved(const ui::PointerEvent& event, aura::Window* target) {} aura::client::CaptureClient* WindowServerTestBase::GetCaptureClient() { return wm_state_.capture_controller(); } aura::PropertyConverter* WindowServerTestBase::GetPropertyConverter() { return &property_converter_; } void WindowServerTestBase::SetWindowManagerClient( aura::WindowManagerClient* client) { window_manager_client_ = client; } bool WindowServerTestBase::OnWmSetBounds(aura::Window* window, gfx::Rect* bounds) { return window_manager_delegate_ ? window_manager_delegate_->OnWmSetBounds(window, bounds) : true; } bool WindowServerTestBase::OnWmSetProperty( aura::Window* window, const std::string& name, std::unique_ptr<std::vector<uint8_t>>* new_data) { return window_manager_delegate_ ? window_manager_delegate_->OnWmSetProperty(window, name, new_data) : true; } aura::Window* WindowServerTestBase::OnWmCreateTopLevelWindow( ui::mojom::WindowType window_type, std::map<std::string, std::vector<uint8_t>>* properties) { return window_manager_delegate_ ? window_manager_delegate_->OnWmCreateTopLevelWindow(window_type, properties) : nullptr; } void WindowServerTestBase::OnWmClientJankinessChanged( const std::set<aura::Window*>& client_windows, bool janky) { if (window_manager_delegate_) window_manager_delegate_->OnWmClientJankinessChanged(client_windows, janky); } void WindowServerTestBase::OnWmWillCreateDisplay( const display::Display& display) { screen_.display_list().AddDisplay(display, display::DisplayList::Type::PRIMARY); if (window_manager_delegate_) window_manager_delegate_->OnWmWillCreateDisplay(display); } void WindowServerTestBase::OnWmNewDisplay( std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, const display::Display& display) { EXPECT_TRUE(QuitRunLoop()); ASSERT_TRUE(window_manager_client_); window_manager_client_->AddActivationParent(window_tree_host->window()); window_tree_hosts_.push_back(std::move(window_tree_host)); if (window_manager_delegate_) window_manager_delegate_->OnWmNewDisplay(nullptr, display); } void WindowServerTestBase::OnWmDisplayRemoved( aura::WindowTreeHostMus* window_tree_host) { if (window_manager_delegate_) window_manager_delegate_->OnWmDisplayRemoved(window_tree_host); ASSERT_TRUE(DeleteWindowTreeHost(window_tree_host)); } void WindowServerTestBase::OnWmDisplayModified( const display::Display& display) { if (window_manager_delegate_) window_manager_delegate_->OnWmDisplayModified(display); } ui::mojom::EventResult WindowServerTestBase::OnAccelerator( uint32_t accelerator_id, const ui::Event& event) { return window_manager_delegate_ ? window_manager_delegate_->OnAccelerator(accelerator_id, event) : ui::mojom::EventResult::UNHANDLED; } void WindowServerTestBase::OnWmPerformMoveLoop( aura::Window* window, ui::mojom::MoveLoopSource source, const gfx::Point& cursor_location, const base::Callback<void(bool)>& on_done) { if (window_manager_delegate_) { window_manager_delegate_->OnWmPerformMoveLoop(window, source, cursor_location, on_done); } } void WindowServerTestBase::OnWmCancelMoveLoop(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->OnWmCancelMoveLoop(window); } void WindowServerTestBase::OnWmSetClientArea( aura::Window* window, const gfx::Insets& insets, const std::vector<gfx::Rect>& additional_client_areas) { if (window_manager_delegate_) { window_manager_delegate_->OnWmSetClientArea(window, insets, additional_client_areas); } } bool WindowServerTestBase::IsWindowActive(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->IsWindowActive(window); return false; } void WindowServerTestBase::OnWmDeactivateWindow(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->OnWmDeactivateWindow(window); } void WindowServerTestBase::Create( const service_manager::Identity& remote_identity, mojom::WindowTreeClientRequest request) { window_tree_clients_.push_back(base::MakeUnique<aura::WindowTreeClient>( connector(), this, nullptr, std::move(request))); } bool WindowServerTestBase::DeleteWindowTreeHost( aura::WindowTreeHostMus* window_tree_host) { for (auto iter = window_tree_hosts_.begin(); iter != window_tree_hosts_.end(); ++iter) { if ((*iter).get() == window_tree_host) { window_tree_hosts_.erase(iter); return true; } } return false; } } // namespace ui
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
41b7677312fd583b5c4034129540a7b406b24f9e
6fe993c6e41af7679ab2bbaafd1b9bec5f0191e5
/src/main.cpp
d4a1816a222e5339d953f1820a544c4a80669e56
[]
no_license
pmaroti/loraTestTransmitter
c91c6c3faad540c0ff15a5fe0b2467a7518f53e4
e1f70f406cc046184f16005186b43e736f2a279b
refs/heads/master
2020-03-18T00:04:06.300115
2018-05-19T15:52:22
2018-05-19T15:52:22
134,076,069
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
/// /// Arduino SX1278_Lora /// GND----------GND (ground in) /// 3V3----------3.3V (3.3V in) /// interrupt 0 pin D2-----------DIO0 (interrupt request out) /// SS pin D10----------NSS (CS chip select in) /// SCK pin D13----------SCK (SPI clock in) /// MOSI pin D11----------MOSI (SPI Data in) /// MISO pin D12----------MISO (SPI Data out) /// #include <SPI.h> #include <RH_RF95.h> // Singleton instance of the radio driver RH_RF95 SX1278; byte counter; char counter_string[]="Counter: 00"; void setup() { Serial.begin(9600); while (!Serial) ; // Wait for serial port to be available if (!SX1278.init()) Serial.println("Notice:init failed"); Serial.println("Initialization OK"); counter = 0; } void loop() { Serial.print("Sending to SX1278_server"); itoa(counter,counter_string+9,10); Serial.println(counter_string); // Send a message to SX1278_server SX1278.send(counter_string, sizeof(counter_string)); Serial.println("mark0"); SX1278.waitPacketSent(); Serial.println("mark1"); // Now wait for a reply uint8_t buf[RH_RF95_MAX_MESSAGE_LEN]; uint8_t len = sizeof(buf); delay(1000); Serial.println("mark2"); counter++; }
[ "pmaroti@gmail.com" ]
pmaroti@gmail.com
6ee77165137b972c9e3b4ca71c1c1468f79af624
1b6c60b5a14f5eb7ea06676159e1a83c18cf6bb5
/kattis/Baby_bites_kattis.cpp
bb4e63cd0050e764070d38bbca67c6b65c91d205
[ "MIT" ]
permissive
NafiAsib/competitive-programming
75595c2b0984baf72a998da8b3d115bf2681e07c
3255b2fe3329543baf9e720e1ccaf08466d77303
refs/heads/master
2022-11-20T06:48:01.951206
2020-07-22T10:20:09
2020-07-22T10:20:09
240,660,207
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
#include <bits/stdc++.h> using namespace std; int main() { int i, index = 0, n, current = 1; char str[10]; bool sense = 1; cin >> n; for(i = 0; i < n; i++, current++) { cin>>str; if(str[0] == 'm') continue; index = atoi(str); if(index != current) sense = 0; } if(sense) cout<<"makes sense"<<"\n"; else cout<<"something is fishy"<<"\n"; return 0; }
[ "nafi.asib@gmail.com" ]
nafi.asib@gmail.com
f3ce73026cd2e9fd5514aae711e7cc7def61c8a7
2ab8b69d144b242552f65738140ffe93f68ccf2b
/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
862f0c5e976b66fcd1fb3e06a08cb52d1f8615da
[ "BSD-3-Clause" ]
permissive
user-lab/chromium
45c41be02fad35e396e3acc12cc2003ae29ac207
f90402556cc8107ed19e5663ed1e7a4e80ff3e94
refs/heads/master
2023-03-03T23:23:08.506668
2019-10-02T18:21:44
2019-10-02T18:21:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,732
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/profiles/profile_menu_view_base.h" #include <algorithm> #include <memory> #include <utility> #include "base/feature_list.h" #include "base/macros.h" #include "base/metrics/user_metrics.h" #include "build/build_config.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/hover_button.h" #include "chrome/browser/ui/views/profiles/incognito_menu_view.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/image/canvas_image_source.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/link.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/separator.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_class_properties.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/views/profiles/profile_menu_view.h" #include "chrome/browser/ui/views/sync/dice_signin_button_view.h" #endif namespace { ProfileMenuViewBase* g_profile_bubble_ = nullptr; // Helpers -------------------------------------------------------------------- constexpr int kMenuWidth = 288; constexpr int kIconSize = 16; constexpr int kIdentityImageSize = 64; constexpr int kMaxImageSize = kIdentityImageSize; // If the bubble is too large to fit on the screen, it still needs to be at // least this tall to show one row. constexpr int kMinimumScrollableContentHeight = 40; // Spacing between the edge of the user menu and the top/bottom or left/right of // the menu items. constexpr int kMenuEdgeMargin = 16; SkColor GetDefaultIconColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_DefaultIconColor); } SkColor GetDefaultSeparatorColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_MenuSeparatorColor); } gfx::ImageSkia SizeImage(const gfx::ImageSkia& image, int size) { return gfx::ImageSkiaOperations::CreateResizedImage( image, skia::ImageOperations::RESIZE_BEST, gfx::Size(size, size)); } gfx::ImageSkia ColorImage(const gfx::ImageSkia& image, SkColor color) { return gfx::ImageSkiaOperations::CreateColorMask(image, color); } class CircleImageSource : public gfx::CanvasImageSource { public: CircleImageSource(int size, SkColor color) : gfx::CanvasImageSource(gfx::Size(size, size)), color_(color) {} ~CircleImageSource() override = default; void Draw(gfx::Canvas* canvas) override; private: SkColor color_; DISALLOW_COPY_AND_ASSIGN(CircleImageSource); }; void CircleImageSource::Draw(gfx::Canvas* canvas) { float radius = size().width() / 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setAntiAlias(true); flags.setColor(color_); canvas->DrawCircle(gfx::PointF(radius, radius), radius, flags); } gfx::ImageSkia CreateCircle(int size, SkColor color = SK_ColorWHITE) { return gfx::CanvasImageSource::MakeImageSkia<CircleImageSource>(size, color); } gfx::ImageSkia CropCircle(const gfx::ImageSkia& image) { DCHECK_EQ(image.width(), image.height()); return gfx::ImageSkiaOperations::CreateMaskedImage( image, CreateCircle(image.width())); } gfx::ImageSkia AddCircularBackground(const gfx::ImageSkia& image, SkColor bg_color, int size) { if (image.isNull()) return gfx::ImageSkia(); return gfx::ImageSkiaOperations::CreateSuperimposedImage( CreateCircle(size, bg_color), image); } std::unique_ptr<views::BoxLayout> CreateBoxLayout( views::BoxLayout::Orientation orientation, views::BoxLayout::CrossAxisAlignment cross_axis_alignment, gfx::Insets insets = gfx::Insets()) { auto layout = std::make_unique<views::BoxLayout>(orientation, insets); layout->set_cross_axis_alignment(cross_axis_alignment); return layout; } std::unique_ptr<views::View> CreateBorderedBoxView() { constexpr int kBorderThickness = 1; auto bordered_box = std::make_unique<views::View>(); bordered_box->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); bordered_box->SetBorder(views::CreateRoundedRectBorder( kBorderThickness, views::LayoutProvider::Get()->GetCornerRadiusMetric(views::EMPHASIS_HIGH), GetDefaultSeparatorColor())); bordered_box->SetProperty(views::kMarginsKey, gfx::Insets(kMenuEdgeMargin)); return bordered_box; } std::unique_ptr<views::Button> CreateCircularImageButton( views::ButtonListener* listener, const gfx::ImageSkia& image, const base::string16& text, bool show_border = false) { constexpr int kImageSize = 28; const int kBorderThickness = show_border ? 1 : 0; const SkScalar kButtonRadius = (kImageSize + 2 * kBorderThickness) / 2.0; auto button = std::make_unique<views::ImageButton>(listener); button->SetImage(views::Button::STATE_NORMAL, SizeImage(image, kImageSize)); button->SetTooltipText(text); button->SetInkDropMode(views::Button::InkDropMode::ON); button->SetFocusForPlatform(); button->set_ink_drop_base_color(GetDefaultIconColor()); if (show_border) { button->SetBorder(views::CreateRoundedRectBorder( kBorderThickness, kButtonRadius, GetDefaultSeparatorColor())); } // Set circular highlight path. auto path = std::make_unique<SkPath>(); path->addCircle(kButtonRadius, kButtonRadius, kButtonRadius); button->SetProperty(views::kHighlightPathKey, path.release()); return button; } } // namespace // MenuItems-------------------------------------------------------------------- ProfileMenuViewBase::MenuItems::MenuItems() : first_item_type(ProfileMenuViewBase::MenuItems::kNone), last_item_type(ProfileMenuViewBase::MenuItems::kNone), different_item_types(false) {} ProfileMenuViewBase::MenuItems::MenuItems(MenuItems&&) = default; ProfileMenuViewBase::MenuItems::~MenuItems() = default; // ProfileMenuViewBase --------------------------------------------------------- // static void ProfileMenuViewBase::ShowBubble( profiles::BubbleViewMode view_mode, signin_metrics::AccessPoint access_point, views::Button* anchor_button, Browser* browser, bool is_source_keyboard) { if (IsShowing()) return; base::RecordAction(base::UserMetricsAction("ProfileMenu_Opened")); ProfileMenuViewBase* bubble; if (base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) { #if !defined(OS_CHROMEOS) // On Desktop, all modes(regular, guest, incognito) are handled within // ProfileMenuView. bubble = new ProfileMenuView(anchor_button, browser, access_point); #else // On ChromeOS, only the incognito menu is implemented. DCHECK(browser->profile()->IsIncognitoProfile()); bubble = new IncognitoMenuView(anchor_button, browser); #endif } else { if (view_mode == profiles::BUBBLE_VIEW_MODE_INCOGNITO) { DCHECK(browser->profile()->IsIncognitoProfile()); bubble = new IncognitoMenuView(anchor_button, browser); } else { DCHECK_EQ(profiles::BUBBLE_VIEW_MODE_PROFILE_CHOOSER, view_mode); #if !defined(OS_CHROMEOS) bubble = new ProfileMenuView(anchor_button, browser, access_point); #else NOTREACHED(); return; #endif } } views::BubbleDialogDelegateView::CreateBubble(bubble)->Show(); if (is_source_keyboard) bubble->FocusButtonOnKeyboardOpen(); } // static bool ProfileMenuViewBase::IsShowing() { return g_profile_bubble_ != nullptr; } // static void ProfileMenuViewBase::Hide() { if (g_profile_bubble_) g_profile_bubble_->GetWidget()->Close(); } // static ProfileMenuViewBase* ProfileMenuViewBase::GetBubbleForTesting() { return g_profile_bubble_; } ProfileMenuViewBase::ProfileMenuViewBase(views::Button* anchor_button, Browser* browser) : BubbleDialogDelegateView(anchor_button, views::BubbleBorder::TOP_RIGHT), browser_(browser), anchor_button_(anchor_button), close_bubble_helper_(this, browser) { DCHECK(!g_profile_bubble_); g_profile_bubble_ = this; // TODO(sajadm): Remove when fixing https://crbug.com/822075 // The sign in webview will be clipped on the bottom corners without these // margins, see related bug <http://crbug.com/593203>. set_margins(gfx::Insets(2, 0)); DCHECK(anchor_button); anchor_button->AnimateInkDrop(views::InkDropState::ACTIVATED, nullptr); EnableUpDownKeyboardAccelerators(); GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenu); } ProfileMenuViewBase::~ProfileMenuViewBase() { // Items stored for menu generation are removed after menu is finalized, hence // it's not expected to have while destroying the object. DCHECK(g_profile_bubble_ != this); DCHECK(menu_item_groups_.empty()); } void ProfileMenuViewBase::SetIdentityInfo(const gfx::ImageSkia& image, const gfx::ImageSkia& badge, const base::string16& title, const base::string16& subtitle) { constexpr int kTopMargin = 16; constexpr int kBottomMargin = 8; constexpr int kImageToLabelSpacing = 4; constexpr int kBadgeSize = 16; constexpr int kBadgePadding = 1; identity_info_container_->RemoveAllChildViews(/*delete_children=*/true); identity_info_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kVertical, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(kTopMargin, 0, kBottomMargin, 0))); views::ImageView* image_view = identity_info_container_->AddChildView( std::make_unique<views::ImageView>()); // Fall back on |kUserAccountAvatarIcon| if |image| is empty. This can happen // in tests and when the account image hasn't been fetched yet. gfx::ImageSkia sized_image = image.isNull() ? gfx::CreateVectorIcon(kUserAccountAvatarIcon, kIdentityImageSize, kIdentityImageSize) : CropCircle(SizeImage(image, kIdentityImageSize)); gfx::ImageSkia sized_badge = AddCircularBackground(SizeImage(badge, kBadgeSize), SK_ColorWHITE, kBadgeSize + 2 * kBadgePadding); gfx::ImageSkia badged_image = gfx::ImageSkiaOperations::CreateIconWithBadge(sized_image, sized_badge); image_view->SetImage(badged_image); views::View* title_label = identity_info_container_->AddChildView(std::make_unique<views::Label>( title, views::style::CONTEXT_DIALOG_TITLE)); title_label->SetBorder( views::CreateEmptyBorder(kImageToLabelSpacing, 0, 0, 0)); if (!subtitle.empty()) { identity_info_container_->AddChildView(std::make_unique<views::Label>( subtitle, views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); } } void ProfileMenuViewBase::SetSyncInfo(const base::string16& description, const base::string16& link_text, base::RepeatingClosure action) { constexpr int kVerticalPadding = 8; sync_info_container_->RemoveAllChildViews(/*delete_children=*/true); sync_info_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); views::View* separator = sync_info_container_->AddChildView(std::make_unique<views::Separator>()); separator->SetBorder( views::CreateEmptyBorder(0, 0, /*bottom=*/kVerticalPadding, 0)); if (!description.empty()) { views::Label* label = sync_info_container_->AddChildView( std::make_unique<views::Label>(description)); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_CENTER); label->SetHandlesTooltips(false); label->SetBorder(views::CreateEmptyBorder(gfx::Insets(0, kMenuEdgeMargin))); } views::Link* link = sync_info_container_->AddChildView( std::make_unique<views::Link>(link_text)); link->SetHorizontalAlignment(gfx::ALIGN_CENTER); link->set_listener(this); link->SetBorder(views::CreateEmptyBorder(/*top=*/0, /*left=*/kMenuEdgeMargin, /*bottom=*/kVerticalPadding, /*right=*/kMenuEdgeMargin)); RegisterClickAction(link, std::move(action)); } void ProfileMenuViewBase::AddShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kBottomMargin = 8; constexpr int kButtonSpacing = 6; // Initialize layout if this is the first time a button is added. if (!shortcut_features_container_->GetLayoutManager()) { views::BoxLayout* layout = shortcut_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(0, 0, kBottomMargin, 0), kButtonSpacing)); layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); } views::Button* button = shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text, /*show_border=*/true)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddAccountFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 16; // Initialize layout if this is the first time a button is added. if (!account_features_container_->GetLayoutManager()) { account_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } account_features_container_->AddChildView( std::make_unique<views::Separator>()); views::Button* button = account_features_container_->AddChildView(std::make_unique<HoverButton>( this, SizeImage(ColorImage(icon, GetDefaultIconColor()), kIconSize), text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::SetProfileHeading(const base::string16& heading) { profile_heading_container_->RemoveAllChildViews(/*delete_children=*/true); profile_heading_container_->SetLayoutManager( std::make_unique<views::FillLayout>()); views::Label* label = profile_heading_container_->AddChildView(std::make_unique<views::Label>( heading, views::style::CONTEXT_LABEL, STYLE_HINT)); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetHandlesTooltips(false); label->SetBorder(views::CreateEmptyBorder(gfx::Insets(0, kMenuEdgeMargin))); } void ProfileMenuViewBase::AddSelectableProfile(const gfx::ImageSkia& image, const base::string16& name, base::RepeatingClosure action) { constexpr int kTopMargin = 8; constexpr int kImageSize = 22; // Initialize layout if this is the first time a button is added. if (!selectable_profiles_container_->GetLayoutManager()) { selectable_profiles_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(kTopMargin, 0, 0, 0))); } gfx::ImageSkia sized_image = CropCircle(SizeImage(image, kImageSize)); views::Button* button = selectable_profiles_container_->AddChildView( std::make_unique<HoverButton>(this, sized_image, name)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { // Initialize layout if this is the first time a button is added. if (!profile_shortcut_features_container_->GetLayoutManager()) { profile_shortcut_features_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kHorizontal, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(0, 0, 0, /*right=*/kMenuEdgeMargin))); } views::Button* button = profile_shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 22; // Initialize layout if this is the first time a button is added. if (!profile_features_container_->GetLayoutManager()) { profile_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } views::Button* button = profile_features_container_->AddChildView( std::make_unique<HoverButton>(this, SizeImage(icon, kIconSize), text)); RegisterClickAction(button, std::move(action)); } gfx::ImageSkia ProfileMenuViewBase::ImageForMenu(const gfx::VectorIcon& icon, float icon_to_image_ratio) { const int padding = static_cast<int>(kMaxImageSize * (1.0 - icon_to_image_ratio) / 2.0); auto sized_icon = gfx::CreateVectorIcon(icon, kMaxImageSize - 2 * padding, GetDefaultIconColor()); return gfx::CanvasImageSource::CreatePadded(sized_icon, gfx::Insets(padding)); } gfx::ImageSkia ProfileMenuViewBase::ColoredImageForMenu( const gfx::VectorIcon& icon, SkColor color) { return gfx::CreateVectorIcon(icon, kMaxImageSize, color); } ax::mojom::Role ProfileMenuViewBase::GetAccessibleWindowRole() { // Return |ax::mojom::Role::kDialog| which will make screen readers announce // the following in the listed order: // the title of the dialog, labels (if any), the focused View within the // dialog (if any) return ax::mojom::Role::kDialog; } void ProfileMenuViewBase::OnThemeChanged() { views::BubbleDialogDelegateView::OnThemeChanged(); SetBackground(views::CreateSolidBackground(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_DialogBackground))); } int ProfileMenuViewBase::GetDialogButtons() const { return ui::DIALOG_BUTTON_NONE; } bool ProfileMenuViewBase::HandleContextMenu( content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) { // Suppresses the context menu because some features, such as inspecting // elements, are not appropriate in a bubble. return true; } void ProfileMenuViewBase::Init() { Reset(); BuildMenu(); if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) RepopulateViewFromMenuItems(); } void ProfileMenuViewBase::WindowClosing() { DCHECK_EQ(g_profile_bubble_, this); if (anchor_button()) anchor_button()->AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr); g_profile_bubble_ = nullptr; } void ProfileMenuViewBase::ButtonPressed(views::Button* button, const ui::Event& event) { OnClick(button); } void ProfileMenuViewBase::LinkClicked(views::Link* link, int event_flags) { OnClick(link); } void ProfileMenuViewBase::StyledLabelLinkClicked(views::StyledLabel* link, const gfx::Range& range, int event_flags) { OnClick(link); } void ProfileMenuViewBase::OnClick(views::View* clickable_view) { DCHECK(!click_actions_[clickable_view].is_null()); base::RecordAction( base::UserMetricsAction("ProfileMenu_ActionableItemClicked")); click_actions_[clickable_view].Run(); } int ProfileMenuViewBase::GetMaxHeight() const { gfx::Rect anchor_rect = GetAnchorRect(); gfx::Rect screen_space = display::Screen::GetScreen() ->GetDisplayNearestPoint(anchor_rect.CenterPoint()) .work_area(); int available_space = screen_space.bottom() - anchor_rect.bottom(); #if defined(OS_WIN) // On Windows the bubble can also be show to the top of the anchor. available_space = std::max(available_space, anchor_rect.y() - screen_space.y()); #endif return std::max(kMinimumScrollableContentHeight, available_space); } void ProfileMenuViewBase::Reset() { if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) { menu_item_groups_.clear(); return; } click_actions_.clear(); RemoveAllChildViews(/*delete_childen=*/true); auto components = std::make_unique<views::View>(); components->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); // Create and add new component containers in the correct order. // First, add the bordered box with the identity and feature buttons. views::View* bordered_box = components->AddChildView(CreateBorderedBoxView()); identity_info_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); shortcut_features_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); sync_info_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); account_features_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); // Second, add the profile header. auto profile_header = std::make_unique<views::View>(); views::BoxLayout* profile_header_layout = profile_header->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal)); profile_heading_container_ = profile_header->AddChildView(std::make_unique<views::View>()); profile_header_layout->SetFlexForView(profile_heading_container_, 1); profile_shortcut_features_container_ = profile_header->AddChildView(std::make_unique<views::View>()); profile_header_layout->SetFlexForView(profile_shortcut_features_container_, 0); components->AddChildView(std::move(profile_header)); // Third, add the profile buttons at the bottom. selectable_profiles_container_ = components->AddChildView(std::make_unique<views::View>()); profile_features_container_ = components->AddChildView(std::make_unique<views::View>()); // Create a scroll view to hold the components. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(components)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); } int ProfileMenuViewBase::GetMarginSize(GroupMarginSize margin_size) const { switch (margin_size) { case kNone: return 0; case kTiny: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_CONTENT_LIST_VERTICAL_SINGLE); case kSmall: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_CONTROL_VERTICAL_SMALL); case kLarge: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_UNRELATED_CONTROL_VERTICAL_LARGE); } } void ProfileMenuViewBase::AddMenuGroup(bool add_separator) { if (add_separator && !menu_item_groups_.empty()) { DCHECK(!menu_item_groups_.back().items.empty()); menu_item_groups_.emplace_back(); } menu_item_groups_.emplace_back(); } void ProfileMenuViewBase::AddMenuItemInternal(std::unique_ptr<views::View> view, MenuItems::ItemType item_type) { DCHECK(!menu_item_groups_.empty()); auto& current_group = menu_item_groups_.back(); current_group.items.push_back(std::move(view)); if (current_group.items.size() == 1) { current_group.first_item_type = item_type; current_group.last_item_type = item_type; } else { current_group.different_item_types |= current_group.last_item_type != item_type; current_group.last_item_type = item_type; } } views::Button* ProfileMenuViewBase::CreateAndAddTitleCard( std::unique_ptr<views::View> icon_view, const base::string16& title, const base::string16& subtitle, base::RepeatingClosure action) { std::unique_ptr<HoverButton> title_card = std::make_unique<HoverButton>( this, std::move(icon_view), title, subtitle); if (action.is_null()) title_card->SetEnabled(false); views::Button* button_ptr = title_card.get(); RegisterClickAction(button_ptr, std::move(action)); AddMenuItemInternal(std::move(title_card), MenuItems::kTitleCard); return button_ptr; } views::Button* ProfileMenuViewBase::CreateAndAddButton( const gfx::ImageSkia& icon, const base::string16& title, base::RepeatingClosure action) { std::unique_ptr<HoverButton> button = std::make_unique<HoverButton>(this, icon, title); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); AddMenuItemInternal(std::move(button), MenuItems::kButton); return pointer; } views::Button* ProfileMenuViewBase::CreateAndAddBlueButton( const base::string16& text, bool md_style, base::RepeatingClosure action) { std::unique_ptr<views::LabelButton> button = md_style ? views::MdTextButton::CreateSecondaryUiBlueButton(this, text) : views::MdTextButton::Create(this, text); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } #if !defined(OS_CHROMEOS) DiceSigninButtonView* ProfileMenuViewBase::CreateAndAddDiceSigninButton( AccountInfo* account_info, gfx::Image* account_icon, base::RepeatingClosure action) { std::unique_ptr<DiceSigninButtonView> button = account_info ? std::make_unique<DiceSigninButtonView>(*account_info, *account_icon, this) : std::make_unique<DiceSigninButtonView>(this); DiceSigninButtonView* pointer = button.get(); RegisterClickAction(pointer->signin_button(), std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(kSmall), kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } #endif views::Label* ProfileMenuViewBase::CreateAndAddLabel(const base::string16& text, int text_context) { std::unique_ptr<views::Label> label = std::make_unique<views::Label>(text, text_context); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetMaximumWidth(kMenuWidth - 2 * kMenuEdgeMargin); views::Label* pointer = label.get(); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(label)); AddMenuItemInternal(std::move(margined_view), MenuItems::kLabel); return pointer; } views::StyledLabel* ProfileMenuViewBase::CreateAndAddLabelWithLink( const base::string16& text, gfx::Range link_range, base::RepeatingClosure action) { auto label_with_link = std::make_unique<views::StyledLabel>(text, this); label_with_link->SetDefaultTextStyle(views::style::STYLE_SECONDARY); label_with_link->AddStyleRange( link_range, views::StyledLabel::RangeStyleInfo::CreateForLink()); views::StyledLabel* pointer = label_with_link.get(); RegisterClickAction(pointer, std::move(action)); AddViewItem(std::move(label_with_link)); return pointer; } void ProfileMenuViewBase::AddViewItem(std::unique_ptr<views::View> view) { // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(view)); AddMenuItemInternal(std::move(margined_view), MenuItems::kGeneral); } void ProfileMenuViewBase::RegisterClickAction(views::View* clickable_view, base::RepeatingClosure action) { DCHECK(click_actions_.count(clickable_view) == 0); click_actions_[clickable_view] = std::move(action); } void ProfileMenuViewBase::RepopulateViewFromMenuItems() { RemoveAllChildViews(true); // Create a view to keep menu contents. auto contents_view = std::make_unique<views::View>(); contents_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets())); for (unsigned group_index = 0; group_index < menu_item_groups_.size(); group_index++) { MenuItems& group = menu_item_groups_[group_index]; if (group.items.empty()) { // An empty group represents a separator. contents_view->AddChildView(new views::Separator()); } else { views::View* sub_view = new views::View(); GroupMarginSize top_margin; GroupMarginSize bottom_margin; GroupMarginSize child_spacing; if (group.first_item_type == MenuItems::kTitleCard || group.first_item_type == MenuItems::kLabel) { top_margin = kTiny; } else { top_margin = kSmall; } if (group.last_item_type == MenuItems::kTitleCard) { bottom_margin = kTiny; } else if (group.last_item_type == MenuItems::kButton) { bottom_margin = kSmall; } else { bottom_margin = kLarge; } if (!group.different_item_types) { child_spacing = kNone; } else if (group.items.size() == 2 && group.first_item_type == MenuItems::kTitleCard && group.last_item_type == MenuItems::kButton) { child_spacing = kNone; } else { child_spacing = kLarge; } // Reduce margins if previous/next group is not a separator. if (group_index + 1 < menu_item_groups_.size() && !menu_item_groups_[group_index + 1].items.empty()) { bottom_margin = kTiny; } if (group_index > 0 && !menu_item_groups_[group_index - 1].items.empty()) { top_margin = kTiny; } sub_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(top_margin), 0, GetMarginSize(bottom_margin), 0), GetMarginSize(child_spacing))); for (std::unique_ptr<views::View>& item : group.items) sub_view->AddChildView(std::move(item)); contents_view->AddChildView(sub_view); } } menu_item_groups_.clear(); // Create a scroll view to hold contents view. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(contents_view)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); if (GetBubbleFrameView()) { SizeToContents(); // SizeToContents() will perform a layout, but only if the size changed. Layout(); } } gfx::ImageSkia ProfileMenuViewBase::CreateVectorIcon( const gfx::VectorIcon& icon) { return gfx::CreateVectorIcon(icon, kIconSize, GetDefaultIconColor()); } int ProfileMenuViewBase::GetDefaultIconSize() { return kIconSize; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
43c66bd5d3a0d11b3eeee4e5e08fcfc4bb1122e4
3c378513afb8e6c2680715c91c31845b67e71885
/include/SIMD_KScheme_2Bit_CU.hpp
9c1861d14dd2662d6beb90ffe6ffe46e1a233875
[]
no_license
yingfeng/integer_encoding_library_sparklezzz
582f21140a0c6cccae692f8e92464b8a1f093674
8ba46561cde38920674f4789f4f413ceed45ef6b
refs/heads/master
2021-01-17T12:26:12.838738
2015-01-14T13:37:40
2015-01-14T13:37:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,447
hpp
/* * SIMD_KScheme_2Bit_CU.hpp * * SIMD_KScheme_2Bit_Complete Unary * * Created on: 2013-3-2 * Author: zxd */ #ifndef SIMD_KSCHEME_2BIT_CU_HPP_ #define SIMD_KSCHEME_2BIT_CU_HPP_ #ifdef USE_SSE_INSTRUCTION #include <stdint.h> #include <cmath> #include <assert.h> #include <string.h> #include "Compressor.hpp" #include "VarByte.hpp" #include <iostream> #include "simd_kscheme_2bit_cu_unpack.hpp" using namespace std; namespace paradise { namespace index { class SIMD_KScheme_2Bit_CU: public Compressor { public: SIMD_KScheme_2Bit_CU() { } virtual ~SIMD_KScheme_2Bit_CU() { } public: virtual int encodeUint32(char* des, const uint32_t* src, uint32_t encodeNum); virtual int decodeUint32(uint32_t* des, const char* src, uint32_t decodeNum); virtual int encodeUint16(char* des, const uint16_t* src, uint32_t encodeNum); virtual int decodeUint16(uint16_t* des, const char* src, uint32_t decodeNum); virtual int encodeUint8(char* des, const uint8_t* src, uint32_t encodeNum); virtual int decodeUint8(uint8_t* des, const char* src, uint32_t decodeNum); virtual std::string getCompressorName() { return "SIMD_KScheme_2Bit_CU"; } virtual Compressor* clone(); private: template<typename T> int encode(char* des, const T* src, uint32_t length); template<typename T> int decode(T* des, const char* src, uint32_t length); template<typename T> int encodeBlock(char* des, const T* src, uint32_t size); template<typename T> int decodeBlock(T* des, const char* src, uint32_t size); }; template<typename T> int SIMD_KScheme_2Bit_CU::encode(char* des, const T* src, uint32_t encodeNum) { if (encodeNum < 4) { return VarByte::encode(des, src, encodeNum); } int compLen = 0; int left = encodeNum % 4; if (left > 0) { compLen = encodeBlock(des, src, encodeNum - left); compLen += VarByte::encode(des + compLen, src + encodeNum - left, left); } else { compLen = encodeBlock(des, src, encodeNum); } return compLen; } template<typename T> int SIMD_KScheme_2Bit_CU::decode(T* des, const char* src, uint32_t decodeNum) { if (decodeNum < 4) { return VarByte::decode(des, src, decodeNum); } int decodeLen = 0; int left = decodeNum % 4; if (left > 0) { decodeLen = decodeBlock(des, src, decodeNum - left); decodeLen += VarByte::decode(des + decodeNum - left, src + decodeLen, left); } else { decodeLen = decodeBlock(des, src, decodeNum); } return decodeLen; } template<typename T> int SIMD_KScheme_2Bit_CU::encodeBlock(char* des, const T* src, uint32_t encodeNum) { const static uint16_t unary_code[17] = {-1, 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, // INVALID, 0, 01, 011, 0111, 01111, 011111, 0111111, 01111111 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, // 011111111,... 0x1fff, 0x3fff, 0x7fff}; uint32_t quadEncodeNum = encodeNum / 4; uint16_t *tmpModeSegBeg = new uint16_t[quadEncodeNum]; //max control bit for one int: 4 uint16_t *tmpModeSegIdx = tmpModeSegBeg; memset(tmpModeSegBeg, 0, quadEncodeNum * sizeof(uint16_t)); char *desBeg = des; uint32_t *desInt = (uint32_t*)des; char *dataSegBeg = des + 4; //leave first 4 byte to record the begin position of data segment uint32_t *dataSegPosInt = (uint32_t*)dataSegBeg; __asm__ volatile("prefetchnta %0"::"m" (src[0])); __asm__("pxor %%xmm0,%%xmm0\n":::); int k = 0; uint32_t curBitOffset = 0; //range from 0 to 4 uint32_t controlBitOffset = 0; //range from 0 to 7 for (uint32_t i=0; i<encodeNum; i+=4) { // step1: get quad max int T quadMaxInt = src[0]; for (uint32_t j=1; j<4; j++) { quadMaxInt |= src[j]; } // step2: get bytes needed for quad max int if (quadMaxInt == 0) quadMaxInt ++; char twoBitCount = 0; while (quadMaxInt > 0) { quadMaxInt >>= 2; twoBitCount ++; } // step3: record the unary descriptor if (controlBitOffset + twoBitCount > 16) { //start new mode and new data seg // pad the descriptor with all 1 uint16_t pad = (0xffff >> controlBitOffset) << controlBitOffset; *tmpModeSegIdx |= pad; tmpModeSegIdx ++; controlBitOffset = controlBitOffset + twoBitCount - 16; *tmpModeSegIdx |= unary_code[controlBitOffset]; } else { *tmpModeSegIdx |= unary_code[twoBitCount] << controlBitOffset; controlBitOffset += twoBitCount; } // step4: encode group of 4 ints uint32_t bitLeftInUInt = 32 - curBitOffset; uint32_t bitCount = twoBitCount * 2; if (bitLeftInUInt < bitCount) { //new data should cross uint boundary // write data with effective bit length of the max val //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) |= (src[k] & byte_mask_map[byteLeftInUInt]) << (curByteOffset<<3); //} __asm__("movdqu %1,%%xmm3\n" //src[0]->xmm0 "movdqa %%xmm3,%%xmm4\n" //backup for next codeword "movd %2,%%xmm1\n" //shiftLeft->xmm1 "pslld %%xmm1,%%xmm3\n" //shift left->xmm0 "psrld %%xmm2,%%xmm0\n" //shift right->xmm "por %%xmm3,%%xmm0\n" "movdqu %%xmm0,%0\n" //write back codeword :"=m" (dataSegPosInt[0]) :"m" (src[0]),"m" (curBitOffset) :"memory"); //start a new group and left val dataSegPosInt += 4; uint32_t bitUnwritten = bitCount - bitLeftInUInt; //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) = (src[k] >> (byteLeftInUInt<<3)) & byte_mask_map[byteUnwritten] ; //} uint32_t shiftLeft = 32 - bitCount; uint32_t shiftRight = 32 - bitUnwritten; __asm__("movdqa %%xmm4,%%xmm0\n" "movd %0,%%xmm1\n" //shiftLeft->xmm1 "movd %1,%%xmm2\n" //shiftRight->xmm2 "pslld %%xmm1,%%xmm0\n" //shift left->xmm0 "psrld %%xmm2,%%xmm0\n" //shift right->xmm0 ::"m" (shiftLeft),"m" (shiftRight) :"memory"); curBitOffset = bitUnwritten; } else { // write data with effective bit length of the max val //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) |= (src[k] & byte_mask_map[byteCount]) << (curByteOffset<<3); //} uint32_t shiftLeft = 32 - bitCount; uint32_t shiftRight = shiftLeft - curBitOffset; __asm__ volatile("prefetchnta %0"::"m" (src[0])); __asm__("movdqu %0,%%xmm3\n" //src[0]->xmm3 "movd %1,%%xmm1\n" //shiftLeft->xmm1 "movd %2,%%xmm2\n" //shiftRight->xmm2 "pslld %%xmm1,%%xmm3\n" //shift left->xmm0 "psrld %%xmm2,%%xmm3\n" //shift right->xmm0 "por %%xmm3,%%xmm0\n" ::"m" (src[0]),"m" (shiftLeft),"m" (shiftRight) :"memory"); curBitOffset += bitCount; } src += 4; } __asm__("movdqu %%xmm0,%0\n" :"=m" (dataSegPosInt[0]) ::"memory"); // pad the descriptor uint16_t pad = (0xffff >> controlBitOffset) << controlBitOffset; *tmpModeSegIdx |= pad; tmpModeSegIdx ++; dataSegPosInt += 4; // record the start offset of mode segment *desInt = 4 + ((char*)dataSegPosInt - dataSegBeg); // append the mode seg to the end of data seg char *modeSegBeg = (char*)dataSegPosInt; uint32_t modeSegSize = (tmpModeSegIdx - tmpModeSegBeg) * sizeof(uint16_t); memcpy(modeSegBeg, tmpModeSegBeg, modeSegSize); delete [] tmpModeSegBeg; return (modeSegBeg - desBeg) + modeSegSize; } template<typename T> int SIMD_KScheme_2Bit_CU::decodeBlock(T* des, const char* src, uint32_t decodeNum) { const uint32_t *srcInt = (const uint32_t*)src; uint32_t modeSegOffset = *srcInt; const uint8_t *dataSegPos = (uint8_t*)src + 4; const uint8_t *modeSegBeg = (uint8_t*)(src + modeSegOffset); //note that we still use 8 bit for mode seg here! const uint8_t *modeSegPos = modeSegBeg; const uint32_t *wordPos = (const uint32_t*)dataSegPos; simd_kscheme_2bit_cu_unpack_prepare<T>(); uint32_t decoded = 0; uint32_t groupFullBitOffset = 0; while (decoded < decodeNum) { // get a valid unary descriptor const SIMDK2CUUnpackInfo &unpackInfo = SIMDK2CUUnpackInfoArr[*modeSegPos]; unpackInfo.m_subFunc((uint32_t*)des, wordPos); modeSegPos ++; des += unpackInfo.m_intNum; decoded += unpackInfo.m_intNum; wordPos += ((groupFullBitOffset + 16) >> 5) << 2; groupFullBitOffset = (groupFullBitOffset + 16) & 0x1f; } uint32_t modeSegSize = modeSegPos - modeSegBeg; if (modeSegSize % 2 != 0) //note that the original unit of mode seg is 16 bit modeSegPos ++; if (groupFullBitOffset != 0) wordPos += 4; return (char*)modeSegPos - src; } } } #endif #endif /* SIMD_KSCHEME_2BIT_CU_HPP_ */
[ "xdzhang@yahoo-inc.com" ]
xdzhang@yahoo-inc.com
06f218de53f4128a70879f3ee00307f0c6ee9126
735d7d9177ba60d7d94577b30ec37857d2bcd4fc
/pointers/demo3.cpp
a59714026b884fb91d638f8297243ad19c3f6c9c
[ "MIT" ]
permissive
KleeTaurus/learn-cpp
5043ddd38eaa778eabe6763c7214db62e3e2f2f2
ec872ac7ea9ee323e7afbf8f717c6120771f81d3
refs/heads/master
2020-12-02T19:19:12.585479
2017-08-12T02:56:41
2017-08-12T02:56:41
96,324,050
1
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include <iostream> using namespace std; int main() { int *ptr = NULL; cout << "The value of ptr is: " << ptr; return 0; }
[ "lining@luojilab.com" ]
lining@luojilab.com
1d412be22cb408024611a815c947ed1dd3e42ac5
dd95d7ea86fcd4f27664653205df0d2005665f2b
/shared/configeditor/include/Trigger.h
b82db6fa3165459ee317fe374fef801d744cfef4
[]
no_license
sawmic/GIMX
ab7437b70e2094399624e93c493dd550144828ce
96cb9d155123a4c1657c4b2f177725395bbafd9e
refs/heads/master
2021-01-12T21:53:13.514674
2014-02-01T14:01:48
2014-02-01T14:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
h
/* Copyright (c) 2011 Mathieu Laurendeau <mat.lau@laposte.net> License: GPLv3 */ #ifndef TRIGGER_H #define TRIGGER_H #include <Device.h> #include <Event.h> class Trigger { public: Trigger(); Trigger(string dtype, string did, string dname, string eid, string switchback, unsigned short delay); virtual ~Trigger(); Trigger(const Trigger& other); Trigger& operator=(const Trigger& other); bool operator==(const Trigger &other) const; Device* GetDevice() { return &m_Device; } void SetDevice(Device val) { m_Device = val; } Event* GetEvent() { return &m_Event; } void SetEvent(Event val) { m_Event = val; } string GetSwitchBack() { return m_SwitchBack; } void SetSwitchBack(string val) { m_SwitchBack = val; } unsigned short GetDelay() { return m_Delay; } void SetDelay(unsigned short val) { m_Delay = val; } protected: private: Device m_Device; Event m_Event; string m_SwitchBack; unsigned short m_Delay; }; #endif // TRIGGER_H
[ "mat.lau@laposte.net" ]
mat.lau@laposte.net
e86075a33bbc78bb3f75b685101273ff2f283314
2576dfefe11dc4eb2588bf7872ebecbc64823833
/include/SPcSteppingMessenger.hh
dc8ab87cabac977294075a8442c495110fcd96c9
[]
no_license
jilic/spacal
8278df8b41f3b7efe65c398622ee49bcc207bf92
413750533857563c9d627666684ed622aac76a1d
refs/heads/master
2021-01-01T05:18:20.425457
2015-02-18T22:41:19
2015-02-18T22:41:19
32,726,429
0
0
null
null
null
null
UTF-8
C++
false
false
640
hh
/* @author Jelena Ilic @mail jelenailic.sk@gmail.com @date Summer 2014 */ #ifndef SPcSteppingMessenger_h #define SPcSteppingMessenger_h 1 #include "G4UImessenger.hh" #include "globals.hh" class SPcSteppingAction; class G4UIcmdWithAnInteger; class G4UIcmdWithABool; class G4UIcmdWithADoubleAndUnit; class SPcSteppingMessenger: public G4UImessenger { public: SPcSteppingMessenger(SPcSteppingAction*); virtual ~SPcSteppingMessenger(); virtual void SetNewValue(G4UIcommand*, G4String); private: SPcSteppingAction* fstep; G4UIcmdWithABool* trackOpticalCommand; G4UIcmdWithADoubleAndUnit* fcutOffCmd; }; #endif
[ "jelenailic.sk@7ba4f6a3-0c5a-dc19-1ee9-c1316467136b" ]
jelenailic.sk@7ba4f6a3-0c5a-dc19-1ee9-c1316467136b
1b5479c9bca6e9ef628ba3441d63cd107bb82757
27974ef06083b306028ade82a6c174377ab649fd
/period/freshman/contest/Week 3/I.cpp
8308a258ebbb6bcbd8f58d18455cdb4cd3ad740f
[]
no_license
lightyears1998/a-gzhu-coder
6ba7fe23f663ee538c162927cfecb57e20bc0dbc
b882a2e8395155db0a57d59e7c5899386c5eb717
refs/heads/master
2021-06-05T05:33:14.988053
2020-05-23T12:52:57
2020-05-23T12:52:57
100,114,337
14
2
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include <bits/stdc++.h> using namespace std; int main() { string s; while (getline(cin, s)) { if (s == "#") break; int sum = 0; for (unsigned i=0; i<s.size(); ++i) { if (isalpha(s[i])) sum += (i+1)*(s[i]-'A'+1); else continue; } cout << sum << endl; } }
[ "lightyears1998@hotmail.com" ]
lightyears1998@hotmail.com
f25229c9f157262511e392464824f7ace0ffd36e
2ccb99e0b35b58622c5a0be2a698ebda3ab29dec
/gfx/skia/skia/src/effects/SkLightingImageFilter.cpp
f701b4c8945952f619404479d11d226574b51bc9
[ "BSD-3-Clause" ]
permissive
roytam1/palemoon27
f436d4a3688fd14ea5423cbcaf16c4539b88781f
685d46ffdaee14705ea40e7ac57c4c11e8f31cd0
refs/heads/master
2023-08-20T10:11:13.367377
2023-08-17T07:28:43
2023-08-17T07:28:43
142,234,965
61
16
NOASSERTION
2022-03-30T07:54:03
2018-07-25T02:10:02
null
UTF-8
C++
false
false
87,541
cpp
/* * Copyright 2012 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkLightingImageFilter.h" #include "SkBitmap.h" #include "SkColorPriv.h" #include "SkDevice.h" #include "SkPoint3.h" #include "SkReadBuffer.h" #include "SkTypes.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrDrawContext.h" #include "GrFragmentProcessor.h" #include "GrInvariantOutput.h" #include "GrPaint.h" #include "SkGr.h" #include "effects/GrSingleTextureEffect.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramDataManager.h" #include "glsl/GrGLSLUniformHandler.h" class GrGLDiffuseLightingEffect; class GrGLSpecularLightingEffect; // For brevity typedef GrGLSLProgramDataManager::UniformHandle UniformHandle; #endif namespace { const SkScalar gOneThird = SkIntToScalar(1) / 3; const SkScalar gTwoThirds = SkIntToScalar(2) / 3; const SkScalar gOneHalf = 0.5f; const SkScalar gOneQuarter = 0.25f; #if SK_SUPPORT_GPU void setUniformPoint3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { GR_STATIC_ASSERT(sizeof(SkPoint3) == 3 * sizeof(float)); pdman.set3fv(uni, 1, &point.fX); } void setUniformNormal3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { setUniformPoint3(pdman, uni, point); } #endif // Shift matrix components to the left, as we advance pixels to the right. inline void shiftMatrixLeft(int m[9]) { m[0] = m[1]; m[3] = m[4]; m[6] = m[7]; m[1] = m[2]; m[4] = m[5]; m[7] = m[8]; } static inline void fast_normalize(SkPoint3* vector) { // add a tiny bit so we don't have to worry about divide-by-zero SkScalar magSq = vector->dot(*vector) + SK_ScalarNearlyZero; SkScalar scale = sk_float_rsqrt(magSq); vector->fX *= scale; vector->fY *= scale; vector->fZ *= scale; } class DiffuseLightingType { public: DiffuseLightingType(SkScalar kd) : fKD(kd) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkScalar colorScale = SkScalarMul(fKD, normal.dot(surfaceTolight)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(255, SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKD; }; static SkScalar max_component(const SkPoint3& p) { return p.x() > p.y() ? (p.x() > p.z() ? p.x() : p.z()) : (p.y() > p.z() ? p.y() : p.z()); } class SpecularLightingType { public: SpecularLightingType(SkScalar ks, SkScalar shininess) : fKS(ks), fShininess(shininess) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkPoint3 halfDir(surfaceTolight); halfDir.fZ += SK_Scalar1; // eye position is always (0, 0, 1) fast_normalize(&halfDir); SkScalar colorScale = SkScalarMul(fKS, SkScalarPow(normal.dot(halfDir), fShininess)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(SkClampMax(SkScalarRoundToInt(max_component(color)), 255), SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKS; SkScalar fShininess; }; inline SkScalar sobel(int a, int b, int c, int d, int e, int f, SkScalar scale) { return SkScalarMul(SkIntToScalar(-a + b - 2 * c + 2 * d -e + f), scale); } inline SkPoint3 pointToNormal(SkScalar x, SkScalar y, SkScalar surfaceScale) { SkPoint3 vector = SkPoint3::Make(SkScalarMul(-x, surfaceScale), SkScalarMul(-y, surfaceScale), SK_Scalar1); fast_normalize(&vector); return vector; } inline SkPoint3 topLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(0, 0, m[4], m[5], m[7], m[8], gTwoThirds), sobel(0, 0, m[4], m[7], m[5], m[8], gTwoThirds), surfaceScale); } inline SkPoint3 topNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[5], m[6], m[8], gOneThird), sobel(m[3], m[6], m[4], m[7], m[5], m[8], gOneHalf), surfaceScale); } inline SkPoint3 topRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[4], m[6], m[7], gTwoThirds), sobel(m[3], m[6], m[4], m[7], 0, 0, gTwoThirds), surfaceScale); } inline SkPoint3 leftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], m[7], m[8], gOneHalf), sobel( 0, 0, m[1], m[7], m[2], m[8], gOneThird), surfaceScale); } inline SkPoint3 interiorNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], m[6], m[8], gOneQuarter), sobel(m[0], m[6], m[1], m[7], m[2], m[8], gOneQuarter), surfaceScale); } inline SkPoint3 rightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], m[6], m[7], gOneHalf), sobel(m[0], m[6], m[1], m[7], 0, 0, gOneThird), surfaceScale); } inline SkPoint3 bottomLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], 0, 0, gTwoThirds), sobel( 0, 0, m[1], m[4], m[2], m[5], gTwoThirds), surfaceScale); } inline SkPoint3 bottomNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], 0, 0, gOneThird), sobel(m[0], m[3], m[1], m[4], m[2], m[5], gOneHalf), surfaceScale); } inline SkPoint3 bottomRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], 0, 0, gTwoThirds), sobel(m[0], m[3], m[1], m[4], 0, 0, gTwoThirds), surfaceScale); } template <class LightingType, class LightType> void lightBitmap(const LightingType& lightingType, const SkImageFilterLight* light, const SkBitmap& src, SkBitmap* dst, SkScalar surfaceScale, const SkIRect& bounds) { SkASSERT(dst->width() == bounds.width() && dst->height() == bounds.height()); const LightType* l = static_cast<const LightType*>(light); int left = bounds.left(), right = bounds.right(); int bottom = bounds.bottom(); int y = bounds.top(); SkPMColor* dptr = dst->getAddr32(0, 0); { int x = left; const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } for (++y; y < bottom - 1; ++y) { int x = left; const SkPMColor* row0 = src.getAddr32(x, y - 1); const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(leftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(interiorNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(rightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } { int x = left; const SkPMColor* row0 = src.getAddr32(x, bottom - 2); const SkPMColor* row1 = src.getAddr32(x, bottom - 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } } SkPoint3 readPoint3(SkReadBuffer& buffer) { SkPoint3 point; point.fX = buffer.readScalar(); point.fY = buffer.readScalar(); point.fZ = buffer.readScalar(); buffer.validate(SkScalarIsFinite(point.fX) && SkScalarIsFinite(point.fY) && SkScalarIsFinite(point.fZ)); return point; }; void writePoint3(const SkPoint3& point, SkWriteBuffer& buffer) { buffer.writeScalar(point.fX); buffer.writeScalar(point.fY); buffer.writeScalar(point.fZ); }; enum BoundaryMode { kTopLeft_BoundaryMode, kTop_BoundaryMode, kTopRight_BoundaryMode, kLeft_BoundaryMode, kInterior_BoundaryMode, kRight_BoundaryMode, kBottomLeft_BoundaryMode, kBottom_BoundaryMode, kBottomRight_BoundaryMode, kBoundaryModeCount, }; class SkLightingImageFilterInternal : public SkLightingImageFilter { protected: SkLightingImageFilterInternal(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect) {} #if SK_SUPPORT_GPU bool canFilterImageGPU() const override { return true; } bool filterImageGPU(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; virtual GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode boundaryMode) const = 0; #endif private: #if SK_SUPPORT_GPU void drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const; #endif typedef SkLightingImageFilter INHERITED; }; #if SK_SUPPORT_GPU void SkLightingImageFilterInternal::drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const { SkRect srcRect = dstRect.makeOffset(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y())); GrPaint paint; GrFragmentProcessor* fp = this->getFragmentProcessor(src, matrix, bounds, boundaryMode); paint.addColorFragmentProcessor(fp)->unref(); paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode); drawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect); } bool SkLightingImageFilterInternal::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap input = src; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInputGPU(0, proxy, src, ctx, &input, &srcOffset)) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, input, &srcOffset, &bounds, &input)) { return false; } SkRect dstRect = SkRect::MakeWH(SkIntToScalar(bounds.width()), SkIntToScalar(bounds.height())); GrTexture* srcTexture = input.getTexture(); GrContext* context = srcTexture->getContext(); GrSurfaceDesc desc; desc.fFlags = kRenderTarget_GrSurfaceFlag, desc.fWidth = bounds.width(); desc.fHeight = bounds.height(); desc.fConfig = kRGBA_8888_GrPixelConfig; SkAutoTUnref<GrTexture> dst(context->textureProvider()->createApproxTexture(desc)); if (!dst) { return false; } // setup new clip GrClip clip(dstRect); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); bounds.offset(-srcOffset); SkRect topLeft = SkRect::MakeXYWH(0, 0, 1, 1); SkRect top = SkRect::MakeXYWH(1, 0, dstRect.width() - 2, 1); SkRect topRight = SkRect::MakeXYWH(dstRect.width() - 1, 0, 1, 1); SkRect left = SkRect::MakeXYWH(0, 1, 1, dstRect.height() - 2); SkRect interior = dstRect.makeInset(1, 1); SkRect right = SkRect::MakeXYWH(dstRect.width() - 1, 1, 1, dstRect.height() - 2); SkRect bottomLeft = SkRect::MakeXYWH(0, dstRect.height() - 1, 1, 1); SkRect bottom = SkRect::MakeXYWH(1, dstRect.height() - 1, dstRect.width() - 2, 1); SkRect bottomRight = SkRect::MakeXYWH(dstRect.width() - 1, dstRect.height() - 1, 1, 1); SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(dst->asRenderTarget())); if (!drawContext) { return false; } this->drawRect(drawContext, srcTexture, matrix, clip, topLeft, kTopLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, top, kTop_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, topRight, kTopRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, left, kLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, interior, kInterior_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, right, kRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomLeft, kBottomLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottom, kBottom_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomRight, kBottomRight_BoundaryMode, bounds); GrWrapTextureInBitmap(dst, bounds.width(), bounds.height(), false, result); return true; } #endif class SkDiffuseLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkDiffuseLightingImageFilter) SkScalar kd() const { return fKD; } protected: SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; SkScalar fKD; }; class SkSpecularLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkSpecularLightingImageFilter) SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } protected: SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect*); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: SkScalar fKS; SkScalar fShininess; friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; }; #if SK_SUPPORT_GPU class GrLightingEffect : public GrSingleTextureEffect { public: GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode); ~GrLightingEffect() override; const SkImageFilterLight* light() const { return fLight; } SkScalar surfaceScale() const { return fSurfaceScale; } const SkMatrix& filterMatrix() const { return fFilterMatrix; } BoundaryMode boundaryMode() const { return fBoundaryMode; } protected: bool onIsEqual(const GrFragmentProcessor&) const override; void onComputeInvariantOutput(GrInvariantOutput* inout) const override { // lighting shaders are complicated. We just throw up our hands. inout->mulByUnknownFourComponents(); } private: const SkImageFilterLight* fLight; SkScalar fSurfaceScale; SkMatrix fFilterMatrix; BoundaryMode fBoundaryMode; typedef GrSingleTextureEffect INHERITED; }; class GrDiffuseLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) { return new GrDiffuseLightingEffect(texture, light, surfaceScale, matrix, kd, boundaryMode); } const char* name() const override { return "DiffuseLighting"; } SkScalar kd() const { return fKD; } private: GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKD; }; class GrSpecularLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) { return new GrSpecularLightingEffect(texture, light, surfaceScale, matrix, ks, shininess, boundaryMode); } const char* name() const override { return "SpecularLighting"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } private: void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKS; SkScalar fShininess; }; /////////////////////////////////////////////////////////////////////////////// class GrGLLight { public: virtual ~GrGLLight() {} /** * This is called by GrGLLightingEffect::emitCode() before either of the two virtual functions * below. It adds a vec3f uniform visible in the FS that represents the constant light color. */ void emitLightColorUniform(GrGLSLUniformHandler*); /** * These two functions are called from GrGLLightingEffect's emitCode() function. * emitSurfaceToLight places an expression in param out that is the vector from the surface to * the light. The expression will be used in the FS. emitLightColor writes an expression into * the FS that is the color of the light. Either function may add functions and/or uniforms to * the FS. The default of emitLightColor appends the name of the constant light color uniform * and so this function only needs to be overridden if the light color varies spatially. */ virtual void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) = 0; virtual void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight); // This is called from GrGLLightingEffect's setData(). Subclasses of GrGLLight must call // INHERITED::setData(). virtual void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const; protected: /** * Gets the constant light color uniform. Subclasses can use this in their emitLightColor * function. */ UniformHandle lightColorUni() const { return fColorUni; } private: UniformHandle fColorUni; typedef SkRefCnt INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDistantLight : public GrGLLight { public: virtual ~GrGLDistantLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fDirectionUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLPointLight : public GrGLLight { public: virtual ~GrGLPointLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fLocationUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpotLight : public GrGLLight { public: virtual ~GrGLSpotLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight) override; private: typedef GrGLLight INHERITED; SkString fLightColorFunc; UniformHandle fLocationUni; UniformHandle fExponentUni; UniformHandle fCosOuterConeAngleUni; UniformHandle fCosInnerConeAngleUni; UniformHandle fConeScaleUni; UniformHandle fSUni; }; #else class GrGLLight; #endif }; /////////////////////////////////////////////////////////////////////////////// class SkImageFilterLight : public SkRefCnt { public: enum LightType { kDistant_LightType, kPoint_LightType, kSpot_LightType, }; virtual LightType type() const = 0; const SkPoint3& color() const { return fColor; } virtual GrGLLight* createGLLight() const = 0; virtual bool isEqual(const SkImageFilterLight& other) const { return fColor == other.fColor; } // Called to know whether the generated GrGLLight will require access to the fragment position. virtual bool requiresFragmentPosition() const = 0; virtual SkImageFilterLight* transform(const SkMatrix& matrix) const = 0; // Defined below SkLight's subclasses. void flattenLight(SkWriteBuffer& buffer) const; static SkImageFilterLight* UnflattenLight(SkReadBuffer& buffer); protected: SkImageFilterLight(SkColor color) { fColor = SkPoint3::Make(SkIntToScalar(SkColorGetR(color)), SkIntToScalar(SkColorGetG(color)), SkIntToScalar(SkColorGetB(color))); } SkImageFilterLight(const SkPoint3& color) : fColor(color) {} SkImageFilterLight(SkReadBuffer& buffer) { fColor = readPoint3(buffer); } virtual void onFlattenLight(SkWriteBuffer& buffer) const = 0; private: typedef SkRefCnt INHERITED; SkPoint3 fColor; }; /////////////////////////////////////////////////////////////////////////////// class SkDistantLight : public SkImageFilterLight { public: SkDistantLight(const SkPoint3& direction, SkColor color) : INHERITED(color), fDirection(direction) { } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { return fDirection; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kDistant_LightType; } const SkPoint3& direction() const { return fDirection; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLDistantLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return false; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kDistant_LightType) { return false; } const SkDistantLight& o = static_cast<const SkDistantLight&>(other); return INHERITED::isEqual(other) && fDirection == o.fDirection; } SkDistantLight(SkReadBuffer& buffer) : INHERITED(buffer) { fDirection = readPoint3(buffer); } protected: SkDistantLight(const SkPoint3& direction, const SkPoint3& color) : INHERITED(color), fDirection(direction) { } SkImageFilterLight* transform(const SkMatrix& matrix) const override { return new SkDistantLight(direction(), color()); } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fDirection, buffer); } private: SkPoint3 fDirection; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkPointLight : public SkImageFilterLight { public: SkPointLight(const SkPoint3& location, SkColor color) : INHERITED(color), fLocation(location) {} SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kPoint_LightType; } const SkPoint3& location() const { return fLocation; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLPointLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kPoint_LightType) { return false; } const SkPointLight& o = static_cast<const SkPointLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation; } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); return new SkPointLight(location, color()); } SkPointLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); } protected: SkPointLight(const SkPoint3& location, const SkPoint3& color) : INHERITED(color), fLocation(location) {} void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); } private: SkPoint3 fLocation; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkSpotLight : public SkImageFilterLight { public: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(SkScalarPin(specularExponent, kSpecularExponentMin, kSpecularExponentMax)) { fS = target - location; fast_normalize(&fS); fCosOuterConeAngle = SkScalarCos(SkDegreesToRadians(cutoffAngle)); const SkScalar antiAliasThreshold = 0.016f; fCosInnerConeAngle = fCosOuterConeAngle + antiAliasThreshold; fConeScale = SkScalarInvert(antiAliasThreshold); } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); SkPoint target2 = SkPoint::Make(fTarget.fX, fTarget.fY); matrix.mapPoints(&target2, 1); SkPoint targetZ = SkPoint::Make(fTarget.fZ, fTarget.fZ); matrix.mapVectors(&targetZ, 1); SkPoint3 target = SkPoint3::Make(target2.fX, target2.fY, SkScalarAve(targetZ.fX, targetZ.fY)); SkPoint3 s = target - location; fast_normalize(&s); return new SkSpotLight(location, target, fSpecularExponent, fCosOuterConeAngle, fCosInnerConeAngle, fConeScale, s, color()); } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; SkPoint3 lightColor(const SkPoint3& surfaceToLight) const { SkScalar cosAngle = -surfaceToLight.dot(fS); SkScalar scale = 0; if (cosAngle >= fCosOuterConeAngle) { scale = SkScalarPow(cosAngle, fSpecularExponent); if (cosAngle < fCosInnerConeAngle) { scale = SkScalarMul(scale, cosAngle - fCosOuterConeAngle); scale *= fConeScale; } } return this->color().makeScale(scale); } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLSpotLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } LightType type() const override { return kSpot_LightType; } const SkPoint3& location() const { return fLocation; } const SkPoint3& target() const { return fTarget; } SkScalar specularExponent() const { return fSpecularExponent; } SkScalar cosInnerConeAngle() const { return fCosInnerConeAngle; } SkScalar cosOuterConeAngle() const { return fCosOuterConeAngle; } SkScalar coneScale() const { return fConeScale; } const SkPoint3& s() const { return fS; } SkSpotLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); fTarget = readPoint3(buffer); fSpecularExponent = buffer.readScalar(); fCosOuterConeAngle = buffer.readScalar(); fCosInnerConeAngle = buffer.readScalar(); fConeScale = buffer.readScalar(); fS = readPoint3(buffer); buffer.validate(SkScalarIsFinite(fSpecularExponent) && SkScalarIsFinite(fCosOuterConeAngle) && SkScalarIsFinite(fCosInnerConeAngle) && SkScalarIsFinite(fConeScale)); } protected: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cosOuterConeAngle, SkScalar cosInnerConeAngle, SkScalar coneScale, const SkPoint3& s, const SkPoint3& color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(specularExponent), fCosOuterConeAngle(cosOuterConeAngle), fCosInnerConeAngle(cosInnerConeAngle), fConeScale(coneScale), fS(s) { } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); writePoint3(fTarget, buffer); buffer.writeScalar(fSpecularExponent); buffer.writeScalar(fCosOuterConeAngle); buffer.writeScalar(fCosInnerConeAngle); buffer.writeScalar(fConeScale); writePoint3(fS, buffer); } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kSpot_LightType) { return false; } const SkSpotLight& o = static_cast<const SkSpotLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation && fTarget == o.fTarget && fSpecularExponent == o.fSpecularExponent && fCosOuterConeAngle == o.fCosOuterConeAngle; } private: static const SkScalar kSpecularExponentMin; static const SkScalar kSpecularExponentMax; SkPoint3 fLocation; SkPoint3 fTarget; SkScalar fSpecularExponent; SkScalar fCosOuterConeAngle; SkScalar fCosInnerConeAngle; SkScalar fConeScale; SkPoint3 fS; typedef SkImageFilterLight INHERITED; }; // According to the spec, the specular term should be in the range [1, 128] : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingSpecularExponentAttribute const SkScalar SkSpotLight::kSpecularExponentMin = 1.0f; const SkScalar SkSpotLight::kSpecularExponentMax = 128.0f; /////////////////////////////////////////////////////////////////////////////// void SkImageFilterLight::flattenLight(SkWriteBuffer& buffer) const { // Write type first, then baseclass, then subclass. buffer.writeInt(this->type()); writePoint3(fColor, buffer); this->onFlattenLight(buffer); } /*static*/ SkImageFilterLight* SkImageFilterLight::UnflattenLight(SkReadBuffer& buffer) { // Read type first. const SkImageFilterLight::LightType type = (SkImageFilterLight::LightType)buffer.readInt(); switch (type) { // Each of these constructors must first call SkLight's, so we'll read the baseclass // then subclass, same order as flattenLight. case SkImageFilterLight::kDistant_LightType: return new SkDistantLight(buffer); case SkImageFilterLight::kPoint_LightType: return new SkPointLight(buffer); case SkImageFilterLight::kSpot_LightType: return new SkSpotLight(buffer); default: SkDEBUGFAIL("Unknown LightType."); buffer.validate(false); return nullptr; } } /////////////////////////////////////////////////////////////////////////////// SkLightingImageFilter::SkLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(1, &input, cropRect) , fLight(SkRef(light)) , fSurfaceScale(surfaceScale / 255) {} SkImageFilter* SkLightingImageFilter::CreateDistantLitDiffuse(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitDiffuse(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitDiffuse(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateDistantLitSpecular(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitSpecular(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitSpecular(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkLightingImageFilter::~SkLightingImageFilter() {} void SkLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); fLight->flattenLight(buffer); buffer.writeScalar(fSurfaceScale * 255); } /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkDiffuseLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(kd)) { return nullptr; } // According to the spec, kd can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feDiffuseLightingElement if (kd < 0) { return nullptr; } return new SkDiffuseLightingImageFilter(light, surfaceScale, kd, input, cropRect); } SkDiffuseLightingImageFilter::SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKD(kd) { } SkFlattenable* SkDiffuseLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar kd = buffer.readScalar(); return Create(light, surfaceScale, kd, common.getInput(0), &common.cropRect()); } void SkDiffuseLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKD); } bool SkDiffuseLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); DiffuseLightingType lightingType(fKD); offset->fX = bounds.left(); offset->fY = bounds.top(); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<DiffuseLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<DiffuseLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<DiffuseLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkDiffuseLightingImageFilter::toString(SkString* str) const { str->appendf("SkDiffuseLightingImageFilter: ("); str->appendf("kD: %f\n", fKD); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkDiffuseLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode ) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrDiffuseLightingEffect::Create(texture, this->light(), scale, matrix, this->kd(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkSpecularLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(ks) || !SkScalarIsFinite(shininess)) { return nullptr; } // According to the spec, ks can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingElement if (ks < 0) { return nullptr; } return new SkSpecularLightingImageFilter(light, surfaceScale, ks, shininess, input, cropRect); } SkSpecularLightingImageFilter::SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKS(ks), fShininess(shininess) { } SkFlattenable* SkSpecularLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar ks = buffer.readScalar(); SkScalar shine = buffer.readScalar(); return Create(light, surfaceScale, ks, shine, common.getInput(0), &common.cropRect()); } void SkSpecularLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKS); buffer.writeScalar(fShininess); } bool SkSpecularLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SpecularLightingType lightingType(fKS, fShininess); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<SpecularLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<SpecularLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<SpecularLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkSpecularLightingImageFilter::toString(SkString* str) const { str->appendf("SkSpecularLightingImageFilter: ("); str->appendf("kS: %f shininess: %f", fKS, fShininess); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkSpecularLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrSpecularLightingEffect::Create(texture, this->light(), scale, matrix, this->ks(), this->shininess(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU namespace { SkPoint3 random_point3(SkRandom* random) { return SkPoint3::Make(SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1())); } SkImageFilterLight* create_random_light(SkRandom* random) { int type = random->nextULessThan(3); switch (type) { case 0: { return new SkDistantLight(random_point3(random), random->nextU()); } case 1: { return new SkPointLight(random_point3(random), random->nextU()); } case 2: { return new SkSpotLight(random_point3(random), random_point3(random), random->nextUScalar1(), random->nextUScalar1(), random->nextU()); } default: SkFAIL("Unexpected value."); return nullptr; } } SkString emitNormalFunc(BoundaryMode mode, const char* pointToNormalName, const char* sobelFuncName) { SkString result; switch (mode) { case kTopLeft_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[4], m[5], m[7], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kTop_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[3], m[5], m[6], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kTopRight_BoundaryMode: result.printf("\treturn %s(%s( 0.0, 0.0, m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[3], m[6], m[4], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], m[7], m[8], %g),\n" "\t %s( 0.0, 0.0, m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kInterior_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], m[6], m[8], %g),\n" "\t %s(m[0], m[6], m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneQuarter, sobelFuncName, gOneQuarter); break; case kRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[0], m[6], m[1], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kBottomLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], 0.0, 0.0, %g),\n" "\t %s( 0.0, 0.0, m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kBottom_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kBottomRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; default: SkASSERT(false); break; } return result; } } class GrGLLightingEffect : public GrGLSLFragmentProcessor { public: GrGLLightingEffect(const GrProcessor&); virtual ~GrGLLightingEffect(); void emitCode(EmitArgs&) override; static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder* b); protected: /** * Subclasses of GrGLLightingEffect must call INHERITED::onSetData(); */ void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; virtual void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) = 0; private: typedef GrGLSLFragmentProcessor INHERITED; UniformHandle fImageIncrementUni; UniformHandle fSurfaceScaleUni; GrGLLight* fLight; BoundaryMode fBoundaryMode; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDiffuseLightingEffect : public GrGLLightingEffect { public: GrGLDiffuseLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKDUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpecularLightingEffect : public GrGLLightingEffect { public: GrGLSpecularLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKSUni; UniformHandle fShininessUni; }; /////////////////////////////////////////////////////////////////////////////// GrLightingEffect::GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode) : INHERITED(texture, GrCoordTransform::MakeDivByTextureWHMatrix(texture)) , fLight(light) , fSurfaceScale(surfaceScale) , fFilterMatrix(matrix) , fBoundaryMode(boundaryMode) { fLight->ref(); if (light->requiresFragmentPosition()) { this->setWillReadFragmentPosition(); } } GrLightingEffect::~GrLightingEffect() { fLight->unref(); } bool GrLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrLightingEffect& s = sBase.cast<GrLightingEffect>(); return fLight->isEqual(*s.fLight) && fSurfaceScale == s.fSurfaceScale && fBoundaryMode == s.fBoundaryMode; } /////////////////////////////////////////////////////////////////////////////// GrDiffuseLightingEffect::GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode), fKD(kd) { this->initClassID<GrDiffuseLightingEffect>(); } bool GrDiffuseLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrDiffuseLightingEffect& s = sBase.cast<GrDiffuseLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->kd() == s.kd(); } void GrDiffuseLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLDiffuseLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrDiffuseLightingEffect::onCreateGLSLInstance() const { return new GrGLDiffuseLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrDiffuseLightingEffect); const GrFragmentProcessor* GrDiffuseLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar kd = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrDiffuseLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, kd, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLLightingEffect::GrGLLightingEffect(const GrProcessor& fp) { const GrLightingEffect& m = fp.cast<GrLightingEffect>(); fLight = m.light()->createGLLight(); fBoundaryMode = m.boundaryMode(); } GrGLLightingEffect::~GrGLLightingEffect() { delete fLight; } void GrGLLightingEffect::emitCode(EmitArgs& args) { GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; fImageIncrementUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec2f_GrSLType, kDefault_GrSLPrecision, "ImageIncrement"); fSurfaceScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "SurfaceScale"); fLight->emitLightColorUniform(uniformHandler); GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder; SkString lightFunc; this->emitLightFunc(uniformHandler, fragBuilder, &lightFunc); static const GrGLSLShaderVar gSobelArgs[] = { GrGLSLShaderVar("a", kFloat_GrSLType), GrGLSLShaderVar("b", kFloat_GrSLType), GrGLSLShaderVar("c", kFloat_GrSLType), GrGLSLShaderVar("d", kFloat_GrSLType), GrGLSLShaderVar("e", kFloat_GrSLType), GrGLSLShaderVar("f", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString sobelFuncName; SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0); fragBuilder->emitFunction(kFloat_GrSLType, "sobel", SK_ARRAY_COUNT(gSobelArgs), gSobelArgs, "\treturn (-a + b - 2.0 * c + 2.0 * d -e + f) * scale;\n", &sobelFuncName); static const GrGLSLShaderVar gPointToNormalArgs[] = { GrGLSLShaderVar("x", kFloat_GrSLType), GrGLSLShaderVar("y", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString pointToNormalName; fragBuilder->emitFunction(kVec3f_GrSLType, "pointToNormal", SK_ARRAY_COUNT(gPointToNormalArgs), gPointToNormalArgs, "\treturn normalize(vec3(-x * scale, -y * scale, 1));\n", &pointToNormalName); static const GrGLSLShaderVar gInteriorNormalArgs[] = { GrGLSLShaderVar("m", kFloat_GrSLType, 9), GrGLSLShaderVar("surfaceScale", kFloat_GrSLType), }; SkString normalBody = emitNormalFunc(fBoundaryMode, pointToNormalName.c_str(), sobelFuncName.c_str()); SkString normalName; fragBuilder->emitFunction(kVec3f_GrSLType, "normal", SK_ARRAY_COUNT(gInteriorNormalArgs), gInteriorNormalArgs, normalBody.c_str(), &normalName); fragBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str()); fragBuilder->codeAppend("\t\tfloat m[9];\n"); const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni); const char* surfScale = uniformHandler->getUniformCStr(fSurfaceScaleUni); int index = 0; for (int dy = 1; dy >= -1; dy--) { for (int dx = -1; dx <= 1; dx++) { SkString texCoords; texCoords.appendf("coord + vec2(%d, %d) * %s", dx, dy, imgInc); fragBuilder->codeAppendf("\t\tm[%d] = ", index++); fragBuilder->appendTextureLookup(args.fSamplers[0], texCoords.c_str()); fragBuilder->codeAppend(".a;\n"); } } fragBuilder->codeAppend("\t\tvec3 surfaceToLight = "); SkString arg; arg.appendf("%s * m[4]", surfScale); fLight->emitSurfaceToLight(uniformHandler, fragBuilder, arg.c_str()); fragBuilder->codeAppend(";\n"); fragBuilder->codeAppendf("\t\t%s = %s(%s(m, %s), surfaceToLight, ", args.fOutputColor, lightFunc.c_str(), normalName.c_str(), surfScale); fLight->emitLightColor(uniformHandler, fragBuilder, "surfaceToLight"); fragBuilder->codeAppend(");\n"); SkString modulate; GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor); fragBuilder->codeAppend(modulate.c_str()); } void GrGLLightingEffect::GenKey(const GrProcessor& proc, const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); b->add32(lighting.boundaryMode() << 2 | lighting.light()->type()); } void GrGLLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); GrTexture* texture = lighting.texture(0); float ySign = texture->origin() == kTopLeft_GrSurfaceOrigin ? -1.0f : 1.0f; pdman.set2f(fImageIncrementUni, 1.0f / texture->width(), ySign / texture->height()); pdman.set1f(fSurfaceScaleUni, lighting.surfaceScale()); SkAutoTUnref<SkImageFilterLight> transformedLight( lighting.light()->transform(lighting.filterMatrix())); fLight->setData(pdman, transformedLight); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// GrGLDiffuseLightingEffect::GrGLDiffuseLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLDiffuseLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* kd; fKDUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KD", &kd); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tfloat colorScale = %s * dot(normal, surfaceToLight);\n", kd); lightBody.appendf("\treturn vec4(lightColor * clamp(colorScale, 0.0, 1.0), 1.0);\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLDiffuseLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { INHERITED::onSetData(pdman, proc); const GrDiffuseLightingEffect& diffuse = proc.cast<GrDiffuseLightingEffect>(); pdman.set1f(fKDUni, diffuse.kd()); } /////////////////////////////////////////////////////////////////////////////// GrSpecularLightingEffect::GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode) , fKS(ks) , fShininess(shininess) { this->initClassID<GrSpecularLightingEffect>(); } bool GrSpecularLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrSpecularLightingEffect& s = sBase.cast<GrSpecularLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->ks() == s.ks() && this->shininess() == s.shininess(); } void GrSpecularLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLSpecularLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrSpecularLightingEffect::onCreateGLSLInstance() const { return new GrGLSpecularLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSpecularLightingEffect); const GrFragmentProcessor* GrSpecularLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar ks = d->fRandom->nextUScalar1(); SkScalar shininess = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrSpecularLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, ks, shininess, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLSpecularLightingEffect::GrGLSpecularLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLSpecularLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* ks; const char* shininess; fKSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KS", &ks); fShininessUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Shininess", &shininess); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tvec3 halfDir = vec3(normalize(surfaceToLight + vec3(0, 0, 1)));\n"); lightBody.appendf("\tfloat colorScale = %s * pow(dot(normal, halfDir), %s);\n", ks, shininess); lightBody.appendf("\tvec3 color = lightColor * clamp(colorScale, 0.0, 1.0);\n"); lightBody.appendf("\treturn vec4(color, max(max(color.r, color.g), color.b));\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLSpecularLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& effect) { INHERITED::onSetData(pdman, effect); const GrSpecularLightingEffect& spec = effect.cast<GrSpecularLightingEffect>(); pdman.set1f(fKSUni, spec.ks()); pdman.set1f(fShininessUni, spec.shininess()); } /////////////////////////////////////////////////////////////////////////////// void GrGLLight::emitLightColorUniform(GrGLSLUniformHandler* uniformHandler) { fColorUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightColor"); } void GrGLLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { fragBuilder->codeAppend(uniformHandler->getUniformCStr(this->lightColorUni())); } void GrGLLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { setUniformPoint3(pdman, fColorUni, light->color().makeScale(SkScalarInvert(SkIntToScalar(255)))); } /////////////////////////////////////////////////////////////////////////////// void GrGLDistantLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kDistant_LightType); const SkDistantLight* distantLight = static_cast<const SkDistantLight*>(light); setUniformNormal3(pdman, fDirectionUni, distantLight->direction()); } void GrGLDistantLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* dir; fDirectionUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightDirection", &dir); fragBuilder->codeAppend(dir); } /////////////////////////////////////////////////////////////////////////////// void GrGLPointLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kPoint_LightType); const SkPointLight* pointLight = static_cast<const SkPointLight*>(light); setUniformPoint3(pdman, fLocationUni, pointLight->location()); } void GrGLPointLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* loc; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &loc); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", loc, fragBuilder->fragmentPosition(), z); } /////////////////////////////////////////////////////////////////////////////// void GrGLSpotLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kSpot_LightType); const SkSpotLight* spotLight = static_cast<const SkSpotLight *>(light); setUniformPoint3(pdman, fLocationUni, spotLight->location()); pdman.set1f(fExponentUni, spotLight->specularExponent()); pdman.set1f(fCosInnerConeAngleUni, spotLight->cosInnerConeAngle()); pdman.set1f(fCosOuterConeAngleUni, spotLight->cosOuterConeAngle()); pdman.set1f(fConeScaleUni, spotLight->coneScale()); setUniformNormal3(pdman, fSUni, spotLight->s()); } void GrGLSpotLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* location; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &location); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", location, fragBuilder->fragmentPosition(), z); } void GrGLSpotLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { const char* color = uniformHandler->getUniformCStr(this->lightColorUni()); // created by parent class. const char* exponent; const char* cosInner; const char* cosOuter; const char* coneScale; const char* s; fExponentUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Exponent", &exponent); fCosInnerConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosInnerConeAngle", &cosInner); fCosOuterConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosOuterConeAngle", &cosOuter); fConeScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "ConeScale", &coneScale); fSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "S", &s); static const GrGLSLShaderVar gLightColorArgs[] = { GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType) }; SkString lightColorBody; lightColorBody.appendf("\tfloat cosAngle = -dot(surfaceToLight, %s);\n", s); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosOuter); lightColorBody.appendf("\t\treturn vec3(0);\n"); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\tfloat scale = pow(cosAngle, %s);\n", exponent); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosInner); lightColorBody.appendf("\t\treturn %s * scale * (cosAngle - %s) * %s;\n", color, cosOuter, coneScale); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\treturn %s;\n", color); fragBuilder->emitFunction(kVec3f_GrSLType, "lightColor", SK_ARRAY_COUNT(gLightColorArgs), gLightColorArgs, lightColorBody.c_str(), &fLightColorFunc); fragBuilder->codeAppendf("%s(%s)", fLightColorFunc.c_str(), surfaceToLight); } #endif SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkDiffuseLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSpecularLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
[ "roytam@gmail.com" ]
roytam@gmail.com
e0942620c15caf086988b0a8d199e5c3eadaa27f
7ebae5ec0378642a1d2c181184460e76c73debbd
/UVA Online Judge/694/694/694.cpp
81d5786ad415701534d07d0812344b7a36947434
[]
no_license
tonyli00000/Competition-Code
a4352b6b6835819a0f19f7f5cc67e46d2a200906
7f5767e3cb997fd15ae6f72145bcb8394f50975f
refs/heads/master
2020-06-17T23:04:10.367762
2019-12-28T22:08:25
2019-12-28T22:08:25
196,091,038
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include <iostream> #include <string> #include <sstream> #include <iomanip> #include <math.h> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <functional> #include <algorithm> using namespace std; int main() { long long a, l,temp,tc=0; while (cin >> a >> l){ if (a < 0 && l < 0)break; long long ct = 1; temp = a; while (true){ if (a == 1)break; if (a % 2 == 0){ a = a / 2; ct++; } else{ a = 3 * a + 1; if (a > l)break; ct++; } } cout << "Case "<<++tc<<": A = "<<temp << ", limit = " << l << ", number of terms = " << ct << "\n"; } return 0; }
[ "tonyli2002@live.com" ]
tonyli2002@live.com
34ec8217a7118d234a343ffebfbdbf93eb84e999
9e86596a4c9dbedaa8aa08923c14cd39da2455e2
/src/operator/cudnn_activation-inl.h
99bbfe93e871dfee942a2c5e0a4f5f3be400bc5e
[ "Apache-2.0" ]
permissive
XinliangZhu/mxnet
0796c687618f84462ec4a57a2d1b44a1570ed68d
016e049fee799bbc1bb0c1e3e3d3ff858603840b
refs/heads/master
2021-01-22T13:12:25.265640
2015-10-19T00:34:16
2015-10-19T00:34:16
44,504,570
1
0
null
2015-10-19T01:33:19
2015-10-19T01:33:19
null
UTF-8
C++
false
false
5,431
h
/*! * Copyright (c) 2015 by Contributors * \file cudnn_activation-inl.h * \brief * \author Bing Xu */ #ifndef MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_ #define MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_ #include <algorithm> #include <vector> #include "./activation-inl.h" namespace mxnet { namespace op { class CuDNNActivationOp : public Operator { public: explicit CuDNNActivationOp(ActivationParam param) { param_ = param; init_cudnn_ = false; dtype_ = CUDNN_DATA_FLOAT; switch (param_.act_type) { case kReLU: mode_ = CUDNN_ACTIVATION_RELU; break; case kSigmoid: mode_ = CUDNN_ACTIVATION_SIGMOID; break; case kTanh: mode_ = CUDNN_ACTIVATION_TANH; break; default: LOG(FATAL) << "Not implmented"; break; } } ~CuDNNActivationOp() { CHECK_EQ(cudnnDestroyTensorDescriptor(shape_desc_), CUDNN_STATUS_SUCCESS); } virtual void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data, const std::vector<TBlob> &aux_args) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(in_data.size(), 1); CHECK_EQ(out_data.size(), 1); Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 4> data; Tensor<gpu, 4> out; if (in_data[kData].ndim() == 2) { uint32_t ds[] = {in_data[kData].shape_[0], in_data[kData].shape_[1], 1, 1}; TShape dshape(ds, ds + 4); data = in_data[kData].get_with_shape<gpu, 4, real_t>(dshape, s); out = out_data[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); } else { data = in_data[kData].get<gpu, 4, real_t>(s); out = out_data[kOut].get<gpu, 4, real_t>(s); } float alpha = 1.0f; float beta = 0.0f; CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle); if (!init_cudnn_) { init_cudnn_ = true; CHECK_EQ(cudnnCreateTensorDescriptor(&shape_desc_), CUDNN_STATUS_SUCCESS); CHECK_EQ(cudnnSetTensor4dDescriptor(shape_desc_, CUDNN_TENSOR_NCHW, dtype_, data.shape_[0], data.shape_[1], data.shape_[2], data.shape_[3]), CUDNN_STATUS_SUCCESS); } CHECK_EQ(cudnnActivationForward(s->dnn_handle_, mode_, &alpha, shape_desc_, data.dptr_, &beta, shape_desc_, out.dptr_), CUDNN_STATUS_SUCCESS); } virtual void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &aux_args) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(out_grad.size(), 1); CHECK_EQ(in_data.size(), 1); CHECK_EQ(out_data.size(), 1); CHECK_EQ(req.size(), 1); CHECK_EQ(in_grad.size(), 1); float alpha = 1.0f; float beta = 0.0f; Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 4> grad; Tensor<gpu, 4> data; Tensor<gpu, 4> output_data; Tensor<gpu, 4> input_grad; if (in_data[kData].ndim() == 2) { uint32_t ds[] = {in_data[kData].shape_[0], in_data[kData].shape_[1], 1, 1}; TShape dshape(ds, ds + 4); data = in_data[kData].get_with_shape<gpu, 4, real_t>(dshape, s); grad = out_grad[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); output_data = out_data[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); input_grad = in_grad[kData].get_with_shape<gpu, 4, real_t>(dshape, s); } else { data = in_data[kData].get<gpu, 4, real_t>(s); output_data = out_data[kOut].get<gpu, 4, real_t>(s); grad = out_grad[kOut].get<gpu, 4, real_t>(s); input_grad = in_grad[kData].get<gpu, 4, real_t>(s); } CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle); CHECK_EQ(cudnnActivationBackward(s->dnn_handle_, mode_, &alpha, shape_desc_, output_data.dptr_, shape_desc_, grad.dptr_, shape_desc_, data.dptr_, &beta, shape_desc_, input_grad.dptr_), CUDNN_STATUS_SUCCESS); } private: bool init_cudnn_; cudnnDataType_t dtype_; cudnnActivationMode_t mode_; cudnnTensorDescriptor_t shape_desc_; ActivationParam param_; }; // class CuDNNActivationOp } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_
[ "antinucleon@gmail.com" ]
antinucleon@gmail.com
9baa977d091165ec1ec51a58a2f93a2a314c935e
cb39c039f974ce7362769d61fedc2f28f3b206e3
/source/NeutronSystem/Window.h
ecc73318aa2f63c6b38ee5c8bdd0ab701ef89f09
[]
no_license
yuen33/Neutron
87c95b59d451fadcee6b6f1c745a5dd605512c01
581d1a3c64745129a70f412a8d5d4fa1e7689cd7
refs/heads/master
2020-04-11T07:21:07.246738
2015-08-20T00:23:33
2015-08-20T00:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
h
#pragma once #include "ProcessingUnit.h" #include "NeutronFoundation/String.h" #include "Pin.h" #if defined NEUTRON_WINDOWS_DESKTOP #include <dxgi.h> #endif using Neutron::Container::String; namespace Neutron { namespace Engine { #if defined NEUTRON_WINDOWS_DESKTOP class NEUTRON_CORE Window : public ProcessingUnit { protected: static LRESULT wndproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); LRESULT msgproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); HWND hWnd; HINSTANCE hInstance; int width; int height; String title; boolean fullscreen; IDXGISwapChain* swapchain; // control flag boolean active; boolean updateFlag; boolean done; public: static ProcessingUnitPtr create( Device* owner ); Window( Device* owner ); virtual ~Window(); virtual boolean init( int width, int height, const char* title, bool fullscreen ); virtual void release(); virtual void onActive( bool active ); virtual void onPaint(); virtual void onEnterSizeMove(); virtual void onSize(); virtual void onExitSizeMove(); virtual void onSetCursor(); virtual void onChar( wchar code ); virtual void onRawInput( HRAWINPUT rawInput ); virtual void onClose(); virtual void onDestroy(); virtual boolean updateUnit(); virtual void update(); virtual void swap(); void run(); inline void stop() { done = true; } inline boolean isDone() const { return done; } inline int getWidth() const { return width; } inline int getHeight() const { return height; } inline const char* getTitle() const { return title.getCStr(); } inline boolean isFullscreen() const { return fullscreen; } inline const void* getHandle() const { return hWnd; } inline void setSwapChain( IDXGISwapChain* sc ) { swapchain = sc; } }; #endif } }
[ "drvkize@gmail.com" ]
drvkize@gmail.com
b2853a2fe4a66380f084b9853b30da5956ecc05b
4cab0f9edb6c0785f9ed1e6b19cef933b48e4466
/05. Arrays/Reverse_string.cpp
1ec3b98225932b88d4fa78047f512c2c1f813eb6
[ "MIT" ]
permissive
Ash515/DSA-cpp-Hacktoberfest2021
00d31ae054ed2a32ea8ef7578a756a6404d7e803
027e24121c9e78caa29badd778e38e7d5aa83824
refs/heads/main
2023-08-02T21:33:14.771477
2021-10-01T05:05:07
2021-10-01T05:05:07
412,330,530
3
0
MIT
2021-10-01T04:50:28
2021-10-01T04:50:25
null
UTF-8
C++
false
false
392
cpp
#include <bits/stdc++.h> using namespace std; string reverseWord(string str); int main() { int t; cin >> t; while (t--) { string s; cin >> s; cout << reverseWord(s) << endl; } return 0; } string reverseWord(string str) { int n = str.length(); for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); return str; }
[ "noreply@github.com" ]
Ash515.noreply@github.com
5c63bcca69e8a9c1f8b64bbae196c5d7ea4d7e77
cd746ef05caa7bfc71aff7076179e8bb46f0f9f4
/Chapter10cpp/wci/backend/interpreter/executors/IfExecutor.h
aee8fb30311d454b64df28d3173ffec087f4095c
[]
no_license
NikkiR97/complex
93c722ef020d2046faf628228dd09670de67d9b0
6789376c082dc7c6a6391de1a64c045300ab569a
refs/heads/master
2020-04-27T15:35:14.695973
2019-03-08T04:02:30
2019-03-08T04:02:30
174,451,846
1
0
null
null
null
null
UTF-8
C++
false
false
993
h
/** * <h1>IfExecutor</h1> * * <p>Execute an IF statement.</p> * * <p>Copyright (c) 2017 by Ronald Mak</p> * <p>For instructional purposes only. No warranties.</p> */ #ifndef IFEXECUTOR_H_ #define IFEXECUTOR_H_ #include "StatementExecutor.h" #include "../../../Object.h" #include "../../../intermediate/ICodeNode.h" namespace wci { namespace backend { namespace interpreter { namespace executors { using namespace std; using namespace wci; using namespace wci::backend::interpreter; using namespace wci::intermediate; class IfExecutor : public StatementExecutor { public: /** * Constructor. * @param the parent executor. */ IfExecutor(Executor *parent); /** * Execute a compound statement. * @param node the root node of the compound statement. * @return nullptr. */ Object execute(ICodeNode *node); }; }}}} // namespace wci::backend::interpreter::executors #endif /* IFEXECUTOR_H_ */
[ "jhjuchau@gmail.com" ]
jhjuchau@gmail.com
b7e5151e5071c02a986c8585d5e15258faecaa30
337e275fb67b008ca92bf8a3162e88653bc8198d
/Tools/qbfpvf_proto/verify.cpp
fbc78f7c35c084336411723221ae8bceab5555eb
[]
no_license
arey0pushpa/qbf-cert
2956e10192b9622b81c58492c97efd7ef6bd893f
a0f9c77edb9cd09a16261447146e0a1f494bae55
refs/heads/master
2021-09-16T02:07:02.322911
2021-08-01T21:55:32
2021-08-01T21:55:32
199,707,111
0
0
null
null
null
null
UTF-8
C++
false
false
20,258
cpp
#include "common.h" #include "lexer.h" bool cfg_gc = true; // Do garbage collection class Variable { private: lit_int_t v; public: inline explicit Variable(lit_int_t _v) : v(_v) { assert (v>=0); }; inline size_t idx() const {return static_cast<size_t>(v);}; inline string str() const {return to_string(v);} inline lit_int_t raw() const {return v; } inline bool operator ==(Variable const&var) const {return v==var.v;}; inline bool operator !=(Variable const&var) const {return v!=var.v;}; inline bool in_bounds(size_t num_vars) const {return idx()<=num_vars; } inline bool is_valid() const {return v!=0;} public: static Variable const invalid; }; Variable const Variable::invalid = Variable(0); class Literal { private: lit_int_t l; public: inline Literal() : l(0) {}; inline explicit Literal(lit_int_t _l) : l(_l) {}; inline explicit Literal(Variable const&v) : l(v.raw()) {} inline bool is_valid() const {return l!=0;} inline string str() const {return std::to_string(l);} inline lit_int_t raw() const {return l;} inline bool operator ==(Literal const&lit) const {return l==lit.l;}; inline bool operator !=(Literal const&lit) const {return l!=lit.l;}; // inline bool operator <(Literal const&lit) const {return abs(l) < abs(lit.l); }; inline Literal neg() const { assert(is_valid()); return Literal(-l);} inline Literal operator -() const {return neg();} Variable var() const {return Variable(abs(l));} static Literal const invalid; inline bool in_bounds(size_t num_vars) const {return var().in_bounds(num_vars); } }; Literal const Literal::invalid = Literal(0); enum class Quant { ALL, EX }; // Map from everything that can be converted to size_t. // T must default-initialize to T::invalid, and have an is_valid() method inline size_t to_size_t(size_t x) {return x;} inline size_t to_size_t(Variable v) {return v.idx();} template<typename K,typename V> class Basic_Int_Cnv_Map { private: vector<V> map; public: inline V lookup(K key) const { size_t i = to_size_t(key); if (i<map.size()) return map[i]; else return V(); } inline V& define(K key) { size_t i = to_size_t(key); if (!(i<map.size())) map.resize(i+1); return map[i]; } inline K next_key() const {return K(map.size());} inline K define_next(V const &v) { K res = K(map.size()); map.push_back(v); return res; } inline void print_stats(string name) { log(name+": " + pretty_vector_stats(map)); } public: typedef typename vector<V>::iterator iterator; typedef typename vector<V>::const_iterator const_iterator; iterator begin() {return map.begin();} iterator end() {return map.end();} const_iterator begin() const {return map.begin();} const_iterator end() const {return map.end();} }; template<typename K,typename V> class Int_Cnv_Map : public Basic_Int_Cnv_Map<K,V> { public: inline bool contains(K k) const { return (this->lookup(k).is_valid()); } inline V const& the_lookup(K k) const { assert(contains(k)); return this->lookup(k); } inline V& the_lookup(K k) { assert(contains(k)); return this->define(k); } inline void remove(K k) { the_lookup(k) = V(); } inline void remove_if_ex(K k) { if (contains(k)) remove(k); } }; template<typename T> class Basic_Varmap : public Basic_Int_Cnv_Map<Variable,T> {}; template<typename T> class Varmap : public Int_Cnv_Map<Variable,T> {}; template<typename T, T invalid_val> class Wrap_Invalid { private: T x = invalid_val; public: inline Wrap_Invalid() : x(invalid_val) {} inline Wrap_Invalid(T _x) : x(_x) {} inline operator T() const {return x;} inline bool is_valid() const {return x!=invalid_val;} }; template<typename T, T invalid_val> class Wrap_Invalid_Expl { private: T x = invalid_val; public: inline Wrap_Invalid_Expl() : x(invalid_val) {} explicit inline Wrap_Invalid_Expl(T _x) : x(_x) {} explicit inline operator T() const {return x;} inline bool is_valid() const {return x!=invalid_val;} }; class ClauseDB { private: // Quantifiers Varmap<Wrap_Invalid<size_t,0>> varpos; // Counting starts at 1, zero for invalid variable size_t cur_pos = 1; Basic_Varmap<Quant> varq; // Quantifier of variable Variable max_var = Variable::invalid; public: inline size_t get_pos(Variable v) { return varpos.the_lookup(v); } inline bool is_valid(Variable v) { return varpos.contains(v); } inline Quant get_q(Variable v) { assert(is_valid(v)); return varq.lookup(v); } inline Quant get_q(Literal l) { return get_q(l.var()); } inline void add_var(Quant q, Variable v) { if (varpos.contains(v)) error("Duplicate variable declaration " + v.str()); varpos.define(v) = cur_pos++; varq.define(v) = q; if (v.idx()>max_var.idx()) max_var=v; } Variable get_maxvar() { return max_var; } // Literals are ordered by variable position inline bool less_lit(Literal l1, Literal l2) { return get_pos(l1.var()) < get_pos(l2.var()); } public: typedef Wrap_Invalid_Expl<size_t,0> ClauseId; typedef Wrap_Invalid_Expl<size_t,SIZE_MAX> Clause_Iterator; private: // Clauses vector<Literal> db; // The clause database Int_Cnv_Map<ClauseId,Clause_Iterator> idmap; // Map from clause IDs to start positions in database. size_t last_clause_start = SIZE_MAX; Quant reduceq = Quant::EX; // Quantifier on which reduction can be performed bool initialized=false; bool contains_empty_flag = false; // True if this contains the empty clause size_t db_max = 0; size_t active_clauses = 0; // Number of active clauses size_t db_clauses = 0; // Number of clauses in DB size_t stat_num_gcs = 0; public: // Create clause inline void start_clause() { assert(initialized); assert(last_clause_start == SIZE_MAX); last_clause_start = db.size(); } // returns argument. Makes for more elegant parsing loops. inline Literal add_lit(Literal l) { assert(initialized); assert(last_clause_start!= SIZE_MAX); if (l.is_valid()) db.push_back(l); // Ignore final 0, will be added by commit-clause db_max = max(db_max,db.capacity()); return l; } inline void discard_clause() { assert(initialized); assert(last_clause_start!= SIZE_MAX); assert(last_clause_start <= db.size()); db.resize(last_clause_start); last_clause_start = SIZE_MAX; } // Note: If clause is not sorted, sort must be true. inline ClauseId commit_clause(bool sort, bool reduce=true) { assert(initialized); assert(last_clause_start!= SIZE_MAX); assert(last_clause_start <= db.size()); if (sort) { std::sort(db.begin() + last_clause_start, db.end(),[this](Literal a, Literal b){return less_lit(a,b);}); } if (reduce) { // Find new ending position size_t i = db.size(); while (i>last_clause_start && get_q(db[i-1]) == reduceq) --i; db.resize(i); } if (last_clause_start==db.size()) contains_empty_flag=true; // Append terminator 0 db.push_back(Literal::invalid); db_max = max(db_max,db.capacity()); ClauseId res = idmap.define_next(Clause_Iterator(last_clause_start)); last_clause_start = SIZE_MAX; ++active_clauses; ++db_clauses; return res; } inline ClauseId cur_id() {return idmap.next_key();} inline void remove(ClauseId cid) { idmap.remove(cid); assert(active_clauses); --active_clauses; // Trigger garbage collection when too empty (e.g. more than half of the clauses deleted). Arbitrary threshold of 1000 to avoid frequent smallish GCs. if (cfg_gc && db_clauses / 2 > active_clauses && db_clauses>1000) compact(); /* TODO * Counting literals (i.e. db storage space) may be more precise, but requires a num-literals field, or literal counting on removal) * Literal count of clause may be given as hint, as it will be known from previous resolution step anyway! */ } inline Clause_Iterator lookup(ClauseId cid) { if (!idmap.contains(cid)) error("Invalid clause/cube id: " + to_string((size_t)cid)); return idmap.the_lookup(cid); } inline Literal ci_peek(Clause_Iterator it) { assert((size_t)it < db.size()); return db[(size_t)it]; } inline bool ci_at_end(Clause_Iterator it) { return !ci_peek(it).is_valid(); } inline Literal ci_next(Clause_Iterator &it) { Literal res=ci_peek(it); it=Clause_Iterator((size_t)it + 1); return res; } inline bool contains_empty() {return contains_empty_flag;} ClauseId resolution(ClauseId cid1, ClauseId cid2) { auto ci1 = lookup(cid1); auto ci2 = lookup(cid2); start_clause(); /* Merge, eliminating duplicates, and allowing one resolution. * * This assumes that the clauses are sorted (which is an invariant for all clauses in the db) */ bool seen_res_lit=false; while (!ci_at_end(ci1) && !ci_at_end(ci2)) { Literal l1 = ci_peek(ci1); Literal l2 = ci_peek(ci2); if (less_lit(l1,l2)) { // l1 < l2 add_lit(l1); ci_next(ci1); } else if (l1 == l2) { add_lit(l1); ci_next(ci1); ci_next(ci2); } else if (l1 == -l2) { if (seen_res_lit) error("Resolution yields tautology: literal " + l1.str()); ci_next(ci1); ci_next(ci2); seen_res_lit=true; } else { add_lit(l2); ci_next(ci2); } } // Handle rest while (!ci_at_end(ci1)) add_lit(ci_next(ci1)); while (!ci_at_end(ci2)) add_lit(ci_next(ci2)); if (!seen_res_lit) error("No resolution"); // We make this an error, though it would be sound to simply combine two clauses without resolution // Commit clause. Reduce. Sorting not required, b/c already sorted due to merge of sorted clauses. return commit_clause(false,true); } private: // Garbage collection void compact() { // Iterate over ID map // Assume/assert clause positions are in ascending order // Copy CDB backwards and adjust addresses assert(active_clauses <= db_clauses); size_t dsti = 0; // New current position in DB // clog<<"GC "<<active_clauses<<" "<<db_clauses<<endl; #ifndef NDEBUG size_t new_active = 0; #endif for (auto it = idmap.begin(); it!=idmap.end(); ++it) { if (it->is_valid()) { size_t srci = (size_t)(*it); size_t new_addr = dsti; assert(srci >= dsti); while (true) { assert(srci < db.size()); Literal l=db[srci]; db[dsti]=l; ++srci; ++dsti; if (!l.is_valid()) break; } *it = Clause_Iterator(new_addr); #ifndef NDEBUG ++new_active; #endif } } assert(new_active == active_clauses); db_clauses = active_clauses; assert(dsti<=db.size()); db.resize(dsti); // db.shrink_to_fit(); // Currently, we don't free the memory, as it may be used by new clauses ++stat_num_gcs; } public: ClauseDB() {} void initialize(Quant _reduceq) { assert(!initialized); reduceq = _reduceq; // Clause-ID 0 does not exist. We just add an invalid ID here. [[maybe_unused]]ClauseId id0 = idmap.define_next(Clause_Iterator()); assert((size_t)id0 == 0); initialized=true; } void print_stats() { varpos.print_stats("varpos map"); varq.print_stats("varq map"); idmap.print_stats("id map"); log("max clause db: " + pretty_size(db_max * sizeof(Literal))); log("number of gcs: " + to_string(stat_num_gcs)); } }; inline size_t to_size_t(ClauseDB::ClauseId cid) {return (size_t)cid;} /* * Parallel Valuation. Uses bit-vectors to store multiple valuations in parallel. * Bit-vectors fit into machine-words here. */ class ParValuation { public: typedef uint64_t mask_t; private: static_assert(numeric_limits<mask_t>::is_integer,""); static_assert(!numeric_limits<mask_t>::is_signed,""); static const size_t bit_width = sizeof(mask_t)*8; static const mask_t max_mask = ((mask_t)1)<<(bit_width-1); private: mask_t cur_mask=1; // Bit that is currently added. 0 when full. private: size_t n = 0; mask_t *base = NULL; mask_t *m = NULL; ParValuation(ParValuation const &) = delete; ParValuation &operator=(ParValuation const &) = delete; private: inline bool in_range(Literal l) {return (size_t)(abs(l.raw())) <= n;} public: void clear() { assert(m); fill(base,base+(2*n+1),0); cur_mask=1; } void init(size_t _n) { assert(!m && _n>0); n=_n; base = new mask_t[2*n+1]; m = base + n; clear(); log("Using deferred initial cube checking, bit_width = " + to_string(bit_width)); } void init(Variable max_var) { init(max_var.idx()); } ParValuation() {} ParValuation(size_t _n) { init(_n); } ~ParValuation() { if (base) delete [] base;} // Getting and setting literals inline void set(Literal l) { assert(m); assert(in_range(l)); auto li = l.raw(); assert((m[-li]&cur_mask) == 0); m[li]|=cur_mask; } inline mask_t get(Literal l) { assert(m && in_range(l)); auto i = l.raw(); return m[i]; } // Management of remaining slots inline bool is_full() { return cur_mask == 0; } inline bool is_empty() { return cur_mask==1; } inline void next_slot() { assert(!is_full()); cur_mask<<=1; } // All used bits inline mask_t bits() { return cur_mask-1; } public: void print_stats() { log("Par-Valuation: " + pretty_size((2*n+1)*sizeof(mask_t))); } }; class Initial_Cube_Checker { private: vector<Literal> clauses; ParValuation val; // ClauseDB &db; public: // inline Initial_Cube_Checker(ClauseDB &_db) : db(_db) {} // Disabled, as this causes funny double-exceptions when error is thrown in flush_checks() // inline ~Initial_Cube_Checker() { // flush_checks(); // } // Must be called before cubes can be checked. Literals can be added earlier. inline void init(Variable max_var) { val.init(max_var); } // Add literals and 0s of formula's clauses inline Literal add_fml_lit(Literal l) {clauses.push_back(l); return l;} // Add next literal of a cube inline void add_cube_lit(Literal l) { assert(!val.is_full()); val.set(l); } // Declare current cube as finished (and get ready for next one) inline void commit_cube() { val.next_slot(); if (val.is_full()) flush_checks(); } // inline void check_cube(ClauseDB::Clause_Iterator cid) { // if (val.is_full()) flush_checks(); // assert(!val.is_full()); // // // Initialize this slot of parallel valuation with cube's literals // clog<<"icube "<<endl; // for (;!db.ci_at_end(cid);db.ci_next(cid)) { // clog<<db.ci_peek(cid).str()<<" "; // val.set(db.ci_peek(cid)); // } // clog<<"0"<<endl; // // val.next_slot(); // } inline void flush_checks() { if (val.is_empty()) return; // Nothing to check ParValuation::mask_t bits = val.bits(); // The outer loops iterates over the clauses, consuming the final zero in each increment step for (auto it = clauses.begin(); it!=clauses.end();++it) { ParValuation::mask_t m=0; // Accumulate valuation over literals of clause while (it->is_valid()) { m|=val.get(*it); ++it; assert(it!=clauses.end()); } // Check if (m != bits) { // clog<<m<<" != "<<bits<<endl; error("Initial cube check failed"); } } // Everything checked. Flush. val.clear(); } void print_stats() { log("ICC formula clauses: " + pretty_vector_stats(clauses)); } }; class Verifier { private: MMap_Range fml_range; MMap_Range prf_range; Lexer plx; ClauseDB db; Initial_Cube_Checker icc; size_t prf_first_id = 0; bool sat_mode = false; bool verified = false; public: Verifier(string dimacs_file, string proof_file) : fml_range(dimacs_file), prf_range(proof_file), plx(prf_range), db(), icc() { } inline bool is_sat() {assert(verified); return sat_mode;} // Parsing private: void parse_prf_header() { plx.eol(); plx.keyword("p"); plx.keyword("redcqrp"); prf_first_id = plx.unsafe_id_int(); plx.eol(); plx.keyword("r"); { string s = plx.word(); if (s=="SAT") sat_mode=true; else if (s=="UNSAT") sat_mode=false; else error("Unknown mode: " + s); plx.eol(); } // Initialize db db.initialize(sat_mode? Quant::EX : Quant::ALL); } static inline Literal parse_literal(Lexer &lx) { return Literal(lx.lit_int()); } static inline Literal parse_unsafe_literal(Lexer &lx) { return Literal(lx.unsafe_lit_int()); } void parse_formula() { Lexer lx(fml_range); // Header (Everything ignored) lx.eol(); lx.keyword("p"); lx.keyword("cnf"); lx.id_int(); lx.id_int(); lx.eol(); // Variable declarations while (true) { // Parse quantifier, break if no more quantifiers Quant q; if (lx.peek()=='e') q=Quant::EX; else if (lx.peek()=='a') q=Quant::ALL; else break; lx.next(); lx.eow(); // Parse variable list { lit_int_t v; while (true) { v = lx.var_int(); if (v==0) break; db.add_var(q,Variable(v)); } } lx.eol(); } if (sat_mode) icc.init(db.get_maxvar()); // Clauses while (!lx.is_eof()) { if (sat_mode) { // Parse formula clauses to their own database while (icc.add_fml_lit(parse_literal(lx)).is_valid()) {}; lx.eol(); } else { // Parse formula clauses to main database db.start_clause(); while (db.add_lit(parse_literal(lx)).is_valid()) {}; lx.eol(); // Sort and reduce db.commit_clause(true,true); } } // Check match of implicit IDs if ((size_t)db.cur_id() != prf_first_id) { error("Current ID after parsing formula ("+to_string((size_t)db.cur_id())+") " + "does not match start ID declared in proof header ("+to_string(prf_first_id)+")"); } } inline auto parse_delid() { bool del = plx.peek()=='d'; if (del) plx.next(); return make_pair(ClauseDB::ClauseId(plx.unsafe_id_int()), del); } void parse_proof() { while (!plx.is_eof() && !db.contains_empty()) { if (plx.peek() == '0') { // Initial cube plx.unsafe_id_int(); // Skip the zero if (!sat_mode) error("Initial cube step in SAT mode"); // Read cube, and add all its literals to cube checker. // NOTE we must add all literals. Some of them may be lost after reduction upon commit_clause. db.start_clause(); while (true) { Literal l = Literal(plx.lit_int()); if (!l.is_valid()) break; db.add_lit(l); icc.add_cube_lit(l); } plx.eol(); // Commit cube to cube checker icc.commit_cube(); // Commit cube to DB (sorts and reduces) db.commit_clause(true,true); } else { // Resolution step auto [cid1,del1] = parse_delid(); auto [cid2,del2] = parse_delid(); plx.eol(); db.resolution(cid1,cid2); if (del1) db.remove(cid1); if (del2) db.remove(cid2); } } if (sat_mode) icc.flush_checks(); if (!db.contains_empty()) error("Found no empty clause/cube"); if (!plx.is_eof()) log("Proof file contains additional content after empty clause/cube was produced"); } public: void do_check() { parse_prf_header(); parse_formula(); parse_proof(); verified=true; } void print_stats() { db.print_stats(); if (sat_mode) icc.print_stats(); } }; int main(int argc, char **argv) { try { if (argc != 3) error("Usage: verify <qdimacs-file> <proof-file>"); Verifier vrf(argv[1],argv[2]); vrf.do_check(); if (vrf.is_sat()) cout<<"s SAT"<<endl; else cout<<"s UNSAT"<<endl; vrf.print_stats(); return 0; } catch (exception &e) { cout<<"s ERROR"<<endl; cerr<<e.what()<<endl; return 1; }; }
[ "plammich@gmail.com" ]
plammich@gmail.com
3a5e762d936f74010952e29c6e10da5236678d0f
6ed1c7d1f2aa137ce2ab879a4a5ddecb8e1790f5
/mltplinh/mltplinh.cpp
bd41514ed22337fb716b52da9d671491dcb50aab
[]
no_license
ruudkoot/Ammeraal
49eeb4a9731ff75fec6740224e2b24ef5a24da8a
535b0c4782bb181dc059ca427bb3cbc3174b9278
refs/heads/master
2023-05-11T15:46:18.480055
2020-09-07T18:44:09
2020-09-07T18:44:09
291,448,052
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
// mltplinh.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> using namespace std; class p1 { public: p1(int n = 1) : n1(n) { cout << "p1(" << n << ")" << endl; } ~p1() { cout << "~p1()" << endl; } private: int n1; }; class p2 { public: p2(float x = 2.0f) : x2(x) { cout << "p2(" << x << ")" << endl; } ~p2() { cout << "~p2()" << endl; } private: float x2; }; class c : public p1, public p2 { public: c(bool b = true, int n = 3, float x = 4.0f) : p1(n), p2(x), bb(b) { cout << "c(" << b << "," << n << "," << x << ")" << endl; } ~c() { cout << "~c()" << endl; } private: bool bb; }; int main() { c cc(false); cout << sizeof p1 << endl; cout << sizeof p2 << endl; cout << sizeof c << endl; return 0; }
[ "inbox@ruudkoot.nl" ]
inbox@ruudkoot.nl
e35cc8abf9c1787926ad71271bcba21576941e33
e84dc130098c288e9f9313636265b7b8676d0de7
/dimmable_LED/dimmable_LED.ino
948b56dfcde11c06399cf64afbc157c6758d729f
[]
no_license
anandpraj/Dimmable_LED
097225904cdf4432f0c5af8eb4999d875fdfbe8e
56ceb3fae654354b907024d20a8169b6e7a397c1
refs/heads/main
2023-06-05T18:25:46.848086
2021-07-04T14:59:34
2021-07-04T14:59:34
382,878,819
0
0
null
null
null
null
UTF-8
C++
false
false
376
ino
int potPin=A1; int ledPin=5; int potVal; float ledVal; void setup() { // put your setup code here, to run once: pinMode(potPin,INPUT); pinMode(ledPin,OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: potVal= analogRead(potPin); ledVal= (255./1023.)*potVal; analogWrite(ledPin,ledVal); Serial.println(ledVal); }
[ "noreply@github.com" ]
anandpraj.noreply@github.com
1d631d863a8c88dd89e41fe7b10a94dfbfe1117f
4b0444102ea9917d581cb837740a2942bf655759
/MMVII/src/Bench/BenchGlob.cpp
47779606786b169938dbda6aac6c7ab73f753a5a
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
gaoshuai/micmac
d415e447bbf28abfefcefaae8a4afee13dac2446
8ab820797de7d2c80490e1291c3a3b8ee6a226a3
refs/heads/master
2020-06-11T01:11:12.127351
2019-06-25T15:55:51
2019-06-25T15:55:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,526
cpp
#include "include/MMVII_all.h" #include <cmath> /** \file BenchGlob.cpp \brief Main bench For now bench are relatively simples and executed in the same process, it's than probable that when MMVII grow, more complex bench will be done by sub process specialized. */ namespace MMVII { #if (THE_MACRO_MMVII_SYS == MMVII_SYS_L) void Bench_0000_SysDepString() { std::string aPath0 = "MMVII"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath0,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath0,false)=="MMVII","File Bench_0000_SysDepString"); std::string aPath1 = "af.tif"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath1,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath1,false)=="af.tif","File Bench_0000_SysDepString"); std::string aPath2 = "./toto.txt"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath2,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath2,false)=="toto.txt","File Bench_0000_SysDepString"); std::string aPath3 = "/a/bb/cc/"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath3,false)==aPath3,"Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath3,false)=="","File Bench_0000_SysDepString"); std::string aPath4 = "/a/bb/cc/tutu"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath4,false)==aPath3,"Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath4,false)=="tutu","File Bench_0000_SysDepString"); std::string aPath5 = "NONE"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath5,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath5,false)=="NONE","File Bench_0000_SysDepString"); } #else void Bench_0000_SysDepString() { } #endif void Bench_0000_Memory() { cMemState aSt = cMemManager::CurState(); int aNb=5; // short * aPtr = static_cast<short *> (cMemManager::Calloc(sizeof(short),aNb)); /// short * aPtr = MemManagerAlloc<short>(aNb); short * aPtr = cMemManager::Alloc<short>(aNb); for (int aK=0; aK<aNb ; aK++) aPtr[aK] = 10 + 234 * aK; // Plein de test d'alteration if (0) aPtr[-1] =9; if (0) aPtr[aNb+6] =9; if (0) aPtr[aNb] =9; if (0) aPtr[aNb+1] =9; // Plante si on teste avant liberation if (0) cMemManager::CheckRestoration(aSt); cMemManager::Free(aPtr); cMemManager::CheckRestoration(aSt); } void Bench_0000_Param() { int a,b; cCollecSpecArg2007 aCol; aCol << Arg2007(a,"UnA") << AOpt2007(b,"b","UnB") ; aCol[0]->InitParam("111"); aCol[1]->InitParam("222"); MMVII_INTERNAL_ASSERT_bench(a==111,"Bench_0000_Param"); MMVII_INTERNAL_ASSERT_bench(b==222,"Bench_0000_Param"); } /*************************************************************/ /* */ /* cAppli_MMVII_Bench */ /* */ /*************************************************************/ /// entry point for all unary test /** This class contain all the unary test to check the validaty of command / classes / function relatively to their specs. For now its essentially a serie of function that are called linearly. When the test become long to execute, it may evolve with option allowing to do only some specific bench. */ class cAppli_MMVII_Bench : public cMMVII_Appli { public : cAppli_MMVII_Bench(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); void Bench_0000_String(); void BenchFiles(); ///< A Bench on creation/deletion/existence of files int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override ; cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override ; std::string mTest; int mNumBugRecall; }; cCollecSpecArg2007 & cAppli_MMVII_Bench::ArgObl(cCollecSpecArg2007 & anArgObl) { return anArgObl << Arg2007(mTest,"Unused, to check reentrance" ) ; } cCollecSpecArg2007 & cAppli_MMVII_Bench::ArgOpt(cCollecSpecArg2007 & anArgOpt) { return anArgOpt << AOpt2007(mNumBugRecall,"NBR","Num to Generate a Bug in Recall") ; } void cAppli_MMVII_Bench::Bench_0000_String() { // Bench elem sur la fonction SplitString std::vector<std::string> aSplit; SplitString(aSplit,"@ @AA BB@CC DD @ "," @"); MMVII_INTERNAL_ASSERT_bench(aSplit.size()==6,"Size in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(0)=="","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(1)=="AA","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(2)=="BB","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(3)=="CC","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(4)=="DD","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(5)=="","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA.tif")=="AA", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.tif")=="tif","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.tif",'t')=="if","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("a.b.c",'.',true,true)=="a.b", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("a.b.c",'.',true,false)=="a", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("a.b.c",'.',true,true)=="c", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("a.b.c",'.',true,false)=="b.c", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.",'.')=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench( Prefix("AA.",'.')=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix(".AA",'.')=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench( Prefix(".AA",'.')=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA",'.',true,true)=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA",'.',true,true)=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA",'.',true,false)=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA",'.',true,false)=="AA","Postfix in Bench_0000_String"); } // std::string & aBefore,std::string & aAfter,const std::string & aStr,char aSep,bool SVP=false,bool PrivPref=true); cAppli_MMVII_Bench::cAppli_MMVII_Bench (const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec), mNumBugRecall (-1) { MMVII_INTERNAL_ASSERT_always ( The_MMVII_DebugLevel >= The_MMVII_DebugLevel_InternalError_tiny, "MMVII Bench requires highest level of debug" ); // The_MMVII_DebugLevel = The_MMVII_DebugLevel_InternalError_weak; } static void CreateFile(const std::string & aNameFile) { cMMVII_Ofs aFile(aNameFile,false); int anI=44; aFile.Write(anI); } void cAppli_MMVII_Bench::BenchFiles() { const std::string & aTDir = TmpDirTestMMVII(); std::string aNameFile = aTDir+"toto.txt"; // Dir should be empty MMVII_INTERNAL_ASSERT_always(!ExistFile(aNameFile),"BenchFiles"); CreateFile(aNameFile); // File should now exist MMVII_INTERNAL_ASSERT_always(ExistFile(aNameFile),"BenchFiles"); // CreateFile(aTDir+"a/b/c/toto.txt"); Do not work directly CreateDirectories(aTDir+"a/b/c/",false); CreateFile(aTDir+"a/b/c/toto.txt"); // Now it works RemoveRecurs(TmpDirTestMMVII(),true,false); } void BenchFilterLinear(); int cAppli_MMVII_Bench::Exe() { // Begin with purging directory CreateDirectories(TmpDirTestMMVII(),true ); RemoveRecurs(TmpDirTestMMVII(),true,false); // On teste les macro d'assertion MMVII_INTERNAL_ASSERT_bench((1+1)==2,"Theoreme fondamental de l'arithmetique"); // La on a verifie que ca marchait pas // MMVII_INTERNAL_ASSERT_all((1+1)==3,"Theoreme pas tres fondamental de l'arithmetique"); BenchRecall(mNumBugRecall); BenchDenseMatrix0(); BenchGlobImage(); Bench_Nums(); BenchFiles(); Bench_0000_SysDepString(); Bench_0000_String(); Bench_0000_Memory(); Bench_0000_Ptxd(); Bench_0000_Param(); BenchSerialization(mDirTestMMVII+"Tmp/",mDirTestMMVII+"Input/"); BenchSet(mDirTestMMVII); BenchSelector(mDirTestMMVII); BenchEditSet(); BenchEditRel(); BenchEnum(); Bench_Random(); Bench_Duration(); BenchStrIO(); BenchFilterLinear(); // We clean the temporary files created RemoveRecurs(TmpDirTestMMVII(),true,false); // TestTimeV1V2(); => Valide ratio ~= 1 return EXIT_SUCCESS; } tMMVII_UnikPApli Alloc_MMVII_Bench(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MMVII_Bench(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecBench ( "Bench", Alloc_MMVII_Bench, "This command execute (many) self verification on MicMac-V2 behaviour", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); /* ========================================================= */ /* */ /* cAppli_MMRecall */ /* */ /* ========================================================= */ /** A class to test mecanism of MMVII recall itself */ class cAppli_MMRecall : public cMMVII_Appli { public : static const int NbMaxArg=2; cAppli_MMRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override; cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override; int mNum; ///< kind of idea of the call int mLev0; ///< to have the right depth we must know level of std::string mAM[NbMaxArg]; std::string mAO[NbMaxArg]; bool mRecalInSameProcess; int mNumBug; ///< Generate bug 4 this num }; cAppli_MMRecall::cAppli_MMRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec), mLev0 (0), mRecalInSameProcess (true), mNumBug (-1) { } int cAppli_MMRecall::Exe() { std::string aDirT = TmpDirTestMMVII() ; // Purge TMP if (mLevelCall == mLev0) { RemovePatternFile(aDirT+".*",true); } // to create a file with Num in name { std::string aNameF = aDirT + ToStr(mNum) + ".txt"; cMMVII_Ofs (aNameF,false); } MMVII_INTERNAL_ASSERT_always(mNum!=mNumBug,"Bug generate by user in cAppli_MMRecall"); // Break recursion if (mLevelCall-mLev0 >= NbMaxArg) return EXIT_SUCCESS; // Recursive call to two son N-> 2N, 2N+1, it's the standard binary tree like in heap, this make it bijective { std::vector<std::string> aLVal; aLVal.push_back(ToStr(2*mNum)); aLVal.push_back(ToStr(2*mNum+1)); cColStrAOpt aSub; eTyModeRecall aMRec = mRecalInSameProcess ? eTyModeRecall::eTMR_Inside : eTyModeRecall::eTMR_Serial; ExeMultiAutoRecallMMVII("0",aLVal ,aSub,aMRec); } // Test that we have exactly the expected file (e.g. 1,2, ... 31 ) and purge if (mLevelCall == mLev0) { tNameSet aSet1 = SetNameFromPat(aDirT+".*"); MMVII_INTERNAL_ASSERT_bench(aSet1.size()== ((2<<NbMaxArg) -1),"Sz set in cAppli_MMRecall"); tNameSet aSet2 ; for (int aK=1 ; aK<(2<<NbMaxArg) ; aK++) aSet2.Add( ToStr(aK) + ".txt"); MMVII_INTERNAL_ASSERT_bench(aSet1.Equal(aSet2),"Sz set in cAppli_MMRecall"); RemovePatternFile(aDirT+".*",true); } return EXIT_SUCCESS; } cCollecSpecArg2007 & cAppli_MMRecall::ArgObl(cCollecSpecArg2007 & anArgObl) { return anArgObl << Arg2007(mNum,"Num" ) << Arg2007(mAM[0],"Mandatory arg0" ) << Arg2007(mAM[1],"Mandatory arg1" ) // << Arg2007(mAM[2],"Mandatory arg2" ) // << Arg2007(mAM[3],"Mandatory arg3" ) ; } cCollecSpecArg2007 & cAppli_MMRecall::ArgOpt(cCollecSpecArg2007 & anArgOpt) { return anArgOpt << AOpt2007(mAO[0],"A0","Optional Arg 0") << AOpt2007(mAO[1],"A1","Optional Arg 1") // << AOpt2007(mAO[2],"A2","Optional Arg 2") // << AOpt2007(mAO[3],"A3","Optional Arg 3") << AOpt2007(mLev0,"Lev0","Level of first call") << AOpt2007(mRecalInSameProcess,"RISP","Recall in same process") << AOpt2007(mNumBug,"NumBug","Num 4 generating purpose scratch") ; } tMMVII_UnikPApli Alloc_TestRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MMRecall(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecTestRecall ( "TestRecall", Alloc_TestRecall, "Use in Bench to Test Recall of MMVII by itself ", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); void OneBenchRecall(bool InSameP,int aNumBug) { cMMVII_Appli & anAp = cMMVII_Appli::CurrentAppli(); anAp.StrObl() << "1"; for (int aK=0 ; aK< cAppli_MMRecall::NbMaxArg; aK++) anAp.StrObl() << ToStr(10*aK); anAp.ExeCallMMVII ( TheSpecTestRecall, anAp.StrObl() , anAp.StrOpt() << t2S("Lev0",ToStr(1+anAp.LevelCall())) << t2S("RISP",ToStr(InSameP)) << t2S("NumBug",ToStr(aNumBug)) ); } void BenchRecall(int aNum) { OneBenchRecall(true,-1); OneBenchRecall(false,aNum); } /* ========================================================= */ /* */ /* cAppli_MPDTest */ /* */ /* ========================================================= */ /// A class to make quick and dirty test /** The code in this class will evolve quickly, it has no perenity, if a test become important it must be put in bench */ class cAppli_MPDTest : public cMMVII_Appli { public : cAppli_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override {return anArgObl;} cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override {return anArgOpt;} }; cAppli_MPDTest:: cAppli_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec) { } void TestArg0(const std::vector<int> & aV0) { for (auto I : aV0){I++; StdOut() << "I=" << I << "\n"; } } std::string BUD(const std::string & aDir); void TestBooostIter(); class cTestShared { public : cTestShared() {StdOut() << "CREATE cTestShared "<< this << "\n";;} ~cTestShared() {StdOut() << "XXXXXX cTestShared "<< this << "\n";;} static void Test() { cTestShared anOb; // std::shared_ptr<cTestShared> aT(&anOb); std::shared_ptr<cTestShared> aT(new cTestShared); } }; /* class cMultipleOfs : public std::ostream { public : cMultipleOfs(std::ostream & aos1,std::ostream & aos2) : mOs1 (aos1), mOs2 (aos2) { } std::ostream & mOs1; std::ostream & mOs2; template <class Type> cMultipleOfs & operator << (const Type & aVal) { mOs1 << aVal; mOs2 << aVal; return *this; } }; class cMultipleOfs : public std::ostream { public : cMultipleOfs() { } void Add(std::ostream & aOfs) {mVOfs.push_back(&aOfs);} std::vector<std::ostream *> mVOfs; template <class Type> cMultipleOfs & operator << (const Type & aVal) { for (const auto & Ofs : mVOfs) *Ofs << aVal; return *this; } }; */ void TestVectBool() { StdOut() << "BEGIN TBOOL \n"; getchar(); for (int aK=0 ; aK<5000 ; aK++) { std::vector<bool> * aV = new std::vector<bool>; for (int aK=0 ; aK<1000000 ; aK++) aV->push_back(true); } StdOut() << "END TBOOL \n"; getchar(); for (int aK=0 ; aK<5000 ; aK++) { std::vector<tU_INT1> * aV = new std::vector<tU_INT1>; for (int aK=0 ; aK<1000000 ; aK++) aV->push_back(1); } StdOut() << "END TBYTE \n"; getchar(); } bool F(const std::string & aMes) {std::cout <<"FFFFF=" << aMes << "\n"; return true;} #define UN 1 #define DEUX 2 // #include <limits> int cAppli_MPDTest::Exe() { if ((UN>DEUX) && F("aaaa")) { F("bbbb"); } F("ccccc"); /* cSparseVect<float> aSV; for (const auto & aP : aSV) { std::cout << aP.mI << "\n"; } */ /* cIm2D<tU_INT1> aIm(cPt2di(3,3)); aIm.DIm().SetV(cPt2di(0,0),13); // aIm.DIm().SetV(cPt2di(0,0),1000); // aIm.DIm().SetV(cPt2di(-1,0),1); // new cIm2D<tU_INT1>(cPt2di(3,3)); cDataIm2D<tU_INT1> & aDIm = aIm.DIm(); tU_INT1* aPtr = aDIm.RawDataLin(); StdOut() << "aIm=" << int(aPtr[0]) << "\n"; aPtr[0] = 14; StdOut() << "aIm=" << (int)aDIm.GetV(cPt2di(0,0)) << "\n"; // aPtr[-1] = 0; */ /* TestVectBool(); cMMVII_Ofs aOs1("toto1.txt"); cMMVII_Ofs aOs2("toto2.txt"); cMultipleOfs amOs; // (aOs1.Ofs(),aOs2.Ofs()); amOs.Add(aOs1.Ofs()); amOs.Add(aOs2.Ofs()); amOs << "1+1=" << 1+1 << "\n"; cMMVII_Ofs aFile("toto.txt"); std::ostream & anOFS = aFile.Ofs(); anOFS << "TEST OFFFSSSSSSSSSSSS\n"; */ return EXIT_SUCCESS; } tMMVII_UnikPApli Alloc_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MPDTest(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecMPDTest ( "MPDTest", Alloc_MPDTest, "This used a an entry point to all quick and dirty test by MPD ...", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); };
[ "marc.pierrot-deseilligny@ensg.eu" ]
marc.pierrot-deseilligny@ensg.eu
83af50aa01d6d4f6082ef28c710a6cc2212d5b16
28f43281141abdaebe57909cfe59897dc256ede4
/cpp_module_02/ex00/main.cpp
9fbeaa838383f32e7246ca4e1017efcb86c1c193
[]
no_license
benjaminmerchin/piscine_CPP
d4476f05da9891c2e5c0eab5f1c46a44c3391a36
4a507669b3877662badb230d807d7f2ad19ce05d
refs/heads/main
2023-07-16T14:12:35.460993
2021-08-30T10:50:32
2021-08-30T10:50:32
383,801,709
4
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
#include "Fixed.hpp" int main(void) { Fixed a; Fixed b(a); Fixed c; c = b; std::cout << a.getRawBits() << std::endl; std::cout << b.getRawBits() << std::endl; std::cout << c.getRawBits() << std::endl; return 0; }
[ "benjaminmerchin@gmail.com" ]
benjaminmerchin@gmail.com
258fa22409d3249149578f5397ad86a78b84d0bb
cf3f10b934b326964f2c9a55f16a6f533407d6a7
/OOP/lab4/Pentagon.h
d8107915d21abea1c6b181887af02c5f4e40b4fc
[]
no_license
VeronikaBurkevich/MAI
4426facb5252ccb91309423eeeffb9a810e9a52f
2de02cde7ab72213f2c88f70b59f030f7baed73b
refs/heads/main
2023-07-14T09:21:08.703153
2021-08-19T07:25:03
2021-08-19T07:25:03
397,688,928
0
0
null
null
null
null
UTF-8
C++
false
false
674
h
#ifndef PENTAGON_H #define PENTAGON_H #include <cstdlib> #include <iostream> #include "Figure.h" class pentagon : public figure { public: pentagon(); pentagon(std::istream &is); pentagon(size_t a); pentagon(const pentagon& orig); int F() override; ////////////////// double Square() override; void Print() override; friend std::ostream& operator<<(std::ostream& os, const pentagon& right); friend std::istream& operator>>(std::istream& is, pentagon& right); friend bool operator==(const pentagon& left, const pentagon& right); pentagon& operator=(const pentagon& right); ~pentagon(); private: size_t side_a; }; #endif // !PENTAGON_H
[ "noreply@github.com" ]
VeronikaBurkevich.noreply@github.com
8d25b9e69968738c10b05071cde8178b1ddc2ac6
1bd9e3cda029e15d43a2e537663495ff27e317e2
/buoyantPimpleFoam_timevaryingBC/timevaryingCavityFoam/58/uniform/cumulativeContErr
a7fd54fe5635b3c993fbec8012e1fd58acb2d7b2
[]
no_license
tsam1307/OpenFoam_heatTrf
810b81164d3b67001bfce5ab9311d9b3d45b5c9d
799753d24862607a3383aa582a6d9e23840c3b15
refs/heads/main
2023-08-10T23:27:40.420639
2021-09-18T12:46:01
2021-09-18T12:46:01
382,377,763
1
0
null
null
null
null
UTF-8
C++
false
false
956
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class uniformDimensionedScalarField; location "58/uniform"; object cumulativeContErr; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; value -1.62605e-13; // ************************************************************************* //
[ "tsinghsamant@gmail.com" ]
tsinghsamant@gmail.com
5ce8041808ab76ce0c7e43affd14b93962080908
fa55d8ed32564195f2687d1e18b99f80c5683073
/lbc_lintcodeII/212-space-replacement.cc
1baf76fe728c8e0ed2dc4a403d1258550ea8e484
[]
no_license
TenFifteen/SummerCamp
1841bf1bd212938cee818540658185cd3e429f0c
383b9321eee9e0721772f93a897c890f737f2eff
refs/heads/master
2020-04-05T23:48:01.393256
2018-03-11T12:37:38
2018-03-11T12:37:38
38,595,086
9
4
null
2016-07-18T14:21:15
2015-07-06T03:15:55
C++
UTF-8
C++
false
false
902
cc
/* 题目大意: 给定一个字符串,将其中的空格替换成20%,原地替换。 解题思路: 见代码。 遇到的问题: 没有。 */ class Solution { public: /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ int replaceBlank(char string[], int length) { // Write your code here int len = length; for (int i = 0; i < length; ++i) { if (string[i] == ' ') len += 2; } int index = len-1; for (int i = length-1; i >= 0; --i) { if (string[i] == ' ') { string[index--] = '0'; string[index--] = '2'; string[index--] = '%'; } else { string[index--] = string[i]; } } return len; } };
[ "libenchao@gmail.com" ]
libenchao@gmail.com
9044dc69514ec1956be70e06a24bf66991c2bd0e
2885e54c807bd70b8eb0cd2bc3ffd5ce51bd66cc
/2007-PIR-Drone Trirotor acrobate/Projet/Informatique/CNES/marmottes-9.8/src/ModeleCine.cpp
15611290d96643a49f9bd615b0dfcb7081cccd65
[]
no_license
crubier/my-personal-projects
622b09ce6d9c846b905fe135892a178c1a0c554b
8cd26b212b0c61f3d5bbe2de82d49891f3f3602a
refs/heads/master
2021-09-12T23:09:14.097634
2018-04-22T07:45:42
2018-04-22T07:45:42
130,488,289
1
0
null
null
null
null
ISO-8859-1
C++
false
false
6,949
cpp
/////////////////////////////////////////////////////////////////////////////// //$<AM-V1.0> // //$Type // DEF // //$Projet // Marmottes // //$Application // Marmottes // //$Nom //> ModeleCine.cpp // //$Resume // fichier d'implantation de la classe ModeleCine // //$Description // Module de définition de la classe // //$Contenu //> class ModeleCine //> ModeleCine() //> operator =() //> prendConsignesEnCompte() //> miseAJourOmegaMax() //> attitude() // //$Historique // $Log: ModeleCine.cpp,v $ // Revision 1.20 2003/02/04 16:30:30 marmottes // DM-ID 17 Mise à jour de l'extension du fichier dans le bandeau // // Revision 1.19 2002/01/17 09:22:41 marmottes // (prendConsignesEnCompte): génération de l'erreur consignes_gyro_elevees (FA 0001) // // Revision 1.18 2001/01/25 16:29:20 luc // modification de la valeur par défaut de la vitesse maximale de // rotation de 2 radians par seconde à 0.4 radian par seconde // // Revision 1.17 2000/06/07 16:43:40 filaire // correction d'une erreur de signe // // Revision 1.16 2000/06/07 14:08:04 luc // correction d'une erreur de valeur absolue // // Revision 1.15 2000/03/30 17:01:19 luc // ajout du copyright CNES // // Revision 1.14 2000/03/14 17:16:50 luc // correction d'une discontinuité du modèle pour les spins faibles mais // non nuls (introduction d'un développement limité du sinus cardinal) // // Revision 1.13 1999/08/06 13:32:13 filaire // Passage à la gestion des erreurs par les exceptions // // Revision 1.12 1999/07/29 12:15:17 filaire // Modification de la signature de la fonction prendConsignesEnCompte // // Revision 1.12 1999/07/02 07:23:07 geraldine // modification de la signature de prendConsignesEnCompte // utilisation des exceptions // // Revision 1.11 1998/10/05 15:24:56 luc // élimination de DBL_EPSILON pour éviter des problèmes de portabilité // contournement d'un bug du compilateur Sun // // Revision 1.10 1998/08/04 06:59:10 luc // réduction de l'intervalle de validité de la variable libre // de [-1 ; +1] à [0 ; 1] // // Revision 1.9 1998/06/24 19:58:40 luc // élimination des variables statiques RCS // modification du format des en-têtes // // Revision 1.8 1998/04/26 18:25:08 luc // inversion de la convention de nommage des attributs // // Revision 1.7 1998/02/19 16:19:02 luc // déplacement d'un constructeur inline dans le .cc // pour contourner un problème d'optimiseur avec g++ 2.8.0 // // Revision 1.6 1997/09/23 09:28:10 luc // utilisation de la consigne indépendante des unités de sortie // pour la modélisation interne // // Revision 1.5 1997/08/20 08:27:17 luc // ajout d'un en-tête de fichier // utilisation du valeurConsigne () commun à tous les senseurs à la place // du omega () spécifique aux senseurs cinématiques qui disparaît // // Revision 1.4 1997/04/27 19:35:50 luc // inversion des codes de retour // changement des règles de nommage // passage de SCCS à RCS // // Revision 1.3 1996/10/03 14:39:58 luc // correction du modèle des consignes en spin // // Revision 1.2 1995/01/27 16:59:56 mercator // propagation du spin dans tous les calculs depuis la modelisation // jusqu'a la sauvegarde de la solution finale dans l'etat // // Revision 1.1 1995/01/27 10:48:27 mercator // Initial revision // //$Version // $Id: ModeleCine.cpp,v 1.20 2003/02/04 16:30:30 marmottes Exp $ // //$Auteur // L. Maisonobe CNES // Copyright (C) 2000 CNES //$<> /////////////////////////////////////////////////////////////////////////////// #include "marmottes/ModeleCine.h" #include "marmottes/SenseurCinematique.h" ModeleCine::ModeleCine () : omegaMax_ (0.4) {} ModeleCine& ModeleCine::operator = (const ModeleCine& m) { if (&m != this) // protection contre x = x { u_ = m.u_; v_ = m.v_; thetaMax_ = m.thetaMax_; omegaMax_ = m.omegaMax_; } return *this; } void ModeleCine::prendConsignesEnCompte () throw (MarmottesErreurs) { SenseurCinematique* s1 = (SenseurCinematique *) senseur1 (); SenseurCinematique* s2 = (SenseurCinematique *) senseur2 (); double scal = s1->sensible () | s2->sensible (); double denominateur = 1.0 - scal * scal; if ((denominateur >= -1.0e-12) && (denominateur <= 1.0e-12)) throw MarmottesErreurs (MarmottesErreurs::gyros_coaxiaux); u_ = VecDBLVD1 ((s1->sensible () * (s1->omega () - s2->omega () * scal) + s2->sensible () * (s2->omega () - s1->omega () * scal) ) / denominateur); v_ = VecDBLVD1 (s1->sensible () ^ s2->sensible ()); double theta2V2 = omegaMax_ * omegaMax_ - (u_ | u_).f0 (); if (theta2V2 <= 0.0) throw MarmottesErreurs (MarmottesErreurs::consignes_gyro_elevees, s1->nom ().c_str (), s2->nom ().c_str (), degres (omegaMax_)); thetaMax_ = sqrt (theta2V2 / (v_ | v_).f0 ()); } void ModeleCine::miseAJourOmegaMax (double omega) throw (MarmottesErreurs) { if (omega <= 0.0) throw MarmottesErreurs (MarmottesErreurs::omega_neg, omega); omegaMax_ = omega; } void ModeleCine::attitude (const Etat& etatPrecedent, double date, const ValeurDerivee1& t, int famille, RotVD1* ptrAtt, VecVD1* ptrSpin) const { // modélisation de la rotation autour des gyros 1 et 2 double dtSur2 = 43200.0 * (date - etatPrecedent.date ()); ValeurDerivee1 theta ((t * 2.0 - 1.0) * thetaMax_); *ptrSpin = u_ + v_ * theta; ValeurDerivee1 vitesse (ptrSpin->norme ()); ValeurDerivee1 demiAngle = vitesse * dtSur2; ValeurDerivee1 sinCardinal; if (fabs (demiAngle.f0 ()) < 4.0e-4) { // si l'angle est trop petit, on utilise un développement limité // pour calculer sin (alpha) / alpha. En se limitant à l'ordre 4, // on obtient les erreurs relatives suivantes : 8.1e-25 sur // la valeur, 9.1e-17 pour la dérivée (pour des demi-angles // inférieurs à 4e-4) ValeurDerivee1 alpha2 = demiAngle * demiAngle; sinCardinal = (120.0 - alpha2 * (20.0 - alpha2)) / 120.0; } else sinCardinal = sin (demiAngle) / demiAngle; // rotation autour de l'axe de spin depuis la date de l'attitude précédente ValeurDerivee1 q0 = cos (demiAngle); VecVD1 q = *ptrSpin * (sinCardinal * dtSur2); RotVD1 evolution (q0, q.x (), q.y (), q.z ()); // calcul de l'attitude après évolution *ptrAtt = evolution (etatPrecedent.attitudeVD1 ()); }
[ "vincent.lecrubier@gmail.com" ]
vincent.lecrubier@gmail.com
8f4ab6ac9f8073f243cae1c7ebbdac292fcd98c2
e1cd579c8dcd952cc338ce3684397eddb0920760
/archive/1/wloska_czekolada.cpp
2a59db69f6866c10d1d8c6c261ea1049ce081fea
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Aleshkev/algoritmika
0b5de063870cb8a87654613241a204b534037079
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
refs/heads/master
2021-06-05T10:46:59.313945
2020-02-02T12:39:47
2020-02-02T12:39:47
148,994,588
3
0
null
null
null
null
UTF-8
C++
false
false
829
cpp
#include <iostream> #include <algorithm> using namespace std; typedef long long int I; int main() { I n; cin >> n; I *t = new I[n]; for(I i = 0; i < n; ++i) { cin >> t[i]; --t[i]; } I max_a = *max_element(t, t + n); I *u = new I[max_a]; fill(u, u + max_a, -1); for(I i = 0; i < n; ++i) { u[t[i]] = i; } for(I i = 0; i < n; ++i) { cout << t[i] << " "; } cout << endl; for(I i = 0; i < max_a; ++i) { if(u[i] != -1) { cout << i << ": " << u[i] << endl; } } I c = 0; I b = 0, e = 0; while(b < n) { do { ++b; e = max(e, u[t[b]]); } while(b < e) cout << "found " << b << ":" << e << endl; ++c; } cout << c << endl; return 0; }
[ "j.aleszkiewicz@gmail.com" ]
j.aleszkiewicz@gmail.com
0fcbc76674961ba16fd3e6349be4230e9f9fb33c
d4da977bb5f060d6b4edebfdf32b98ee91561b16
/Note/集训队作业/2014/作业1/试题泛做/ytl13508111107/ytl/题目与程序/D6545. Bee Breeding/ran/bc.cpp
863bb228172e2060129223673c106dccc7874f3d
[]
no_license
lychees/ACM-Training
37f9087f636d9e4eead6c82c7570e743d82cf68e
29fb126ad987c21fa204c56f41632e65151c6c23
refs/heads/master
2023-08-05T11:21:22.362564
2023-07-21T17:49:53
2023-07-21T17:49:53
42,499,880
100
22
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
e2 5406 0 R >> endobj 5236 0 obj [ 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000
[ "lychees67@gmail.com" ]
lychees67@gmail.com
35b1f8bc6243426c5f5110180ff44e7d17ac7b2a
56b847482dd3cd1b55bc19e1ff3ec1dfcbd6a0bd
/Adafruit_SGP30.cpp
0068231945f927a5a76d156ed8f0624a72f4644c
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
winkj/Adafruit_SGP30
431645284ca12f175940013170e4510ef5239a71
729ddf4e3c43e22643b1ae9dabb97a8affc0a297
refs/heads/master
2021-05-10T14:30:42.551946
2018-01-17T18:26:17
2018-01-17T18:26:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,321
cpp
/*! * @file Adafruit_SGP30.cpp * * @mainpage Adafruit SGP30 gas sensor driver * * @section intro_sec Introduction * * This is the documentation for Adafruit's SGP30 driver for the * Arduino platform. It is designed specifically to work with the * Adafruit SGP30 breakout: http://www.adafruit.com/products/3709 * * These sensors use I2C to communicate, 2 pins (SCL+SDA) are required * to interface with the breakout. * * Adafruit invests time and resources providing this open source code, * please support Adafruit and open-source hardware by purchasing * products from Adafruit! * * * @section author Author * Written by Ladyada for Adafruit Industries. * * @section license License * BSD license, all text here must be included in any redistribution. * */ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "Adafruit_SGP30.h" //#define I2C_DEBUG /**************************************************************************/ /*! @brief Instantiates a new SGP30 class */ /**************************************************************************/ Adafruit_SGP30::Adafruit_SGP30() { } /**************************************************************************/ /*! @brief Setups the hardware and detects a valid SGP30. Initializes I2C then reads the serialnumber and checks that we are talking to an SGP30 @param theWire Optional pointer to I2C interface, otherwise use Wire @returns True if SGP30 found on I2C, False if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::begin(TwoWire *theWire) { _i2caddr = SGP30_I2CADDR_DEFAULT; if (theWire == NULL) { _i2c = &Wire; } else { _i2c = theWire; } _i2c->begin(); uint8_t command[2]; command[0] = 0x36; command[1] = 0x82; if (! readWordFromCommand(command, 2, 10, serialnumber, 3)) return false; uint16_t featureset; command[0] = 0x20; command[1] = 0x2F; if (! readWordFromCommand(command, 2, 10, &featureset, 1)) return false; //Serial.print("Featureset 0x"); Serial.println(featureset, HEX); if (featureset != SGP30_FEATURESET) return false; if (! IAQinit()) return false; return true; } /**************************************************************************/ /*! @brief Commands the sensor to begin the IAQ algorithm. Must be called after startup. @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::IAQinit(void) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x03; return readWordFromCommand(command, 2, 10); } /**************************************************************************/ /*! @brief Commands the sensor to take a single eCO2/VOC measurement. Places results in {@link TVOC} and {@link eCO2} @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::IAQmeasure(void) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x08; uint16_t reply[2]; if (! readWordFromCommand(command, 2, 10, reply, 2)) return false; TVOC = reply[1]; eCO2 = reply[0]; return true; } /**************************************************************************/ /*! @brief Request baseline calibration values for both CO2 and TVOC IAQ calculations. Places results in parameter memory locaitons. @param eco2_base A pointer to a uint16_t which we will save the calibration value to @param tvoc_base A pointer to a uint16_t which we will save the calibration value to @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x15; uint16_t reply[2]; if (! readWordFromCommand(command, 2, 10, reply, 2)) return false; *eco2_base = reply[0]; *tvoc_base = reply[1]; return true; } /**************************************************************************/ /*! @brief Assign baseline calibration values for both CO2 and TVOC IAQ calculations. @param eco2_base A uint16_t which we will save the calibration value from @param tvoc_base A uint16_t which we will save the calibration value from @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base) { uint8_t command[8]; command[0] = 0x20; command[1] = 0x1e; command[2] = tvoc_base >> 8; command[3] = tvoc_base & 0xFF; command[4] = generateCRC(command+2, 2); command[5] = eco2_base >> 8; command[6] = eco2_base & 0xFF; command[7] = generateCRC(command+5, 2); uint16_t reply[2]; if (! readWordFromCommand(command, 8, 10, reply, 0)) return false; return true; } /**************************************************************************/ /*! @brief I2C low level interfacing */ /**************************************************************************/ boolean Adafruit_SGP30::readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delayms, uint16_t *readdata, uint8_t readlen) { uint8_t data; _i2c->beginTransmission(_i2caddr); #ifdef I2C_DEBUG Serial.print("\t\t-> "); #endif for (uint8_t i=0; i<commandLength; i++) { _i2c->write(command[i]); #ifdef I2C_DEBUG Serial.print("0x"); Serial.print(command[i], HEX); Serial.print(", "); #endif } #ifdef I2C_DEBUG Serial.println(); #endif _i2c->endTransmission(); delay(delayms); if (readlen == 0) return true; uint8_t replylen = readlen * (SGP30_WORD_LEN +1); if (_i2c->requestFrom(_i2caddr, replylen) != replylen) return false; uint8_t replybuffer[replylen]; #ifdef I2C_DEBUG Serial.print("\t\t<- "); #endif for (uint8_t i=0; i<replylen; i++) { replybuffer[i] = _i2c->read(); #ifdef I2C_DEBUG Serial.print("0x"); Serial.print(replybuffer[i], HEX); Serial.print(", "); #endif } #ifdef I2C_DEBUG Serial.println(); #endif for (uint8_t i=0; i<readlen; i++) { uint8_t crc = generateCRC(replybuffer+i*3, 2); #ifdef I2C_DEBUG Serial.print("\t\tCRC calced: 0x"); Serial.print(crc, HEX); Serial.print(" vs. 0x"); Serial.println(replybuffer[i * 3 + 2], HEX); #endif if (crc != replybuffer[i * 3 + 2]) return false; // success! store it readdata[i] = replybuffer[i*3]; readdata[i] <<= 8; readdata[i] |= replybuffer[i*3 + 1]; #ifdef I2C_DEBUG Serial.print("\t\tRead: 0x"); Serial.println(readdata[i], HEX); #endif } return true; } uint8_t Adafruit_SGP30::generateCRC(uint8_t *data, uint8_t datalen) { // calculates 8-Bit checksum with given polynomial uint8_t crc = SGP30_CRC8_INIT; for (uint8_t i=0; i<datalen; i++) { crc ^= data[i]; for (uint8_t b=0; b<8; b++) { if (crc & 0x80) crc = (crc << 1) ^ SGP30_CRC8_POLYNOMIAL; else crc <<= 1; } } return crc; }
[ "limor@ladyada.net" ]
limor@ladyada.net
4490353c42541fc5da6555ac1f7b6a1d374656e2
7f7ebd4118d60a08e4988f95a846d6f1c5fd8eda
/wxWidgets-2.9.1/include/wx/palmos/stattext.h
00ff0e28866adbc5da2d973d774bf75a2c65208f
[]
no_license
esrrhs/fuck-music-player
58656fc49d5d3ea6c34459630c42072bceac9570
97f5c541a8295644837ad864f4f47419fce91e5d
refs/heads/master
2021-05-16T02:34:59.827709
2021-05-10T09:48:22
2021-05-10T09:48:22
39,882,495
2
0
null
null
null
null
UTF-8
C++
false
false
1,730
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/palmos/stattext.h // Purpose: wxStaticText class // Author: William Osborne - minimal working wxPalmOS port // Modified by: Wlodzimierz ABX Skiba - native wxStaticText implementation // Created: 10/13/04 // RCS-ID: $Id$ // Copyright: (c) William Osborne, Wlodzimierz Skiba // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_STATTEXT_H_ #define _WX_STATTEXT_H_ class WXDLLIMPEXP_CORE wxStaticText : public wxStaticTextBase { public: wxStaticText() { } wxStaticText(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxStaticTextNameStr) { Create(parent, id, label, pos, size, style, name); } bool Create(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxStaticTextNameStr); // override some methods to resize the window properly virtual bool SetFont( const wxFont &font ); protected: // implement/override some base class virtuals virtual wxBorder GetDefaultBorder() const; virtual wxSize DoGetBestSize() const; DECLARE_DYNAMIC_CLASS_NO_COPY(wxStaticText) }; #endif // _WX_STATTEXT_H_
[ "esrrhs@esrrhs-PC" ]
esrrhs@esrrhs-PC
097a3e358def8251e2084cdf4d2755e737d5bbed
d2c3b5de367707f5049a478044e2e9bb1eafd7ea
/components/hub-wifi/wifi.cpp
ab3ac684c1227b0d6da552a031c2761a82b73ce3
[]
no_license
kazuph/home-iot-hub
56d871cc7f52d0ec7e48cc6458c85ba6f3e9523d
108ff4fc4973d1b0ef95be4861557a8dfab5777c
refs/heads/main
2023-08-28T19:34:57.932493
2021-10-21T06:15:15
2021-10-21T06:15:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,719
cpp
#include "wifi/wifi.hpp" #include <cstring> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_netif.h" #include "esp_event.h" #include "esp_log.h" #include "nvs.h" #include "nvs_flash.h" #include "lwip/err.h" #include "lwip/sys.h" namespace hub::wifi { constexpr const char* TAG { "hub::wifi" }; constexpr EventBits_t WIFI_CONNECTED_BIT { BIT0 }; static EventGroupHandle_t wifi_event_group; static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { esp_err_t result = ESP_OK; if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { result = esp_wifi_connect(); if (result != ESP_OK) { ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); } } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { result = esp_wifi_connect(); if (result != ESP_OK) { ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); } ESP_LOGI(TAG, "Disconnected, retrying..."); } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t* event = reinterpret_cast<ip_event_got_ip_t*>(event_data); ESP_LOGI(TAG, "Connected. IP: " IPSTR, IP2STR(&event->ip_info.ip)); if (wifi_event_group != nullptr) { xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT); } } } tl::expected<void, esp_err_t> connect(std::string_view ssid, std::string_view password, timing::duration_t timeout) noexcept { esp_err_t result = ESP_OK; wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT(); if (result = nvs_flash_init(); result != ESP_OK) { ESP_LOGE(TAG, "NVS flash initialization failed."); tl::expected<void, esp_err_t>(tl::unexpect, result); } if (result = esp_event_loop_create_default(); result != ESP_OK) { ESP_LOGE(TAG, "Default event loop creation failed."); goto cleanup_nvs; } if (wifi_event_group = xEventGroupCreate(); wifi_event_group == nullptr) { ESP_LOGE(TAG, "Could not create event group."); result = ESP_FAIL; goto cleanup_event_loop; } esp_netif_init(); esp_netif_create_default_wifi_sta(); if (result = esp_wifi_init(&wifi_init_config); result != ESP_OK) { ESP_LOGE(TAG, "Wi-Fi initialization failed with error code %x [%s].", result, esp_err_to_name(result)); return tl::expected<void, esp_err_t>(tl::unexpect, result); } if (result = esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_wifi_init; } if (result = esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } if (result = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } if (result = esp_wifi_set_mode(WIFI_MODE_STA); result != ESP_OK) { ESP_LOGE(TAG, "Setting WiFi mode failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } { wifi_config_t config{}; std::strcpy(reinterpret_cast<char*>(config.sta.ssid), ssid.data()); std::strcpy(reinterpret_cast<char*>(config.sta.password), password.data()); if (result = esp_wifi_set_config(static_cast<wifi_interface_t>(ESP_IF_WIFI_STA), &config); result != ESP_OK) { ESP_LOGE(TAG, "Setting WiFi configuration failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } } if (result = esp_wifi_start(); result != ESP_OK) { ESP_LOGE(TAG, "WiFi start failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } { EventBits_t bits = xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, pdTRUE, pdFALSE, static_cast<TickType_t>(timeout)); if (bits & WIFI_CONNECTED_BIT) { ESP_LOGI(TAG, "WiFi connected."); } else { result = ESP_ERR_TIMEOUT; ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_wifi_start; } } return tl::expected<void, esp_err_t>(); cleanup_wifi_start: esp_wifi_stop(); cleanup_event_handler_register: esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler); cleanup_wifi_init: esp_wifi_deinit(); cleanup_event_loop: esp_event_loop_delete_default(); cleanup_nvs: nvs_flash_deinit(); return tl::expected<void, esp_err_t>(tl::unexpect, result); } tl::expected<void, esp_err_t> disconnect() noexcept { esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler); esp_wifi_disconnect(); esp_wifi_stop(); esp_wifi_deinit(); vEventGroupDelete(wifi_event_group); esp_event_loop_delete_default(); nvs_flash_deinit(); return tl::expected<void, esp_err_t>(); } }
[ "borchy97@gmail.com" ]
borchy97@gmail.com
6abef3013c1b31aa18b5593f15a3738819df5168
17af777718e66d1735632c171e5286ff04c42665
/BOJ1236.cpp
5efecf26d8195006c4ff9ea3be089a08b2a50654
[]
no_license
girinssh/BOJ
4ddff350e309d85a153232062426f660e1144498
0964033e66081ecc81da6db421812ffb7f2eeacd
refs/heads/master
2023-07-14T19:08:52.364347
2021-08-17T09:11:24
2021-08-17T09:11:24
284,575,573
0
0
null
null
null
null
UTF-8
C++
false
false
914
cpp
#include <iostream> using namespace std; int main(void) { cin.tie(NULL); cin.sync_with_stdio(false); char arr[50][50] = { 0 }; int a, b; int n = 0, m = 0; cin >> a >> b; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { cin >> arr[i][j]; } } for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { if (arr[i][j] == 'X') { n++; break; } } } for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { if (arr[j][i] == 'X') { m++; break; } } } cout << (a - n > b - m ? a - n : b - m); return 0; } /* XXXXXXXXXXXXXXXXXXXX .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... */
[ "tngus5851@naver.com" ]
tngus5851@naver.com
434dd7416e82d5993450e88accdf19927bd427bf
8845158756cddf7368896a659fe13423d244c9a1
/Functions_Of_C/Exercises/multiple.cpp
50baec3de450bead4f217c9611c1051ca859c9b1
[]
no_license
Verg84/COOP
e0ef2cd478d0b669a95acdbf4b13f2e6dac20c3d
8cd1ec842ebc6729fc349e82f3f8ee3b87bac07a
refs/heads/main
2023-07-18T19:21:18.595563
2021-09-24T16:26:03
2021-09-24T16:26:03
405,047,236
0
0
null
2021-09-10T15:36:42
2021-09-10T10:47:56
C++
UTF-8
C++
false
false
533
cpp
// Multiple - Check if a pair of numbers // are multiple together #include<stdio.h> int multiple(int a,int b); int main(){ int a,b; printf("* Enter first value :"); scanf("%d",&a); printf("* Enter second value :"); scanf("%d",&b); if(multiple(a,b)) printf("\n\t\t * Multiples"); else printf("\n\t\t * Not multiples"); printf("\n\n"); return 0; } int multiple(int a,int b){ if(a%b==0) return 1; else return 0; }
[ "50481854+Verg84@users.noreply.github.com" ]
50481854+Verg84@users.noreply.github.com
c8fecf042797381cee307bb72ecefb44336b5726
05bd8b96db62137f8487e602a7b8a88f2a2c0fe4
/算法初步/二分/1085 Perfect Sequence (25分).cpp
5770e674459516978f3ddfd4c50050443cbf02e0
[]
no_license
PeiLeizzz/Algorithm-PAT-A
a8b71abeb26c4127f6ee6de166b3bfa5d0b3fb61
d1d58adb0b90e7a0fdd480e8e6d11a5de4272282
refs/heads/master
2022-12-23T14:47:50.912282
2020-08-28T12:31:57
2020-08-28T12:31:57
291,039,897
1
0
null
null
null
null
GB18030
C++
false
false
940
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<ll> numble; int main() { int n; ll p; scanf("%d %lld", &n, &p); for (int i = 0; i < n; i++) { ll a; scanf("%lld", &a); numble.push_back(a); } sort(numble.begin(), numble.end()); int len = 1; for (int i = 0; i < n && i + len < n; i++) { int left = i + 1; int right = n; // 查找区间 [left, right] // right 取 n 的原因:可能整个序列都满足条件,那么left 最多可以到 n // 即 len = n 符合条件 // 如果取 right = n - 1 需要单独判断 numble[n-1] > cmpNum ll cmpNum = numble[i] * p; // 寻找第一个 mid 使 numble[mid] > cmpNum while (left < right) { int mid = (left + right) / 2; if (numble[mid] > cmpNum) { // 区间:[left, mid] right = mid; } else { // 区间:[mid+1, right] left = mid + 1; } } len = max(len, left - i); } printf("%d", len); return 0; }
[ "714838284@qq.com" ]
714838284@qq.com
80039d48587c48ed44914c9a44b423385c59d8c2
1a29e2f587d88dac68dcdddac38ce9d7d450d058
/cs4499/midtern/bunny_generator.hpp
d1837d6f47dbd84f11e084e884a9139494e76e4a
[]
no_license
TheNumberOne/school_code
a41395e64dcc9089fb251fb2da0fa721161b5897
42d4aa7dc4bb1f23331382dc5875f261dc9e31c7
refs/heads/master
2020-08-08T11:52:50.008711
2019-10-09T05:07:47
2019-10-09T05:07:47
213,825,898
0
0
null
null
null
null
UTF-8
C++
false
false
690
hpp
#pragma once #include "bunny.hpp" #include <utility> #include <memory> /** * Randomly generates rabbits using the passed random number generator. */ class random_bunny_generator { public: explicit random_bunny_generator(std::shared_ptr<std::default_random_engine> rng) : _rng(std::move(rng)) { } /** * Creates a randomly generated bunny. */ bunny operator()(); /** * Creates a randomly generated bunny using the specified colors. Mostly used for when two rabbits have a child. */ bunny operator()(const std::vector<std::string> &colors); private: /** * Rng used */ std::shared_ptr<std::default_random_engine> _rng; };
[ "robepea2@isu.edu" ]
robepea2@isu.edu
dbddfeb9a35e8a81acf1614c7607c1414b91e835
2c104d39633cf440c33fa34d6c3516ceefb4bd39
/call_info.cpp
ef9980d994dccf10863876936bf98342a88d22e0
[]
no_license
chrisrteti/call_info
d45a0e7a85e419802b26a06dd57c5a547899d48b
71bd3fb3f63ab8f3817b6c273aa934f699c096ac
refs/heads/master
2020-04-17T03:49:58.010579
2016-09-03T12:54:15
2016-09-03T12:54:15
67,289,911
0
0
null
null
null
null
UTF-8
C++
false
false
5,293
cpp
/* Name: Christopher Teti Z#:23293126 Course: Foundations of Computer Science (COP3014) Professor: Dr. Lofton Bullard Due Date: 9/4/2016 Due Time:9/04/2016 Total Points: 100 Assignment 2: Description: In this assignment a program a call management system is implemented. The program used three functions: input, output, and process. The function input gets input from the user, the function process performs the necessary calculations, and the function output prints the results. *************************************************************************************************************************/ //Include the following #include <iostream> #include <string> using namespace std; //Prototypes for your functions: Input, Output, and Process will go here void Input(string & cell_number, int & relays, int & call_length); void Output(const string cell_number, const int relays, const int call_length, const double & net_cost, const double & call_tax, const double & total_cost_of_call); void Process(const int relays, const int call_length, double & net_cost, double & call_tax, double & total_cost_of_call, double & tax_rate); //Function Implementations will go here ///************************************************************************************* //Name: Input //Precondition: State what is true before the function is called. // Example: the varialbes (formal parameters) have not been initialized //Postcondition: State what is true after the function has executed. // Example: the varaibles (formal parameters) have been initialized //Description: // Example:Get input (values of cell_number, relays, and call_length) from the user. //PURPOSE: SHOW ME THAT YOU KNOW HOW TO READ INPUT AND USE INPUT (CALL BY VALUE) & OUTPUT (CALL BY VALUE) PARAMETERS //FORMAL PARAMETERS ARE: cell_number (string), relays (integer), call_length (integer) //************************************************************************************* void Input(string & cell_number, int & relays, int & call_length) // example of all formal parameter using the call by reference mechanism in C++ { cout << "Enter your Cell Phone Number: "; cin >> cell_number; cout << "Enter the number of relay stations: "; cin >> relays; cout << "Enter the length of the call in minutes: "; cin >> call_length; } ///************************************************************************************* //Name: Output //Precondition: State what is true before the function is called. //Postcondition: State what is true after the function has executed. //Description: Describe what the function does (purpose). //************************************************************************************* //NOTE: ALL FORMAL PARAMETERS ARE BEING PASSED BY VALUE. ALSO WE USED CONST TO MAKE SURE THEY WOULD NOT BE CHANGED BY MISTAKE // USED THE SAMPLE OUTPUT TO HELP YOU FORMAT YOU OUTPUT void Output(const string cell_number, const int relays, const int call_length, const double & net_cost, const double & call_tax, const double & total_cost_of_call) { //Use thee following statement to help you format you our output. These statements are called the magic formula. cout.setf(ios::showpoint); cout.precision(2); cout.setf(ios::fixed); cout << "the net cost is: " << net_cost << endl; cout << "the tax on the call is: " << call_tax << endl; cout << "the total cost comes to: " << total_cost_of_call << endl; /********************************************/ } ///************************************************************************************* //Name: Process //Precondition: The state what is true before the function is called. //Postcondition: State what is true after the function has executed. //Description: Describe what the function does (purpose). //************************************************************************************* //Note: there are 3 input parameter and 3 output parameters void Process(const int relays, const int call_length, double & net_cost, double & call_tax, double & total_cost_of_call, double & tax_rate){ //this is an example of a stub net_cost = relays / 50.0 * .40 * call_length; if ((relays >= 1) && (relays <= 5)) { tax_rate = 1.00; } else if ((relays >= 6) && (relays <= 11)) { tax_rate = 3.00; } else if ((relays >= 12) && (relays <= 20)) { tax_rate = 5.00; } else if ((relays >= 21) && (relays <= 50)) { tax_rate = 8.00; } else { tax_rate = 12.00; } call_tax = (net_cost * tax_rate) / 100; total_cost_of_call = net_cost + call_tax; } //Here is your driver to test the program int main() { string user_response = "y"; string cell_number; int relays; int call_length; double net_cost; double call_tax; double total_cost_of_call; double tax_rate; while (user_response == "y" || user_response == "Y") { Input(cell_number, relays, call_length); Process(relays, call_length, net_cost, call_tax, total_cost_of_call, tax_rate); Output(cell_number, relays, call_length, net_cost, call_tax, total_cost_of_call); cout << "Would you like to do another calculation (Y or N): " << endl; cin >> user_response; } return 0; }
[ "noreply@github.com" ]
chrisrteti.noreply@github.com
9615bbd1404b28e543a3d82d69d5efdda71028c9
06e3a51780fe6906a8713b7e274a35c0d89d2506
/qtmdsrv/ui/ringbufferform.cpp
d1747adf391cf8b30fffc927844d205b265e9c8a
[]
no_license
ssh352/qtctp-1
d91fc8d432cd93019b23e7e29f40b41b1493aceb
248d09e629b09cbe1adbf7cd818679721bf156d0
refs/heads/master
2020-04-01T16:55:31.012740
2015-10-27T15:56:02
2015-10-27T15:56:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,065
cpp
#include "ringbufferform.h" #include "ui_ringbufferform.h" #include "mdsm.h" #include "ApiStruct.h" #include "ringbuffer.h" #include "servicemgr.h" #include "ctpmgr.h" #include "datapump.h" #include "historyform.h" RingBufferForm::RingBufferForm(QWidget* parent) : QWidget(parent) , ui(new Ui::RingBufferForm) { ui->setupUi(this); //设置列= instruments_col_ = { "TradingDay", "UpdateTime", "UpdateMillisec", "LastPrice", "Volume", "OpenInterest", "BidPrice1", "BidVolume1", "AskPrice1", "AskVolume1" }; this->ui->tableWidget->setColumnCount(instruments_col_.length()); for (int i = 0; i < instruments_col_.length(); i++) { ui->tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(instruments_col_.at(i))); } } RingBufferForm::~RingBufferForm() { delete ui; } void RingBufferForm::init(QString id) { id_ = id; this->setWindowTitle(QString("ringbuffer-")+id); scanTicks(); } void RingBufferForm::scanTicks() { DataPump* datapump = g_sm->dataPump(); if(!datapump){ return; } ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); RingBuffer* rb = datapump->getRingBuffer(id_); int head = rb->head(); if (head < 0) { return; } for (int i = 0; i < rb->count() / 2; i++) { void* p = rb->get(head); if (p == nullptr) { return; } onGotTick(p); head -= 1; if (head == -1) { head += rb->count(); } } } void RingBufferForm::onGotTick(void* tick) { auto mdf = (DepthMarketDataField*)tick; QVariantMap mdItem; mdItem.insert("TradingDay", mdf->TradingDay); mdItem.insert("UpdateTime", mdf->UpdateTime); mdItem.insert("UpdateMillisec", mdf->UpdateMillisec); mdItem.insert("LastPrice", mdf->LastPrice); mdItem.insert("Volume", mdf->Volume); mdItem.insert("OpenInterest", mdf->OpenInterest); mdItem.insert("BidPrice1", mdf->BidPrice1); mdItem.insert("BidVolume1", mdf->BidVolume1); mdItem.insert("AskPrice1", mdf->AskPrice1); mdItem.insert("AskVolume1", mdf->AskVolume1); //根据id找到对应的行,然后用列的text来在map里面取值设置到item里面= int row = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(row); for (int i = 0; i < instruments_col_.count(); i++) { QVariant raw_val = mdItem.value(instruments_col_.at(i)); QString str_val = raw_val.toString(); if (raw_val.type() == QMetaType::Double || raw_val.type() == QMetaType::Float) { str_val = QString().sprintf("%6.1f", raw_val.toDouble()); } QTableWidgetItem* item = new QTableWidgetItem(str_val); ui->tableWidget->setItem(row, i, item); } } void RingBufferForm::on_historyButton_clicked() { HistoryForm* form = new HistoryForm(); form->setWindowFlags(Qt::Window); form->init(id_,g_sm->dataPump()->getTodayDB(),false); form->show(); } void RingBufferForm::on_refreshButton_clicked() { scanTicks(); }
[ "sunwangme@gmail.com" ]
sunwangme@gmail.com
e34850a83c2a437b0050b2ed8021b5a8d7f3474f
d23d36fd5b4e6851fef68940b15ed625677a576b
/作业6-3/作业6-3/作业6-3Doc.cpp
969c9abd145439c48a9d8fe1f7a6e72f9907f682
[]
no_license
DJQ0926/test
0d5fd731edef513e08b1169578e70fe9139d7d05
e9a755ac66750e14bbb870d211531d91a92fc2ee
refs/heads/master
2021-02-15T23:03:21.681207
2020-07-05T09:51:20
2020-07-05T09:51:20
244,942,227
0
0
null
null
null
null
GB18030
C++
false
false
2,576
cpp
// 作业6-3Doc.cpp : C作业63Doc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "作业6-3.h" #endif #include "作业6-3Doc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // C作业63Doc IMPLEMENT_DYNCREATE(C作业63Doc, CDocument) BEGIN_MESSAGE_MAP(C作业63Doc, CDocument) END_MESSAGE_MAP() // C作业63Doc 构造/析构 C作业63Doc::C作业63Doc() { // TODO: 在此添加一次性构造代码 } C作业63Doc::~C作业63Doc() { } BOOL C作业63Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // C作业63Doc 序列化 void C作业63Doc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } } #ifdef SHARED_HANDLERS // 缩略图的支持 void C作业63Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void C作业63Doc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void C作业63Doc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // C作业63Doc 诊断 #ifdef _DEBUG void C作业63Doc::AssertValid() const { CDocument::AssertValid(); } void C作业63Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // C作业63Doc 命令
[ "964158009@qq.com" ]
964158009@qq.com
e801316a8a1504c3980d6f4df705e94be1506057
4a769d01e49f4dbc24bc7715cb0d1f269e86f697
/functions.h
6e560452b9cd9af4976486a8101561b1648e0466
[]
no_license
BaylorGroup-CSI-1430/MarioProject
31e1b13bbea9b63bef16bd9b0bd7e9f7fc9f5b15
82bc17e809f619fe1d8c829e68eabf3e31f6f160
refs/heads/master
2020-04-06T12:45:31.980976
2018-12-03T03:53:39
2018-12-03T03:53:39
157,469,423
0
1
null
null
null
null
UTF-8
C++
false
false
20,351
h
/*This source code copyrighted by Lazy Foo' Productions (2004-2015) and may not be redistributed without written permission.*/ //Using SDL, SDL_image, standard IO, and strings #include <SDL.h> #include <SDL_image.h> #include <stdio.h> #include <string> //#include "SDL_Plotter.h" //using namespace std; //Screen dimension constants const int SCREEN_WIDTH = 1000; const int SCREEN_HEIGHT = 1000; const int JUMPSTEPS = 2; const int JUMPHEIGHT = 80; const int JUMPWIDTH = 40; const int JUMPDELAY = 100; //Current animation frame int frame = 0; bool doneflipping = false; SDL_Texture* bannerTexture; //The window we'll be rendering to SDL_Window* gWindow = NULL; //SDL_Surface* gScreenSurface = NULL; SDL_Surface* gbannerSurface = NULL; //The window renderer SDL_Renderer* gRenderer = NULL; SDL_Texture* gTexture = NULL; //Walking animation const int WALKING_ANIMATION_FRAMES = 6; SDL_Rect gSpriteClips[ WALKING_ANIMATION_FRAMES ]; SDL_Rect gBannerClips[ 9 ]; class LTexture { public: //Initializes variables LTexture(); //Deallocates memory ~LTexture(); //Loads image at specified path bool loadFromFile( std::string path ); #ifdef _SDL_TTF_H //Creates image from font string bool loadFromRenderedText( std::string textureText, SDL_Color textColor ); #endif //Deallocates texture void free(); //Set color modulation void setColor( Uint8 red, Uint8 green, Uint8 blue ); //Set blending void setBlendMode( SDL_BlendMode blending ); //Set alpha modulation void setAlpha( Uint8 alpha ); //Renders texture at given point void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE ); //Gets image dimensions int getWidth(); int getHeight(); private: //The actual hardware texture SDL_Texture* mTexture; //Image dimensions int mWidth; int mHeight; }; //The dot that will move around on the screen class Mario { public: //The dimensions of the dot static const int DOT_WIDTH = 24; static const int DOT_HEIGHT = 32; //Maximum axis velocity of the dot static const int DOT_VEL = 10; //Initializes the variables Mario(); //Takes key presses and adjusts the dot's velocity void handleEvent( SDL_Event& e ); //Moves the dot and checks collision void move(); // SDL_Rect& wall ); void jump(int j); // SDL_Rect& wall ); // //Shows the dot on the screen // void render(SDL_Rect* passClip); //Renders texture at given point void render(SDL_Rect* passClip, LTexture &mRenderTexture); //Gets image dimensions int getWidth(); int getHeight(); private: //The X and Y offsets of the dot int mPosX, mPosY; //The velocity of the dot int mVelX, mVelY; //Dot's collision box SDL_Rect mCollider; SDL_RendererFlip flipType = SDL_FLIP_NONE; bool xdir = 1; // int j; }; //Starts up SDL and creates window bool init(); //Loads media bool loadMedia(); //Frees media and shuts down SDL void close(); void loadmario(); //Box collision detector bool checkCollision( SDL_Rect a, SDL_Rect b ); LTexture::LTexture() { //Initialize mTexture = NULL; mWidth = 0; mHeight = 0; } LTexture::~LTexture() { //Deallocate free(); } bool LTexture::loadFromFile( std::string path ) { //Get rid of preexisting texture free(); //The final texture SDL_Texture* newTexture = NULL; //Load image at specified path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); if( loadedSurface == NULL ) { printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() ); } else { //Color key image SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0, 0 ) ); //0, 0xFF, 0xFF ) ); //Create texture from surface pixels newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface ); if( newTexture == NULL ) { printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() ); } else { //Get image dimensions mWidth = loadedSurface->w; mHeight = loadedSurface->h; } //Get rid of old loaded surface SDL_FreeSurface( loadedSurface ); } //Return success mTexture = newTexture; // bannerTexture = newTexture; return mTexture != NULL; } #ifdef _SDL_TTF_H bool LTexture::loadFromRenderedText( std::string textureText, SDL_Color textColor ) { //Get rid of preexisting texture free(); //Render text surface SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor ); if( textSurface != NULL ) { //Create texture from surface pixels mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface ); if( mTexture == NULL ) { printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() ); } else { //Get image dimensions mWidth = textSurface->w; mHeight = textSurface->h; } //Get rid of old surface SDL_FreeSurface( textSurface ); } else { printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() ); } //Return success return mTexture != NULL; } #endif void LTexture::free() { //Free texture if it exists if( mTexture != NULL ) { SDL_DestroyTexture( mTexture ); mTexture = NULL; mWidth = 0; mHeight = 0; } } void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue ) { //Modulate texture rgb SDL_SetTextureColorMod( mTexture, red, green, blue ); } void LTexture::setBlendMode( SDL_BlendMode blending ) { //Set blending function SDL_SetTextureBlendMode( mTexture, blending ); } void LTexture::setAlpha( Uint8 alpha ) { //Modulate texture alpha SDL_SetTextureAlphaMod( mTexture, alpha ); } void LTexture::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip ) { //Set rendering space and render to screen SDL_Rect renderQuad = { x, y, mWidth, mHeight }; //Set clip rendering dimensions if( clip != NULL ) { renderQuad.w = clip->w; renderQuad.h = clip->h; } //Render to screen SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip ); } int LTexture::getWidth() { return mWidth; } int LTexture::getHeight() { return mHeight; } Mario::Mario() { //Initialize the offsets mPosX = 80; mPosY = 400; //Set collision box dimension mCollider.w = DOT_WIDTH; mCollider.h = DOT_HEIGHT; //Initialize the velocity mVelX = 0; mVelY = 0; flipType = SDL_FLIP_NONE; } void Mario::handleEvent( SDL_Event& e ) { //If a key was pressed if( e.type == SDL_KEYDOWN && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mVelY -= DOT_VEL; break; case SDLK_DOWN: mVelY += DOT_VEL; break; case SDLK_LEFT: mVelX -= DOT_VEL; xdir = 0; flipType = SDL_FLIP_NONE; break; case SDLK_RIGHT: mVelX += DOT_VEL; xdir = 1; flipType = SDL_FLIP_HORIZONTAL; break; } //Go to next frame ++frame; //Cycle animation if( frame >= WALKING_ANIMATION_FRAMES - 1) { frame = 0; } } //If a key was released else if( e.type == SDL_KEYUP && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mVelY += DOT_VEL; break; case SDLK_DOWN: mVelY -= DOT_VEL; break; case SDLK_LEFT: mVelX += DOT_VEL; break; case SDLK_RIGHT: mVelX -= DOT_VEL; break; } frame = 0; } } void Mario::move( ) //SDL_Rect& wall ) { //Move the dot left or right mPosX += mVelX; mCollider.x = mPosX; //If the dot collided or went too far to the left or right if( ( mPosX < 0 ) || ( mPosX + DOT_WIDTH > SCREEN_WIDTH ) ) //|| checkCollision( mCollider, wall ) ) { //Move back mPosX -= mVelX; mCollider.x = mPosX; } //Move the dot up or down mPosY += mVelY; mCollider.y = mPosY; //If the dot collided or went too far up or down if( ( mPosY < 0 ) || ( mPosY + DOT_HEIGHT > SCREEN_HEIGHT ) ) //|| checkCollision( mCollider, wall ) ) { //Move back mPosY -= mVelY; mCollider.y = mPosY; } } void Mario::jump(int j) { if (xdir == 1 && (mPosX + DOT_WIDTH < SCREEN_WIDTH)) { mPosX += DOT_VEL / JUMPSTEPS; } if (xdir == 0 && (mPosX - DOT_WIDTH > 0)) { mPosX -= DOT_VEL / JUMPSTEPS; } if (j < JUMPSTEPS / 2 ) { mPosY -= JUMPHEIGHT; } if (j>=JUMPSTEPS / 2) { mPosY += JUMPHEIGHT; } } void Mario::render(SDL_Rect* passClip, LTexture &mRenderTexture) { //Show the dot // gDotTexture.render( mPosX, mPosY ); mRenderTexture.render( mPosX, mPosY, passClip, NULL, NULL, flipType); } bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Set texture filtering to linear if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) ) { printf( "Warning: Linear texture filtering not enabled!" ); } //Create window gWindow = SDL_CreateWindow( "MARIO BROS.", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create vsynced renderer for window gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if( gRenderer == NULL ) { printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Initialize renderer color SDL_SetRenderDrawColor( gRenderer, 0, 0, 0, 0 ); //0xFF, 0xFF, 0xFF, 0xFF ); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if( !( IMG_Init( imgFlags ) & imgFlags ) ) { printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() ); success = false; } } } } return success; } bool loadMedia(LTexture& gLoadSheetTexture) { //Loading success flag bool success = true; // int index; //Load sprite sheet texture if( !gLoadSheetTexture.loadFromFile( "/Users/luisc/Xcode Projects/Game3/mb_spritesheet.png" ) ) { printf( "Failed to load walking animation texture!\n" ); success = false; } else { //Set sprite No1: Mario_Stand gSpriteClips[ 0 ].x = 3; gSpriteClips[ 0 ].y = 602; gSpriteClips[ 0 ].w = 16; gSpriteClips[ 0 ].h = 21; //SSet sprite No2: Mario_Walk_1 gSpriteClips[ 1 ].x = 22; gSpriteClips[ 1 ].y = 602; gSpriteClips[ 1 ].w = 13; //26 gSpriteClips[ 1 ].h = 21; //Set sprite No3: Mario_Walk_2 gSpriteClips[ 2 ].x = 36; gSpriteClips[ 2 ].y = 602; gSpriteClips[ 2 ].w = 14; gSpriteClips[ 2 ].h = 21; //Set sprite No4:Mario_Walk_3 gSpriteClips[ 3 ].x = 54; gSpriteClips[ 3 ].y = 602; gSpriteClips[ 3 ].w = 14; gSpriteClips[ 3 ].h = 21; //Set sprite No5:Mario_Jump gSpriteClips[ 4 ].x = 93; gSpriteClips[ 4 ].y = 602; gSpriteClips[ 4 ].w = 15; gSpriteClips[ 4 ].h = 21; //Set sprite No5:Mario_Jump gSpriteClips[ 5 ].x = 0; gSpriteClips[ 5 ].y = 0; gSpriteClips[ 5 ].w = 208; gSpriteClips[ 5 ].h = 87; } return success; } void close(LTexture gCloseSheetTexture) { //Free loaded images gCloseSheetTexture.free(); //Destroy window SDL_DestroyRenderer( gRenderer ); SDL_DestroyWindow( gWindow ); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems IMG_Quit(); SDL_Quit(); } bool checkCollision( SDL_Rect a, SDL_Rect b ) { //The sides of the rectangles int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; //Calculate the sides of rect A leftA = a.x; rightA = a.x + a.w; topA = a.y; bottomA = a.y + a.h; //Calculate the sides of rect B leftB = b.x; rightB = b.x + b.w; topB = b.y; bottomB = b.y + b.h; //If any of the sides from A are outside of B if( bottomA <= topB ) { return false; } if( topA >= bottomB ) { return false; } if( rightA <= leftB ) { return false; } if( leftA >= rightB ) { return false; } //If none of the sides from A are outside B return true; } void loadmario( ) //int argc, char* args[] ) { //Scene textures LTexture gBannerTexture; LTexture gSpriteSheetTexture; //Start up SDL and create window // if( !init() ) // { // printf( "Failed to initialize!\n" ); // } // else // { //Load media if( !loadMedia(gSpriteSheetTexture) ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //The dot that will be moving around on the screen // Mario mario; // //Event handler // SDL_Event e; // // SDL_SetRenderDrawColor( gRenderer, 0, 0, 0, 0 ); // SDL_RenderClear( gRenderer ); // // //Render to screen // SDL_Rect* bannerClip = &gSpriteClips[ 5 ]; // SDL_Rect wall; // wall.x = 216; // wall.y = - 220; // wall.w = 208; // wall.h = 87; //// int bannerstep = 0; // gbannerSurface = IMG_Load( "/Users/luisc/Xcode Projects/Game3/banner.png" ); // bannerTexture = SDL_CreateTextureFromSurface(gRenderer, gbannerSurface); // SDL_FreeSurface(gbannerSurface); /* we got the texture now -> free surface */ // wall.x = 216; // wall.y = 200; // SDL_RenderCopyEx( gRenderer, bannerTexture, bannerClip, &wall, NULL, NULL, SDL_FLIP_NONE ); // SDL_RenderDrawRect( gRenderer, &wall ); // // // SDL_SetRenderDrawColor( gRenderer, 0x00, 0x00, 0xFF, 0xFF ); // // SDL_RenderDrawRect( gRenderer, &wall ); // // // // //While application is running // while( !quit ) // { // //Handle events on queue // while( SDL_PollEvent( &e ) != 0 ) // { // //User requests quit // if( e.type == SDL_QUIT ) // { // quit = true; // } // // //Handle input for the dot // mario.handleEvent( e ); // // // } // // SDL_SetRenderDrawColor( gRenderer, 0, 0, 0, 0 ); // SDL_RenderClear( gRenderer ); // //Render current frame // SDL_Rect* currentClip = &gSpriteClips[ frame / 3 ]; // mario.render(currentClip, gSpriteSheetTexture); // // // // if (e.key.keysym.sym == SDLK_SPACE) // { // int i; // for(i = 0;i < JUMPSTEPS ;i++) // { // mario.jump(i); // if (i == JUMPSTEPS -1) // { // frame = 0; // } // else // { // frame = 4; // } // SDL_Rect* currentClip = &gSpriteClips[ frame ]; // mario.render(currentClip, gSpriteSheetTexture); // SDL_RenderPresent( gRenderer ); // SDL_Delay( JUMPDELAY ); // //Clear screen // SDL_SetRenderDrawColor( gRenderer, 0, 0, 0, 0 ); // SDL_RenderClear( gRenderer ); // // } // e.key.keysym.sym = NULL; // // } // else // { // mario.move(); // // // if (bannerstep < 400) // { // wall.y = -200+bannerstep; // //Clear screen // // SDL_RenderCopyEx( gRenderer, bannerTexture, bannerClip, &wall, NULL, NULL, SDL_FLIP_VERTICAL ); // //Update screen //// SDL_RenderPresent( gRenderer ); // bannerstep += 10; // SDL_Delay(50); // // } // else if (!doneflipping) // { // wall.x = 216; // wall.y = 200; // SDL_RenderCopyEx( gRenderer, bannerTexture, bannerClip, &wall, NULL, NULL, SDL_FLIP_VERTICAL ); // } // else // { // wall.x = 216; // wall.y = 200; // SDL_RenderCopyEx( gRenderer, bannerTexture, bannerClip, &wall, NULL, NULL, SDL_FLIP_NONE ); // // } // //Render current frame // SDL_Rect* currentClip = &gSpriteClips[ frame / 3 ]; // mario.render(currentClip, gSpriteSheetTexture); // // // //Update screen // SDL_RenderPresent( gRenderer ); // // } // } // } } //Free resources and close SDL // close(gSpriteSheetTexture); return; // 0; } //void plotmario() //{ // int x, int y, int r, int g, int b; // int xd; // int yd; // int i; // // for (i = 1; i < (24); i++) // { // for (j = 1; j < 34; j++) // { // g.plotPixel(x + xd, y + yd, R, G, B); // } //gSpriteClips[ 5 ] //}
[ "noreply@github.com" ]
BaylorGroup-CSI-1430.noreply@github.com
428be9e5a38ec5cd79b1901360613480d9f6f32e
0fa5fc9365c65eb5ac7c48c16e9feee199d1ff0a
/arduino/cocktailmaschine/cocktailmaschine.ino
2190ead73f234d8d8ce7318693f6552031c9abc4
[]
no_license
tobiwe/cocktailmachine
51f6d9d484d2844da603169304be42a939a2a5d4
0881025acffd6275b4ad3eea1c8ebd5556e54f67
refs/heads/main
2023-07-13T23:29:47.614353
2021-08-26T12:22:11
2021-08-26T12:22:11
332,493,284
1
0
null
null
null
null
UTF-8
C++
false
false
11,696
ino
#include "Waage.hpp" #include "pumpe.hpp" #include "Luftpumpe.hpp" #include "Led.hpp" #include "Ventil.hpp" #include "Drucksensor.hpp" #include "config.hpp" int peristalicLed[6] = { 5, 4, 3, 2, 1, 0}; int airLed[4] = { 13, 12, 15, 14}; int bottleLed[6] = {6, 7, 8, 9, 10, 11}; int glasLed = 16; char newCommand[20]; char command[20]; int program = 0; int old = 0; char oldCommand[20]; int zaehler = 0; bool newSerialEvent = false; bool switchtoOldProgram = false; Waage waage; Led ledstripe; Ventil ventile[4] = { Ventil(VENTIL1), Ventil(VENTIL2), Ventil(VENTIL3), Ventil(VENTIL4) }; Drucksensor sensoren[4] = { Drucksensor(DRUCK1), Drucksensor(DRUCK2), Drucksensor(DRUCK3), Drucksensor(DRUCK4), }; Pumpe p1(PERISTALIC, MOTOR1_In1, MOTOR1_In2, MOTOR1_En, peristalicLed[0], bottleLed[0], false); Pumpe p2(PERISTALIC, MOTOR2_In1, MOTOR2_In2, MOTOR2_En, peristalicLed[1], bottleLed[1], false); Pumpe p3(PERISTALIC, MOTOR3_In1, MOTOR3_In2, MOTOR3_En, peristalicLed[2], bottleLed[2], true); Pumpe p4(PERISTALIC, MOTOR4_In1, MOTOR4_In2, MOTOR4_En, peristalicLed[3], bottleLed[3], true); Pumpe p5(PERISTALIC, MOTOR5_In1, MOTOR5_In2, MOTOR5_En, peristalicLed[4], bottleLed[4], false); Pumpe p6(PERISTALIC, MOTOR6_In1, MOTOR6_In2, MOTOR6_En, peristalicLed[5], bottleLed[5], true); Luftpumpe a1(AIR, MOTOR7_In1, MOTOR7_In2, MOTOR7_En, airLed[0], airLed[0], ventile[0], &(sensoren[0]), false); Luftpumpe a2(AIR, MOTOR8_In1, MOTOR8_In2, MOTOR8_En, airLed[1], airLed[1], ventile[1], &(sensoren[1]), false); Luftpumpe a3(AIR, MOTOR9_In1, MOTOR9_In2, MOTOR9_En, airLed[2], airLed[2], ventile[2], &(sensoren[2]), false); Luftpumpe a4(AIR, MOTOR10_In1, MOTOR10_In2, MOTOR10_En, airLed[3], airLed[3], ventile[3], &(sensoren[3]), false); Pumpe *pumpen[10] = {&p1, &p2, &p3, &p4, &p5, &p6, &a1, &a2, &a3, &a4}; void setup() { Serial.begin(BAUDRATE); waage.setup(); for (Pumpe *p : pumpen) { p->setup(); if (p->getType() == PERISTALIC) { p->setSpeed(255); } } a1.setSpeed(150); a2.setSpeed(150); a3.setSpeed(150); a4.setSpeed(150); for (Ventil v : ventile) { v.setup(); v.open(); } delay(1000); for (Ventil v : ventile) { v.setup(); v.close(); } for (int i = 0; i < 4; i++) { sensoren[i].update(); sensoren[i].setDefaultPressure(sensoren[i].getValue()); } ledstripe.setup(); } void loop() { for (int i = 0; i < 4; i++) { sensoren[i].update(); } waage.update(); checkForSerialEvent(); if (newSerialEvent) { old = program; memcpy(oldCommand, command, sizeof(command)); memcpy(command, newCommand, sizeof(newCommand)); program = getValue(command, ' ', 0); newSerialEvent = false; /** Debug Serial.print("Old: "); Serial.print(old); Serial.print(", "); Serial.print("Buffer"); Serial.println(oldCommand); Serial.print("New: "); Serial.print(program); Serial.print(", "); Serial.print("Buffer"); Serial.println(command);*/ } float amount, mass; int motor, motorSpeed, ventil, state, pumpe, ledShow, wait, r, g, b, sub, cmd, pressure; switch (program) { case 1: cmd = getValue(command, ' ', 1); if (cmd == 1) { ledstripe.setLed(getValue(command, ' ', 2), strip.Color(getValue(command, ' ', 3), getValue(command, ' ', 4), getValue(command, ' ', 5))); } else if (cmd == 2) { ledstripe.fillLed(strip.Color(getValue(command, ' ', 2), getValue(command, ' ', 3), getValue(command, ' ', 4))); } program = 0; break; case 2: motor = getValue(command, ' ', 1); motorSpeed = getValue(command, ' ', 2); if (motorSpeed == 0) { pumpen[motor]->stop(); } else if (motorSpeed > 0) { pumpen[motor]->setSpeed(motorSpeed); pumpen[motor]->forward(); } else if (motorSpeed < 0) { pumpen[motor]->setSpeed(-1 * motorSpeed); pumpen[motor]->backward(); } program = 0; break; case 3: ventil = getValue(command, ' ', 1); state = getValue(command, ' ', 2); if (state == 1)ventile[ventil].open(); else if (state == 0) ventile[ventil].close(); program = 0; break; case 4: pumpe = getValue(command, ' ', 1); amount = getValue(command, ' ', 2); fillGlas(pumpen[pumpe - 1], amount); program = 0; break; case 5: sub = getValue(command, ' ', 1); if (sub == 1) { Serial.write(0x02); Serial.print(waage.getValue()); Serial.write(0x03); } else if (sub == 2) { waage.tare(); } else if (sub == 3) { mass = getValue(command, ' ', 2); waage.calibrate(mass); } else if (sub == 4) { waage.calibrate(); } switchtoOldProgram = true; break; case 6: ledShow = getValue(command, ' ', 1); if (ledShow == 1) { wait = getValue(command, ' ', 2); ledstripe.fasterRainbow(wait); } else if (ledShow == 2) { wait = getValue(command, ' ', 2); ledstripe.fasterTheaterChaseRainbow(wait); } else if (ledShow == 3) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.theaterChase(strip.Color(r, g, b), wait); } else if (ledShow == 4) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.colorWipe(strip.Color(r, g, b), wait); } else if (ledShow == 5) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.fasterBlinkOnOff(strip.Color(r, g, b), wait); } break; case 7: pressure = getValue(command, ' ', 1); Serial.write(0x02); Serial.print(sensoren[pressure].getValue()); Serial.write(0x03); program = 0; break; default: //do nothing break; } if (program != 6) { delay(50); } else { delay(1); } if (switchtoOldProgram) { //Toggle Program int tmp = old; old = program; program = tmp; //Toggle Commands char tmpCommand[20];; memcpy(tmpCommand, command, sizeof(command)); memcpy(command, oldCommand, sizeof(oldCommand)); memcpy(oldCommand, tmpCommand, sizeof(tmpCommand)); switchtoOldProgram = false; } } float getValue(String data, char separator, int index) { int found = 0; int strIndex[] = { 0, -1 }; int maxIndex = data.length() - 1; for (int i = 0; i <= maxIndex && found <= index; i++) { if (data.charAt(i) == separator || i == maxIndex) { found++; strIndex[0] = strIndex[1] + 1; strIndex[1] = (i == maxIndex) ? i + 1 : i; } } String sub = data.substring(strIndex[0], strIndex[1]); return found > index ? sub.toFloat() : 0; } void fillGlas(Pumpe *pumpe, float amount) { delay(100); long startTime = millis(); long lastTime = startTime; long lastSpeedCheck = startTime; float loadCell = waage.getValue(); float oldSpeedWeight = loadCell; float oldValue = loadCell; float oldPressure = 0; bool finished = false; bool refill = false; float startValue = loadCell; float goalValue = startValue + amount; bool interrupt = false; Drucksensor *sensor = nullptr; if (pumpe->getType() == AIR) { sensor = ((Luftpumpe*)pumpe)->sensor; oldPressure = sensor->getValue(); } int interval = 6000; int maxInterval = 10000; while (loadCell < goalValue) { ledstripe.fillLed(strip.Color(0, 0, 0)); waage.update(); if (pumpe->getType() == AIR) { sensor->update(); }; loadCell = waage.getValue(); pumpe->forward(); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 255)); ledstripe.setLed(glasLed, strip.Color(0, 0, 255)); long actualTime = millis(); bool updateInterval = false; if (actualTime - lastTime >= interval) { if (pumpe->getType() == AIR) { if (oldPressure + 0.2 > sensor->getValue() && oldValue + 1 > loadCell) { refill = true; } } else if (oldValue + 1 > loadCell) { refill = true; } lastTime = actualTime; interval = 1000; oldValue = loadCell; oldPressure = sensor->getValue(); } // Flow per time check for speed optimization if (pumpe->getType() == AIR) { if (actualTime - lastSpeedCheck >= 1000 && loadCell > oldValue) { int actualSpeed = pumpe->getSpeed(); int change = loadCell - oldSpeedWeight; //Check for 10g if (change < 15 && actualSpeed < 200) { pumpe->setSpeed(actualSpeed += 5); } else if (change > 5 && actualSpeed > 100) { pumpe->setSpeed(actualSpeed -= 5); } lastSpeedCheck = actualTime; oldSpeedWeight = loadCell; } } if (refill) { pumpe->stop(false); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 0)); ledstripe.setLed(glasLed, strip.Color(0, 0, 0)); Serial.write(0x02); Serial.print("refill"); Serial.write(0x03); interval = 5000; while (refill) { //Blink here ledstripe.setLed(pumpe->bottleLed, strip.Color(255, 0, 0)); for (int i : peristalicLed) { ledstripe.setLed(i, strip.Color(255, 0, 0)); } delay(250); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 0)); for (int i : peristalicLed) { ledstripe.setLed(i, strip.Color(0, 0, 0)); } delay(250); if (Serial.available()) { String test = Serial.readString(); if (test == "done\n") { refill = false; } } } startTime = millis(); lastTime = startTime; } if (loadCell >= goalValue) { finished = true; } if (Serial.available()) { String test = Serial.readString(); if (test == "interrupt\n") { finished = true; break; } } } if (finished) { pumpe->stop(false); if (pumpe->getType() == AIR) { Luftpumpe* air = (Luftpumpe*)pumpe; air->ventil.open(); } ledstripe.fillLed(strip.Color(255, 255, 255)); //Wait till weight stays the same bool valueChange = true; float first, second; while (valueChange) { first = waage.getValue(); long startTime = millis(); while (millis() - startTime < 2000) { waage.update(); delay(10); } second = waage.getValue(); if ((second - first) < 0.1) { valueChange = false; if (pumpe->getType() == AIR) { Luftpumpe* air = (Luftpumpe*)pumpe; air->ventil.close(); } } } Serial.write(0x02); Serial.print("finish"); Serial.write(0x03); finished = false; delay(100); } } void checkForSerialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); if (inChar == 0x02) { zaehler = 0; } else if (inChar == 0x03) { newSerialEvent = true; newCommand[zaehler] = '\0'; break; } else { newCommand[zaehler] = inChar; zaehler++; } } }
[ "pebble@towan.de" ]
pebble@towan.de
640f9115446c596ca507fe9aba2d705540971961
efb3753829a06413a4411a4753c547eec11e4c40
/src/libzerocoin/Params.h
1a0ea842c8d7c8e706365160d613f03588b48ac0
[ "MIT" ]
permissive
BitHostCoin/BitHost
69c6471b150104fc1147ca7541274bba546647c8
cd83067acbe16cffa16ab0f752e6da05136c783a
refs/heads/master
2020-04-01T19:55:33.954484
2019-02-22T15:43:29
2019-02-22T15:43:29
153,578,694
4
6
MIT
2019-05-21T21:23:34
2018-10-18T07:06:13
C++
UTF-8
C++
false
false
6,097
h
/** * @file Params.h * * @brief Parameter classes for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017 The Bithost developers #ifndef PARAMS_H_ #define PARAMS_H_ #include "bignum.h" #include "ZerocoinDefines.h" namespace libzerocoin { class IntegerGroupParams { public: /** @brief Integer group class, default constructor * * Allocates an empty (uninitialized) set of parameters. **/ IntegerGroupParams(); /** * Generates a random group element * @return a random element in the group. */ CBigNum randomElement() const; bool initialized; /** * A generator for the group. */ CBigNum g; /** * A second generator for the group. * Note log_g(h) and log_h(g) must * be unknown. */ CBigNum h; /** * The modulus for the group. */ CBigNum modulus; /** * The order of the group */ CBigNum groupOrder; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(g); READWRITE(h); READWRITE(modulus); READWRITE(groupOrder); } }; class AccumulatorAndProofParams { public: /** @brief Construct a set of Zerocoin parameters from a modulus "N". * @param N A trusted RSA modulus * @param securityLevel A security level expressed in symmetric bits (default 80) * * Allocates and derives a set of Zerocoin parameters from * a trustworthy RSA modulus "N". This routine calculates all * of the remaining parameters (group descriptions etc.) from N * using a verifiable, deterministic procedure. * * Note: this constructor makes the fundamental assumption that "N" * encodes a valid RSA-style modulus of the form "e1 * e2" where * "e1" and "e2" are safe primes. The factors "e1", "e2" MUST NOT * be known to any party, or the security of Zerocoin is * compromised. The integer "N" must be a MINIMUM of 1024 * in length. 3072 bits is strongly recommended. **/ AccumulatorAndProofParams(); //AccumulatorAndProofParams(CBigNum accumulatorModulus); bool initialized; /** * Modulus used for the accumulator. * Product of two safe primes who's factorization is unknown. */ CBigNum accumulatorModulus; /** * The initial value for the accumulator * A random Quadratic residue mod n thats not 1 */ CBigNum accumulatorBase; /** * Lower bound on the value for committed coin. * Required by the accumulator proof. */ CBigNum minCoinValue; /** * Upper bound on the value for a comitted coin. * Required by the accumulator proof. */ CBigNum maxCoinValue; /** * The second of two groups used to form a commitment to * a coin (which it self is a commitment to a serial number). * This one differs from serialNumberSokCommitment due to * restrictions from Camenisch and Lysyanskaya's paper. */ IntegerGroupParams accumulatorPoKCommitmentGroup; /** * Hidden order quadratic residue group mod N. * Used in the accumulator proof. */ IntegerGroupParams accumulatorQRNCommitmentGroup; /** * Security parameter. * Bit length of the challenges used in the accumulator proof. */ uint32_t k_prime; /** * Security parameter. * The statistical zero-knowledgeness of the accumulator proof. */ uint32_t k_dprime; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(accumulatorModulus); READWRITE(accumulatorBase); READWRITE(accumulatorPoKCommitmentGroup); READWRITE(accumulatorQRNCommitmentGroup); READWRITE(minCoinValue); READWRITE(maxCoinValue); READWRITE(k_prime); READWRITE(k_dprime); } }; class ZerocoinParams { public: /** @brief Construct a set of Zerocoin parameters from a modulus "N". * @param N A trusted RSA modulus * @param securityLevel A security level expressed in symmetric bits (default 80) * * Allocates and derives a set of Zerocoin parameters from * a trustworthy RSA modulus "N". This routine calculates all * of the remaining parameters (group descriptions etc.) from N * using a verifiable, deterministic procedure. * * Note: this constructor makes the fundamental assumption that "N" * encodes a valid RSA-style modulus of the form "e1 * e2" where * "e1" and "e2" are safe primes. The factors "e1", "e2" MUST NOT * be known to any party, or the security of Zerocoin is * compromised. The integer "N" must be a MINIMUM of 1024 * in length. 3072 bits is strongly recommended. **/ ZerocoinParams(CBigNum accumulatorModulus, uint32_t securityLevel = ZEROCOIN_DEFAULT_SECURITYLEVEL); bool initialized; AccumulatorAndProofParams accumulatorParams; /** * The Quadratic Residue group from which we form * a coin as a commitment to a serial number. */ IntegerGroupParams coinCommitmentGroup; /** * One of two groups used to form a commitment to * a coin (which it self is a commitment to a serial number). * This is the one used in the serial number poof. * It's order must be equal to the modulus of coinCommitmentGroup. */ IntegerGroupParams serialNumberSoKCommitmentGroup; /** * The number of iterations to use in the serial * number proof. */ uint32_t zkp_iterations; /** * The amount of the hash function we use for * proofs. */ uint32_t zkp_hash_len; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(accumulatorParams); READWRITE(coinCommitmentGroup); READWRITE(serialNumberSoKCommitmentGroup); READWRITE(zkp_iterations); READWRITE(zkp_hash_len); } }; } /* namespace libzerocoin */ #endif /* PARAMS_H_ */
[ "44026210+BitHostCoin@users.noreply.github.com" ]
44026210+BitHostCoin@users.noreply.github.com
05050db2ee33635a1609b87ea8f76da4e6d43966
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/8.1.1/vtkBiQuadraticQuadWrap.h
f55ab11479c289095c16f2d45ff02e9f75c00238
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
2,057
h
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKBIQUADRATICQUADWRAP_H #define NATIVE_EXTENSION_VTK_VTKBIQUADRATICQUADWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkBiQuadraticQuad.h> #include "vtkNonLinearCellWrap.h" #include "../../plus/plus.h" class VtkBiQuadraticQuadWrap : public VtkNonLinearCellWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkBiQuadraticQuadWrap(vtkSmartPointer<vtkBiQuadraticQuad>); VtkBiQuadraticQuadWrap(); ~VtkBiQuadraticQuadWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void CellBoundary(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCellDimension(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCellType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetEdge(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetFace(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfEdges(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfFaces(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetParametricCenter(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateDerivs(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateFunctions(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void Triangulate(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKBIQUADRATICQUADWRAP_CLASSDEF VTK_NODE_PLUS_VTKBIQUADRATICQUADWRAP_CLASSDEF #endif }; #endif
[ "axkibe@gmail.com" ]
axkibe@gmail.com
52bbb597c8c8f98cd62105b33a12a1372127acfd
1ffb0d73aed05458f75936360948d6964de387af
/src/solver/pibt.h
a95a42b97ddbf3e04292ad313929b67ac3b4f596
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kei18/pibt
2a05011129cc760395f5c5eabba03a83bf4e53c4
2ad94bc7e9a817d93acef9849b743b6357b8e510
refs/heads/master
2021-12-10T04:22:36.826941
2021-11-23T02:46:06
2021-11-23T02:46:06
187,332,062
24
8
MIT
2020-10-02T12:30:04
2019-05-18T08:14:33
C++
UTF-8
C++
false
false
1,427
h
#pragma once #include "solver.h" class PIBT : public Solver { protected: std::vector<float> epsilon; // tie-breaker std::vector<int> eta; // usually increment every step std::vector<float> priority; // eta + epsilon void init(); void allocate(); virtual void updatePriority(); Nodes createCandidates(Agent* a, Nodes CLOSE_NODE); Nodes createCandidates(Agent* a, Nodes CLOSE_NODE, Node* tmp); bool priorityInheritance(Agent* a, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); bool priorityInheritance(Agent* a, Agent* aFrom, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); virtual bool priorityInheritance(Agent* a, Nodes C, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); virtual Node* chooseNode(Agent* a, Nodes C); void updateC(Nodes& C, Node* target, Nodes CLOSE_NODE); float getDensity(Agent* a); // density can be used as effective prioritization public: PIBT(Problem* _P); PIBT(Problem* _P, std::mt19937* _MT); ~PIBT(); bool solve(); virtual void update(); virtual std::string logStr(); };
[ "keisuke.oku18@gmail.com" ]
keisuke.oku18@gmail.com
ee299c6fc322467f474d0050b3b484d7dcabe082
aefb8cde419ab4c59383ffe10ca655e9333f149b
/MechanicsTest/Source/MechanicsTest/ProjectileClass.h
2715f1ed5f9f5f958570ba925fcf20f6d22addb6
[]
no_license
DavidBrando/ARGP_Tests
a0837af63bc3605bda5edd6f9be2f1f4169d5ae3
d157df226eb5a5c11226e36239812c6ddd42da58
refs/heads/main
2023-02-21T13:45:41.590497
2021-01-24T14:07:06
2021-01-24T14:07:06
331,369,725
0
0
null
null
null
null
UTF-8
C++
false
false
2,107
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ProjectileClass.generated.h" class USphereComponent; class UParticleSystemComponent; class USceneComponent; class UProjectileMovementComponent; class UParticleSystem; class UCapsuleComponent; UCLASS() class MECHANICSTEST_API AProjectileClass : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AProjectileClass(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //For colision purposes UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UCapsuleComponent* capsule; //root component of the projectile UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) USceneComponent* root; //VFX UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UParticleSystemComponent* bullet; //Component for movement with the logic implemented UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UProjectileMovementComponent* projectileMovement; //More VFX for cool explosions UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UParticleSystem* explosion = nullptr; //Damage of the projectile UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) float damage = 0.0f; public: // Called every frame virtual void Tick(float DeltaTime) override; UFUNCTION() virtual void OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); void SetDamage(float nDamage); //seeting a new damage if we want more powerful shoots void MakeProjectileHoming(USceneComponent* target); };
[ "davidtbs@hotmail.es" ]
davidtbs@hotmail.es
1822abed2252e2145fff8d699f6bf926725acda8
3f3095dbf94522e37fe897381d9c76ceb67c8e4f
/Current/Tutorial_Hint_Escort_BoscoOilShale.hpp
c457a0ce7c16462ae8dca5d8bb425633baca970b
[]
no_license
DRG-Modding/Header-Dumps
763c7195b9fb24a108d7d933193838d736f9f494
84932dc1491811e9872b1de4f92759616f9fa565
refs/heads/main
2023-06-25T11:11:10.298500
2023-06-20T13:52:18
2023-06-20T13:52:18
399,652,576
8
7
null
null
null
null
UTF-8
C++
false
false
467
hpp
#ifndef UE4SS_SDK_Tutorial_Hint_Escort_BoscoOilShale_HPP #define UE4SS_SDK_Tutorial_Hint_Escort_BoscoOilShale_HPP class UTutorial_Hint_Escort_BoscoOilShale_C : public UTutorialHintComponent { FPointerToUberGraphFrame UberGraphFrame; void ReceiveOnInitialized(); void OnBoscoChanged(class ABosco* Bosco); void OnObjectiveUpdated(class UObjective* Objective); void ExecuteUbergraph_Tutorial_Hint_Escort_BoscoOilShale(int32 EntryPoint); }; #endif
[ "bobby45900@gmail.com" ]
bobby45900@gmail.com
d78eea6fdad2b5d91a548e8b035a361769309fb2
aa78ede78f08eecde9a78fe1066b81e47ae19390
/Server/Network/MessageProcessing/getstatisticsrequestprocessorobject.h
b62e2d3321221c0310d0f136d0e0ed39c9aa351c
[]
no_license
MafiaMakers/Backend-server
51c342d6e202194b47e183310e348643cbff5d31
1fdc213e841d78aca3b5f70bca45684664e32435
refs/heads/master
2023-01-12T04:57:25.511124
2020-11-02T12:53:50
2020-11-02T12:53:50
254,849,281
0
0
null
null
null
null
UTF-8
C++
false
false
725
h
#ifndef GETSTATISTICSREQUESTPROCESSOROBJECT_H #define GETSTATISTICSREQUESTPROCESSOROBJECT_H #include "processorobject.h" namespace Mafia { namespace Network { namespace MessageProcessing { class GetStatisticsRequestProcessorObject : public ProcessorObject { public: GetStatisticsRequestProcessorObject(Message_t message); /*! * \brief id, которые используются: * userId (int) : id пользователя, статистику которого мы хотим посмотреть */ void process() override; }; } } } #endif // GETSTATISTICSREQUESTPROCESSOROBJECT_H
[ "andrusov.n@gmail.com" ]
andrusov.n@gmail.com
650419388cf51f37f453b09d92170a02d5325a07
9fad4848e43f4487730185e4f50e05a044f865ab
/src/ash/wm/window_state.h
2c0bb5ca61be87b01d3ceb2e16d44b920375a22b
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
14,982
h
// Copyright 2013 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. #ifndef ASH_WM_WINDOW_STATE_H_ #define ASH_WM_WINDOW_STATE_H_ #include <memory> #include "ash/ash_export.h" #include "ash/wm/drag_details.h" #include "ash/wm/wm_types.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/observer_list.h" #include "ui/aura/window_observer.h" #include "ui/base/ui_base_types.h" namespace aura { class Window; } namespace gfx { class Rect; } namespace ash { class WorkspaceLayoutManager; class LockWindowState; class MaximizeModeWindowState; namespace wm { class WindowStateDelegate; class WindowStateObserver; class WMEvent; // WindowState manages and defines ash specific window state and // behavior. Ash specific per-window state (such as ones that controls // window manager behavior) and ash specific window behavior (such as // maximize, minimize, snap sizing etc) should be added here instead // of defining separate functions (like |MaximizeWindow(aura::Window* // window)|) or using aura Window property. // The WindowState gets created when first accessed by // |wm::GetWindowState|, and deleted when the window is deleted. // Prefer using this class instead of passing aura::Window* around in // ash code as this is often what you need to interact with, and // accessing the window using |window()| is cheap. class ASH_EXPORT WindowState : public aura::WindowObserver { public: // A subclass of State class represents one of the window's states // that corresponds to WindowStateType in Ash environment, e.g. // maximized, minimized or side snapped, as subclass. // Each subclass defines its own behavior and transition for each WMEvent. class State { public: State() {} virtual ~State() {} // Update WindowState based on |event|. virtual void OnWMEvent(WindowState* window_state, const WMEvent* event) = 0; virtual WindowStateType GetType() const = 0; // Gets called when the state object became active and the managed window // needs to be adjusted to the State's requirement. // The passed |previous_state| may be used to properly implement state // transitions such as bound animations from the previous state. // Note: This only gets called when the state object gets changed. virtual void AttachState(WindowState* window_state, State* previous_state) = 0; // Gets called before the state objects gets deactivated / detached from the // window, so that it can save the various states it is interested in. // Note: This only gets called when the state object gets changed. virtual void DetachState(WindowState* window_state) = 0; private: DISALLOW_COPY_AND_ASSIGN(State); }; // Call GetWindowState() to instantiate this class. ~WindowState() override; aura::Window* window() { return window_; } const aura::Window* window() const { return window_; } bool HasDelegate() const; void SetDelegate(std::unique_ptr<WindowStateDelegate> delegate); // Returns the window's current ash state type. // Refer to WindowStateType definition in wm_types.h as for why Ash // has its own state type. WindowStateType GetStateType() const; // Predicates to check window state. bool IsMinimized() const; bool IsMaximized() const; bool IsFullscreen() const; bool IsMaximizedOrFullscreen() const; bool IsSnapped() const; // True if the window's state type is WINDOW_STATE_TYPE_NORMAL or // WINDOW_STATE_TYPE_DEFAULT. bool IsNormalStateType() const; bool IsNormalOrSnapped() const; bool IsActive() const; bool IsDocked() const; // Returns true if the window's location can be controlled by the user. bool IsUserPositionable() const; // Checks if the window can change its state accordingly. bool CanMaximize() const; bool CanMinimize() const; bool CanResize() const; bool CanSnap() const; bool CanActivate() const; // Returns true if the window has restore bounds. bool HasRestoreBounds() const; // These methods use aura::WindowProperty to change the window's state // instead of using WMEvent directly. This is to use the same mechanism as // what views::Widget is using. void Maximize(); void Minimize(); void Unminimize(); void Activate(); void Deactivate(); // Set the window state to normal. // TODO(oshima): Change to use RESTORE event. void Restore(); // Caches, then disables always on top state and then stacks |window_| below // |window_on_top| if a |window_| is currently in always on top state. void DisableAlwaysOnTop(aura::Window* window_on_top); // Restores always on top state that a window might have cached. void RestoreAlwaysOnTop(); // Invoked when a WMevent occurs, which drives the internal // state machine. void OnWMEvent(const WMEvent* event); // TODO(oshima): Try hiding these methods and making them accessible only to // state impl. State changes should happen through events (as much // as possible). // Saves the current bounds to be used as a restore bounds. void SaveCurrentBoundsForRestore(); // Same as |GetRestoreBoundsInScreen| except that it returns the // bounds in the parent's coordinates. gfx::Rect GetRestoreBoundsInParent() const; // Returns the restore bounds property on the window in the virtual screen // coordinates. The bounds can be NULL if the bounds property does not // exist for the window. The window owns the bounds object. gfx::Rect GetRestoreBoundsInScreen() const; // Same as |SetRestoreBoundsInScreen| except that the bounds is in the // parent's coordinates. void SetRestoreBoundsInParent(const gfx::Rect& bounds_in_parent); // Sets the restore bounds property on the window in the virtual screen // coordinates. Deletes existing bounds value if exists. void SetRestoreBoundsInScreen(const gfx::Rect& bounds_in_screen); // Deletes and clears the restore bounds property on the window. void ClearRestoreBounds(); // Replace the State object of a window with a state handler which can // implement a new window manager type. The passed object will be owned // by this object and the returned object will be owned by the caller. std::unique_ptr<State> SetStateObject(std::unique_ptr<State> new_state); // True if the window should be unminimized to the restore bounds, as // opposed to the window's current bounds. |unminimized_to_restore_bounds_| is // reset to the default value after the window is unminimized. bool unminimize_to_restore_bounds() const { return unminimize_to_restore_bounds_; } void set_unminimize_to_restore_bounds(bool value) { unminimize_to_restore_bounds_ = value; } // Gets/sets whether the shelf should be hidden when this window is // fullscreen. bool hide_shelf_when_fullscreen() const { return hide_shelf_when_fullscreen_; } void set_hide_shelf_when_fullscreen(bool value) { hide_shelf_when_fullscreen_ = value; } // If the minimum visibility is true, ash will try to keep a // minimum amount of the window is always visible on the work area // when shown. // TODO(oshima): Consolidate this and window_position_managed // into single parameter to control the window placement. bool minimum_visibility() const { return minimum_visibility_; } void set_minimum_visibility(bool minimum_visibility) { minimum_visibility_ = minimum_visibility; } // Specifies if the window can be dragged by the user via the caption or not. bool can_be_dragged() const { return can_be_dragged_; } void set_can_be_dragged(bool can_be_dragged) { can_be_dragged_ = can_be_dragged; } // Gets/Sets the bounds of the window before it was moved by the auto window // management. As long as it was not auto-managed, it will return NULL. const gfx::Rect* pre_auto_manage_window_bounds() const { return pre_auto_manage_window_bounds_.get(); } void SetPreAutoManageWindowBounds(const gfx::Rect& bounds); // Layout related properties void AddObserver(WindowStateObserver* observer); void RemoveObserver(WindowStateObserver* observer); // Whether the window is being dragged. bool is_dragged() const { return !!drag_details_; } // Whether or not the window's position can be managed by the // auto management logic. bool window_position_managed() const { return window_position_managed_; } void set_window_position_managed(bool window_position_managed) { window_position_managed_ = window_position_managed; } // Whether or not the window's position or size was changed by a user. bool bounds_changed_by_user() const { return bounds_changed_by_user_; } void set_bounds_changed_by_user(bool bounds_changed_by_user); // True if this window is an attached panel. bool panel_attached() const { return panel_attached_; } void set_panel_attached(bool panel_attached) { panel_attached_ = panel_attached; } // True if the window is ignored by the shelf layout manager for // purposes of darkening the shelf. bool ignored_by_shelf() const { return ignored_by_shelf_; } void set_ignored_by_shelf(bool ignored_by_shelf) { ignored_by_shelf_ = ignored_by_shelf; } // True if the window should be offered a chance to consume special system // keys such as brightness, volume, etc. that are usually handled by the // shell. bool can_consume_system_keys() const { return can_consume_system_keys_; } void set_can_consume_system_keys(bool can_consume_system_keys) { can_consume_system_keys_ = can_consume_system_keys; } // True if this window has requested that the top-row keys (back, forward, // brightness, volume) should be treated as function keys. bool top_row_keys_are_function_keys() const { return top_row_keys_are_function_keys_; } void set_top_row_keys_are_function_keys(bool value) { top_row_keys_are_function_keys_ = value; } // True if the window is in "immersive full screen mode" which is slightly // different from the normal fullscreen mode by allowing the user to reveal // the top portion of the window through a touch / mouse gesture. It might // also allow the shelf to be shown in some situations. bool in_immersive_fullscreen() const { return in_immersive_fullscreen_; } void set_in_immersive_fullscreen(bool enable) { in_immersive_fullscreen_ = enable; } // Creates and takes ownership of a pointer to DragDetails when resizing is // active. This should be done before a resizer gets created. void CreateDragDetails(aura::Window* window, const gfx::Point& point_in_parent, int window_component, aura::client::WindowMoveSource source); // Deletes and clears a pointer to DragDetails. This should be done when the // resizer gets destroyed. void DeleteDragDetails(); // Sets the currently stored restore bounds and clears the restore bounds. void SetAndClearRestoreBounds(); // Returns a pointer to DragDetails during drag operations. const DragDetails* drag_details() const { return drag_details_.get(); } DragDetails* drag_details() { return drag_details_.get(); } // aura::WindowObserver overrides: void OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) override; private: friend class DefaultState; friend class ash::LockWindowState; friend class ash::MaximizeModeWindowState; friend ASH_EXPORT WindowState* GetWindowState(aura::Window*); FRIEND_TEST_ALL_PREFIXES(WindowAnimationsTest, CrossFadeToBounds); FRIEND_TEST_ALL_PREFIXES(WindowAnimationsTest, CrossFadeToBoundsFromTransform); explicit WindowState(aura::Window* window); WindowStateDelegate* delegate() { return delegate_.get(); } // Returns the window's current always_on_top state. bool GetAlwaysOnTop() const; // Returns the window's current show state. ui::WindowShowState GetShowState() const; // Sets the window's bounds in screen coordinates. void SetBoundsInScreen(const gfx::Rect& bounds_in_screen); // Adjusts the |bounds| so that they are flush with the edge of the // workspace if the window represented by |window_state| is side snapped. void AdjustSnappedBounds(gfx::Rect* bounds); // Updates the window show state according to the current window state type. // Note that this does not update the window bounds. void UpdateWindowShowStateFromStateType(); void NotifyPreStateTypeChange(WindowStateType old_window_state_type); void NotifyPostStateTypeChange(WindowStateType old_window_state_type); // Sets |bounds| as is and ensure the layer is aligned with pixel boundary. void SetBoundsDirect(const gfx::Rect& bounds); // Sets the window's |bounds| with constraint where the size of the // new bounds will not exceeds the size of the work area. void SetBoundsConstrained(const gfx::Rect& bounds); // Sets the wndow's |bounds| and transitions to the new bounds with // a scale animation. void SetBoundsDirectAnimated(const gfx::Rect& bounds); // Sets the window's |bounds| and transition to the new bounds with // a cross fade animation. void SetBoundsDirectCrossFade(const gfx::Rect& bounds); // The owner of this window settings. aura::Window* window_; std::unique_ptr<WindowStateDelegate> delegate_; bool window_position_managed_; bool bounds_changed_by_user_; bool panel_attached_; bool ignored_by_shelf_; bool can_consume_system_keys_; bool top_row_keys_are_function_keys_; std::unique_ptr<DragDetails> drag_details_; bool unminimize_to_restore_bounds_; bool in_immersive_fullscreen_; bool hide_shelf_when_fullscreen_; bool minimum_visibility_; bool can_be_dragged_; bool cached_always_on_top_; // A property to remember the window position which was set before the // auto window position manager changed the window bounds, so that it can get // restored when only this one window gets shown. std::unique_ptr<gfx::Rect> pre_auto_manage_window_bounds_; base::ObserverList<WindowStateObserver> observer_list_; // True to ignore a property change event to avoid reentrance in // UpdateWindowStateType() bool ignore_property_change_; std::unique_ptr<State> current_state_; DISALLOW_COPY_AND_ASSIGN(WindowState); }; // Returns the WindowState for active window. Returns |NULL| // if there is no active window. ASH_EXPORT WindowState* GetActiveWindowState(); // Returns the WindowState for |window|. Creates WindowState // if it didn't exist. The settings object is owned by |window|. ASH_EXPORT WindowState* GetWindowState(aura::Window* window); // const version of GetWindowState. ASH_EXPORT const WindowState* GetWindowState(const aura::Window* window); } // namespace wm } // namespace ash #endif // ASH_WM_WINDOW_STATE_H_
[ "dummas@163.com" ]
dummas@163.com
f3d85195f02824ace4971350cec934c1c1d033ce
388299829e68a249430ac1c21afc3261ad7ca6dc
/src/test/matrix_io_test.cc
7abea1e6388c9116efcdc6e348ad76f631b00aee
[ "Apache-2.0" ]
permissive
raindreams/parameter_server-1
7c85e5b96145be44b6326dca2f5324726cafc814
c54bb1913b5d2b2187012eb5f063ab01387943f0
refs/heads/master
2021-01-12T22:19:37.490735
2014-09-22T02:32:39
2014-09-22T02:32:39
24,549,568
1
0
null
null
null
null
UTF-8
C++
false
false
1,770
cc
#include "gtest/gtest.h" #include "base/matrix_io_inl.h" using namespace PS; class MatrixIOTest : public ::testing::Test { protected: virtual void SetUp() { } void verifyRCV1(MatrixPtrList<double> data) { EXPECT_EQ(data.size(), 2); auto y = data[0]->value().eigenArray(); EXPECT_EQ(y.size(), 20242); EXPECT_EQ(y.sum(), 740); auto X = std::static_pointer_cast<SparseMatrix<uint64, double> >(data[1]); auto os = X->offset().eigenArray(); // auto idx = X->index().eigenArray(); auto val = X->value().eigenArray(); EXPECT_EQ(os.sum(), 15016151914); // EXPECT_EQ(idx.sum(), 35335196536); EXPECT_GE(val.sum(), 138760); EXPECT_LE(val.sum(), 138770); EXPECT_EQ(SizeR(1, 47237), SizeR(X->info().col())); // LL << data[0]->info().DebugString(); // LL << data[0]->debugString(); // LL << data[1]->debugString(); } }; TEST_F(MatrixIOTest, ReadRCV1Single) { DataConfig dc; dc.set_format(DataConfig::TEXT); dc.set_text(DataConfig::LIBSVM); dc.add_file("../data/rcv1_train.binary"); auto data = readMatricesOrDie<double>(dc); verifyRCV1(data); } TEST_F(MatrixIOTest, ReadRCV1Multi) { DataConfig dc; dc.set_format(DataConfig::TEXT); dc.set_text(DataConfig::LIBSVM); dc.add_file("../data/rcv1/train/part.*"); dc.add_file("../data/rcv1/test/part.*"); auto data = readMatricesOrDie<double>(searchFiles(dc)); verifyRCV1(data); } TEST_F(MatrixIOTest, ReadADFEA) { DataConfig dc; dc.set_format(DataConfig::TEXT); dc.set_text(DataConfig::ADFEA); dc.add_file("../../data/ctrc/train/part-0001.gz"); auto data = readMatricesOrDie<double>(dc); // for (int i = 0; i < data.size(); ++i) { // data[i]->info().clear_ins_info(); // LL << data[i]->debugString(); // } }
[ "muli@cs.cmu.edu" ]
muli@cs.cmu.edu
b1b7969b2e76d46428c40d1c8b690ec9c8f22448
c74e77aed37c97ad459a876720e4e2848bb75d60
/800-899/854/(30197365)[WRONG_ANSWER]D[ b'Jury Meeting' ].cpp
aed6d71d77c2fbf97929480890ff7c5224ac9f9a
[]
no_license
yashar-sb-sb/my-codeforces-submissions
aebecf4e906a955f066db43cb97b478d218a720e
a044fccb2e2b2411a4fbd40c3788df2487c5e747
refs/heads/master
2021-01-21T21:06:06.327357
2017-11-14T21:20:28
2017-11-14T21:28:39
98,517,002
1
1
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long uLL; typedef long double ldb; typedef pair<int,int> pii; vector<int> C[1000001]; LL OC[1000001]; vector<int> F[1000001]; map<int,int> ma; int n, m, k; LL sum = 0; void fun(int i) { for(int j = 0; j < int(F[i].size()); ++j) { if(!ma.count(F[i][j])) { ma[F[i][j]] = C[i][j]; sum += C[i][j]; } else if(C[i][j]<ma[F[i][j]]) { sum -= ma[F[i][j]] - C[i][j]; ma[F[i][j]] = C[i][j]; } } if(int(ma.size())==n) OC[i] = sum; else OC[i] = 1e18; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int d, f, t, c; cin>>n>>m>>k; for(int i = 0; i < m; ++i) { cin>>d>>f>>t>>c; f= max(f, t); F[d].push_back(f); C[d].push_back(c); } for(int i = 1000000; i > 0; --i) fun(i); sum = 0; ma.clear(); LL ans = 1e18; for(int i = 0; i < 1000000-k; ++i) { fun(i); ans = min(ans, OC[i]+OC[i+k+1]); } if(ans > 1e15) ans = -1; cout<<ans<<endl; return 0; }
[ "yashar_sb_sb@yahoo.com" ]
yashar_sb_sb@yahoo.com
bc1822abe4f0e880e932005c5f2d365cab479d51
d2ba0389accde0370662b9df282ef1f8df8d69c7
/frameworks/cocos2d-x/cocos/renderer/scene/assembler/SimpleSprite2D.hpp
01ee7031c8426da5d0a7034a5c3c73104621d72c
[]
no_license
Kuovane/LearnOpenGLES
6a42438db05eecf5c877504013e9ac7682bc291c
8458b9c87d1bf333b8679e90a8a47bc27ebe9ccd
refs/heads/master
2022-07-27T00:28:02.066179
2020-05-14T10:34:46
2020-05-14T10:34:46
262,535,484
0
0
null
null
null
null
UTF-8
C++
false
false
1,600
hpp
/**************************************************************************** Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #pragma once #include "AssemblerSprite.hpp" RENDERER_BEGIN class SimpleSprite2D: public AssemblerSprite { public: SimpleSprite2D(); virtual ~SimpleSprite2D(); virtual void fillBuffers(NodeProxy* node, MeshBuffer* buffer, std::size_t index) override; }; RENDERER_END
[ "811408414@qq.com" ]
811408414@qq.com
c785b64b16be440f107c762357ce17bc722ecc39
5bedc85ef4ad015cb1075f048a85768a3ead0717
/src/modules/ESModuleOscillatorBase.h
5fa9040ff1dd1c1028aeafe8555b525442727700
[ "MIT" ]
permissive
siqueiraets/essynth
a875ff071303fb69200cf4e65516de11a4a6435a
acd2a32752530728787cdc92962bc88b7df4ba48
refs/heads/master
2021-09-09T10:06:20.931082
2018-03-15T02:06:40
2018-03-15T02:06:40
118,532,038
0
0
null
null
null
null
UTF-8
C++
false
false
2,562
h
#ifndef ESMODULEOSCILLATORBASE_H_ #define ESMODULEOSCILLATORBASE_H_ #include "ESEngine.h" #define ES_OSC_RESOLUTION 1024 // TODO sample rate needs to be read at runtime #define SAMPLE_RATE 44100 namespace ESSynth { enum class ESModuleOscillatorBaseInputs { Frequency, Clock }; enum class ESModuleOscillatorBaseOutputs { Amplitude }; enum class ESModuleOscillatorBaseInternals { Phase }; template <typename Type> struct ESModuleOscillatorBase : ESModule<ESModuleOscillatorBase<Type>, ESModuleOscillatorBaseInputs, ESModuleOscillatorBaseOutputs, ESModuleOscillatorBaseInternals> { using BaseType = ESModule<ESModuleOscillatorBase<Type>, ESModuleOscillatorBaseInputs, ESModuleOscillatorBaseOutputs, ESModuleOscillatorBaseInternals>; static ESFloatType osc_table[ES_OSC_RESOLUTION]; static constexpr auto GetInputList() { return BaseType::MakeIoList( BaseType::MakeInput(ESDataType::Float, "Frequency", BaseType::TIn::Frequency), BaseType::MakeInput(ESDataType::Integer, "Clock", BaseType::TIn::Clock)); } static constexpr auto GetOutputList() { return BaseType::MakeIoList( BaseType::MakeOutput(ESDataType::Float, "Amplitude", BaseType::TOut::Amplitude)); } static constexpr auto GetInternalList() { return BaseType::MakeIoList( BaseType::MakeInternal(ESDataType::Float, "Phase", BaseType::TInt::Phase)); } static ESInt32Type Process(const ESData* inputs, ESOutputRuntime* outputs, ESData* internals, const ESInt32Type& flags) { if (!(flags & BaseType::InputFlag(BaseType::TIn::Clock))) { return 0; } ESFloatType frequency = BaseType::template Input<BaseType::TIn::Frequency>(inputs); ESFloatType increment = (ES_OSC_RESOLUTION * frequency) / (ESFloatType)SAMPLE_RATE; ESFloatType phase = BaseType::template Internal<BaseType::TInt::Phase>(internals); phase += increment; if (phase >= (ESFloatType)ES_OSC_RESOLUTION) { phase -= (ESFloatType)ES_OSC_RESOLUTION; } ESFloatType value = osc_table[(ESInt32Type)phase]; BaseType::template Internal<BaseType::TInt::Phase>(internals) = phase; BaseType::template WriteOutput<BaseType::TOut::Amplitude>(outputs, value); return 0; } }; template <typename Type> ESFloatType ESModuleOscillatorBase<Type>::osc_table[ES_OSC_RESOLUTION]; } // namespace ESSynth #endif /* ESMODULEOSCILLATORBASE_H_ */
[ "siqueiraets@gmail.com" ]
siqueiraets@gmail.com
8e39cc9b9f8b9ebd6de05dce55bcaeee703d7c1d
01fb222322f3f37b4fff999c53182162a24ce337
/libs/ml/tests/ml/ops/leaky_relu_op.cpp
46ec9057095af7f7e5ff4d9bf1771f8893b8355b
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
MissingNO57/ledger
51cc4b932909d9d25145ac9649b0caa193c5fb0e
0afeb1582da6ddae07155878b6a0c109c7ab2680
refs/heads/master
2020-05-29T17:19:02.935379
2019-05-29T13:59:39
2019-05-29T13:59:39
189,269,908
1
0
Apache-2.0
2020-02-24T11:02:56
2019-05-29T17:28:42
C++
UTF-8
C++
false
false
3,065
cpp
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "ml/ops/leaky_relu_op.hpp" #include "math/fixed_point/fixed_point.hpp" #include "math/tensor.hpp" #include <gtest/gtest.h> template <typename T> class LeakyReluOpTest : public ::testing::Test { }; using MyTypes = ::testing::Types<fetch::math::Tensor<float>, fetch::math::Tensor<double>, fetch::math::Tensor<fetch::fixed_point::FixedPoint<32, 32>>>; TYPED_TEST_CASE(LeakyReluOpTest, MyTypes); TYPED_TEST(LeakyReluOpTest, forward_test) { using DataType = typename TypeParam::Type; using ArrayType = TypeParam; ArrayType data(8); ArrayType alpha(8); ArrayType gt(8); std::vector<double> data_input({1, -2, 3, -4, 5, -6, 7, -8}); std::vector<double> alphaInput({0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}); std::vector<double> gt_input({1, -0.4, 3, -1.6, 5, -3.6, 7, -6.4}); for (std::uint64_t i(0); i < 8; ++i) { data.Set(i, DataType(data_input[i])); gt.Set(i, DataType(gt_input[i])); alpha.Set(i, DataType(alphaInput[i])); } fetch::ml::ops::LeakyReluOp<ArrayType> op; TypeParam prediction(op.ComputeOutputShape({data, alpha})); op.Forward({data, alpha}, prediction); // test correct values ASSERT_TRUE( prediction.AllClose(gt, typename TypeParam::Type(1e-5), typename TypeParam::Type(1e-5))); } TYPED_TEST(LeakyReluOpTest, backward_test) { using DataType = typename TypeParam::Type; using ArrayType = TypeParam; ArrayType data(8); ArrayType alpha(8); ArrayType error(8); ArrayType gt(8); std::vector<double> data_input({1, -2, 3, -4, 5, -6, 7, -8}); std::vector<double> alphaInput({0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}); std::vector<double> errorInput({0, 0, 0, 0, 1, 1, 0, 0}); std::vector<double> gt_input({0, 0, 0, 0, 1, 0.6, 0, 0}); for (std::uint64_t i(0); i < 8; ++i) { data.Set(i, DataType(data_input[i])); error.Set(i, DataType(errorInput[i])); gt.Set(i, DataType(gt_input[i])); alpha.Set(i, DataType(alphaInput[i])); } fetch::ml::ops::LeakyReluOp<ArrayType> op; std::vector<ArrayType> prediction = op.Backward({data, alpha}, error); // test correct values ASSERT_TRUE(prediction[0].AllClose(gt, DataType(1e-5), DataType(1e-5))); }
[ "noreply@github.com" ]
MissingNO57.noreply@github.com
a2856338366b452cb3013205add7fb77d387fe03
5a6ff800792bf62756fe9750bf8a4d94e7abc3a4
/Project X/Space.cpp
fb37b64d5fee20916e30c95d23c32ef073037009
[]
no_license
Barsegyans/ProjectX
8cc85d8ed8e9da365e55c077d12039af86c8f5c9
1aa2808ba93b34565488edee60667592a8b57a51
refs/heads/master
2021-01-13T09:02:47.337835
2016-12-02T12:03:16
2016-12-02T12:03:16
72,372,142
0
0
null
2016-12-02T11:58:32
2016-10-30T19:59:35
C++
UTF-8
C++
false
false
206
cpp
#include"Space.h" Space::Space(float x, float y): Box2D(Point2D(0,0),Point2D(x, y)) {}; Space::Space(Point2D const & a, Point2D const & b): Box2D(a,b) {}; Space::Space(Box2D const & b): Box2D(b){};
[ "Serbarmephi@gmail.com" ]
Serbarmephi@gmail.com
f0d413b81ee182cdb6206fb1b665f0c013fd0e16
f2339e85157027dada17fadd67c163ecb8627909
/Server/EffectServer/Src/EffectAttackEntityAddBuff.h
2950b143e08d127f166f0f3691e3a9f93388e418
[]
no_license
fynbntl/Titan
7ed8869377676b4c5b96df953570d9b4c4b9b102
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
refs/heads/master
2021-09-01T22:52:37.516407
2017-12-29T01:59:29
2017-12-29T01:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,586
h
/******************************************************************* ** 文件名: EffectAttackEntityAddBuff.h ** 版 权: (C) 深圳冰川网络技术有限公司 2008 - All Rights Reserved ** 创建人: 彭政林 ** 日 期: 3/04/2016 ** 版 本: 1.0 ** 描 述: 效果-攻击实体增加Buff http://172.16.0.120/redmine/issues/1660 ********************************************************************/ #pragma once #include "IEffect.h" #include "EffectDef.h" #include "IEntity.h" using namespace EFFECT_SERVER; #include "IEventEngine.h" #include "IEntityEvent.h" class CEffectAttackEntityAddBuff : public IEffectEx,public IEventExecuteSink { public: typedef EffectServer_AttackEntityAddBuff SCHEME_DATA; CEffectAttackEntityAddBuff( SCHEME_DATA &data ) : m_data(data),m_pEntity(0),m_dwLastTick(0) { } // 获取效果ID virtual int GetID() { return m_data.nID; } // 效果启用 virtual bool Start( EFFECT_CONTEXT * context,CONDITION_CONTEXT *pConditionContext ) { if ( context==0 || context->pEntity==0 ) return false; m_pEntity = context->pEntity; g_EHelper.Subscibe(m_pEntity, this, EVENT_ENTITY_ATTACK, "CEffectAttackEntityAddBuff"); return true; } // 效果停止 virtual void Stop() { if (m_pEntity != 0) { g_EHelper.UnSubscibe(m_pEntity, this, EVENT_ENTITY_ATTACK); m_pEntity = 0; } } // 克隆一个新效果 virtual IEffect * Clone() { return new CEffectAttackEntityAddBuff(m_data); } // 释放 virtual void Release() { Stop(); delete this; } /////////////////////////////////////////IEventExecuteSink///////////////////////////////////////// /** @param wEventID :事件ID @param bSrcType :发送源类型 @param dwSrcID : 发送源标识(实体为UID中"序列号"部份,非实体就为0) @param pszContext : 上下文 @param nLen : 上下文长度 @return @note @warning @retval buffer */ virtual void OnExecute(WORD wEventID, BYTE bSrcType, DWORD dwSrcID, LPCSTR pszContext, int nLen) { switch (wEventID) { case EVENT_ENTITY_ATTACK: { if (m_pEntity == NULL) { break; } UID uidSelf = m_pEntity->getUID(); DWORD dwTick = getTickCountEx(); if (dwTick < m_dwLastTick + m_data.nInterval) { break; } __IBuffPart *pBuffPart = (__IBuffPart *)m_pEntity->getEntityPart(PART_BUFF); if (pBuffPart == NULL) { break; } if (pszContext == NULL || nLen != sizeof(event_entity_attack)) { break; } event_entity_attack *pAttck = (event_entity_attack*)pszContext; UID uidTarget = pAttck->uidTarget; if (isInvalidUID(uidTarget)) { break; } int nType = UID_2_TYPE(uidTarget); switch (nType) { case TYPE_PLAYER_ROLE: { // 检测死亡目标 if (!g_EHelper.chooseTarget(m_pEntity, m_data.nValue, uidTarget)) { return; } } break; case TYPE_MONSTER: { // 取得怪物ID int nMonsterID = getProperty_Integer(uidTarget, PROPERTY_ID); if (nMonsterID == 0) { return; } if (nMonsterID != m_data.nValue) { return; } } break; default: { return; } break; } if (m_data.nBuffID > 0 && m_data.nBuffLevel > 0) { pBuffPart->Add(m_data.nBuffID, m_data.nBuffLevel, uidSelf); m_dwLastTick = dwTick; } } break; default: break; } } private: SCHEME_DATA m_data; // 实体指针 __IEntity *m_pEntity; // 上次时间 DWORD m_dwLastTick; };
[ "85789685@qq.com" ]
85789685@qq.com
9b86b7fbc7674926693b9f1ae7ccb69aac45400a
9bbc105183d2241fa7204201e3dac18078bdc14c
/cpp/src/msgpack/rpc/session_pool.cc
e0a9d551285999f0aba53949d874653db501b37a
[ "Apache-2.0" ]
permissive
nowelium/msgpack-rpc
f220a4b0d2849f18abce72b7a55e44ab7afc715e
a9a5762d981524d7559bc67ba2feb0f4e58bf188
refs/heads/master
2021-01-17T12:06:04.481011
2010-06-08T11:50:25
2010-06-08T11:50:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,093
cc
// // msgpack::rpc::session_pool - MessagePack-RPC for C++ // // Copyright (C) 2009-2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "session_pool.h" #include "session_impl.h" namespace msgpack { namespace rpc { MP_UTIL_DEF(session_pool) { bool step_timeout(); }; session_pool::session_pool(loop lo) : loop_util(lo) { m_loop->add_timer(1.0, 1.0, mp::bind(&MP_UTIL_IMPL(session_pool)::step_timeout, &MP_UTIL)); // FIXME thisの寿命: weak_ptrのlock()が失敗したらタイマーを終了? //start_timer(&t, &t, // mp::bind(&session_pool::step_timeout, this, // mp::weak_ptr<session_pool>(shared_from_this()) )); } session_pool::~session_pool() { } session session_pool::get_session(const address& addr) { table_ref ref(m_table); table_t::iterator found = ref->find(addr); if(found != ref->end()) { shared_session s = found->second.lock(); if(s) { return session(s); } } shared_session s = create_session(addr); ref->insert( table_t::value_type(addr, weak_session(s)) ); return session(s); } shared_session session_pool::create_session(const address& addr) { return shared_session(new session_impl( addr, m_default_opt, address(), NULL, m_loop)); } bool MP_UTIL_IMPL(session_pool)::step_timeout() { table_ref ref(m_table); for(table_t::iterator it(ref->begin()); it != ref->end(); ) { shared_session s(it->second.lock()); if(s) { s->step_timeout(); ++it; } else { ref->erase(it++); } } return true; } } // namespace rpc } // namespace msgpack
[ "frsyuki@users.sourceforge.jp" ]
frsyuki@users.sourceforge.jp
8b33590abdca58d7a01830dfe2b145bf79030188
44ae1b40f1cbc0703855f4d011cd9988b968adc0
/objects.h
5fdc41b4bdae12c5afdfe11f257fd35361098ed5
[]
no_license
matthewpetela/cop3503-rsvp
54670d1b499442ed67c04a268e96656c9e6e19c0
524b2de0bbb74dae3658e627600000dc516e9c33
refs/heads/master
2021-04-15T06:14:22.856876
2018-04-26T06:33:48
2018-04-26T06:33:48
126,245,421
1
0
null
null
null
null
UTF-8
C++
false
false
390
h
/* * objects.h * * Created on: Apr 22, 2018 * Author: Kimmy Spencer */ #ifndef OBJECTS_H_ #define OBJECTS_H_ #include <iostream> #include <string> using namespace std; class objects{ private: string name; int amnt; public: objects(string name, int amnt); void setRegistry(string gift); void setAmount(int qnty); string getRegistry(); }; #endif /* OBJECTS_H_ */
[ "noreply@github.com" ]
matthewpetela.noreply@github.com
aa23b09b3c4e8803a5c6279d42d878e0949508d9
7e16344d6eea32fbee8c8fc018025530417ea9fb
/src/GameObjects.cpp
24aea87a2a6afa249798745adad2c2cebe401b52
[]
no_license
Bezifabr/BoardGameProject-Editor
8df1c57687e1dcd55b1c2955ab408a8bbae6e080
9d0e5037c3d0c2e14af70e5624c6c8522f5e7d2b
refs/heads/master
2020-03-22T10:59:42.246626
2018-07-07T09:36:23
2018-07-07T09:36:23
139,939,962
0
0
null
null
null
null
UTF-8
C++
false
false
16,206
cpp
/// //////////////////////////////////////////////////////////////////////////// // // Project: 'The Board Game Project' // GameObjects.cpp // Purpose: Contains the definitions of Item, Skill and Effect classes containers. // // Copyright (C) Maciej Saranda 2016 (Bezifabr@gmail.com) // Code written only for use by Mighty Gorilla Studio. // // // /// //////////////////////////////////////////////////////////////////////////// #include <fstream> #include "GameObjects.h" #include <iostream> #include <exception> bool GameObjects::AddItem(std::string key, Item item) { if (items_.count(key) == 0) { items_[key] = item; itemsKeys_.push_back(key); return true; } std::cout << "GameObjects::AddItem(): key is occupied" << std::endl; return false; } bool GameObjects::ChangeItem(std::string key, Item item) { if (items_.count(key) == 1) { items_[key] = item; return true; } std::cout << "GameObjects::ChangeItem(): item doesn't exist" << std::endl; return false; } bool GameObjects::RemoveItem(std::string key) { if (items_.count(key) == 1) { items_.erase(key); if (!itemsKeys_.empty()) { for (auto i = itemsKeys_.begin(); i != itemsKeys_.end(); i++) if (itemsKeys_[std::distance(itemsKeys_.begin(), i)] == key) { itemsKeys_.erase(i); break; } } return true; } std::cout << "GameObjects::RemoveItem(): item doesn't exist" << std::endl; return false; } Item & GameObjects::GetItem(std::string key) { if (items_.count(key) == 0) throw "GameObjects::GetItem(): Item doesn't exist"; return items_[key]; } bool GameObjects::AddSkill(std::string key, Skill skill) { if (skills_.count(key) == 0) { skills_[key] = skill; skillsKeys_.push_back(key); return true; } std::cout << "GameObjects::AddSkill(): key is occupied" << std::endl; return false; } bool GameObjects::ChangeSkill(std::string key, Skill skill) { if (skills_.count(key) == 1) { skills_[key] = skill; return true; } std::cout << "GameObjects::ChangeSkill(): skill doesn't exist" << std::endl; return false; } bool GameObjects::RemoveSkill(std::string key) { if (skills_.count(key) == 1) { skills_.erase(key); if (!skillsKeys_.empty()) { for (auto i = skillsKeys_.begin(); i != skillsKeys_.end(); i++) if (skillsKeys_[std::distance(skillsKeys_.begin(), i)] == key) { skillsKeys_.erase(i); break; } } return true; } std::cout << "GameObjects::RemoveSkill(): skill doesn't exist" << std::endl; return false; } Skill & GameObjects::GetSkill(std::string key) { if (skills_.count(key) == 0) throw "GameObjects::GetSkill(): Skill doesn't exist"; return skills_[key]; } bool GameObjects::AddEffect(std::string key, Effect effect) { if (effects_.count(key) == 0) { effect.SetID(key); effects_[key] = effect; effectsKeys_.push_back(key); return true; } std::cout << "GameObjects::AddEffect(): key is occupied" << std::endl; return false; } bool GameObjects::ChangeEffect(std::string key, Effect effect) { if (effects_.count(key) == 1) { effects_[key] = effect; effects_[key].SetID(key); return true; } std::cout << "GameObjects::ChangeEffect(): Effect doesn't exist" << std::endl; return false; } bool GameObjects::RemoveEffect(std::string key) { if (effects_.count(key) == 1) { effects_.erase(key); RemoveEffectsKeys(key); return true; } std::cout << "GameObjects::RemoveEffect(): Effect doesn't exist" << std::endl; return false; } Effect& GameObjects::GetEffect(std::string key) { if (effects_.count(key) == 0) throw "Effect doesn't exists"; return effects_[key]; } std::vector<std::string>& GameObjects::GetItemsKeys() { if(itemsKeys_.empty()) std::cout << "GameObjects::GetItemsKeys(): vector is empty" << std::endl; return itemsKeys_; } std::vector<std::string>& GameObjects::GetSkillsKeys() { if (skillsKeys_.empty()) std::cout << "GameObjects::GetSkillsKeys(): vector is empty" << std::endl; return skillsKeys_; } std::vector<std::string>& GameObjects::GetEffectsKeys() { if (effectsKeys_.empty()) std::cout << "GameObjects::GetEffectsKeys(): vector is empty" << std::endl; return effectsKeys_; } bool GameObjects::SetEffectID(std::string currentID, std::string newID) { if (effects_.count(currentID) == 1) { effects_[currentID].SetID(newID); for (auto i = effectsKeys_.begin(); i != effectsKeys_.end(); i++) if (effectsKeys_[std::distance(effectsKeys_.begin(), i)] == currentID) { effectsKeys_[std::distance(effectsKeys_.begin(), i)] = newID; break; } return true; } return false; } bool GameObjects::SetSkillID(std::string currentID, std::string newID) { if (skills_.count(currentID) == 1) { skills_[currentID].SetName(newID); for (auto i = skillsKeys_.begin(); i != skillsKeys_.end(); i++) if (skillsKeys_[std::distance(skillsKeys_.begin(), i)] == currentID) { skillsKeys_[std::distance(skillsKeys_.begin(), i)] = newID; break; } return true; } return false; } void GameObjects::SaveEffects() { std::ofstream file; if (remove("Effects.txt") != 0) perror("Creating new file to save data"); else puts("File found and prepared to save data"); file.open("Effects.txt", std::ofstream::out | std::ofstream::trunc); for (auto itr = effects_.begin(), end = effects_.end(); itr != end; itr++) { file << "Effect{" << std::endl; file << "ID = " << itr->second.GetID() << std::endl; for (int i = 0; i <= itr->second.GetOrdersNumber() + 1; i++) { file << "Order = " << itr->second.GetFrontOrder() << std::endl; itr->second.PopOrder(); } file << "}" << std::endl; } file.close(); } void GameObjects::SaveItems() { std::ofstream file; if (remove("Items.txt") != 0) perror("Creating new file to save data"); else puts("File found and prepared to save data"); file.open("Items.txt", std::ofstream::out | std::ofstream::trunc); for (auto itr = items_.begin(), end = items_.end(); itr != end; itr++) { file << "Item{" << std::endl; file << "ID = " << itr->second.GetID() << std::endl; file << "Name = " << itr->second.GetName() << std::endl; file << "Description = " << itr->second.GetDescription() << std::endl; file << "Icon = " << itr->second.GetIconTextureID() << std::endl; file << "Cooldown = " << itr->second.GetTimeOfCooldown() << std::endl; file << "Charges = " << itr->second.GetAmounOfCharges() << std::endl; file << "Price = " << itr->second.GetPrice() << std::endl; file << "IsTargetingAlly = " << ConvertToString(itr->second.IsTargetingAlly()) << std::endl; file << "IsTargetingEnemy = " << ConvertToString(itr->second.IsTargetingEnemy()) << std::endl; file << "IsTargetingSelf = " << ConvertToString(itr->second.IsTargetingSelf()) << std::endl; file << "IsUsingOnTarget = " << ConvertToString(itr->second.IsUsingOnTarget()) << std::endl; file << "IsUsingImmediately = " << ConvertToString(itr->second.IsUsingImmediately()) << std::endl; file << "IsUsable = " << ConvertToString(itr->second.IsUsable()) << std::endl; file << "}" << std::endl; } } void GameObjects::SaveSkills() { std::ofstream file; if (remove("Skills.txt") != 0) perror("Creating new file to save data"); else puts("File found and prepared to save data"); file.open("Skills.txt", std::ofstream::out | std::ofstream::trunc); for (auto itr = skills_.begin(), end = skills_.end(); itr != end; itr++) { file << "Skill{" << std::endl; file << "ID = " << itr->second.GetID() << std::endl << "Name = " << itr->second.GetName() << std::endl << "Description = " << itr->second.GetDescription() << std::endl << "Icon = " << itr->second.GetIconTextureID() << std::endl << "Cooldown = " << std::to_string(itr->second.GetTimeOfCooldown()) << std::endl; file << "IsTargetingSelf = " << ConvertToString(itr->second.IsTargetingSelf()) << std::endl; file << "IsTargetingEnemy = " << ConvertToString(itr->second.IsTargetingEnemy()) << std::endl; file << "IsTargetingAlly = " << ConvertToString(itr->second.IsTargetingAlly()) << std::endl; file << "IsUseImmediately = " << ConvertToString(itr->second.IsUsingImmediately()) << std::endl; file << "IsUseOnTarget = " << ConvertToString(itr->second.IsUsingOnTarget()) << std::endl; file << "IsUsable = " << ConvertToString(itr->second.IsUsable()) << std::endl; file << "}" << std::endl; } } void GameObjects::LoadEffects() { std::ifstream openFile("Effects.txt"); if (openFile.is_open()) { effects_.clear(); effectsKeys_.clear(); bool effectFound; Effect tempEffect; while (!openFile.eof()) { std::string line; std::getline(openFile, line); //< Load line line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); //< Remove spaces from line if (line.find("//") != std::string::npos) line.erase(line.begin(), line.end()); else if (line.find("Effect{") != std::string::npos) effectFound = true; if(effectFound == true) if (line.find("ID=") != std::string::npos || line.find("id=") != std::string::npos) { line.erase(0, line.find('=') + 1); tempEffect.SetID(line); std::cout << "ID(" << line << ")" << std::endl << "Orders: " << std::endl; } else if (line.find("Order=") != std::string::npos || line.find("order=") != std::string::npos) { line.erase(0, line.find('=') + 1); tempEffect.PushOrder(line); std::cout << "- " << line << std::endl; } if (line.find("}") != std::string::npos) { AddEffect(tempEffect.GetID(), tempEffect); effectFound = false; } } } } void GameObjects::LoadItems() { std::ifstream openFile("Items.txt"); if (openFile.is_open()) { items_.clear(); itemsKeys_.clear(); Item tempItem; bool itemFound; while (!openFile.eof()) { std::string line; std::getline(openFile, line); line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); if (line.find("//") != std::string::npos) line.erase(line.begin(), line.end()); else if (line.find("Item{") != std::string::npos) itemFound = true; if (itemFound == true) { if(line.find("ID=") != std::string::npos) tempItem.SetID(LoadStringValue(line, "ID=")); if(line.find("Name=") != std::string::npos) tempItem.SetName(LoadStringValue(line, "Name=")); if(line.find("Description=") != std::string::npos) tempItem.SetDescription(LoadStringValue(line, "Description=")); if (line.find("Icon=") != std::string::npos) tempItem.SetIconTextureID(LoadStringValue(line, "Icon=")); if (line.find("Cooldown=") != std::string::npos) tempItem.SetTimeOfCooldown(LoadIntegerValue(line, "Cooldown=")); if (line.find("Charges=") != std::string::npos) tempItem.SetAmountOfCharges(LoadIntegerValue(line, "Charges=")); if (line.find("Price=") != std::string::npos) tempItem.SetPrice(LoadIntegerValue(line, "Price=")); if (line.find("IsTargetingAlly=") != std::string::npos) tempItem.IsTargetingAlly(LoadBooleanValue(line, "IsTargetingAlly=")); if (line.find("IsTargetingEnemy=") != std::string::npos) tempItem.IsTargetingEnemy(LoadBooleanValue(line, "IsTargetingEnemy=")); if (line.find("IsTargetingSelf=") != std::string::npos) tempItem.IsTargetingSelf(LoadBooleanValue(line, "IsTargetingSelf=")); if (line.find("IsUsingImmediately=") != std::string::npos) tempItem.IsUsingImmediately(LoadBooleanValue(line, "IsUsingImmediately=")); if (line.find("IsUsingOnTarget=") != std::string::npos) tempItem.IsUsingOnTarget(LoadBooleanValue(line, "IsUsingOnTarget=")); if (line.find("IsUsable=") != std::string::npos) tempItem.IsUsable(LoadBooleanValue(line, "IsUsable=")); } if (line.find("}") != std::string::npos) { AddItem(tempItem.GetID(), tempItem); itemFound = false; } } } } void GameObjects::LoadSkills() { std::ifstream openFile("Skills.txt"); if (openFile.is_open()) { items_.clear(); itemsKeys_.clear(); Skill tempSkill; bool skillFound; while (!openFile.eof()) { std::string line; std::getline(openFile, line); line.erase(std::remove(line.begin(), line.end(), ' '), line.end()); if (line.find("//") != std::string::npos) line.erase(line.begin(), line.end()); else if (line.find("Skill{") != std::string::npos) skillFound = true; if (skillFound == true) { if (line.find("ID=") != std::string::npos) tempSkill.SetID(LoadStringValue(line, "ID=")); if(line.find("Name=") != std::string::npos) tempSkill.SetName(LoadStringValue(line, "Name=")); if (line.find("Descr-tion=") != std::string::npos) tempSkill.SetDescription(LoadStringValue(line, "Description=")); if(line.find("Icon=") !=std::string::npos) tempSkill.SetIconTextureID(LoadStringValue(line,"Icon=")); if(line.find("Cooldown=") != std::string::npos) tempSkill.SetTimeOfCooldown(LoadIntegerValue(line, "Cooldown=")); if(line.find("IsTargetingSelf=") != std::string::npos) tempSkill.IsTargetingSelf(LoadBooleanValue(line, "IsTargetingSelf=")); if(line.find("IsTargetingEnemy=") != std::string::npos) tempSkill.IsTargetingEnemy(LoadBooleanValue(line, "IsTargetingEnemy=")); if(line.find("IsTargetingAlly=") != std::string::npos) tempSkill.IsTargetingAlly(LoadBooleanValue(line, "IsTargetingAlly=")); if(line.find("IsUseImmediately=") != std::string::npos) tempSkill.IsUsingImmediately(LoadBooleanValue(line, "IsUseImmediately=")); if(line.find("IsUseOnTarget=")!=std::string::npos) tempSkill.IsUsingOnTarget(LoadBooleanValue(line, "IsUseOnTarget=")); if(line.find("IsUsable=") != std::string::npos) tempSkill.IsUsable(LoadBooleanValue(line,"IsUsable=")); if(line.find("}") != std::string::npos) { skillFound=false; AddSkill(tempSkill.GetID(), tempSkill); } } } } } bool GameObjects::DidItemExists(std::string key) { if (items_.count(key) == 1) return true; std::cout << "GameObjects::DidItemExists(): Item doesn't exists" << std::endl; return false; } bool GameObjects::DidEffectExists(std::string key) { if (effects_.count(key) == 1) return true; std::cout << "GameObjects::DidEffectExists(): Effect doesn't exists" << std::endl; return false; } bool GameObjects::DidSkillExists(std::string key) { if (skills_.count(key) == 1) return true; std::cout << "GameObjects::DidSkillsExists(): Skill doesn't exists" << std::endl; return false; } int GameObjects::LoadIntegerValue(std::string textLine, std::string searchedCommand) { textLine.erase(0, textLine.find('=') + 1); std::cout << searchedCommand << textLine << std::endl; return atoi(textLine.c_str()); } std::string GameObjects::LoadStringValue(std::string textLine, std::string searchedCommand) { textLine.erase(0, textLine.find('=') + 1); std::cout << searchedCommand << textLine << std::endl; return textLine; } bool GameObjects::LoadBooleanValue(std::string textLine, std::string searchedCommand) { textLine.erase(0, textLine.find('=') + 1); std::cout << searchedCommand << textLine << std::endl; if(textLine == "True"||textLine == "true" || textLine == "1") return true; return false; } std::string GameObjects::ConvertToString(bool booleanVariable) { if (booleanVariable == true) return "true"; return "false"; } std::string GameObjects::ConvertToString(int integerVariable) { return std::to_string(integerVariable); } void GameObjects::RemoveEffectsKeys(std::string key) { if (!effectsKeys_.empty()) { for (auto i = effectsKeys_.begin(); i != effectsKeys_.end(); i++) if (effectsKeys_[std::distance(effectsKeys_.begin(), i)] == key) { effectsKeys_.erase(i); break; } } else std::cout << "GameObjects::RemoveEffectsKeys(): keys vector is empty" << std::endl; } bool GameObjects::SetItemID(std::string currentID, std::string newID) { if (items_.count(currentID) == 1) { items_[currentID].SetName(newID); for (auto i = itemsKeys_.begin(); i != itemsKeys_.end(); i++) if (itemsKeys_[std::distance(itemsKeys_.begin(), i)] == currentID) { itemsKeys_[std::distance(itemsKeys_.begin(), i)] = newID; break; } return true; } return false; }
[ "bezifabr@gmail.com" ]
bezifabr@gmail.com
a6bedb2125e6a6a65bc4e2c6b505beec43c42de5
c3a424748ca2a3bc8604d76f1bf70ff3fee40497
/legacy_POL_source/POL_2008/src/clib/sckutil.h
db2cc990fee3681e6fb6a9443e1f9cf6a7818fbf
[]
no_license
polserver/legacy_scripts
f597338fbbb654bce8de9c2b379a9c9bd4698673
98ef8595e72f146dfa6f5b5f92a755883b41fd1a
refs/heads/master
2022-10-25T06:57:37.226088
2020-06-12T22:52:22
2020-06-12T22:52:22
23,924,142
4
0
null
null
null
null
UTF-8
C++
false
false
379
h
#ifndef SCKUTIL_H #define SCKUTIL_H #include <string> class Socket; bool readline( Socket& sck, std::string& s, unsigned long interchar_timeout_secs = 0, unsigned maxlen = 0 ); void writeline( Socket& sck, const std::string& s ); bool readstring( Socket& sck, string& s, unsigned long interchar_secs, unsigned length ); #endif
[ "hopelivesproject@gmail.com" ]
hopelivesproject@gmail.com
64f47e1458608b9e4a50813a2f9ea782da0c6433
65ece8de4e4f0b440454c316e6e4fc8702221894
/chapter4/ex4.7.1.cpp
3ad596752a4240a1d7e14c021ad25a22ae179f9d
[]
no_license
bobchin/self-study-cpp
da765839cb0b2a5cbd1f03c68988b7e6bacb88ef
fd244d915ebe29eca66aeabff3c0e751553e4157
refs/heads/master
2021-01-15T08:32:10.456531
2016-10-11T05:03:52
2016-10-11T05:03:52
68,779,098
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include <iostream> using namespace std; class myclass { int who; public: myclass(int n) { who = n; cout << "コンストラクタ呼び出し" << who << "\n"; } ~myclass() { cout << "デストラクタ呼び出し" << who << "\n"; } int id() { return who; } }; // myclassオブジェクトを値渡しする void f(myclass o) { cout << "受け取り " << o.id() << "\n"; } int main() { // 値渡ししているのでオブジェクトがコピーされ // デストラクタが関数の終わりでコールされる myclass x(1); f(x); return 0; }
[ "k-ichihashi@hokkai-v.co.jp" ]
k-ichihashi@hokkai-v.co.jp
20f66cc234465bfa5861f0c1bcdc94db680bfa50
734686d6c88a779eda24392ede30311872790490
/Main/UVLeds.ino
9275f3d486c1b24730b320352b97ef8b9166913e
[]
no_license
jeroenremans/bomb_escape
47e4340e82b5b2583ededbd7440827a995e8a02e
0afa422f9d0eaac28bb46661322137e3a00fd975
refs/heads/master
2021-04-06T00:16:11.333517
2018-03-11T17:24:30
2018-03-11T17:24:30
124,778,637
1
0
null
null
null
null
UTF-8
C++
false
false
714
ino
// 14-17 const int LED_1_PIN = 22; const int LED_2_PIN = 23; const int LED_3_PIN = 24; const int LED_4_PIN = 25; void uvLedsSetup() { // Servo pinMode(LED_1_PIN, OUTPUT); pinMode(LED_2_PIN, OUTPUT); pinMode(LED_3_PIN, OUTPUT); pinMode(LED_4_PIN, OUTPUT); } void uvLedsLoop() { digitalWrite(22, LOW); digitalWrite(23, LOW); } void demoLoopUvLeds() { if ((millis()/1000) % 2 == 0) { digitalWrite(LED_1_PIN, HIGH); digitalWrite(LED_2_PIN, HIGH); digitalWrite(LED_3_PIN, HIGH); digitalWrite(LED_4_PIN, HIGH); } else { digitalWrite(LED_1_PIN, LOW); digitalWrite(LED_2_PIN, LOW); digitalWrite(LED_3_PIN, LOW); digitalWrite(LED_4_PIN, LOW); } }
[ "joenremans@gmail.com" ]
joenremans@gmail.com
fb2982d24264bf30d3025e8802a736477a2ab730
08a46d882b8e69efd5090555915f39583cb0067a
/src/rpc/client.cpp
f4e6c87f5f99ae2f71e64ceeeb4717c95d7f8bd4
[ "MIT" ]
permissive
Bitcoin-OLD/Bitcoin-OLD
3a7d36ce9d7ba6c238b5e67443290172318c09d0
16627f390aa418a99103843f9d94c48931fad826
refs/heads/master
2020-04-16T21:00:10.631744
2019-01-15T19:39:39
2019-01-15T19:39:39
165,907,352
0
0
null
null
null
null
UTF-8
C++
false
false
7,689
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoinold Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specifiy a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "settxfee", 0, "amount" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbyaccount", 1, "minconf" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "include_empty" }, { "listreceivedbyaddress", 2, "include_watchonly" }, { "listreceivedbyaccount", 0, "minconf" }, { "listreceivedbyaccount", 1, "include_empty" }, { "listreceivedbyaccount", 2, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "include_watchonly" }, { "getblockhash", 0, "height" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "move", 2, "amount" }, { "move", 3, "minconf" }, { "sendfrom", 2, "amount" }, { "sendfrom", 3, "minconf" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "listaccounts", 0, "minconf" }, { "listaccounts", 1, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 4, "subtractfeefrom" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "signrawtransaction", 1, "prevtxs" }, { "signrawtransaction", 2, "privkeys" }, { "sendrawtransaction", 1, "allowhighfees" }, { "fundrawtransaction", 1, "options" }, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatefee", 0, "nblocks" }, { "estimatepriority", 0, "nblocks" }, { "estimatesmartfee", 0, "nblocks" }, { "estimatesmartpriority", 0, "nblocks" }, { "prioritisetransaction", 1, "priority_delta" }, { "prioritisetransaction", 2, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find("="); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; }
[ "bitcoinold@protonmail.com" ]
bitcoinold@protonmail.com
52e25b03e075ccdc306265ca26eeb151a8055f50
bdfca7d4bd6e1baf2c43e593de66fcba80afadeb
/prog-verf/assignment1/sketch-1.7.5/sketch-frontend/test/sk/seq/miniTestb475.cpp
5820e9526009cba0d8b432a3231ee597f62cef58
[]
no_license
wanghanxiao123/Semester4
efa82fc435542809d6c1fbed46ed5fea1540787e
c37ecda8b471685b0b6350070b939d01122f5e7f
refs/heads/master
2023-03-22T06:47:16.823584
2021-03-15T10:46:53
2021-03-15T10:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <cstdio> #include <assert.h> #include <iostream> using namespace std; #include "vops.h" #include "miniTestb475.h" namespace ANONYMOUS{ void main__Wrapper(int i, int j) { _main(i, j); } void main__WrapperNospec(int i, int j) {} void _main(int i, int j) { int x_s1=0; foo(i, x_s1); int y_s3=0; foo(j, y_s3); if ((i) == (j)) { assert ((x_s1) == (y_s3));; } if ((i) > (j)) { assert ((x_s1) >= (j));; } assert ((x_s1) > (10));; assert ((y_s3) > (10));; } void foo(int i, int& _out) { int rv_s5=0; moo(i, rv_s5); _out = rv_s5; assert ((rv_s5) > (10));; assert ((rv_s5) >= (i));; return; } void moo(int i, int& _out) { _out = i + 11; } }
[ "akshatgoyalak23@gmail.com" ]
akshatgoyalak23@gmail.com
7479b30794e09926f655b5a65d801b1d3888a066
50e0524989ca0c59fa169169897979e1de28506b
/aliengo_gazebo/src/body.h
481f0125b96ac4af0b13bcc848ea7f007f664ce9
[]
no_license
SiChiTong/aliengo_delivery
dfadcf8170b51fc46d474775ded88c951e11aa1d
c4f28b91c32dd42f6043e5a582cc32a87aa3870e
refs/heads/master
2023-01-31T07:33:46.249875
2020-12-09T07:15:39
2020-12-09T07:15:39
320,000,768
1
1
null
2020-12-09T15:35:48
2020-12-09T15:35:47
null
UTF-8
C++
false
false
820
h
/************************************************************************ Copyright (c) 2018-2019, Unitree Robotics.Co.Ltd. All rights reserved. Use of this source code is governed by the MPL-2.0 license, see LICENSE. ************************************************************************/ #ifndef __BODY_H__ #define __BODY_H__ #include "ros/ros.h" #include "laikago_msgs/LowCmd.h" #include "laikago_msgs/LowState.h" #include "laikago_msgs/HighState.h" #define PosStopF (2.146E+9f) #define VelStopF (16000.f) namespace laikago_model { extern ros::Publisher servo_pub[12]; extern ros::Publisher highState_pub; extern laikago_msgs::LowCmd lowCmd; extern laikago_msgs::LowState lowState; void stand(); void motion_init(); void sendServoCmd(); void moveAllPosition(double* jointPositions, double duration); } #endif
[ "e0444217@u.nus.edu" ]
e0444217@u.nus.edu
04627e49abe72378ce57c80066d3472ee4d9ea35
0ecfa021ff82d67132b18ffe6ad7ad05c4e3a71d
/Convolutional Code/S_random interleaver/s-random.cpp
331305507e035a0937e85f22217c0a800d4a0d6f
[]
no_license
JosephHuang913/Channel-Coding
954673264db96cc4c882a09fca6e818b4c2e8584
6e6efa9f3970a93a343b8ec36f49365df5607e30
refs/heads/main
2023-01-21T00:08:12.570899
2020-11-24T01:07:35
2020-11-24T01:07:35
315,481,921
0
0
null
null
null
null
UTF-8
C++
false
false
2,622
cpp
/**********************************************/ /* Author: Chao-wang Huang */ /* Date: Thursday, September 23, 2004 */ /* S-random interleaver generator */ /**********************************************/ #include <stdio.h> #include <math.h> //#include <time.h> #include <ctime> #include <conio.h> #include <stdlib.h> #include <iostream> #include <stdafx.h> using namespace std; #define N 2048 // Interleaver size #define S 32 // S parameter of S-random interleaver int main(void) { time_t t, start, end; int i, j, k, sol, position, flag, count, *interleaver, *check; FILE *fp1; start = time(NULL); printf("S-random Interleaver Generator\n"); printf("This program is running. Don't close, please!\n\n"); srand((unsigned) time(&t)); interleaver = new int[N]; check = new int[N]; fp1 = fopen("s_random.txt", "w"); count = 0; do { count ++; for(i=0; i<N; i++) check[i] = 0; for(i=0; i<N; i++) { do { flag = 0; //position = random(N); position = rand() % N; if(check[position]==1) flag = 1; else { for(j=i-1; (j>i-S && j>=0); j--) if(abs(position - interleaver[j]) < S) { flag = 1; break; } if(flag==1) { for(k=0; k<N; k++) if(check[k]==0) { sol = 1; for(j=i-1; (j>i-S && j>=0); j--) if(abs(k - interleaver[j]) < S) { sol = 0; break; } if(sol==1) break; } if(sol==0) { flag = 0; } } } } while(flag); // printf("%d %d\n", i, position); // cout << i << " " << position << endl; check[position] = 1; interleaver[i] = position; } } while(sol==0); cout << endl << "Iteration: " << count << endl; for(i=0; i<N; i++) fprintf(fp1, "%d %d\n", i, interleaver[i]); delete interleaver; delete check; fclose(fp1); end = time(NULL); printf("Total elapsed time: %.0f(sec)\n", difftime(end,start)); printf("This program is ended. Press any key to continue.\n"); getch(); return 0; }
[ "huangcw913@gmail.com" ]
huangcw913@gmail.com
441764aedd755eec87ae91579180957396c752da
09e5294e6019b13f8bdfd9daf1b6ce358062ce34
/src/main.cpp
efe364abc6732a48176ec7081761b43c0bc752ef
[]
no_license
soarchorale/interview
2f84801ac994a41e3c2e8436b8f350859396353e
433181772aa37ca6b195a42ff38d7b93c6684d44
refs/heads/main
2023-02-19T21:53:39.470325
2021-01-24T12:10:51
2021-01-24T12:10:51
332,129,412
1
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
#include "complexAdd.h" #include <iostream> #include <thread> int main() { ComplexAdd* complex_add = new ComplexAdd(); std::thread A(&ComplexAdd::ProducerInt, complex_add); std::thread B(&ComplexAdd::ProducerDouble, complex_add); std::thread C(&ComplexAdd::Comsumer, complex_add); std::thread D(&ComplexAdd::Print, complex_add); A.join(); B.join(); C.join(); D.join(); delete complex_add; return 0; }
[ "463052596@qq.com" ]
463052596@qq.com
317a32a13b362247e026cb11bc72104b18b3f5c2
69a8a80e7016e3ff2b26f0355941dba0d441a638
/src/Block.cpp
894595ad022474c6a7283d60f975def1598c9f0d
[]
no_license
questcoinn/Qkcolb
7231f5787e0a7ddaaf3ba5350b7c7e86b2e58515
03961303f85605c0b0ed0fced1752319ff34719f
refs/heads/master
2023-05-02T03:18:11.859874
2021-05-10T10:56:31
2021-05-10T10:56:31
365,523,492
0
0
null
null
null
null
UTF-8
C++
false
false
2,802
cpp
#include <ctime> #include "Block.hpp" #include "sha256.hpp" #ifdef DEBUG #include <iostream> #endif qb::Block::Block(std::string data, std::string prevBlockHash, int64 targetBit) :data(data) ,prevBlockHash(prevBlockHash) { this->timestamp = std::chrono::system_clock::now(); this->setHash(targetBit); } void qb::Block::setHash(int64 targetBit) { std::string _timestamp = std::to_string(std::chrono::system_clock::to_time_t(this->timestamp)); std::string targetHash = ""; for(int i = 0; i < 64; i++) { if(i != (targetBit - 1) / 4) { targetHash += '0'; } else if(targetBit % 4 == 0) { targetHash += '1'; } else if(targetBit % 4 == 3) { targetHash += '2'; } else if(targetBit % 4 == 2) { targetHash += '4'; } else { targetHash += '8'; } } #ifdef DEBUG std::cout << "Mining the block containing \"" << this->data << "\"\n"; #endif for(int64 salt = 0; salt < INT64_MAX; salt++) { std::string _salt = std::to_string(salt); std::string newHash = qb::sha256(this->prevBlockHash + this->data + _timestamp + _salt); #ifdef DEBUG std::cout << "\r" << newHash; #endif if(newHash < targetHash) { this->hash = newHash; this->nonce = salt; break; } } #ifdef DEBUG std::cout << "\n\n"; #endif } bool qb::Block::isValid() { std::string _timestamp = std::to_string(std::chrono::system_clock::to_time_t(this->timestamp)); std::string _nonce = std::to_string(this->nonce); return this->hash == qb::sha256(this->prevBlockHash + this->data + _timestamp + _nonce); } #ifdef DEBUG void qb::Block::print() { std::cout << "Prev. hash: " << std::hex << this->prevBlockHash << "\n"; std::cout << "Data: " << std::hex << this->data << "\n"; std::cout << "Hash: " << std::hex << this->hash << "\n"; std::cout << "\n"; } #endif qb::BlockChain::BlockChain(int64 targetBit) :targetBit(targetBit) { this->list = std::list<qb::Block>(); this->list.push_back(qb::Block("Genesis Block", "", this->targetBit)); } std::list<qb::Block>::iterator &qb::BlockChain::begin() { this->iterator = this->list.begin(); return this->iterator; } std::list<qb::Block>::iterator &qb::BlockChain::end() { this->iterator = this->list.end(); return this->iterator; } std::size_t qb::BlockChain::size() { return this->list.size(); } void qb::BlockChain::addBlock(std::string data) { qb::Block newBlock(data, this->list.back().hash, this->targetBit); if(newBlock.isValid()) { this->list.push_back(newBlock); } #ifdef DEBUG else { std::cout << "Failed mining for some reason\n"; } #endif }
[ "iopell2007@gmail.com" ]
iopell2007@gmail.com
73497bc7b6d44357f434c69ef5ef567cdb63c810
d5328e2f5c2817cf8e558119f7084528a9ab75eb
/src/std/rng.cpp
218aa8f25fab20a860cf974bdd8622c71e422692
[ "MIT" ]
permissive
arudei-dev/Feral
a0e31517fd809533b5b1b8836c69fb991cf0d1c1
44c0254f9f85dbf0f11f8cc1f86dc106f6a16d92
refs/heads/master
2023-06-09T11:24:00.851064
2021-06-29T13:21:59
2021-06-29T13:22:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
cpp
/* MIT License Copyright (c) 2021 Feral Language repositories 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. */ #include <random> #include "VM/VM.hpp" gmp_randstate_t rngstate; ////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// Functions //////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// var_base_t *rng_seed(vm_state_t &vm, const fn_data_t &fd) { if(!fd.args[1]->istype<var_int_t>()) { vm.fail(fd.src_id, fd.idx, "expected seed value to be integer, found: %s", vm.type_name(fd.args[1]).c_str()); return nullptr; } gmp_randseed(rngstate, INT(fd.args[1])->get()); return vm.nil; } // [0, to) var_base_t *rng_get(vm_state_t &vm, const fn_data_t &fd) { if(!fd.args[1]->istype<var_int_t>()) { vm.fail(fd.src_id, fd.idx, "expected upper bound to be an integer, found: %s", vm.type_name(fd.args[1]).c_str()); return nullptr; } var_int_t *res = make<var_int_t>(0); mpz_urandomm(res->get(), rngstate, INT(fd.args[1])->get()); return res; } INIT_MODULE(rng) { gmp_randinit_default(rngstate); var_src_t *src = vm.current_source(); src->add_native_fn("seed", rng_seed, 1); src->add_native_fn("get_native", rng_get, 1); return true; } DEINIT_MODULE(rng) { gmp_randclear(rngstate); }
[ "ElectruxRedsworth@gmail.com" ]
ElectruxRedsworth@gmail.com
c01abc4221d204f7b00785a4efb7dc23025165c0
d31b701323aa0d0752fee4a373c8e41f0304f5f8
/lge_texcache.cpp
92cbd545ace9f237d3e2e6d74d9b2565dc89fa79
[ "CC0-1.0" ]
permissive
lieff/lge
444c2b93ad6b9cb92585e9dce3617bbe98d77c29
2738ddcdb83431a5113bdce06fac80d7571a39ee
refs/heads/master
2020-04-22T02:55:15.575204
2015-09-08T16:26:50
2015-09-08T16:26:50
42,123,892
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cpp
#include "lge_texcache.h" CTexturesCache::CTexturesCache() { m_tex_ssbo_buf = 0; m_ssbo_buf_size = 0; m_commit_needed = false; m_textures.reserve(16); m_tex_handles.reserve(16); } CTexturesCache::~CTexturesCache() { DeleteTexturesBlock(0, (unsigned int)m_textures.size()); } unsigned int CTexturesCache::AllocTexture() { GLuint texId = 0; glGenTextures(1, &texId); if (!m_free_gaps.empty()) { std::map<unsigned int, bool>::iterator it = m_free_gaps.begin(); m_textures[it->first] = texId; m_tex_handles[it->first] = 0; m_free_gaps.erase(it); return it->first; } if (m_textures.size() == m_textures.capacity()) { m_textures.reserve(m_textures.capacity() * 2); m_tex_handles.reserve(m_textures.capacity() * 2); } m_textures.push_back(texId); m_tex_handles.push_back(0); m_commit_needed = true; return (unsigned int)(m_textures.size() - 1); } unsigned int CTexturesCache::AllocTexture(unsigned int width, unsigned int height, void *image) { unsigned int tex = AllocTexture(); glBindTexture(GL_TEXTURE_2D, m_textures[tex]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); pglGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLuint64 texHandle = pglGetTextureHandleNV(m_textures[tex]); pglMakeTextureHandleResidentNV(texHandle); m_tex_handles[tex] = texHandle; return tex; } bool CTexturesCache::AllocTextureBlock(unsigned int count, unsigned int *texs) { for (unsigned int i = 0; i < count; i++) texs[i] = AllocTexture(); return true; } unsigned int CTexturesCache::LoadTexture(const char *filename) { int tex = AllocTexture(); return tex; } bool CTexturesCache::LoadToTexture(unsigned int tex, const char *filename) { return true; } void CTexturesCache::DeleteTexture(unsigned int tex) { glDeleteTextures(1, &m_textures[tex]); m_textures[tex] = 0; m_tex_handles[tex] = 0; m_free_gaps[tex] = true; } void CTexturesCache::DeleteTexturesBlock(unsigned int first, unsigned int count) { for (unsigned int i = 0; i < count; i++) DeleteTexture(i); } void CTexturesCache::DeleteTexturesBuf(unsigned int *texs, unsigned int count) { for (unsigned int i = 0; i < count; i++) DeleteTexture(texs[i]); } void CTexturesCache::CommitToGPU() { if (!m_commit_needed || m_tex_handles.size() == 0) return; bool allocated = false; if (m_tex_handles.size() != m_ssbo_buf_size) { if (m_tex_ssbo_buf) pglDeleteBuffers(1, &m_tex_ssbo_buf); pglGenBuffers(1, &m_tex_ssbo_buf); allocated = true; } pglBindBuffer(GL_UNIFORM_BUFFER, m_tex_ssbo_buf); if (allocated) pglBufferData(GL_UNIFORM_BUFFER, m_tex_handles.size()*sizeof(GLuint64), &m_tex_handles[0], GL_DYNAMIC_DRAW); else pglBufferSubData(GL_UNIFORM_BUFFER, 0, m_tex_handles.size()*sizeof(GLuint64), &m_tex_handles[0]); pglBindBufferRange(GL_SHADER_STORAGE_BUFFER, TEX_SSBO_BINDING, m_tex_ssbo_buf, 0, m_tex_handles.size()*sizeof(GLuint64)); pglBindBuffer(GL_UNIFORM_BUFFER, 0); }
[ "lieff@users.noreply.github.com" ]
lieff@users.noreply.github.com
747caa5696a175c03637a3efc80546768a7c0fb2
93f4aa14d544952c0fdc7ed29404d47fd2fda32a
/Source/Delay.cpp
37fe8ae75f4c84f412d16d7bd8e7c69ad01d1ca8
[]
no_license
harpershapiro/BuzzSaw
be2c248d8cfa58f5009ddbfd8889a6106695ef20
c2f92771464ac48f2f6a2a66358507b99a77fac2
refs/heads/master
2022-12-10T07:43:17.715081
2020-09-07T22:27:01
2020-09-07T22:27:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,369
cpp
/* ============================================================================== Delay.cpp Created: 23 May 2020 5:47:22pm Author: harpe ============================================================================== */ #include "Delay.h" Delay::Delay() : delayWritePosition(0), delayReadPosition(0) { } Delay::~Delay() { } void Delay::initialize(double sampleRate) { // Allocate and zero the delay buffer (size will depend on current sample rate) delayBufferLength = static_cast<int>(2.0 * sampleRate); //sanity check length if (delayBufferLength < 1) delayBufferLength = 1; delayBuffer.setSize(1, delayBufferLength); delayBuffer.clear(); this->sampleRate = sampleRate; delayReadPosition = static_cast<int>(delayWritePosition - (delaySec * sampleRate) + delayBufferLength) % delayBufferLength; setActive(true); } //process a single channel void Delay::processBlock(float* buffer, const int numSamples) { //bypassed if (!isActive || delaySec<=0) { return; } //temps for write and read positions int dpr = delayReadPosition; int dpw = delayWritePosition; //assuming a single channel so i'll just use the left float* delayData = delayBuffer.getWritePointer(0); // for (int i = 0; i < numSamples; i++) { const float in = buffer[i]; float out = 0.0; //output blended out = (dryLevel * in) + (wetLevel * delayData[dpr]); delayData[dpw] = in + (delayData[dpr] * feedback); //increment + wrap r/w positions if (++dpr >= delayBufferLength) dpr = 0; if (++dpw >= delayBufferLength) dpw = 0; buffer[i] = out; } //write back r/w positions delayReadPosition = dpr; delayWritePosition = dpw; } void Delay::setDelaySec(float ds) { delaySec = ds; //just trying this to parameterize delaySec delayReadPosition = static_cast<int>(delayWritePosition - (delaySec * sampleRate) + delayBufferLength) % delayBufferLength; } void Delay::setFeedback(float fb) { feedback = fb; } void Delay::setWetLevel(float wl) { wetLevel = wl; } void Delay::setDryLevel(float dl) { dryLevel = dl; } void Delay::setActive(bool state) { isActive = state; //clear buffer when disabled if (!state) { delayBuffer.clear(); } }
[ "harper.shapiro@gmail.com" ]
harper.shapiro@gmail.com
08026c54d5c4ab5e7ba65f8ea661e01872940235
f80beb46c4d1ee75953c10d152e71be2dbce2ce7
/RBox/src/RBDetectorConstruction.cc
974e18e806a5777785e3ee78fc6f5c99c8630e9b
[]
no_license
zLng1/RBox
34638c15d2caee970205eb5b8b03bad5f8d7c647
68ce85dcb9f1245fb8ce1d6a694984668737c881
refs/heads/main
2023-04-09T12:20:54.390281
2021-04-24T00:10:18
2021-04-24T00:10:18
360,943,267
0
0
null
null
null
null
UTF-8
C++
false
false
15,234
cc
#include "RBDetectorConstruction.hh" #include "G4NistManager.hh" #include "G4Material.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4RotationMatrix.hh" #include "G4Transform3D.hh" #include "G4SubtractionSolid.hh" #include "G4OpticalSurface.hh" #include "G4LogicalBorderSurface.hh" #include "G4LogicalSkinSurface.hh" #include "G4SDManager.hh" #include "G4VSensitiveDetector.hh" #include "G4MultiFunctionalDetector.hh" #include "G4VPrimitiveScorer.hh" #include "G4PSEnergyDeposit.hh" #include "G4PSDoseDeposit.hh" #include "G4VisAttributes.hh" #include "G4RotationMatrix.hh" #include "G4PhysicalConstants.hh" #include "G4SystemOfUnits.hh" #include "RBSiPMSD.hh" RBDetectorConstruction::RBDetectorConstruction() : G4VUserDetectorConstruction(), fCheckOverlaps(true) //check for overlaps in geometry { BoxXYZ = 20.0*cm; //Define the dimensions of the Box. } //Destructor for RBDetector Construction. RBDetectorConstruction::~RBDetectorConstruction() = default; G4VPhysicalVolume* RBDetectorConstruction::Construct() { G4NistManager* nist = G4NistManager::Instance(); default_mat = nist->FindOrBuildMaterial("G4_AIR"); //get our default Air properties from Geant4 Box_mat = nist->FindOrBuildMaterial("G4_Al"); //get our default Aluminum properties from Geant4 // Necessary Values G4double world_sizeXYZ = 50*cm; // For our world volume size. G4double padding_1 = 0.1*mm; // For our Al foil wrapping G4double padding_2 = 0.2*mm; // For our Al foil wrapping G4double SiPM_x = (padding_2 - padding_1)+0.5*cm; // define the 'depth' of the SiPM G4double SiPM_y = 1.09*cm; // define the 'length' of the SiPM G4double SiPM_z = 1.09*cm; // define the 'width' of the SiPM G4double Hole_x = (padding_2 - padding_1)+0.5*cm; // define the 'depth' of the hole for the SiPM G4double Hole_y = 1.1*cm; // define the 'length' of the hole for the SiPM G4double Hole_z = 1.1*cm; // define the 'width' of the hole for the SiPM G4RotationMatrix* yRot = new G4RotationMatrix; // need to rotate our hole and SiPM so they align properly relative to the box yRot->rotateY(90*deg); //rotate about the y-axis 90 degrees. // // Building the world volume where the simulation takes place. // //Build the world geometry as a big box with dimension of world_sizeXYZ^3. G4Box* solidWorld = new G4Box("World", //declare its name 0.5*world_sizeXYZ, 0.5*world_sizeXYZ, 0.5*world_sizeXYZ); //declare its dimensions G4LogicalVolume* WorldLV = //Making our Logical volume for the world new G4LogicalVolume(solidWorld, //declare its geometric solid default_mat, //declare its material (Air here) "WorldLV"); //declare its name G4VPhysicalVolume* WorldPV = //Making our Physical volume for the world new G4PVPlacement(0, //declare no rotation G4ThreeVector(), //place at (0,0,0) (This denotes the origin for the whole simulation geometry) WorldLV, //declare its logical volume "WorldPV", //declare its name 0, //declare its mother volume (It has none as it is the mother to all other volumes in the simulation). false, //no boolean operations (such as subtraction) 0, //copy number fCheckOverlaps); //checking overlaps // // Making the box geometry: // // Build a slightly smaller block which we subtract from the larger block which will create the box. G4Box* smallerBox = new G4Box("SmallerBox", //declare its name 0.5*BoxXYZ+padding_1, 0.5*BoxXYZ+padding_1, 0.5*BoxXYZ+padding_1); //declare its size // Build the slightly bigger block which we turn into a box. G4Box* biggerBox = new G4Box("BiggerBox", //declare its name 0.5*BoxXYZ+padding_2, 0.5*BoxXYZ+padding_2, 0.5*BoxXYZ+padding_2); //declare its dimensions // Subtract the smaller block from the bigger block to make our reflective Aluminum box. G4SubtractionSolid* RBox = new G4SubtractionSolid("RBox", biggerBox, smallerBox); // // Building the SiPM: // G4Box* solidSensor = new G4Box("SiPM", SiPM_x/2, SiPM_y/2, SiPM_z/2); //Build the SiPM geometry as a small wall-like rectangular prism sipmLV = //Making our Logical volume for the SiPM new G4LogicalVolume(solidSensor, //declare its geometric solid default_mat, //declare its material (we also used air here to ensure photons that hit the SiPM exit the box for visualization sake) "sipmLV"); //declare its name G4PVPlacement* sipmPV = //Making our Physical volume for the SiPM new G4PVPlacement(yRot, //rotate about y-axis 90 degrees G4ThreeVector( 0, 0, 0.5*BoxXYZ ), //at (0,0,0) sipmLV, //its logical volume "sipmPV", //its name WorldLV, //its mother volume false, //no boolean operation 0, //copy number fCheckOverlaps); //checking overlaps // SiPM sensor visualization attribute G4VisAttributes photonDetectorVisAtt(G4Colour::Red()); //makes the SiPM red so we can see it easier photonDetectorVisAtt.SetForceWireframe(true); //makes the SiPM visualization wire frame so we can see photons through it photonDetectorVisAtt.SetLineWidth(3.); //setting the line width sipmLV->SetVisAttributes(photonDetectorVisAtt); //give the SiPM these settings // // Making a hole for the SiPM. // G4Box* solidSensorHole = new G4Box("Hole", Hole_x/2, Hole_y/2, Hole_z/2); //Create a opening hole in one wall of the box for installing the SiPM G4ThreeVector holeTrans( 0, 0, 0.5*BoxXYZ); //this is where we are going to place our hole. //Create the hole by subtracting our hole 'box' from the geometry of the box. G4SubtractionSolid* BoxHole = new G4SubtractionSolid("BoxHole", RBox, solidSensorHole, yRot, holeTrans); // // Building the reflective Aluminum box: // //Define our logical volume for the Box G4LogicalVolume* BoxLV = //Making our Logical volume for the SiPM new G4LogicalVolume(BoxHole, //declare its geometric solid Box_mat, //declare its material (Aluminum here) "BoxLV"); //declare its name //Define our Physical volume for the Box G4PVPlacement* BoxPV = new G4PVPlacement(0, //declare no rotation G4ThreeVector(), //place at (0,0,0) BoxLV, //delare its logical volume "BoxPV", //define its name WorldLV, //delare its mother volume false, //declare that we are using no boolean operation 0, //copy number fCheckOverlaps); //checking overlaps //Make our world volume invisible. WorldLV->SetVisAttributes (G4VisAttributes::GetInvisible()); // //Optical and Surface Properties // //The energy range of our optical photons (roughly aligns with the visible spectrum) G4double photonEnergy[] = {1.79*eV,1.82*eV,1.85*eV,1.88*eV,1.91*eV, 1.94*eV,1.97*eV,2.00*eV,2.03*eV,2.06*eV, 2.09*eV,2.12*eV,2.15*eV,2.18*eV,2.21*eV, 2.24*eV,2.27*eV,2.30*eV,2.33*eV,2.36*eV, 2.39*eV,2.42*eV,2.45*eV,2.48*eV,2.51*eV, 2.54*eV,2.57*eV,2.60*eV,2.63*eV,2.66*eV, 2.69*eV,2.72*eV,2.75*eV,2.78*eV,2.81*eV, 2.84*eV,2.87*eV,2.90*eV,2.93*eV,2.96*eV, 2.99*eV,3.02*eV,3.05*eV,3.08*eV,3.11*eV, 3.14*eV,3.17*eV,3.20*eV,3.23*eV,3.26*eV}; const G4int nEntries = sizeof(photonEnergy)/sizeof(G4double); //define the size of all our arrays based on their interaction with photons of these energies // // Define optical material properties for air // //Refractive index of air is 1.0 G4double RefractiveIndex_Air[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}; assert(sizeof(RefractiveIndex_Air) == sizeof(photonEnergy)); //assert the size of this array to be the same as the photon energy array //Gives the attenuation length of photons to be 10m at all energies. Note this is guessed value. G4double Absorption_Air[] = {10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m, 10.0*m }; assert(sizeof(Absorption_Air) == sizeof(photonEnergy)); //assert the size of this array to be the same as the photon energy array //Allows for 1% chance of optical photons being absorbed by air, otherwise they will reflect/refract through the air (continue their track) G4double AirReflect[] = {0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99 }; assert(sizeof(AirReflect) == sizeof(photonEnergy)); //assert the size of this array to be the same as the photon energy array // // Optical surfaces and boundaries // /* GROUND:The incidence of a photon upon a rough surface requires choosing the angle, a, between a ‘micro-facet’ normal and that of the average surface. The UNIFIED model assumes that the probability of micro-facet normals populates the annulus of solid angle sin(a)dawill be proportional to a gaussian of SigmaAlpha:theOpSurface->SetSigmaAlpha(0.1);where sigma_alpha is in [rad] In the GLISUR model this is indicated by the value of polish; when it is <1, then a random point is generated in a sphere of radius (1-polish), and the corresponding vector is added to the normal. The value 0 means maximum roughness with effective plane of reflection distributedas cos(a).theOpSurface -> SetPolish (0.0) */ // For Air // Material Properties: G4MaterialPropertiesTable *Air = new G4MaterialPropertiesTable(); Air->AddProperty("RINDEX", photonEnergy, RefractiveIndex_Air, nEntries); //set the refractive index based on the above array Air->AddProperty("REFLECTIVITY", photonEnergy, AirReflect, nEntries); //set the reflectivity based on the above array Air->AddProperty("ABSLENGTH", photonEnergy, Absorption_Air, nEntries); //set the attenuation length based on the above array default_mat->SetMaterialPropertiesTable(Air); //add these properties to the Air material // Optical Surface and Boundary Properties G4OpticalSurface *OpticalAir = new G4OpticalSurface("AirSurface"); //declare our air surface OpticalAir->SetModel(unified); //using the unified model OpticalAir->SetType(dielectric_dielectric); //air surface interactions are dielectric-dielectric OpticalAir->SetFinish(polished); //saying air is a polished surface // note: // polishedfrontpainted: only reflection, absorption and no refraction // polished: follows Snell's law // ground: follows Snell's law // // Define a simple mirror-like property for the wrapping material // G4double fBoxPolish = 1; G4OpticalSurface* reflectiveSurface = new G4OpticalSurface("ReflectiveSurface", //declare its name glisur, //using the glisur model ground, //using a ground surface as opposed to a polished one dielectric_metal, fBoxPolish); G4MaterialPropertiesTable* reflectiveSurfaceProperty = new G4MaterialPropertiesTable(); //Since these properties do not depend on photon energies, simply take a two-element array G4double p_box[] = {1.79*eV, 3.26*eV}; //energy range of the optical photons the box interacts with const G4int nbins = sizeof(p_box)/sizeof(G4double); G4double fBoxReflectivity = 1.0; //set reflectivity to 1.0 G4double refl_box[] = {fBoxReflectivity, fBoxReflectivity}; //set array for reflectivity interactions assert(sizeof(refl_box) == sizeof(p_box)); G4double effi_box[] = {0, 0}; //set the array for the reflective efficiency (100% efficiency -> not 100% realistic) assert(sizeof(effi_box) == sizeof(effi_box)); reflectiveSurfaceProperty->AddProperty("REFLECTIVITY",p_box, refl_box, nbins); //set the reflectivity based on the above array reflectiveSurfaceProperty->AddProperty("EFFICIENCY",p_box, effi_box, nbins); //set the reflection efficiency based on the above array reflectiveSurface -> SetMaterialPropertiesTable(reflectiveSurfaceProperty); //set the surface properties for the Box. // Use G4LogicalSkinSurface for one-directional photon propagation new G4LogicalSkinSurface("WrappingSurface", BoxLV, reflectiveSurface); //assign the surface properties to the box logical volume // Print materials G4cout << *(G4Material::GetMaterialTable()) << G4endl; return WorldPV; //always return the physical World } // Use sensitive detector scheme for SiPM. void RBDetectorConstruction::ConstructSDandField() { G4SDManager::GetSDMpointer()->SetVerboseLevel(1); // sensitive detectors auto sdManager = G4SDManager::GetSDMpointer(); //access the Sensitive Detector Manager G4String SDname; auto sipmSD = new RBSiPMSD(SDname="/sipmSD"); //declare our SiPM Sensitive detector sdManager->AddNewDetector(sipmSD); //Give detector attributes to the SiPM sipmLV->SetSensitiveDetector(sipmSD); //link the SiPM logical volume to the Sensitive detector object }
[ "noreply@github.com" ]
zLng1.noreply@github.com
c6933b5e403d3fee4eb28722561e8177c9d2c60b
be6656863a8bb75f4843e0c69cff688f67027e20
/caracter.cpp
7633707afc6ee4d70e0873037912528a337fd4af
[]
no_license
rafaelapure82/C-Parte-2
31669440fa1a12fe67fb8f607608dbec636ce6f7
215c8821e2c9fe3f8b4494b02878bed5731d0f3a
refs/heads/master
2021-05-13T11:54:22.583554
2018-01-11T19:54:16
2018-01-11T19:54:16
117,146,226
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include <iostream> using namespace std; int main(void) { char car; cout << "Introduzca un caracter: "; cin >> car; switch (car) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << car << " es una vocal" << endl; break; default : cout << car << " no es una vocal" << endl; } system("pause"); }
[ "noreply@github.com" ]
rafaelapure82.noreply@github.com
f1338377d4bfc15dee127bcec2220087e998249d
cd5cb70f499898578772195a217ce3b9c9c606ba
/common/redisapi/redisbase.hpp
07f993bda51aac00154ef4a27ee61c8e0291cbee
[]
no_license
qinchun2000/autotrader
9aa6ebdef31a01597f52c55cedea1c7f22de6279
8651754e2562188a5acf9ac400e9709c693afe5e
refs/heads/main
2023-03-21T19:25:07.257203
2021-03-08T09:40:22
2021-03-08T09:40:22
340,294,521
1
1
null
null
null
null
UTF-8
C++
false
false
876
hpp
#ifndef _REDISBASE_H_ #define _REDISBASE_H_ #include <iostream> #include <string.h> #include <string> #include <stdio.h> #include <hiredis/hiredis.h> #include <json/json.h> #include "depthmarket.hpp" using namespace std; class RedisBase { public: RedisBase(); ~RedisBase(); std::string GetHost(); void SetDbNumber(int num); int GetDbNumber(); redisContext *GetRedisContext(); void SetRedisReply(redisReply *reply); redisReply *GetRedisReply(); bool Connect(string host, int port); void DisConnect(); void Empty(); void SelectDb(); void SelectDb(int num); int GetDbSize(); int Exists(string key); void FlushDB(); string Get(string key); void Set(string key, string value); private: redisContext* _connect=nullptr; redisReply *_reply=nullptr; std::string _host; int _port; int _dbnumber=0; }; #endif //_REDISBASE_H_
[ "root@localhost.localdomain" ]
root@localhost.localdomain
c105f68c2e3379ed124e265ce0505fa8055b16e3
d2fb019e63eb66f9ddcbdf39d07f7670f8cf79de
/groups/bsl/bslalg/bslalg_bidirectionallink.h
ff9f8579bdb9deced864adcaa629371da52aa650
[ "MIT" ]
permissive
gosuwachu/bsl
4fa8163a7e4b39e4253ad285b97f8a4d58020494
88cc2b2c480bcfca19e0f72753b4ec0359aba718
refs/heads/master
2021-01-17T05:36:55.605787
2013-01-15T19:48:00
2013-01-15T19:48:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,330
h
// bslalg_bidirectionallink.h -*-C++-*- #ifndef INCLUDED_BSLALG_BIDIRECTIONALLINK #define INCLUDED_BSLALG_BIDIRECTIONALLINK #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide a basic link type for building doubly-linked lists. // //@CLASSES: // bslalg::BidirectionalLink : A node in a doubly-linked list // //@SEE_ALSO: bslalg_bidirectionallinklistutil, bslalg_hashtableimputil // //@DESCRIPTION: This component provides a single POD-like class, // 'BidirectionalLink', used to represent a node in a doubly-linked list. A // 'BidirectionalLink' provides the address to its preceding node, and the // address of its successor node. A null-pointer value for either address // signifies the end of the list. 'BidirectionalLink' does not, however, // contain "payload" data (e.g., a value), as it is intended to work with // generalized list operations (see 'bslalg_bidirectionallinklistutil'). // Clients creating a doubly-linked list must define their own node type that // incorporates 'BidirectionalLink' (generally via inheritance), and that // maintains the "value" stored in that node. // //----------------------------------------------------------------------------- // ///Usage ///----- // This section illustrates intended usage of this component. // ///Example 1: Creating and Using a List Template Class ///- - - - - - - - - - - - - - - - - - - - - - - - - - // Suppose we want to create a linked list template class, it will be called // 'MyList'. // // First, we create the 'MyNode' class, which derives from the // BidirectionalLink class to carry a 'PAYLOAD' object. //.. // template <class PAYLOAD> // class MyNode : public bslalg::BidirectionalLink { // public: // // PUBLIC TYPES // typedef PAYLOAD ValueType; // // private: // // DATA // ValueType d_value; // // private: // // NOT IMPLEMENTED // MyNode(); // MyNode(const MyNode&); // MyNode& operator=(const MyNode&); // // public: // // CREATOR // ~MyNode() {} // // Destroy this object. // // // MANIPULATOR // ValueType& value() { return d_value; } // // Return a reference to the modifiable value stored in this node. // // // ACCESSOR // const ValueType& value() const { return d_value; } // // Return a reference to the non-modifiable value stored in this // // node. // }; //.. // Next, we create the iterator helper class, which will eventually be // defined as a nested type within the 'MyList' class. //.. // // =============== // // MyList_Iterator // // =============== // // template <class PAYLOAD> // class MyList_Iterator { // // PRIVATE TYPES // typedef MyNode<PAYLOAD> Node; // // // DATA // Node *d_node; // // // FRIENDS // template <class PL> // friend bool operator==(MyList_Iterator<PL>, // MyList_Iterator<PL>); // // public: // // CREATORS // MyList_Iterator() : d_node(0) {} // explicit // MyList_Iterator(Node *node) : d_node(node) {} // //! MyList_Iterator(const MyList_Iterator& original) = default; // //! MyList_Iterator& operator=(const MyList_Iterator& other) = default; // //! ~MyList_Iterator() = default; // // // MANIPULATORS // MyList_Iterator operator++(); // // // ACCESSORS // PAYLOAD& operator*() const { return d_node->value(); } // }; //.. // Then, we define our 'MyList' class, with 'MyList::Iterator' being a public // typedef of 'MyList_Iterator'. For brevity, we will omit a lot of // functionality that a full, general-purpose list class would have, // implmenting only what we will need for this example. //.. // // ====== // // MyList // // ====== // // template <class PAYLOAD> // class MyList { // // PRIVATE TYPES // typedef MyNode<PAYLOAD> Node; // // public: // // PUBLIC TYPES // typedef PAYLOAD ValueType; // typedef MyList_Iterator<ValueType> Iterator; // // private: // // DATA // Node *d_begin; // Node *d_end; // bslma::Allocator *d_allocator_p; // // public: // // CREATORS // explicit // MyList(bslma::Allocator *basicAllocator = 0) // : d_begin(0) // , d_end(0) // , d_allocator_p(bslma::Default::allocator(basicAllocator)) // {} // // ~MyList(); // // // MANIPULATORS // Iterator begin(); // Iterator end(); // void pushBack(const ValueType& value); // void popBack(); // }; //.. // Next, we implment the functions for the iterator type. //.. // // --------------- // // MyList_Iterator // // --------------- // // // MANIPULATORS // template <class PAYLOAD> // MyList_Iterator<PAYLOAD> MyList_Iterator<PAYLOAD>::operator++() // { // d_node = (Node *) d_node->nextLink(); // return *this; // } // // template <class PAYLOAD> // inline // bool operator==(MyList_Iterator<PAYLOAD> lhs, // MyList_Iterator<PAYLOAD> rhs) // { // return lhs.d_node == rhs.d_node; // } // // template <class PAYLOAD> // inline // bool operator!=(MyList_Iterator<PAYLOAD> lhs, // MyList_Iterator<PAYLOAD> rhs) // { // return !(lhs == rhs); // } //.. // Then, we implement the functions for the 'MyList' class: //.. // // ------ // // MyList // // ------ // // // CREATORS // template <class PAYLOAD> // MyList<PAYLOAD>::~MyList() // { // for (Node *p = d_begin; p; ) { // Node *toDelete = p; // p = (Node *) p->nextLink(); // // d_allocator_p->deleteObjectRaw(toDelete); // } // } // // // MANIPULATORS // template <class PAYLOAD> // typename MyList<PAYLOAD>::Iterator MyList<PAYLOAD>::begin() // { // return Iterator(d_begin); // } // // template <class PAYLOAD> // typename MyList<PAYLOAD>::Iterator MyList<PAYLOAD>::end() // { // return Iterator(0); // } // // template <class PAYLOAD> // void MyList<PAYLOAD>::pushBack(const PAYLOAD& value) // { // Node *node = (Node *) d_allocator_p->allocate(sizeof(Node)); // node->setNextLink(0); // node->setPreviousLink(d_end); // bslalg::ScalarPrimitives::copyConstruct(&node->value(), // value, // d_allocator_p); // // if (d_end) { // BSLS_ASSERT_SAFE(d_begin); // // d_end->setNextLink(node); // d_end = node; // } // else { // BSLS_ASSERT_SAFE(0 == d_begin); // // d_begin = d_end = node; // } // } // // template <class PAYLOAD> // void MyList<PAYLOAD>::popBack() // { // BSLS_ASSERT_SAFE(d_begin && d_end); // // Node *toDelete = d_end; // d_end = (Node *) d_end->previousLink(); // // if (d_begin != toDelete) { // BSLS_ASSERT_SAFE(0 != d_end); // d_end->setNextLink(0); // } // else { // BSLS_ASSERT_SAFE(0 == d_end); // d_begin = 0; // } // // d_allocator_p->deleteObject(toDelete); // } //.. // Next, in 'main', we use our 'MyList' class to store a list of ints: //.. // MyList<int> intList; //.. // Then, we declare an array of ints to populate it with: //.. // int intArray[] = { 8, 2, 3, 5, 7, 2 }; // enum { NUM_INTS = sizeof intArray / sizeof *intArray }; //.. // Now, we iterate, pushing ints to the list: //.. // for (const int *pInt = intArray; pInt < intArray + NUM_INTS; ++pInt) { // intList.pushBack(*pInt); // } //.. // Finally, we use our 'Iterator' type to traverse the list and observe its // values: //.. // MyList<int>::Iterator it = intList.begin(); // assert(8 == *it); // assert(2 == *++it); // assert(3 == *++it); // assert(5 == *++it); // assert(7 == *++it); // assert(2 == *++it); // assert(intList.end() == ++it); //.. #ifndef INCLUDED_BSLSCM_VERSION #include <bslscm_version.h> #endif namespace BloombergLP { namespace bslalg { // ======================= // class BidirectionalLink // ======================= class BidirectionalLink { // This POD-like 'class' describes a node suitable for use in a doubly- // linked (bidirectional) list, holding the addresses of the preceding and // succeeding nodes, either or both of which may be 0. This class is // "POD-like" to facilitate efficient allocation and use in the context of // a container implementations. In order to meet the essential // requirements of a POD type, this 'class' does not declare a constructor // or destructor. However its data members are private. It satisfies the // requirements of a *trivial* type and a *standard* *layout* type defined // by the C++11 standard. Note that this type does not contain any // "payload" member data: Clients creating a doubly-linked list of data // must define an appropriate node type that incorporates // 'BidirectionalLink' (generally via inheritance), and that holds the // "value" of any data stored in that node. private: // DATA BidirectionalLink *d_next_p; // The next node in a list traversal BidirectionalLink *d_prev_p; // The preceding node in a list traversal public: // CREATORS //! BidirectionalLink() = default; // Create a 'BidirectionalLink' object having uninitialized values, // or zero-initialized values if value-initialized. //! BidirectionalLink(const BidirectionalLink& original) = default; // Create a 'BidirectionalLink' object having the same data member // values as the specified 'original' object. //! ~BidirectionalLink() = default; // Destroy this object. // MANIPULATORS //! BidirectionalLink& operator= (const BidirectionalLink& rhs) = default; // Assign to the data members of this object the values of the data // members of the specified 'rhs' object, and return a reference // providing modifiable access to this object. void setNextLink(BidirectionalLink *next); // Set the successor of this node to be the specified 'next' link. void setPreviousLink(BidirectionalLink *previous); // Set the predecessor of this node to be the specified 'prev' link. void reset(); // Set the 'nextLink' and 'previousLink' attributes of this value to 0. // ACCESSORS BidirectionalLink *nextLink() const; // Return the address of the next node linked from this node. BidirectionalLink *previousLink() const; // Return the address of the preceding node linked from this node. }; // =========================================================================== // TEMPLATE AND INLINE FUNCTION DEFINITIONS // =========================================================================== //------------------------ // class BidirectionalLink //------------------------ // MANIPULATORS inline void BidirectionalLink::setNextLink(BidirectionalLink *next) { d_next_p = next; } inline void BidirectionalLink::setPreviousLink(BidirectionalLink *previous) { d_prev_p = previous; } inline void BidirectionalLink::reset() { d_prev_p = 0; d_next_p = 0; } // ACCESSORS inline BidirectionalLink *BidirectionalLink::nextLink() const { return d_next_p; } inline BidirectionalLink *BidirectionalLink::previousLink() const { return d_prev_p; } } // close namespace bslalg } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright (C) 2012 Bloomberg L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
[ "abeels@bloomberg.net" ]
abeels@bloomberg.net
9a269666a41104087c46932f21163b0f89806dbe
3a6b77c6d8b8997334468667df5a92b2fba6dd26
/twain-v2/twain_png.cpp
ea0341ae87a2d651eb173e8900308117d8d78f47
[]
no_license
miyako/4d-plugin-twain
0071bcc723915268200b1fc8502cb43c72316f76
79ed909badc39cbef3897cfc3effccb9315ae71d
refs/heads/master
2022-04-12T10:31:56.962629
2020-04-05T03:01:42
2020-04-05T03:01:42
104,451,668
1
0
null
null
null
null
UTF-8
C++
false
false
2,382
cpp
#include "twain_png.h" void PNG::write_data_fn(png_structp png_ptr, png_bytep buf, png_size_t size) { C_BLOB *blob = (C_BLOB *)png_get_io_ptr(png_ptr); blob->addBytes((const uint8_t *)buf, (uint32_t)size); } void PNG::output_flush_fn(png_structp png_ptr) { } void png_write_blob(C_BLOB &data, C_BLOB &picture, int width, int height, int depth, int bytes_per_line, int color, int dpi_x, int dpi_y) { C_BLOB png; png_structp png_ptr; png_infop info_ptr; png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if(png_ptr) { info_ptr = png_create_info_struct(png_ptr); if(info_ptr) { if(setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); }else{ png_set_write_fn(png_ptr, (png_voidp)&png, PNG::write_data_fn, PNG::output_flush_fn); png_set_IHDR(png_ptr, info_ptr, width, //pixels_per_line height,//lines depth, color, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_pHYs(png_ptr, info_ptr, dpi_x * INCHES_PER_METER, dpi_y * INCHES_PER_METER, PNG_RESOLUTION_METER); //TODO:support icc_profile png_write_info(png_ptr, info_ptr); unsigned char *p = (unsigned char *)data.getBytesPtr(); /* //takes as much time, with no way to yield std::vector<png_byte *>rows(height); for(int y = 0; y < height; y++) { rows[y] = p; p += bytes_per_line; }//height png_write_image(png_ptr, &rows[0]); */ for(int y = 0; y < height; y++) { //byteswap for depth 16 if (depth == 16) { unsigned char *byte_l, *byte_h, *ptr; ptr = p; for (int j = 0; j < bytes_per_line; j += 2) { byte_l = ptr; byte_h = ptr + 1; unsigned char b = *byte_l; *byte_l = *byte_h; *byte_h = b; ptr += 2; } } png_write_row(png_ptr, p); p += bytes_per_line; }//height png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); size_t outbuffersize = png.getBytesLength(); picture.addBytes((const uint8_t *)&outbuffersize, sizeof(outbuffersize)); } } } }
[ "miyako@wakanda.jp" ]
miyako@wakanda.jp
1b1a1d6a27f6de29e618a4706f34a72c6a77039f
adf8386eae06b82a85b1c9a4ff0abb2ec1057464
/MengeConfig/src/main/ContextManager.cpp
e3ab5d98ccd4e1a8ef69e2ac6debf1492d560fed
[]
no_license
curds01/MengeConfig
5fa847ce632164c96099d1197295d2dcc30c569e
b1e5086e2b05d8e0c1655475bbdbaa13f3efb4c9
refs/heads/master
2021-01-18T05:13:30.165985
2017-03-08T04:30:10
2017-03-08T04:30:10
84,278,174
0
1
null
null
null
null
UTF-8
C++
false
false
2,457
cpp
#include "ContextManager.hpp" #include "QtContext.h" /////////////////////////////////////////////////////////////////////////////// // Implementation of ContextManager /////////////////////////////////////////////////////////////////////////////// ContextManager * ContextManager::_instance = 0x0; size_t ContextManager::_nextId = 1; /////////////////////////////////////////////////////////////////////////////// ContextManager::ContextManager() : _active(0x0), _idToContext(), _contextToId() { } /////////////////////////////////////////////////////////////////////////////// QtContext * ContextManager::getContext(size_t id) { std::unordered_map<size_t, QtContext *>::const_iterator itr = _idToContext.find(id); if (itr != _idToContext.end()) { return itr->second; } return 0; } /////////////////////////////////////////////////////////////////////////////// ContextManager * ContextManager::instance() { if (_instance == 0x0) { _instance = new ContextManager(); } return _instance; } /////////////////////////////////////////////////////////////////////////////// size_t ContextManager::registerContext(QtContext * ctx) { std::unordered_map<QtContext *, size_t>::const_iterator itr = _contextToId.find(ctx); size_t id = 0; if (itr == _contextToId.end()) { id = _nextId; ++_nextId; _contextToId[ctx] = id; _idToContext[id] = ctx; } else { id = itr->second; } return id; } /////////////////////////////////////////////////////////////////////////////// void ContextManager::unregisterContext(QtContext * ctx) { std::unordered_map<QtContext *, size_t>::const_iterator itr = _contextToId.find(ctx); if (itr != _contextToId.end()) { _idToContext.erase(itr->second); _contextToId.erase(itr); } } /////////////////////////////////////////////////////////////////////////////// size_t ContextManager::activate(QtContext * ctx) { if (_active != 0x0) { size_t id = _contextToId[_active]; _active->deactivate(); emit deactivated(id); _active = 0x0; } size_t id = 0; if (ctx != 0x0) { std::unordered_map<QtContext *, size_t>::iterator itr = _contextToId.find(ctx); if (itr == _contextToId.end()) { return 0; } id = itr->second; _active = ctx; _active->activate(); emit activated(id); } return id; } /////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
[ "Sean" ]
Sean
3c0f24207d06462a683cf8ee287cac8297089fc3
2e9b9f4992c8afaa8d90f6e70494f25583e43aec
/src/3rdparty/brpc/src/butil/containers/mru_cache.h
e2bbef7d0bd70ed0d9f873a4c528e668071d9242
[ "Apache-2.0", "BSD-Source-Code", "BSD-3-Clause", "ICU", "bzip2-1.0.6", "dtoa", "MIT", "LicenseRef-scancode-bsd-x11", "BSL-1.0", "BSD-2-Clause-Views", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-facebook-patent-rights-2" ...
permissive
KeyviDev/keyvi-server
e77668bd64cbed9bfbcf69d777c23a7728dafb4a
787e4ce8f6f104bfd3d3c9ff96d8985c5fb7b925
refs/heads/master
2021-12-12T08:50:48.215460
2021-10-29T16:00:40
2021-10-29T16:00:40
174,194,731
8
2
Apache-2.0
2020-12-07T20:12:56
2019-03-06T18:02:14
C++
UTF-8
C++
false
false
10,996
h
// Copyright (c) 2011 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 contains a template for a Most Recently Used cache that allows // constant-time access to items using a key, but easy identification of the // least-recently-used items for removal. Each key can only be associated with // one payload item at a time. // // The key object will be stored twice, so it should support efficient copying. // // NOTE: While all operations are O(1), this code is written for // legibility rather than optimality. If future profiling identifies this as // a bottleneck, there is room for smaller values of 1 in the O(1). :] #ifndef BUTIL_CONTAINERS_MRU_CACHE_H_ #define BUTIL_CONTAINERS_MRU_CACHE_H_ #include <list> #include <map> #include <utility> #include "butil/basictypes.h" #include "butil/containers/hash_tables.h" #include "butil/logging.h" namespace butil { // MRUCacheBase ---------------------------------------------------------------- // This template is used to standardize map type containers that can be used // by MRUCacheBase. This level of indirection is necessary because of the way // that template template params and default template params interact. template <class KeyType, class ValueType> struct MRUCacheStandardMap { typedef std::map<KeyType, ValueType> Type; }; // Base class for the MRU cache specializations defined below. // The deletor will get called on all payloads that are being removed or // replaced. template <class KeyType, class PayloadType, class DeletorType, template <typename, typename> class MapType = MRUCacheStandardMap> class MRUCacheBase { public: // The payload of the list. This maintains a copy of the key so we can // efficiently delete things given an element of the list. typedef std::pair<KeyType, PayloadType> value_type; private: typedef std::list<value_type> PayloadList; typedef typename MapType<KeyType, typename PayloadList::iterator>::Type KeyIndex; public: typedef typename PayloadList::size_type size_type; typedef typename PayloadList::iterator iterator; typedef typename PayloadList::const_iterator const_iterator; typedef typename PayloadList::reverse_iterator reverse_iterator; typedef typename PayloadList::const_reverse_iterator const_reverse_iterator; enum { NO_AUTO_EVICT = 0 }; // The max_size is the size at which the cache will prune its members to when // a new item is inserted. If the caller wants to manager this itself (for // example, maybe it has special work to do when something is evicted), it // can pass NO_AUTO_EVICT to not restrict the cache size. explicit MRUCacheBase(size_type max_size) : max_size_(max_size) { } MRUCacheBase(size_type max_size, const DeletorType& deletor) : max_size_(max_size), deletor_(deletor) { } virtual ~MRUCacheBase() { iterator i = begin(); while (i != end()) i = Erase(i); } size_type max_size() const { return max_size_; } // Inserts a payload item with the given key. If an existing item has // the same key, it is removed prior to insertion. An iterator indicating the // inserted item will be returned (this will always be the front of the list). // // The payload will be copied. In the case of an OwningMRUCache, this function // will take ownership of the pointer. iterator Put(const KeyType& key, const PayloadType& payload) { // Remove any existing payload with that key. typename KeyIndex::iterator index_iter = index_.find(key); if (index_iter != index_.end()) { // Erase the reference to it. This will call the deletor on the removed // element. The index reference will be replaced in the code below. Erase(index_iter->second); } else if (max_size_ != NO_AUTO_EVICT) { // New item is being inserted which might make it larger than the maximum // size: kick the oldest thing out if necessary. ShrinkToSize(max_size_ - 1); } ordering_.push_front(value_type(key, payload)); index_.insert(std::make_pair(key, ordering_.begin())); return ordering_.begin(); } // Retrieves the contents of the given key, or end() if not found. This method // has the side effect of moving the requested item to the front of the // recency list. // // TODO(brettw) We may want a const version of this function in the future. iterator Get(const KeyType& key) { typename KeyIndex::iterator index_iter = index_.find(key); if (index_iter == index_.end()) return end(); typename PayloadList::iterator iter = index_iter->second; // Move the touched item to the front of the recency ordering. ordering_.splice(ordering_.begin(), ordering_, iter); return ordering_.begin(); } // Retrieves the payload associated with a given key and returns it via // result without affecting the ordering (unlike Get). iterator Peek(const KeyType& key) { typename KeyIndex::const_iterator index_iter = index_.find(key); if (index_iter == index_.end()) return end(); return index_iter->second; } const_iterator Peek(const KeyType& key) const { typename KeyIndex::const_iterator index_iter = index_.find(key); if (index_iter == index_.end()) return end(); return index_iter->second; } // Erases the item referenced by the given iterator. An iterator to the item // following it will be returned. The iterator must be valid. iterator Erase(iterator pos) { deletor_(pos->second); index_.erase(pos->first); return ordering_.erase(pos); } // MRUCache entries are often processed in reverse order, so we add this // convenience function (not typically defined by STL containers). reverse_iterator Erase(reverse_iterator pos) { // We have to actually give it the incremented iterator to delete, since // the forward iterator that base() returns is actually one past the item // being iterated over. return reverse_iterator(Erase((++pos).base())); } // Shrinks the cache so it only holds |new_size| items. If |new_size| is // bigger or equal to the current number of items, this will do nothing. void ShrinkToSize(size_type new_size) { for (size_type i = size(); i > new_size; i--) Erase(rbegin()); } // Deletes everything from the cache. void Clear() { for (typename PayloadList::iterator i(ordering_.begin()); i != ordering_.end(); ++i) deletor_(i->second); index_.clear(); ordering_.clear(); } // Returns the number of elements in the cache. size_type size() const { // We don't use ordering_.size() for the return value because // (as a linked list) it can be O(n). DCHECK(index_.size() == ordering_.size()); return index_.size(); } // Allows iteration over the list. Forward iteration starts with the most // recent item and works backwards. // // Note that since these iterators are actually iterators over a list, you // can keep them as you insert or delete things (as long as you don't delete // the one you are pointing to) and they will still be valid. iterator begin() { return ordering_.begin(); } const_iterator begin() const { return ordering_.begin(); } iterator end() { return ordering_.end(); } const_iterator end() const { return ordering_.end(); } reverse_iterator rbegin() { return ordering_.rbegin(); } const_reverse_iterator rbegin() const { return ordering_.rbegin(); } reverse_iterator rend() { return ordering_.rend(); } const_reverse_iterator rend() const { return ordering_.rend(); } bool empty() const { return ordering_.empty(); } private: PayloadList ordering_; KeyIndex index_; size_type max_size_; DeletorType deletor_; DISALLOW_COPY_AND_ASSIGN(MRUCacheBase); }; // MRUCache -------------------------------------------------------------------- // A functor that does nothing. Used by the MRUCache. template<class PayloadType> class MRUCacheNullDeletor { public: void operator()(PayloadType& /*payload*/) { } }; // A container that does not do anything to free its data. Use this when storing // value types (as opposed to pointers) in the list. template <class KeyType, class PayloadType> class MRUCache : public MRUCacheBase<KeyType, PayloadType, MRUCacheNullDeletor<PayloadType> > { private: typedef MRUCacheBase<KeyType, PayloadType, MRUCacheNullDeletor<PayloadType> > ParentType; public: // See MRUCacheBase, noting the possibility of using NO_AUTO_EVICT. explicit MRUCache(typename ParentType::size_type max_size) : ParentType(max_size) { } virtual ~MRUCache() { } private: DISALLOW_COPY_AND_ASSIGN(MRUCache); }; // OwningMRUCache -------------------------------------------------------------- template<class PayloadType> class MRUCachePointerDeletor { public: void operator()(PayloadType& payload) { delete payload; } }; // A cache that owns the payload type, which must be a non-const pointer type. // The pointers will be deleted when they are removed, replaced, or when the // cache is destroyed. template <class KeyType, class PayloadType> class OwningMRUCache : public MRUCacheBase<KeyType, PayloadType, MRUCachePointerDeletor<PayloadType> > { private: typedef MRUCacheBase<KeyType, PayloadType, MRUCachePointerDeletor<PayloadType> > ParentType; public: // See MRUCacheBase, noting the possibility of using NO_AUTO_EVICT. explicit OwningMRUCache(typename ParentType::size_type max_size) : ParentType(max_size) { } virtual ~OwningMRUCache() { } private: DISALLOW_COPY_AND_ASSIGN(OwningMRUCache); }; // HashingMRUCache ------------------------------------------------------------ template <class KeyType, class ValueType> struct MRUCacheHashMap { typedef butil::hash_map<KeyType, ValueType> Type; }; // This class is similar to MRUCache, except that it uses butil::hash_map as // the map type instead of std::map. Note that your KeyType must be hashable // to use this cache. template <class KeyType, class PayloadType> class HashingMRUCache : public MRUCacheBase<KeyType, PayloadType, MRUCacheNullDeletor<PayloadType>, MRUCacheHashMap> { private: typedef MRUCacheBase<KeyType, PayloadType, MRUCacheNullDeletor<PayloadType>, MRUCacheHashMap> ParentType; public: // See MRUCacheBase, noting the possibility of using NO_AUTO_EVICT. explicit HashingMRUCache(typename ParentType::size_type max_size) : ParentType(max_size) { } virtual ~HashingMRUCache() { } private: DISALLOW_COPY_AND_ASSIGN(HashingMRUCache); }; } // namespace butil #endif // BUTIL_CONTAINERS_MRU_CACHE_H_
[ "noreply@github.com" ]
KeyviDev.noreply@github.com
2ffc3ac3a984e5f4d4e5ec5b5d7eaf72dcdf577d
f3102a100ad7f5606af620caca37c706ed2d5e55
/Baekjoon/10952.cpp
c56ccfbb5d3bf55462ed557645c7f42dc933b736
[]
no_license
ameliacode/Algorithm
c746797b27cf1f783874acc89d024920c0b45897
d6de240c5c0347cd8f58b59361a8eed5e79733db
refs/heads/master
2022-02-22T12:36:06.466225
2022-02-17T02:55:05
2022-02-17T02:55:05
210,334,019
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
#include<iostream> using namespace std; int main() { int a, b; while(1) { cin >> a >> b; if (a == 0 && b == 0) break; cout << a + b << endl; } return 0; }
[ "emilyjr1@naver.com" ]
emilyjr1@naver.com
1765c3149420624afd5706ed72ee3f974a935d11
5c0bc7d833e37161ad7409d2e56fd1207e3234b2
/HW_5/exam.cpp
478ea8787b52a1a642018fd0a0debb5d15790edb
[]
no_license
gabrieletrata/MTH_3300
9888c00b2c75cca307817fd7c19cdfe36123fe77
24030cac363181b50841bf73ad8ee0547393d6a3
refs/heads/master
2020-03-24T05:56:59.347450
2018-07-27T00:58:38
2018-07-27T00:58:38
142,510,175
0
0
null
null
null
null
UTF-8
C++
false
false
1,838
cpp
//****************************************************************************** // exam.cpp // Computes the probability of passing an exam. // This exam is 35 multiple choice questions, with 5 choices per question. // A score of 11, or greater is considered a pass. //****************************************************************************** // Name: Gabriel Etrata // Class: MTH 3300 // Professor: Evan Fink // Homework_5 //****************************************************************************** // Collaborators/outside sources used: @Evan Fink //****************************************************************************** // @author Gabriel Etrata // @version 1.0 03/19/17 #include <iostream> #include <stdlib.h> #include <time.h> #include <ctime> #include <iomanip> using namespace std; //Initializes program int main() { srand ((time(NULL))); //ignore precision error; int trials = 1e6; double questions[35]; int questionsRight = 0; double numOfPasses = 0; double probability; for(int i = 0; i < trials; i++){ //runs 1e6 simulations questionsRight = 0; //reset questionsRight to 0 after each simulation for(int j = 0; j < 35; j++){ //runs through 35 questions questions[j] = ((rand() % 5) + 1); if(questions[j] == 5){ questionsRight++; //if choice 5 is picked, increment questionsRight } if(questionsRight >= 11){ numOfPasses++; //if questionsRight >= 11, increment numOfPasses questionsRight = 0; //reset questionsRight back to 0 after each exam trial is finished } } } probability = numOfPasses/trials; //compute the probability of event cout << setprecision (3) << probability << endl; system("pause"); return 0; }
[ "gabrieletrata@gmail.com" ]
gabrieletrata@gmail.com
f5514a1052e5f51f1fcffeb3c4fb663ffd4a7621
8afa1e06465eeef8354087293b14c54d42af9cc2
/src/qt/bitcoingui.cpp
b4d73f94c9b1c90b3e6dfb5e6a8c26670a58eebd
[ "MIT" ]
permissive
ShinDaniel/spon
20577f0d8f6f884aff45ef6cc2729ecbd8cbeb31
9d768d68812028709611f8ffc5c06daf903493a1
refs/heads/master
2020-04-08T08:30:09.562087
2018-11-26T14:18:53
2018-11-26T14:18:53
155,554,669
0
0
null
null
null
null
UTF-8
C++
false
false
52,273
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The SPON developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoingui.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "miner.h" #include "networkstyle.h" #include "notificator.h" #include "openuridialog.h" #include "optionsdialog.h" #include "optionsmodel.h" #include "rpcconsole.h" #include "utilitydialog.h" #ifdef ENABLE_WALLET #include "blockexplorer.h" #include "walletframe.h" #include "walletmodel.h" #endif // ENABLE_WALLET #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include "init.h" #include "masternodelist.h" #include "ui_interface.h" #include "util.h" #include <iostream> #include <QAction> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QIcon> #include <QListWidget> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QProgressDialog> #include <QSettings> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QVBoxLayout> #if QT_VERSION < 0x050000 #include <QTextDocument> #include <QUrl> #else #include <QUrlQuery> #endif const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelStakingIcon(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), masternodeAction(0), quitAction(0), sendCoinsAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), bip38ToolAction(0), aboutAction(0), receiveCoinsAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), multiSendAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), explorerWindow(0), prevBlocks(0), spinnerFrame(0) { /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("SPON Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if (enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", "")); if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle; windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getAppIcon()); setWindowIcon(networkStyle->getAppIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(enableWallet ? this : 0); #ifdef ENABLE_WALLET if (enableWallet) { /** Create wallet frame*/ walletFrame = new WalletFrame(this); explorerWindow = new BlockExplorer(this); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(networkStyle); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Status bar notification icons QFrame* frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0, 0, 0, 0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3, 0, 3, 0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(); labelStakingIcon = new QLabel(); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QPushButton(); labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}"); labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelBlocksIcon = new QLabel(); if (enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); } frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelStakingIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(true); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(true); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Jump directly to tabs in RPC-console connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo())); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole())); connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork())); connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers())); connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair())); connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor())); connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor())); connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups())); connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers())); // Get restart command-line parameters and handle restart connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList))); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); connect(openBlockExplorerAction, SIGNAL(triggered()), explorerWindow, SLOT(show())); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), explorerWindow, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); QTimer* timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus())); timerStakingIcon->start(10000); setStakingStatus(); } BitcoinGUI::~BitcoinGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); GUIUtil::saveWindowGeometry("nWindow", this); if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::cleanup(); #endif } void BitcoinGUI::createActions(const NetworkStyle* networkStyle) { QActionGroup* tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); #ifdef Q_OS_MAC overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1)); #else overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); #endif tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a SPON address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); #ifdef Q_OS_MAC sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); #else sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); #endif tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and spon: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); #ifdef Q_OS_MAC receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3)); #else receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); #endif tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); #ifdef Q_OS_MAC historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4)); #else historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); #endif tabGroup->addAction(historyAction); #ifdef ENABLE_WALLET QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this); masternodeAction->setStatusTip(tr("Browse masternodes")); masternodeAction->setToolTip(masternodeAction->statusTip()); masternodeAction->setCheckable(true); #ifdef Q_OS_MAC masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5)); #else masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); #endif tabGroup->addAction(masternodeAction); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage())); } // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); #endif // ENABLE_WALLET quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About SPON Core"), this); aboutAction->setStatusTip(tr("Show information about SPON Core")); aboutAction->setMenuRole(QAction::AboutRole); #if QT_VERSION < 0x050000 aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #else aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); #endif aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for SPON")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this); unlockWalletAction->setToolTip(tr("Unlock wallet")); lockWalletAction = new QAction(tr("&Lock Wallet"), this); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your SPON addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified SPON addresses")); bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this); bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase")); multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this); multiSendAction->setToolTip(tr("MultiSend Settings")); multiSendAction->setCheckable(true); openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this); openInfoAction->setStatusTip(tr("Show diagnostic information")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging console")); openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this); openNetworkAction->setStatusTip(tr("Show network monitor")); openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this); openPeersAction->setStatusTip(tr("Show peers info")); openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this); openRepairAction->setStatusTip(tr("Show wallet repair options")); openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this); openConfEditorAction->setStatusTip(tr("Open configuration file")); openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this); openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file")); showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this); showBackupsAction->setStatusTip(tr("Show automatically created wallet backups")); usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a SPON: URI or payment request")); openBlockExplorerAction = new QAction(QIcon(":/icons/explorer"), tr("&Blockchain explorer"), this); openBlockExplorerAction->setStatusTip(tr("Block explorer window")); showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this); showHelpMessageAction->setMenuRole(QAction::NoRole); showHelpMessageAction->setStatusTip(tr("Show the SPON Core help message to get a list with possible SPON command-line options")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked())); #ifdef ENABLE_WALLET if (walletFrame) { connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(unlockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(unlockWallet())); connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool())); connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses())); connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog())); } #endif // ENABLE_WALLET } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu* file = appMenuBar->addMenu(tr("&File")); if (walletFrame) { file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(usedSendingAddressesAction); file->addAction(usedReceivingAddressesAction); file->addSeparator(); } file->addAction(quitAction); QMenu* settings = appMenuBar->addMenu(tr("&Settings")); if (walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addAction(unlockWalletAction); settings->addAction(lockWalletAction); settings->addAction(bip38ToolAction); settings->addAction(multiSendAction); settings->addSeparator(); } settings->addAction(optionsAction); if (walletFrame) { QMenu* tools = appMenuBar->addMenu(tr("&Tools")); tools->addAction(openInfoAction); tools->addAction(openRPCConsoleAction); tools->addAction(openNetworkAction); tools->addAction(openPeersAction); tools->addAction(openRepairAction); tools->addSeparator(); tools->addAction(openConfEditorAction); tools->addAction(openMNConfEditorAction); tools->addAction(showBackupsAction); tools->addAction(openBlockExplorerAction); } QMenu* help = appMenuBar->addMenu(tr("&Help")); help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { if (walletFrame) { QToolBar* toolbar = new QToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { toolbar->addAction(masternodeAction); } toolbar->setMovable(false); // remove unused icon in upper left corner overviewAction->setChecked(true); /** Create additional container for toolbar and walletFrame and make it the central widget. This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too. */ QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(toolbar); layout->addWidget(walletFrame); layout->setSpacing(0); layout->setContentsMargins(QMargins()); QWidget* containerWidget = new QWidget(); containerWidget->setLayout(layout); setCentralWidget(containerWidget); } } void BitcoinGUI::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks()); connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); // Receive and report messages from client model connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int))); // Show progress dialog connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int))); rpcConsole->setClientModel(clientModel); #ifdef ENABLE_WALLET if (walletFrame) { walletFrame->setClientModel(clientModel); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(clientModel->getOptionsModel()); } else { // Disable possibility to show main window via action toggleHideAction->setEnabled(false); if (trayIconMenu) { // Disable context menu on tray icon trayIconMenu->clear(); } } } #ifdef ENABLE_WALLET bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel) { if (!walletFrame) return false; setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { if (!walletFrame) return false; return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { if (!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif // ENABLE_WALLET void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setEnabled(enabled); } encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); bip38ToolAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); QString toolTip = tr("SPON Core client") + " " + networkStyle->getTitleAddText(); trayIcon->setToolTip(toolTip); trayIcon->setIcon(networkStyle->getAppIcon()); trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon, this); } void BitcoinGUI::createTrayIconMenu() { #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow*)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addAction(bip38ToolAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openInfoAction); trayIconMenu->addAction(openRPCConsoleAction); trayIconMenu->addAction(openNetworkAction); trayIconMenu->addAction(openPeersAction); trayIconMenu->addAction(openRepairAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(openConfEditorAction); trayIconMenu->addAction(openMNConfEditorAction); trayIconMenu->addAction(showBackupsAction); trayIconMenu->addAction(openBlockExplorerAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if (reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHidden(); } } #endif void BitcoinGUI::optionsClicked() { if (!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this, enableWallet); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { if (!clientModel) return; HelpMessageDialog dlg(this, true); dlg.exec(); } void BitcoinGUI::showHelpMessageClicked() { HelpMessageDialog* help = new HelpMessageDialog(this, false); help->setAttribute(Qt::WA_DeleteOnClose); help->show(); } #ifdef ENABLE_WALLET void BitcoinGUI::openClicked() { OpenURIDialog dlg(this); if (dlg.exec()) { emit receivedURI(dlg.getURI()); } } void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoMasternodePage() { QSettings settings; if (settings.value("fShowMasternodesTab").toBool()) { masternodeAction->setChecked(true); if (walletFrame) walletFrame->gotoMasternodePage(); } } void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::gotoBip38Tool() { if (walletFrame) walletFrame->gotoBip38Tool(); } void BitcoinGUI::gotoMultiSendDialog() { multiSendAction->setChecked(true); if (walletFrame) walletFrame->gotoMultiSendDialog(); } void BitcoinGUI::gotoBlockExplorerPage() { if (walletFrame) walletFrame->gotoBlockExplorerPage(); } #endif // ENABLE_WALLET void BitcoinGUI::setNumConnections(int count) { QString icon; switch (count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE); labelConnectionsIcon->setIcon(connectionItem); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to SPON network", "", count)); } void BitcoinGUI::setNumBlocks(int count) { if (!clientModel) return; // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); tooltip = tr("Processed %n blocks of transaction history.", "", count); // Set icon state: spinning if catching up, tick otherwise // if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster if (masternodeSync.IsBlockchainSynced()) { QString strSyncStatus; tooltip = tr("Up to date") + QString(".<br>") + tooltip; if (masternodeSync.IsSynced()) { progressBarLabel->setVisible(false); progressBar->setVisible(false); labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); } else { int nAttempt; int progress = 0; labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(false); #endif // ENABLE_WALLET nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ? masternodeSync.RequestedMasternodeAttempt + 1 : MASTERNODE_SYNC_THRESHOLD; progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD; progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD); progressBar->setFormat(tr("Synchronizing additional data: %p%")); progressBar->setValue(progress); } strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str()); progressBarLabel->setText(strSyncStatus); tooltip = strSyncStatus + QString("<br>") + tooltip; } else { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60 * 60; const int DAY_IN_SECONDS = 24 * 60 * 60; const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if (secs < 2 * DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS); } else if (secs < 2 * WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS); } else if (secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS); } else { int years = secs / YEAR_IN_SECONDS; int remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if (count != prevBlocks) { labelBlocksIcon->setPixmap(QIcon(QString( ":/movies/spinner-%1") .arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if (walletFrame) walletFrame->showOutOfSyncWarning(true); #endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret) { QString strTitle = tr("SPON Core"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "SPON - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent* e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if (e->type() == QEvent::WindowStateChange) { if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e); if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent* event) { #ifndef Q_OS_MAC // Ignored on Mac if (clientModel && clientModel->getOptionsModel()) { if (!clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } } #endif QMainWindow::closeEvent(event); } #ifdef ENABLE_WALLET void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); pwalletMain->fMultiSendNotify = false; } #endif // ENABLE_WALLET void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event) { // Accept only URIs if (event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent* event) { if (event->mimeData()->hasUrls()) { foreach (const QUrl& uri, event->mimeData()->urls()) { emit receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject* object, QEvent* event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } void BitcoinGUI::setStakingStatus() { if (pwalletMain) fMultiSend = pwalletMain->isMultiSendEnabled(); if (nLastCoinStakeSearchInterval) { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } else { labelStakingIcon->show(); labelStakingIcon->setPixmap(QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelStakingIcon->setToolTip(tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active"))); } } #ifdef ENABLE_WALLET bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } return false; } void BitcoinGUI::setEncryptionStatus(int status) { switch (status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(false); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::UnlockedForAnonymizationOnly: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for anonimization and staking only")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); unlockWalletAction->setVisible(true); lockWalletAction->setVisible(false); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } #endif // ENABLE_WALLET void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { if (!clientModel) return; // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if (fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) { if (rpcConsole) rpcConsole->hide(); qApp->quit(); } } void BitcoinGUI::showProgress(const QString& title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); // The SECURE flag has no effect in the Qt GUI. // bool secure = (style & CClientUIInterface::SECURE); style &= ~CClientUIInterface::SECURE; bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void BitcoinGUI::subscribeToCoreSignals() { // Connect signals to client uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } void BitcoinGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } /** Get restart command-line parameters and request restart */ void BitcoinGUI::handleRestart(QStringList args) { if (!ShutdownRequested()) emit requestedRestart(args); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0), menu(0) { createContextMenu(); setToolTip(tr("Unit to show amounts in. Click to select another unit.")); } /** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event) { onDisplayUnitsClicked(event->pos()); } /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(); foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); } connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*))); } /** Lets the control know about the Options Model (and its signals) */ void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel) { if (optionsModel) { this->optionsModel = optionsModel; // be aware of a display unit change reported by the OptionsModel object. connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int))); // initialize the display units label with the current value in the model. updateDisplayUnit(optionsModel->getDisplayUnit()); } } /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits) { if (Params().NetworkID() == CBaseChainParams::MAIN) { setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } else { setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE)); } } /** Shows context menu with Display Unit options by the mouse coordinates */ void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point) { QPoint globalPos = mapToGlobal(point); menu->exec(globalPos); } /** Tells underlying optionsModel to update its current display unit. */ void UnitDisplayStatusBarControl::onMenuSelection(QAction* action) { if (action) { optionsModel->setDisplayUnit(action->data()); } }
[ "sis3719@gmail.com" ]
sis3719@gmail.com
00e97a5d1663024ba9e5858d25fab591af090fb7
39a6b3e717a3b49bbca508b4b8c602d99e6b08f5
/tensorflow/compiler/mlir/xla/hlo_utils.cc
bfa57d97336ee88e7d73cb126036bcca10330718
[ "Apache-2.0" ]
permissive
lucigrigo/tensorflow
a584b81c9c7de513197a5ef9aabf1eb3411b5cce
39ee10bb064086ea7fd6d4cb831e02958671cfb7
refs/heads/master
2020-12-10T11:58:37.722788
2020-01-13T10:20:58
2020-01-13T10:20:58
233,582,234
2
0
Apache-2.0
2020-04-16T17:12:35
2020-01-13T11:40:52
null
UTF-8
C++
false
false
3,134
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file defines helpers useful when creating or manipulating lhlo/hlo. #include "tensorflow/compiler/mlir/xla/hlo_utils.h" #include "mlir/IR/Attributes.h" // TF:llvm-project #include "mlir/IR/StandardTypes.h" // TF:llvm-project #include "mlir/IR/TypeUtilities.h" // TF:llvm-project #include "tensorflow/compiler/xla/literal.h" namespace xla { namespace { using mlir::Builder; using mlir::DenseElementsAttr; using mlir::ShapedType; using xla::Literal; using xla::StatusOr; template <typename CppType> ::mlir::DenseElementsAttr CreateDenseAttrFromLiteral(const ShapedType& type, const Literal& literal) { auto data_span = literal.data<CppType>(); return ::mlir::DenseElementsAttr::get( type, llvm::makeArrayRef(data_span.data(), data_span.size())); } } // namespace StatusOr<mlir::DenseElementsAttr> CreateDenseElementsAttrFromLiteral( const Literal& literal, Builder builder) { TF_ASSIGN_OR_RETURN(auto type, ConvertTensorShapeToType<mlir::RankedTensorType>( literal.shape(), builder)); auto element_type = literal.shape().element_type(); switch (element_type) { case PrimitiveType::PRED: return CreateDenseAttrFromLiteral<bool>(type, literal); case PrimitiveType::F16: return CreateDenseAttrFromLiteral<float>(type, literal); case PrimitiveType::F32: return CreateDenseAttrFromLiteral<float>(type, literal); case PrimitiveType::F64: return CreateDenseAttrFromLiteral<double>(type, literal); case PrimitiveType::S8: return CreateDenseAttrFromLiteral<int8>(type, literal); case PrimitiveType::S16: return CreateDenseAttrFromLiteral<int16>(type, literal); case PrimitiveType::S32: return CreateDenseAttrFromLiteral<int32>(type, literal); case PrimitiveType::S64: return CreateDenseAttrFromLiteral<int64>(type, literal); default: return tensorflow::errors::Internal( absl::StrCat("Unsupported type: ", PrimitiveType_Name(element_type))); } } mlir::DenseIntElementsAttr CreateDenseIntElementsAttrFromVector( const llvm::ArrayRef<int64> vector, mlir::Builder builder) { return mlir::DenseIntElementsAttr::get( mlir::RankedTensorType::get(vector.size(), builder.getIntegerType(64)), vector) .cast<mlir::DenseIntElementsAttr>(); } } // namespace xla
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
3ab0453f080f4bb201b3210c8febf37062e197d8
c82d5b7031d567ad7b76f1a9fffafb717b5e23de
/面试高频题/HashTable.h
322222c313342c1ca8fbee8f693a7d48a6b1077a
[]
no_license
newhandLiu/First
55cd2715df924423f6afacc59a4cfe925284a0e2
37d1ba62531737a0809f74c298d1b013048e8aca
refs/heads/master
2021-01-01T17:00:07.552590
2012-04-23T05:58:19
2012-04-23T05:58:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,307
h
//链地址散列表 #ifndef HASHTABLE_H #define HASHTABLE_H #include<vector> #include<list> #include<string> #include<algorithm> using namespace std; template<class T> class HashTable { public: explicit HashTable(int size=101); bool contains(const T& obj)const; void clear(); bool insert(const T& obj); bool remove(const T& obj); private: void reHash();//expand the size of HashTable int myHash(const T& obj)const; //hash function private: vector<list<T> > theLists; //The array of lists int currentSize; }; int hash(string key); int hash(int key); #endif int hash(string key) { int hashVal = 0; for(int i=0; i<key.length(); ++i) { hashVal = 37*hashVal + key[i]; } return hashVal; } int hash(int key) { return key*key; } template<class T> int HashTable<T>::myHash(const T& obj)const { int hashVal = hash(obj); hashVal %= theLists.size(); if(hashVal<0) hashVal += theLists.size(); return hashVal; } template<class T> void HashTable<T>::reHash() { vector<list<T> > oldLists = theLists; theLists.resize(theLists.size()*2); int i; for(i=0; i<theLists.size(); ++i) { theLists[i].clear(); } typename list<T>::iterator itr; currentSize = 0; for(i=0; i<oldLists.size(); ++i) { itr = oldLists[i].begin(); while(itr!=oldLists[i].end()) { insert(*itr++); } } } template<class T> HashTable<T>::HashTable(int size) :theLists(size) { clear(); } template<class T> bool HashTable<T>::contains(const T& obj)const { const list<T> & theList = theLists[myHash(obj)]; return (find(theList.begin(), theList.end(), obj)!=theList.end()); } template<class T> void HashTable<T>::clear() { for(int i=0; i<theLists.size(); i++) { theLists[i].clear(); } currentSize = 0; } template<class T> bool HashTable<T>::insert(const T& obj) { list<T> & theList = theLists[myHash(obj)]; if(find(theList.begin(), theList.end(), obj)==theList.end()) { theList.push_back(obj); if(++currentSize>theLists.size()) { reHash(); } return true; } else { return false; } } template<class T> bool HashTable<T>::remove(const T& obj) { list<T>& theList = theLists[myHash(obj)]; typename list<T>::iterator itr = find(theList.begin(), theList.end(), obj); if(itr!=theList.end()) { theList.erase(itr); --currentSize; return true; } else { return false; } }
[ "dearliujun@gmail.com" ]
dearliujun@gmail.com
4bd89306ab76ec3f50e4859e2fe2f92c02240073
b086e2648679bb952cb2dbc0a8255932981adfe4
/src/YScoket.h
a0f4af2fb597422cfec7df2c9f89b5a0bda7519a
[]
no_license
yuangu/YNet
845092164f9443bc540bc688ccb227b59305b2a0
fdf7d7c832b4f1172381938e4de9473903b7ddf5
refs/heads/master
2020-04-11T20:21:38.757975
2019-04-02T10:41:53
2019-04-02T10:41:53
162,068,004
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
h
#pragma once #include "socket_header.h" #include "poll/IOPoll.h" #ifndef Y_BUFF_SIZE #define Y_BUFF_SIZE 1024 #endif class YAddress; class YSocket; class YTLS; typedef std::function<void(YSocket*)> SocketEventCallBack; class YSocket { public: YSocket(); YSocket(SOCKET_FD fd); virtual ~YSocket(); void bind(YAddress* address, bool allow_reuse = true); virtual void setSSLFlag(bool enable); virtual bool close(); bool isClosed(); bool isBlocking(); void setBlocking(bool blocking); unsigned int getTimeout(); void setTimeout(unsigned int timeout); bool getOption(int level, int optname, void *optval, socklen_t *optlen); bool setOption(int level, int optname, const void *optval, socklen_t optlen); int getLastError(); SOCKET_FD fd(); //YAddress* localAddress(); virtual bool isTCP() = 0; public: virtual void setIOPoll(IOPoll*); void onError(SocketEventCallBack); void onWrite(SocketEventCallBack); protected: virtual void onErrorCallBack(); virtual void onWriteCallBack(); virtual void onReadCallBack(); SocketEventCallBack errorCallBack; SocketEventCallBack writeCallBack; SocketEventCallBack readCallBack; IOPoll* mPoll; protected: void createSocketIfNecessary(bool isIPV6); protected: bool isBlock; bool mIsClose; bool mIsEableSSL; YTLS* mYTLS; SOCKET_FD mfd; };
[ "lifulinghan@aol.com" ]
lifulinghan@aol.com
af147a75f5134d9b3c19feedb30deafd7efcf4ea
77ffb0bb747d96a7995c5a750e5ca9d41a64eff8
/ethzasl_msf/msf_core/include/msf_core/msf_IMUHandler_ROS.h
3d9b72d3c88f1ec3cca9e761b6a4bb72df76ae3c
[ "Apache-2.0" ]
permissive
Sprann9257/3D-mapping
43a634c8e49de7a869c0c414aa201b92c61e90c5
8d59fe91bb7fd128a7d716da3b7f6984de6697f3
refs/heads/master
2021-04-03T07:07:03.217522
2017-05-18T13:18:46
2017-05-18T13:18:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,245
h
/* * Copyright (C) 2012-2013 Simon Lynen, ASL, ETH Zurich, Switzerland * You can contact the author at <slynen at ethz dot ch> * * 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 MSF_IMUHANDLER_ROS_H_ #define MSF_IMUHANDLER_ROS_H_ #include <msf_core/msf_IMUHandler.h> namespace msf_core { template<typename EKFState_T> class IMUHandler_ROS : public IMUHandler<EKFState_T> { ros::Subscriber subState_; ///< subscriber to external state propagation ros::Subscriber subImu_; ///< subscriber to IMU readings ros::Subscriber subImuCustom_; ///< subscriber to IMU readings for asctec custom public: IMUHandler_ROS(MSF_SensorManager<EKFState_T>& mng, const std::string& topic_namespace, const std::string& parameternamespace) : IMUHandler<EKFState_T>(mng, topic_namespace, parameternamespace) { ros::NodeHandle nh(topic_namespace); subImu_ = nh.subscribe("imu_state_input", 100, &IMUHandler_ROS::IMUCallback, this); subState_ = nh.subscribe("hl_state_input", 10, &IMUHandler_ROS::StateCallback, this); } virtual ~IMUHandler_ROS() { } void StateCallback(const sensor_fusion_comm::ExtEkfConstPtr & msg) { static_cast<MSF_SensorManagerROS<EKFState_T>&>(this->manager_) .SetHLControllerStateBuffer(*msg); // Get the imu values. msf_core::Vector3 linacc; linacc << msg->linear_acceleration.x, msg->linear_acceleration.y, msg ->linear_acceleration.z; msf_core::Vector3 angvel; angvel << msg->angular_velocity.x, msg->angular_velocity.y, msg ->angular_velocity.z; int32_t flag = msg->flag; // Make sure we tell the HL to ignore if data playback is on. if (this->manager_.GetDataPlaybackStatus()) flag = sensor_fusion_comm::ExtEkf::ignore_state; bool isnumeric = true; if (flag == sensor_fusion_comm::ExtEkf::current_state) { isnumeric = CheckForNumeric( Eigen::Map<const Eigen::Matrix<float, 10, 1> >(msg->state.data()), "before prediction p,v,q"); } // Get the propagated states. msf_core::Vector3 p, v; msf_core::Quaternion q; p = Eigen::Matrix<double, 3, 1>(msg->state[0], msg->state[1], msg->state[2]); v = Eigen::Matrix<double, 3, 1>(msg->state[3], msg->state[4], msg->state[5]); q = Eigen::Quaternion<double>(msg->state[6], msg->state[7], msg->state[8], msg->state[9]); q.normalize(); bool is_already_propagated = false; if (flag == sensor_fusion_comm::ExtEkf::current_state && isnumeric) { is_already_propagated = true; } this->ProcessState(linacc, angvel, p, v, q, is_already_propagated, msg->header.stamp.toSec(), msg->header.seq); } void IMUCallback(const sensor_msgs::ImuConstPtr & msg) { static int lastseq = constants::INVALID_SEQUENCE; if (static_cast<int>(msg->header.seq) != lastseq + 1 && lastseq != constants::INVALID_SEQUENCE) { MSF_WARN_STREAM( "msf_core: imu message drop curr seq:" << msg->header.seq << " expected: " << lastseq + 1); } lastseq = msg->header.seq; msf_core::Vector3 linacc; linacc << msg->linear_acceleration.x, msg->linear_acceleration.y, msg ->linear_acceleration.z; msf_core::Vector3 angvel; angvel << msg->angular_velocity.x, msg->angular_velocity.y, msg ->angular_velocity.z; this->ProcessIMU(linacc, angvel, msg->header.stamp.toSec(), msg->header.seq); } virtual bool Initialize() { return true; } }; } #endif // MSF_IMUHANDLER_ROS_H_
[ "chenmengxiao11@nudt.edu.cn" ]
chenmengxiao11@nudt.edu.cn
cb63f0c808e5f127d5e0bd339782d6d1f1651ebc
815486fd4ac8010bebce3d7cce1081d56a54179c
/exp01/task02.cpp
9a5e690f31c6ef101804f64c86ffe931b0dd9b8c
[]
no_license
Jinyers/homework
ca7d567bc3d4f2125be11eabf7808506960e6085
1331a6e145a33501abaa1dc3bda19f9b3dad99d2
refs/heads/master
2023-02-05T18:00:30.988969
2020-12-21T22:57:11
2020-12-21T22:57:11
308,596,044
0
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
#include <iostream> using namespace std; int main() { int size = 0; cout << "Введите размер массива: "; cin >> size; int* massive = new int[size]; for (int i=0; i<size; i++) { cout << "Введите " << i+1 << "-ный элемент: "; cin >> massive[i]; } // Sum int sum = 0; for (int i=0; i<size; i++) { if (massive[i]%2 == -1) // В проверке massive[i] < 0 нет необходимости sum += massive[i]; } // End cout << "Сумма нечетных отрицательных элементов: " << sum << endl; delete[] massive; return 0; }
[ "jinyer@Jinyer-Mac.local" ]
jinyer@Jinyer-Mac.local
0f6ade00767bd619b2ea46bda9b7b705151d31b6
ffcdb598bebc8a8c9d190b98cc88953c748dc88a
/05.cc
30e7a6b36bf469fd71d74d5ed7e5a9df19094ce2
[]
no_license
aztecrex/try-sdl
e2cfa961bc187ccd78473625f47b12f999b2c641
1468979d55c44fc21189c34006cdc32bbf9ba6aa
refs/heads/master
2021-01-20T00:21:36.370424
2017-04-29T21:44:33
2017-04-29T21:44:33
89,119,244
0
0
null
null
null
null
UTF-8
C++
false
false
3,455
cc
/*This source code copyrighted by Lazy Foo' Productions (2004-2015) and may not be redistributed without written permission.*/ //Using SDL, standard IO, and strings #include <SDL.h> #include <stdio.h> #include <string> //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; //Starts up SDL and creates window bool init(); //Loads media bool loadMedia(); //Frees media and shuts down SDL void close(); //Loads individual image SDL_Surface* loadSurface( std::string path ); //The window we'll be rendering to SDL_Window* gWindow = NULL; //The surface contained by the window SDL_Surface* gScreenSurface = NULL; //Current displayed image SDL_Surface* gStretchedSurface = NULL; bool init() { //Initialization flag bool success = true; //Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Create window gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( gWindow == NULL ) { printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); success = false; } else { //Get window surface gScreenSurface = SDL_GetWindowSurface( gWindow ); } } return success; } bool loadMedia() { //Loading success flag bool success = true; //Load stretching surface gStretchedSurface = loadSurface( "05_stretch.bmp" ); if( gStretchedSurface == NULL ) { printf( "Failed to load stretching image!\n" ); success = false; } return success; } void close() { //Free loaded image SDL_FreeSurface( gStretchedSurface ); gStretchedSurface = NULL; //Destroy window SDL_DestroyWindow( gWindow ); gWindow = NULL; //Quit SDL subsystems SDL_Quit(); } SDL_Surface* loadSurface( std::string path ) { //The final optimized image SDL_Surface* optimizedSurface = NULL; //Load image at specified path SDL_Surface* loadedSurface = SDL_LoadBMP( path.c_str() ); if( loadedSurface == NULL ) { printf( "Unable to load image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() ); } else { //Convert surface to screen format optimizedSurface = SDL_ConvertSurface( loadedSurface, gScreenSurface->format, 0 ); if( optimizedSurface == NULL ) { printf( "Unable to optimize image %s! SDL Error: %s\n", path.c_str(), SDL_GetError() ); } //Get rid of old loaded surface SDL_FreeSurface( loadedSurface ); } return optimizedSurface; } int main( int argc, char* args[] ) { //Start up SDL and create window if( !init() ) { printf( "Failed to initialize!\n" ); } else { //Load media if( !loadMedia() ) { printf( "Failed to load media!\n" ); } else { //Main loop flag bool quit = false; //Event handler SDL_Event e; //While application is running while( !quit ) { //Handle events on queue while( SDL_PollEvent( &e ) != 0 ) { //User requests quit if( e.type == SDL_QUIT ) { quit = true; } } //Apply the image stretched SDL_Rect stretchRect; stretchRect.x = 0; stretchRect.y = 0; stretchRect.w = SCREEN_WIDTH; stretchRect.h = SCREEN_HEIGHT; SDL_BlitScaled( gStretchedSurface, NULL, gScreenSurface, &stretchRect ); //Update the surface SDL_UpdateWindowSurface( gWindow ); } } } //Free resources and close SDL close(); return 0; }
[ "aztec.rex@jammm.com" ]
aztec.rex@jammm.com
17d5e8f0e19ff0de249bc01951094aa1b308a5e6
719e93f4e5799fb75ed99a4e3f69abd6ad9b8895
/lab_1/main.cpp
fde6ec0013a8213dea1912901cc2140a3ab2ce3e
[]
no_license
rafal166/pamsi_project
acdad488901779ef1f904f8a05d11d7b7b75c7ea
ba4d25b838f602c47b7156dd2d629634459d2d1d
refs/heads/master
2021-02-13T17:20:24.457833
2020-05-07T11:39:00
2020-05-07T11:39:00
244,716,117
0
0
null
null
null
null
UTF-8
C++
false
false
6,308
cpp
/* * File: main.cpp * Author: rafal * * Created on 24 marca 2020, 17:37 */ #include <cstdlib> #include <iostream> #include <vector> #include <cmath> #include <memory> #include <time.h> #include <thread> #include "utilities.h" #include "MergeSort.h" #include "HeapSort.h" #include "QuickSort.h" #include "IntroSort.h" #include "CSVSaver.h" using namespace std; #define NUM_ARRAYS 100 #define NUM_ELEM_IN_ARRAY_LV0 10000 // A #define NUM_ELEM_IN_ARRAY_LV1 50000 // B #define NUM_ELEM_IN_ARRAY_LV2 100000 // C #define NUM_ELEM_IN_ARRAY_LV3 500000 // D #define NUM_ELEM_IN_ARRAY_LV4 1000000 // E #define SAVING_VERSION 4 vector<string> CSVcolumnList = {"sortType", "A", "B", "C", "D", "E"}; vector<float> sortTypes = {0, 25, 50, 75, 95, 99, 99.7}; void test_merge_sort() { CSVSaver saver = CSVSaver("MergeSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList); shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4; for (float type : sortTypes) { saver.addData("First " + to_string(type) + " sorted"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type); saver.addData(MergeSort<int>::sortAll(array_lv0)); saver.addData(MergeSort<int>::sortAll(array_lv1)); saver.addData(MergeSort<int>::sortAll(array_lv2)); saver.addData(MergeSort<int>::sortAll(array_lv3)); saver.addData(MergeSort<int>::sortAll(array_lv4)); saver.newLine(); } // Wszystkie elementy posortowane odwrotnie saver.addData("All sorted reverse"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true); saver.addData(MergeSort<int>::sortAll(array_lv0)); saver.addData(MergeSort<int>::sortAll(array_lv1)); saver.addData(MergeSort<int>::sortAll(array_lv2)); saver.addData(MergeSort<int>::sortAll(array_lv3)); saver.addData(MergeSort<int>::sortAll(array_lv4)); saver.save(); } void test_quick_sort() { CSVSaver saver = CSVSaver("QuickSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList); shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4; for (float type : sortTypes) { saver.addData("First " + to_string(type) + " sorted"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type); saver.addData(QuickSort<int>::sortAll(array_lv0)); saver.addData(QuickSort<int>::sortAll(array_lv1)); saver.addData(QuickSort<int>::sortAll(array_lv2)); saver.addData(QuickSort<int>::sortAll(array_lv3)); saver.addData(QuickSort<int>::sortAll(array_lv4)); saver.newLine(); } // Wszystkie elementy posortowane odwrotnie saver.addData("All sorted reverse"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true); saver.addData(QuickSort<int>::sortAll(array_lv0)); saver.addData(QuickSort<int>::sortAll(array_lv1)); saver.addData(QuickSort<int>::sortAll(array_lv2)); saver.addData(QuickSort<int>::sortAll(array_lv3)); saver.addData(QuickSort<int>::sortAll(array_lv4)); saver.save(); } void test_intro_sort() { CSVSaver saver = CSVSaver("IntroSort_" + to_string(SAVING_VERSION) + ".csv", CSVcolumnList); shared_ptr<vector < shared_ptr<vector < int>>>> array_lv0, array_lv1, array_lv2, array_lv3, array_lv4; for (float type : sortTypes) { saver.addData("First " + to_string(type) + " sorted"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, type); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, type); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, type); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, type); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, type); saver.addData(IntroSort<int>::sortAll(array_lv0)); saver.addData(IntroSort<int>::sortAll(array_lv1)); saver.addData(IntroSort<int>::sortAll(array_lv2)); saver.addData(IntroSort<int>::sortAll(array_lv3)); saver.addData(IntroSort<int>::sortAll(array_lv4)); saver.newLine(); } // Wszystkie elementy posortowane odwrotnie saver.addData("All sorted reverse"); array_lv0 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV0, 100, true); array_lv1 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV1, 100, true); array_lv2 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV2, 100, true); array_lv3 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV3, 100, true); array_lv4 = allocateArrays<int>(NUM_ARRAYS, NUM_ELEM_IN_ARRAY_LV4, 100, true); saver.addData(IntroSort<int>::sortAll(array_lv0)); saver.addData(IntroSort<int>::sortAll(array_lv1)); saver.addData(IntroSort<int>::sortAll(array_lv2)); saver.addData(IntroSort<int>::sortAll(array_lv3)); saver.addData(IntroSort<int>::sortAll(array_lv4)); saver.save(); } int main(int argc, char** argv) { srand((unsigned) time(NULL)); // inicjowanie generatora liczb losowych thread merge_thread(test_merge_sort); thread quick_thread(test_quick_sort); thread intro_thread(test_intro_sort); merge_thread.join(); quick_thread.join(); intro_thread.join(); return 0; }
[ "rafal.rzewucki@gmail.com" ]
rafal.rzewucki@gmail.com
a90bbf71662b50c08b720b550e0f7b663fea5fba
aea5a52d44cd8907efc483fcbb0c6092ba571735
/gamewidget.cpp
d0491f8b25723aee62f812b4b74fce0f122f755d
[]
no_license
giarld/gxinMine
b06400e14527a3aad65fd4121f5f31dbeef65a81
7b3ba6bcd7c49f9a622d4a891cabd02659277ecf
refs/heads/master
2020-04-10T22:47:30.019065
2014-07-06T15:26:51
2014-07-06T15:26:51
21,043,468
1
0
null
null
null
null
UTF-8
C++
false
false
5,496
cpp
#include "gamewidget.h" #include <ctime> #include <cstring> GameWidget::GameWidget(QWidget *parent) : QWidget(parent) { this->setFixedSize(QSize(270+100,270+100)); init(); // newGame(); } void GameWidget::init() { this->wCount=this->hCount=9; this->MineCount=10; blockSize=30; update(); for(int i=0;i<Max;i++) { for(int j=0;j<Max;j++) { map[i][j]=new Block(this); map[i][j]->setPoint(j,i); map[i][j]->setFixedSize(blockSize,blockSize); map[i][j]->move(50+30*j,50+30*i); map[i][j]->setVisible(false); map[i][j]->locked(); connect(this,SIGNAL(setmk()),map[i][j],SLOT(setmk())); } } } void GameWidget::updateMap() { this->mapSize.setWidth(wCount*blockSize); this->mapSize.setHeight(hCount*blockSize); this->setFixedSize(QSize(mapSize.width()+100,mapSize.height()+100)); } ///public int rr[2][8]={{0,1,0,-1,1,1,-1,-1},{1,0,-1,0,1,-1,1,-1}}; void GameWidget::createGame() { if(firstRun) firstRun=0; else return; int i,j; for(i=0;i<hCount;i++) { for(j=0;j<wCount;j++) { for(int k=0;k<8;k++) { if(cmp(i+rr[0][k],j+rr[1][k])) { map[i][j]->setBrothers(map[i+rr[0][k]][j+rr[1][k]]); } } map[i][j]->setInit(); } } blockSum=hCount*wCount; flagSum=0; Block *temp=qobject_cast<Block *>(sender()); int lod; double q=(double)MineCount/(double)blockSum; if(q<0.5) { lod=MineCount; qsrand(time(NULL)); while(lod>0) { int rw=qrand()%wCount; int rh=qrand()%hCount; if(!map[rh][rw]->isMine() && (rw!=temp->getPoint().x() && rh!=temp->getPoint().y()) && !(temp->isBrother(map[rh][rw]) )) { map[rh][rw]->setMine(1); lod--; } } } else { //qDebug()<<">=0.5"; lod=blockSum-MineCount; bool dmap[Max][Max]; memset(dmap,1,sizeof(dmap)); qsrand(time(NULL)); int tx=temp->getPoint().y(); int ty=temp->getPoint().x(); dmap[tx][ty]=0; for(int i=0;i<8;i++) { dmap[tx+rr[0][i]][ty+rr[1][i]]=0; } lod-=9; while(lod>0) { int rw=qrand()%wCount; int rh=qrand()%hCount; if(dmap[rh][rw]) { dmap[rh][rw]=0; lod--; } } for(int i=0;i<hCount;i++) { for(int j=0;j<wCount;j++) { if(dmap[i][j]) map[i][j]->setMine(1); } } } emit start(); } ///slots bool GameWidget::cmp(int i, int j) { if(i<0 || j<0) return false; if(i>=hCount || j>=wCount) return false; return true; } void GameWidget::newGame() { for(int i=0;i<Max;i++) { for(int j=0;j<Max;j++) { map[i][j]->setVisible(false); map[i][j]->reBrothers(); map[i][j]->setInit(); } } for(int i=0;i<hCount;i++) { for(int j=0;j<wCount;j++) { map[i][j]->setVisible(true); connect(map[i][j],SIGNAL(start()),this,SLOT(createGame())); connect(map[i][j],SIGNAL(isOpen()),this,SLOT(openBlock())); connect(map[i][j],SIGNAL(isBoom()),this,SLOT(gameMiss())); connect(map[i][j],SIGNAL(isFlag()),this,SLOT(isFlag())); connect(map[i][j],SIGNAL(disFlag()),this,SLOT(disFlag())); map[i][j]->unLocked(); } } firstRun=1; emit mineSum(MineCount); } void GameWidget::gameMiss() { emit miss(); } void GameWidget::gamePause() { for(int i=0;i<hCount;i++) { for(int j=0;j<wCount;j++) { map[i][j]->locked(); map[i][j]->setVisible(false); } } } void GameWidget::gameStart() { for(int i=0;i<hCount;i++) { for(int j=0;j<wCount;j++) { map[i][j]->unLocked(); map[i][j]->setVisible(true); } } } void GameWidget::setLevel(int w,int h,int s) { this->wCount=w; this->hCount=h; this->MineCount=s; newGame(); } void GameWidget::openBlock() { blockSum--; // qDebug()<<blockSum; if(blockSum==MineCount) { for(int i=0;i<Max;i++) { for(int j=0;j<Max;j++) { if(map[i][j]->getStatus()==Block::Default) { map[i][j]->setFlag(); } map[i][j]->locked(); } } emit win(); } } void GameWidget::isFlag() { flagSum++; emit mineSum(MineCount-flagSum); } void GameWidget::disFlag() { flagSum--; if(flagSum<0) flagSum=0; emit mineSum(MineCount-flagSum); } void GameWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); QPen pen; pen.setWidth(2); pen.setColor(QColor(255,0,0)); painter.setPen(pen); QRect rect(50-1,50-1,(blockSize)*wCount+2,(blockSize)*hCount+2); painter.drawRect(rect); painter.setFont(QFont("default",25)); painter.drawText(rect,tr("暂停")); updateMap(); }
[ "xinxinqqts@gmail.com" ]
xinxinqqts@gmail.com
6e1c98a0e62f74dbd84661f052ae9a31c508fadf
76420c48c525228d1947f3a22e89a2904262dc79
/incl/subber.hpp
da74917b6dca876427dd4e0840936ec9d0e640f6
[]
no_license
longde123/caxe
559c16f9011693db5a03b4a8c82fa3487644cf53
8bf411e936a2ca9c45d72a9b8b2f30971f5d7b2b
refs/heads/master
2020-07-10T21:19:54.506801
2012-11-25T12:30:48
2012-11-25T12:30:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
541
hpp
#ifndef subber_hpp #define subber_hpp #include <parser_obj.hpp> #include <caxe_util.hpp> #include <deque> #include <vector> #include <string> class Subber : public Thread { ref<std::deque<ptr<MFile>>::iterator> ite; ref<tsDeque<ptr<MFile>>> files; size_t run(); public: Subber(); void init(std::deque<ptr<MFile>>::iterator&,tsDeque<ptr<MFile>>&); }; void subs_data(std::vector<ptr<State>>& ret, std::vector<ptr<State>>& in_data, ptr<Macros> macros); void subs(ptr<Scope> cscope); #endif
[ "luca@deltaluca.me.uk" ]
luca@deltaluca.me.uk
7651a777b05f3ac82a000c321349967ba31183bd
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_old_hunk_59.cpp
214eeec1bee6d6d331677f4aa003915e16dbebda
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
{ announceInitiatorAbort(theLauncher); // propogate to the transaction clearInitiator(); mustStop("initiator gone"); } void Adaptation::Iterator::noteAdaptationQueryAbort(bool final) { debugs(93,5, HERE << "final: " << final << " plan: " << thePlan); clearAdaptation(theLauncher); updatePlan(false); // can we replace the failed service (group-level bypass)?
[ "993273596@qq.com" ]
993273596@qq.com
f69a60ba7ee7ce0ed00722e076682df16cecbaf2
61fcc3fc81cb5ab59f8e857f0ecab472917f04b1
/datastructure/cumulativesum/cumulativesum.hpp
8dce6fe589b1814681ac821f73d7159cc34f176a
[]
no_license
morioprog/cpplib
4a4e6b9c0eb5dd3d8306041580e4c6c76b65d11e
71697ee35e8da1c7ae706e323304c170ad1851d6
refs/heads/master
2023-01-30T22:31:01.629203
2020-12-12T15:14:07
2020-12-12T15:14:07
257,325,284
0
0
null
2020-10-27T10:20:23
2020-04-20T15:33:06
C++
UTF-8
C++
false
false
670
hpp
/** * @brief 1次元累積和 * @docs docs/datastructure/cumulativesum/cumulativesum.md */ template <typename T> struct CumulativeSum { int sz; vector<T> data; CumulativeSum(const vector<T> &v, const T margin = 0) : sz(v.size()), data(1, margin) { for (int i = 0; i < sz; ++i) data.emplace_back(data[i] + v[i]); } T query(const int &l, const int &r) const { if (l >= r) return 0; return data[min(r, sz)] - data[max(l, 0)]; } T operator[](const int &k) const { return query(k, k + 1); } void print() { for (int i = 0; i < sz; ++i) cerr << data[i] << ' '; cerr << endl; } };
[ "morio.prog@gmail.com" ]
morio.prog@gmail.com
91d4679d82f33124715e5012d041495a05108cdb
33a0162aa373ecf1e99fa587bd5d7a09ad6c81ab
/lib/tvseg/settings/serializerbase.h
0898368bd7a4d389ae17e0bd0bfd038598f1e125
[ "MIT", "BSD-3-Clause", "BSL-1.0", "BSD-2-Clause" ]
permissive
nihalsid/tvseg
8b972febb36964bca57455edcdcebb096e81b07a
a97a63f81cc45d25f450199e044f041f5d81c150
refs/heads/master
2020-04-19T14:23:51.751661
2019-01-29T23:06:20
2019-01-29T23:06:20
168,243,627
0
0
null
2019-01-29T23:03:37
2019-01-29T23:03:37
null
UTF-8
C++
false
false
1,118
h
#ifndef TVSEG_SETTINGS_SERIALIZERBASE_H #define TVSEG_SETTINGS_SERIALIZERBASE_H #include "serializer.h" #include "backend.h" namespace tvseg { namespace settings { class SerializerBase : public Serializer { public: // types typedef Backend::iterator iterator; typedef Backend::const_iterator const_iterator; public: SerializerBase(BackendPtr backend, std::string location = ""); // Serializer interface public: void save(std::string location = ""); void load(std::string location = ""); protected: virtual void saveImpl(std::string location) = 0; virtual void loadImpl(std::string location) = 0; iterator begin() { return backend_->begin(); } const_iterator begin() const { return backend_->begin(); } iterator end() { return backend_->end(); } const_iterator end() const { return backend_->end(); } BackendConstPtr backend() const { return backend_; } BackendPtr backend() { return backend_; } private: BackendPtr backend_; std::string lastLocation_; }; } // namespace settings } // namespace tvseg #endif // TVSEG_SETTINGS_SERIALIZERBASE_H
[ "nikolaus@nikolaus-demmel.de" ]
nikolaus@nikolaus-demmel.de