blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
73454d7e45286935f4ed510e78327d3ec4b482c3
c55b9c3db364ee8259651e857878b776c4bdb724
/cpp/mountainview/src/msv/views/clusterdetailview.h
14cb64f662a681dafbf64d978f5832f76d7fc33b
[]
no_license
flatironinstitute/mountainview
7fdf94a0da33fe27e4728cb62e192e03ecb9fcfa
a87a587726b401a99430ec76c787d3de73569d50
refs/heads/master
2021-09-06T03:30:10.788265
2018-02-02T02:13:26
2018-02-02T02:13:26
107,665,822
2
1
null
2018-02-01T14:56:53
2017-10-20T10:37:11
C++
UTF-8
C++
false
false
2,859
h
clusterdetailview.h
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * 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 MVCLUSTERDETAILWIDGET_H #define MVCLUSTERDETAILWIDGET_H #include "diskreadmda.h" #include "mda.h" #include <QWidget> #include <mda32.h> #include "mvabstractview.h" /** \class ClusterDetailView * \brief Display a view of each cluster -- mainly the template shapes and some stats * * The user may click to change the current cluster, or use the Ctrl/Shift keys to select multiple clusters. */ class ClusterView; class ClusterDetailViewPrivate; class ClusterDetailView : public MVAbstractView { Q_OBJECT public: friend class ClusterDetailViewPrivate; friend class ClusterView; ClusterDetailView(MVAbstractContext* context); virtual ~ClusterDetailView(); void prepareCalculation() Q_DECL_OVERRIDE; void runCalculation() Q_DECL_OVERRIDE; void onCalculationFinished() Q_DECL_OVERRIDE; void setStaticData(const Mda32 &templates, const Mda32 &template_stdevs); void zoomAllTheWayOut(); ///Create an image of the current view QImage renderImage(int W = 0, int H = 0); //QJsonObject exportStaticView() Q_DECL_OVERRIDE; //void loadStaticView(const QJsonObject& X) Q_DECL_OVERRIDE; protected: void leaveEvent(QEvent*); void paintEvent(QPaintEvent* evt); void keyPressEvent(QKeyEvent* evt); void mousePressEvent(QMouseEvent* evt); void mouseReleaseEvent(QMouseEvent* evt); void mouseMoveEvent(QMouseEvent* evt); void mouseDoubleClickEvent(QMouseEvent* evt); void wheelEvent(QWheelEvent* evt); void prepareMimeData(QMimeData& mimeData, const QPoint& pos); signals: ///A cluster has been double-clicked (or enter pressed?) //void signalTemplateActivated(); private slots: //void slot_context_menu(const QPoint& pos); //void slot_export_waveforms(); void slot_export_image(); void slot_toggle_stdev_shading(); void slot_zoom_in(); void slot_zoom_out(); void slot_vertical_zoom_in(); void slot_vertical_zoom_out(); //void slot_export_static_view(); void slot_update_sort_order(); void slot_view_properties(); void slot_export_template_waveforms(); void slot_export_template_waveform_stdevs(); private: ClusterDetailViewPrivate* d; }; #endif // MVCLUSTERDETAILWIDGET_H
6fbbb091cd4ad07b672819f5b97edece6b971c87
6881369b3876a47418e239329594f2e1eab1a124
/pfs_file_server.cpp
347ebc4febcaa6729525532bc889acbd08494ad8
[]
no_license
arminvakil/PFS
bce9fe04b6f245fbf284a4f3ca29c295cf8bc8c6
e783b53097eadc591973a463cb6dc9e3a2b37759
refs/heads/master
2021-01-16T08:15:39.022486
2020-09-18T17:55:53
2020-09-18T17:55:53
243,038,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
pfs_file_server.cpp
/* * pfs_file_server.cpp * * Created on: Nov 28, 2019 * Author: armin */ #include <iostream> #include <memory> #include <string> #include <grpcpp/grpcpp.h> #include "message.grpc.pb.h" #include "file_server.h" using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::Status; int main(int argc, char** argv) { if(argc < 2) { std::cerr << "Usage : " << argv[0] << " server_no\n"; return -1; } std::string server_address("0.0.0.0:3000"); server_address.append(argv[1]); FileServerServiceImpl service(server_address); ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to an *synchronous* service. builder.RegisterService(&service); // Finally assemble the server. std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "File Server listening on " << server_address << std::endl; // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); }
df76a597b6d0b681af53a0acd70fd6eeacbc93ef
94e5a9e157d3520374d95c43fe6fec97f1fc3c9b
/Light OJ/1236.cpp
1f358cba93b5cb2532f13902ce49661ff28b785e
[ "MIT" ]
permissive
dipta007/Competitive-Programming
0127c550ad523884a84eb3ea333d08de8b4ba528
998d47f08984703c5b415b98365ddbc84ad289c4
refs/heads/master
2021-01-21T14:06:40.082553
2020-07-06T17:40:46
2020-07-06T17:40:46
54,851,014
8
4
null
2020-05-02T13:14:41
2016-03-27T22:30:02
C++
UTF-8
C++
false
false
9,232
cpp
1236.cpp
#pragma comment(linker, "/stack:640000000") #include <bits/stdc++.h> using namespace std; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; const double PI=acos(-1.0); #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long #define POPCOUNT __builtin_popcount #define POPCOUNTLL __builtin_popcountll #define RIGHTMOST __builtin_ctzll #define LEFTMOST(x) (63-__builtin_clzll((x))) template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; ///****************** template ends here **************** int t,n,m; // Utility function to do modular exponentiation. // It returns (x^y) % p ll power(ll x, ll y, ll p) { ll res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res; } // This function is called for all k trials. It returns // false if n is composite and returns false if n is // probably prime. // d is an odd number such that d*2<sup>r</sup> = n-1 // for some r >= 1 bool miillerTest(ll d, ll n) { // Pick a random number in [2..n-2] // Corner cases make sure that n > 4 ll a = 2 + rand() % (n - 4); // Compute a^d % n ll x = power(a, d, n); if (x == 1 || x == n-1) return true; // Keep squaring x while one of the following doesn't // happen // (i) d does not reach n-1 // (ii) (x^2) % n is not 1 // (iii) (x^2) % n is not n-1 while (d != n-1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n-1) return true; } // Return composite return false; } // It returns false if n is composite and returns true if n // is probably prime. k is an input parameter that determines // accuracy level. Higher value of k indicates more accuracy. bool isPrime(ll n, int k) { // Corner cases if (n <= 1 || n == 4) return false; if (n <= 3) return true; if(n%2==0) return false; // Find r such that n = 2^d * r + 1 for some r >= 1 ll d = n - 1; while (d % 2 == 0) d /= 2; // Iterate given nber of 'k' times for (int i = 0; i < k; i++) if (miillerTest(d, n) == false) return false; return true; } #define MAXL (50000>>5)+1 int mark[MAXL]; #define GETP(x) (mark[x>>5]>>(x&31)&1) #define SETP(x) (mark[x>>5] |= 1<<(x&31)) int P[50000], Pt = 0; void sieve() { register int i, j, k; SETP(1); int n = 46340; for (i = 2; i <= n; i++) { if (!GETP(i)) { for (k = n/i, j = i*k; k >= i; k--, j -= i) SETP(j); P[Pt++] = i; } } } long long mul(unsigned long long a, unsigned long long b, unsigned long long mod) { long long ret = 0; for (a %= mod, b %= mod; b != 0; b >>= 1, a <<= 1, a = a >= mod ? a - mod : a) { if (b&1) { ret += a; if (ret >= mod) ret -= mod; } } return ret; } void exgcd(long long x, long long y, long long &g, long long &a, long long &b) { if (y == 0) g = x, a = 1, b = 0; else exgcd(y, x%y, g, b, a), b -= (x/y) * a; } long long llgcd(long long x, long long y) { if (x < 0) x = -x; if (y < 0) y = -y; if (!x || !y) return x + y; long long t; while (x%y) t = x, x = y, y = t%y; return y; } long long inverse(long long x, long long p) { long long g, b, r; exgcd(x, p, g, r, b); if (g < 0) r = -r; return (r%p + p)%p; } long long mpow(long long x, long long y, long long mod) { // mod < 2^32 long long ret = 1; while (y) { if (y&1) ret = (ret * x)%mod; y >>= 1, x = (x * x)%mod; } return ret % mod; } long long mpow2(long long x, long long y, long long mod) { long long ret = 1; while (y) { if (y&1) ret = mul(ret, x, mod); y >>= 1, x = mul(x, x, mod); } return ret % mod; } int isPrime(long long p) { // implements by miller-babin if (p < 2 || !(p&1)) return 0; if (p == 2) return 1; long long q = p-1, a, t; int k = 0, b = 0; while (!(q&1)) q >>= 1, k++; for (int it = 0; it < 2; it++) { a = rand()%(p-4) + 2; t = mpow2(a, q, p); b = (t == 1) || (t == p-1); for (int i = 1; i < k && !b; i++) { t = mul(t, t, p); if (t == p-1) b = 1; } if (b == 0) return 0; } return 1; } long long pollard_rho(long long n, long long c) { long long x = 2, y = 2, i = 1, k = 2, d; while (true) { x = (mul(x, x, n) + c); if (x >= n) x -= n; d = llgcd(x - y, n); if (d > 1) return d; if (++i == k) y = x, k <<= 1; } return n; } void factorize(int n, vector<long long> &f) { for (int i = 0; i < Pt && P[i]*P[i] <= n; i++) { if (n%P[i] == 0) { while (n%P[i] == 0) f.push_back(P[i]), n /= P[i]; } } if (n != 1) f.push_back(n); } void llfactorize(long long n, vector<long long> &f) { if (n == 1) return ; if (n < 1e+9) { factorize(n, f); return ; } if (isPrime(n)) { debug("n", n) f.push_back(n); return ; } long long d = n; for (int i = 2; d == n; i++) d = pollard_rho(n, i); llfactorize(d, f); llfactorize(n/d, f); } #define TIME 20 int main() { #ifdef dipta007 //READ("in.txt"); // WRITE("out.txt"); #endif // dipta007 // ios_base::sync_with_stdio(0);cin.tie(0); int t; getI(t); sieve(); FOR(ci,1,t) { ll n; getL(n); printf("Case %d: ",ci); if(isPrime(n, TIME)) { printf("2\n"); continue; } vector < ll > fact; llfactorize(n, fact); ll now = 1; ll ans = 1; fact.PB(INF); sort(ALL(fact)); FOR(i,1,(int)fact.size()-1) { if(fact[i]==fact[i-1]) now++; else { ans *= (2LL*now + 1); now = 1; } } ans ++; ans/= 2; printf("%lld\n",ans); } return 0; }
a2eb04457e76cf07992b7d20e9d6607ab42553b4
299fa324c437c1fe468189a67d28331a361b301f
/Code/Vector2.cpp
1fcf1b013902c09492c3a9c0028152c45da665ba
[]
no_license
ClementCapart/FengShuiEngine
247504835ded294e30042a19560c74afe4b8054e
907b11d505e0e5c15779b9a0e86b4878a4f8795b
refs/heads/master
2021-06-09T18:07:10.134363
2017-01-15T21:44:39
2017-01-15T21:44:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
Vector2.cpp
#include "FengShuiEngine_PCH.h" #include "Vector2.h" #include <cmath> float Vector2::Length() const { return sqrt(SquaredLength()); } float Vector2::SquaredLength() const { return (X * X) + (Y * Y); } Vector2 Vector2::Normalized() const { float length = Length(); return *this / length; } Vector2 Vector2::Inverse() const { return Vector2(-X, -Y); } float Vector2::Dot(const Vector2& other) const { return X * other.X + Y * other.Y; } ///////////////////////////////////// //Static const Vector2 Vector2::Zero = Vector2(0.0f, 0.0f); const Vector2 Vector2::One = Vector2(1.0f, 1.0f); const Vector2 Vector2::Right = Vector2(1.0f, 0.0f); const Vector2 Vector2::Up = Vector2(0.0f, 1.0f); Vector2 Vector2::Lerp(const Vector2& start, const Vector2& end, float time) { return start + (end - start) * time; }
1569672ea2845d6a4b979b875eff034dd7d566d9
a090af918e3ec59140027dbddd54aa4ca1c73910
/Algo/bitmask_ternary.cpp
d1f4b87ec883dca932d385ba7349ae918b6aa85e
[]
no_license
nitesh-147/Programming-Problem-Solution
b739e2a3c9cfeb2141baf1d34e43eac0435ecb2a
df7d53e0863954ddf358539d23266b28d5504212
refs/heads/master
2023-03-16T00:37:10.236317
2019-11-28T18:11:33
2019-11-28T18:11:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,956
cpp
bitmask_ternary.cpp
#include<bits/stdc++.h> #define LL long long using namespace std; int n; int w[12], c[12]; bool arr[12][12]; int power[12]; int dp[12][2*59050]; inline void precal() { power[0]=1; for(int i=1; i<11; i++) power[i]=power[i-1]*3; } int makeint(string str) { int len=str.length(); int ret=0; for(int i=0; i<len; i++) { int cn=str[i]-'0'; ret= ret + cn*power[i]; } return ret; } string make_string(int mask) { string str=""; for(int i=0; i<n; i++) str+="0"; int i=0; while(mask>0) { str[i]=((mask%3)+'0'); mask=mask/3; i++; } return str; } int solve(int ind, int mask) { if(dp[ind][mask]!=-1) return dp[ind][mask]; int ret=0; string str=make_string(mask); if(str[ind]=='2') return dp[ind][mask]=0; if(str[ind]=='0') ret=c[ind]; int mx=0; str[ind]=str[ind]+1; int temp=makeint(str); for(int i=0; i<n; i++) { if(i==ind) continue; if(arr[ind][i]==false) continue; mx=max(mx, solve(i, temp)); } return dp[ind][mask]=ret+mx; } int main() { int i,j,k, u, v,m; precal(); cin>>n>>m; for(i=0; i<n; i++) { cin>>w[i]; } for(i=0; i<n; i++) { cin>>c[i]; } memset(arr, false, sizeof arr); for(i=0; i<m; i++) { cin>>u>>v; u--; v--; arr[u][v]=true; arr[v][u]=true; } int mx=0; memset(dp, -1, sizeof dp); for(i=0; i<n; i++) { // memset(dp, -1, sizeof dp); mx=max(mx, solve(i,0)); } cout<<mx<<endl; return 0; } /* 3 2 // n is the number of bits, m is the connection 1 1 2 // how many welcome 1 1 1 // cost 1 2 2 3 out: 3 THe graph: 1 \ 2 \ 3 6 5 1 2 2 1 2 2 1 1 1 1 1 1 1 2 2 6 2 3 3 4 4 5 Out: 6 Graph: 1 \ 2---6 \ 3 \ 4 \ 5 */
f0be12891af618579c21f45fbec5a15ec58933e9
de434ff675f555172a58e53416a2d405a7b4669d
/timer1-percision-test/src/main.cpp
e61b4aba866d5b8bae61bd000d49f62406706c58
[]
no_license
ndunks/arduino-esp8266-learn
7fff41dd5e198c2a61ffdaec838cae972eec23b0
078a66b692523364bbdb11a576e8fb6e2a46cf85
refs/heads/master
2022-12-24T14:30:39.636763
2021-05-01T17:47:59
2021-05-01T17:47:59
232,722,214
0
0
null
2022-12-11T21:01:26
2020-01-09T04:28:16
C++
UTF-8
C++
false
false
2,358
cpp
main.cpp
#include <Arduino.h> #include <ESP8266WiFi.h> const uint8_t tick_max = 8; volatile int32_t tick_snap[tick_max] = {}; volatile uint8_t tick_counter = 0; volatile int8_t done = 0; const uint32_t tick_delay = 80; // tick // https://sub.nanona.fi/esp8266/timing-and-ticks.html static inline int32_t asm_ccount(void) { int32_t r; asm volatile("rsr %0, ccount" : "=r"(r)); return r; } void ICACHE_RAM_ATTR timer_tick() { do { // difference casted as uint32_t. // This magically compensates if etime overflows returning // difference of value despite which is larger and which smaller. // minus tick is over head, 23 overhead is based on code execution while (((uint32_t)(asm_ccount() - tick_snap[tick_counter - 1])) < tick_delay - 23) { } // Exact 80 tick delay = 1 us tick_snap[tick_counter] = asm_ccount(); } while ((++tick_counter) < tick_max); done++; } void clear_tick() { tick_counter = 0; memset((void *)tick_snap, 0, sizeof(tick_snap)); } void start_tick(timercallback callback) { clear_tick(); timer1_attachInterrupt(callback); /** * TIM_DIV1 80MHz (80 ticks/us - 104857.588 us max) * Under 1 second loop/timer * * TIM_DIV16 5MHz (5 ticks/us - 1677721.4 us max) * 1 second = 5 * 1000 * 1000 = 5000000 tick * * TIM_DIV256 312.5Khz (1 tick = 3.2us - 26843542.4 us max) * 1 second = 1000 * 1000 / 3.2 = 312500 tick */ timer1_write(0); //80 tick at 80MHz tick_snap[tick_counter++] = asm_ccount(); timer1_enable(TIM_DIV1, TIM_EDGE, TIM_SINGLE); } void dump_tick(const char *title) { Serial.printf("\n%s:\n ", title); uint32_t gap = 0; float_t gap_us = 0.0f; for (int i = 0; i < tick_max; i++) { if (i > 0) { gap = tick_snap[i] - tick_snap[i - 1]; gap_us = gap / 80.0f; } Serial.printf("%3u %0.2f us\t", gap, gap_us); } Serial.printf("\n"); } void setup() { Serial.begin(115200); timer1_isr_init(); } void loop() { switch (done) { case 0: if (!timer1_enabled()) { start_tick(timer_tick); } break; case 2: case 1: dump_tick("TEST"); done = -1; break; } delay(1000); } /* TEST: 0 0.00 us 296 3.70 us 178 2.22 us 178 2.22 us 178 2.22 us 178 2.22 us 178 2.22 us 178 2.22 us */
e4c681f1ccf876587d88cde248321a65e476f3fc
cb0f510888d4d80c8fe16c22a0f40787677abfe0
/central_control_ui/include/central_control_ui/CusLabelMenu.h
24c53810a8dfc13d69e51fdbfbc71306ee3a0f7f
[ "MIT" ]
permissive
DeepBlue14/usar_system
89f4fb384c3fb41c3fefb9fe0eb339eb011c267f
a1b3d78a65f064be897f75dfc5f4dad4214f9d74
refs/heads/master
2021-01-17T21:03:37.653042
2017-11-16T05:21:50
2017-11-16T05:21:50
61,601,115
0
0
null
null
null
null
UTF-8
C++
false
false
2,742
h
CusLabelMenu.h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: CLabelMenu.h * Author: csrobot * * Created on March 26, 2016, 4:29 PM */ #ifndef CUS_LABEL_MENU_H #define CUS_LABEL_MENU_H #include <QMenu> #include <iostream> using namespace std; class CusLabelMenu : public QWidget { Q_OBJECT private: QMenu* menu; QAction* openAct; QAction* hideAct; QAction* deleteAct; QAction* renameAct; QAction* refactorAct; QAction* addAct; QAction* commitAct; QAction* removeAct; QAction* propertiesAct; QString* fileNameStrPtr; QString* fileLocStrPtr; QString* lastModdedStrPtr; //FilePropGui* filePropGuiPtr; private slots: void handleOpenMenuSlot(); void handleHideMenuSlot(); void handleDeleteMenuSlot(); void handleRenameMenuSlot(); void handleRefactorMenuSlot(); void handleAddMenuSlot(); void handleCommitMenuSlot(); void handleRemoveMenuSlot(); void handlePropertiesMenuSlot(); public: /** * Constructor. */ CusLabelMenu(QWidget* parent = 0); /** * Inits the menu for a file. */ void initMenu(); /** * * * @return */ QMenu* getMenu(); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ void setFileNameStrPtr(QString* fileNameStrPtr); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ QString* getFileNameStrPtr(); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ void setFileLocStrPtr(QString* fileLocStrPtr); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ QString* getFileLocStrPtr(); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ void setLastModdedStrPtr(QString* lastModdedStrPtr); /** * * * <dt><b>Pre: None.<b></dd> * <dt><b>Post: None.<b></dd> */ QString* getLastModdedStrPtr(); /** * Destructor. */ ~CusLabelMenu(); }; #endif /* CUSLABELMENU_H */
8f5fdd3f4b6cb5c7b70cd8e72d9b241793d5c457
b174d92f45384d1db4d669a874dec517d495439f
/TreeMain/TreeClass.cpp
b6f0e82c08385c98121cdbbb43441a705dd88d16
[]
no_license
parker37/TreeClass
521641ce86b7bd8d8122d7c3a7a826067caf145f
029fcf0909c8c427c1e4ded013ae648f02afaf5a
refs/heads/master
2023-07-27T11:05:45.774999
2021-09-08T08:45:26
2021-09-08T08:45:26
403,827,459
0
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
TreeClass.cpp
#include "TreeClass.h" void TreeClass::inorder(Node* root) { if (root == nullptr) { return; } inorder(root->left); cout << root->data << " "; inorder(root->right); } TreeClass::Node* TreeClass::insert(Node* root, int key) { if (root == nullptr) { return newNode(key); } if (key < root->data) { root->left = insert(root->left, key); } else { root->right = insert(root->right, key); } return root; }
a1ff03102394afbce8265b8fc47aae0d23d6ba84
152060017bbdfffa89b3fec361e53cb1b22a8b0e
/codeforces/Color the Fence.cpp
881f75846112ce19e799b809793dd3ab09df477b
[]
no_license
Mohammad-Yasfo/ACM_Problems
ea2d2f0ddcde2e9fea27cc1288d066b6ed155ca1
81f5bd39d53237f4d89df8ee65cf5241eb1f6c59
refs/heads/master
2021-05-12T11:00:49.913083
2018-01-13T18:21:27
2018-01-13T18:21:27
117,373,760
0
0
null
null
null
null
UTF-8
C++
false
false
1,395
cpp
Color the Fence.cpp
/* B. Color the Fence time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard output Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number. Help Igor find the maximum number he can write on the fence. Input The first line contains a positive integer v (0 ≤ v ≤ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105). Output Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1. Sample test(s) Input 5 5 4 3 2 1 2 3 4 5 Output 55555 Input 2 9 11 1 12 5 8 9 10 6 Output 33 Input 0 1 1 1 1 1 1 1 1 1 Output -1 */ #include<iostream> using namespace std; int i,n,s=1000001,l,a[9]; int main(){ cin>>n; while(cin>>a[i++]) s=min(s,a[i-1]); l=n/s; if(!l) cout<<-1; while(l--) for(i=8;i>=0;i--) if((n-a[i])/s==l && n>=a[i]){ cout<<i+1; n-=a[i]; break; } return 0; }
7a49d4c119cda591427ddbed7ec30acbdf461846
eabbf9e98437de2cef573e4f4dc6433dec2c7466
/stl_tuning.cpp
5cb3556c1466b7d3bdcaba57d1bc44c1a4d8b925
[]
no_license
glebmish/algorithms
d2ffe2dfe4fb87deea4d125e4c623a1106f517a9
fc0455c17deeae14409643bdbb7b28767e048ffd
refs/heads/master
2020-07-06T02:04:25.625108
2018-12-03T11:57:08
2018-12-03T11:57:08
74,063,462
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
cpp
stl_tuning.cpp
#include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <queue> #include <iostream> using namespace std; void tune_map() { cout << "Tune map" << endl; struct CmpStrLength { bool operator()(const string& a, const string& b) const { return a.size() < b.size(); } }; cout << "Lexicographical order" << endl; map<string, int> m = {{"c", 1}, {"abcde", 4}, {"df", 3}, {"bbb", 2}}; for (auto e : m) { cout << e.first << " " << e.second << endl; } cout << endl; cout << "Ordered by length" << endl; map<string, int, CmpStrLength> m2(m.begin(), m.end()); for (auto e : m2) { cout << e.first << " " << e.second << endl; } cout << endl; } void tune_unordered_map() { cout << "Tune unordered map" << endl; struct Pair { string first; string second; Pair(string first, string second): first(first), second(second) {} }; cout << "Saved in map based on first AND second" << endl; struct HashAll { size_t operator()(const Pair& n) const { return hash<string>()(n.first) ^ hash<string>()(n.second); } }; struct EqAll { bool operator()(const Pair& n1, const Pair& n2) const { return n1.first == n2.first && n1.second == n2.second; } }; unordered_map<Pair, int, HashAll, EqAll> m = { { {"a", "a"}, 1 }, { {"b", "b"}, 2 }, { {"a", "b"}, 3 } }; for (auto e : m) { cout << e.first.first << " " << e.first.second << " " << e.second << endl; } cout << endl; cout << "Saved in map based ONLY on first" << endl; struct HashFirst { size_t operator()(const Pair& n) const { return hash<string>()(n.first); } }; struct EqFirst { bool operator()(const Pair& n1, const Pair& n2) const { return n1.first == n2.first; } }; unordered_map<Pair, int, HashFirst, EqFirst> m2(m.begin(), m.end()); for (auto e : m2) { cout << e.first.first << " " << e.first.second << " " << e.second << endl; } cout << endl; } void tune_priority_queue() { cout << "Tune priority queue" << endl; cout << "Top of pq is the last element in strict weak ordering\ndefined by comparator (the greatest element)" << endl; vector<int> input = {5, 10, 12, 2, 144}; cout << "Descending order" << endl; priority_queue<int> pq(input.begin(), input.end()); while (!pq.empty()) { auto e = pq.top(); pq.pop(); cout << e << endl; } cout << endl; cout << "Ordered from the farthest to 7 to the closest" << endl; struct CmpCloseTo7 { bool operator()(const int a, const int b) const { return abs(a - 7) < abs(b - 7); } }; priority_queue<int, vector<int>, CmpCloseTo7> pq2(input.begin(), input.end()); while (!pq2.empty()) { auto e = pq2.top(); pq2.pop(); cout << e << endl; } cout << endl; } int main() { tune_map(); tune_unordered_map(); tune_priority_queue(); }
791405ea34bf0b3446b7d838cdcc814f36f0c1ca
c9ba44c641a4035c4064f431fd85044ec11b95b4
/fs/adaptor.hpp
6495ee31a559582c7fec5c1acd2fb1b76c99000a
[ "Apache-2.0" ]
permissive
kevin20x2/KVFS
f53f6bc3ec0cfab1afc4f44bc4ddd426412b19a8
829e172f1195f66dba67db4b5810084ab9562c31
refs/heads/master
2020-04-13T14:42:50.756447
2018-12-27T09:22:19
2018-12-27T09:22:19
163,270,173
0
0
null
null
null
null
UTF-8
C++
false
false
930
hpp
adaptor.hpp
/** * @file adaptor.hpp * @brief * @author kevin20x2@gmail.com * @version 1.0 * @date 2018-12-17 */ #ifndef KVFS_ADAPTOR_HPP #define KVFS_ADAPTOR_HPP #include "rocksdb/db.h" #include "rocksdb/slice.h" #include "rocksdb/options.h" #include <string> namespace kvfs { using namespace rocksdb; class RocksDBAdaptor { public: Status Put(const Slice & key, const Slice & value ); //Status Get(const Slice & key); Status Get(const std::string & key,std::string * value); Status Delete(const std::string & key ); Status PutFileMetaData(const char * path); Status Sync(); // int SetOptions(const Options & op); Status Init(const std::string & path = ""); inline Iterator * NewIterator() { return db_->NewIterator(ReadOptions()); } RocksDBAdaptor(); protected: bool inited_; DB * db_; Options options_; static const std::string default_DBpath; }; } #endif
f554f5e8dcdf3ff71248c0758d9893758107d6a2
046713242d1247555d07f571e17ea0c15663a8fa
/xTetBrick.h
821fd0e13601e8b40b01b2eafe1d6ff1c0a0bcc2
[]
no_license
dnelson2000/FEMpolar
a633afc4ef0183fd889ffa3d99af970655a8a89c
8f0cee9de9a2fef01ceb550f48eca16396d5b1f5
refs/heads/master
2020-09-14T01:10:23.888470
2019-11-20T15:03:27
2019-11-20T15:03:27
222,962,838
0
0
null
null
null
null
UTF-8
C++
false
false
7,157
h
xTetBrick.h
#pragma once #ifndef _TET_BRICK_H_ #define _TET_BRICK_H_ #include "xTetrahedra.h" #include "xBlockSparse.h" template <class T> class xTetBrick : public xTetrahedra<T> { public: xTetBrick( const std::vector< xTetMaterial >& material, int widthIn, int heightIn, int depthIn) : width(widthIn), height(heightIn), depth(depthIn) { xTetrahedra<T>::m_centerMaterial = material; } virtual ~xTetBrick() {} void vAddNodes(std::vector< xMath::Vector3 >& x0) { xTetrahedra<T>::m_startNode = (int) x0.size(); xTetrahedra<T>::m_nNodes = width*depth*height; x0.resize(x0.size() + xTetrahedra<T>::m_nNodes); vDefaultShape(x0); vCreateElements(x0); xTetrahedra<T>::vLumpedNodes(); } void vDefaultShape(std::vector< xMath::Vector3 >& x0) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { for (int k = 0; k < depth; k++) { #if 1 x0[xTetrahedra<T>::m_startNode+ i*height*depth + j*depth + k] = xMath::Vector3((float)i, (float)j, (float)k); #else double r = 10.0+0.3*i + 5.0*k; double a = 0.2*i; x0[xTetrahedra<T>::m_startNode+ i*height*depth + j*depth + k] = //xMath::Vector3((float)i, (float)j, (float)k); xMath::Vector3(r*cos(a),(double)j,r*sin(a)); #endif } } } } void vSetStiffness(const std::vector<xMath::Vector3>& x0, const std::vector<xTetMaterial> & mat) { if(!xTetrahedra<T>::m_bEnabled) return; for ( int i = 0; i < int(xTetrahedra<T>::m_tets.size()); ++i ) { xTetrahedra<T>::m_tets[i].vSetStiffness(x0, mat[0]); } } virtual void setMass(std::vector< xMath::Vector3 >& M, const std::vector< xMath::Vector3 >& x0); void getNodes( std::vector<xMath::Vector3> &nodes, std::vector<int> &elems, const std::vector< xMath::Vector3 >& x ) { nodes.resize(xTetrahedra<T>::m_nNodes); for ( int i = 0; i < m_nNodes; ++i ) nodes[i] = x[i + xTetrahedra<T>::m_startNode]; elems.resize(xTetrahedra<T>::m_tets.size()*24); for ( int i = 0; i < xTetrahedra<T>::m_tets.size(); ++i ) { int i24 = i*24; int *nodes = xTetrahedra<T>::m_tets[i].getNodes(); elems[i24+0] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+1] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i24+2] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i24+3] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+4] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+5] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+6] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+7] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+8] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+9] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+10] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+11] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+12] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+13] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i24+14] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i24+15] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+16] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+17] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i24+18] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i24+19] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+20] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i24+21] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+22] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i24+23] = nodes[1]-xTetrahedra<T>::m_startNode; } } void getNodesTris( std::vector<xMath::Vector3> &nodes, std::vector<int> &elems, const std::vector< xMath::Vector3 >& x ) { nodes.resize(xTetrahedra<T>::m_nNodes); for ( int i = 0; i < m_nNodes; ++i ) nodes[i] = x[i + xTetrahedra<T>::m_startNode]; elems.resize(xTetrahedra<T>::m_tets.size()*12); for ( int i = 0; i < xTetrahedra<T>::m_tets.size(); ++i ) { int i12 = i*12; int *nodes = xTetrahedra<T>::m_tets[i].getNodes(); xMath::Vector3 mid = 0.25*(x[nodes[0]]+x[nodes[1]]+x[nodes[2]]+x[nodes[3]]); xMath::Vector3 n0 = xMath::cross( x[nodes[0]]-x[nodes[1]], x[nodes[0]]-x[nodes[2]] ); xMath::Vector3 n1 = xMath::cross( x[nodes[0]]-x[nodes[2]], x[nodes[0]]-x[nodes[3]] ); xMath::Vector3 n2 = xMath::cross( x[nodes[0]]-x[nodes[3]], x[nodes[0]]-x[nodes[1]] ); xMath::Vector3 n3 = xMath::cross( x[nodes[1]]-x[nodes[3]], x[nodes[1]]-x[nodes[2]] ); if ( xMath::dot( x[nodes[0]]-mid, n0 ) < 0 ) { elems[i12+0] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+1] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i12+2] = nodes[2]-xTetrahedra<T>::m_startNode; } else { elems[i12+0] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+1] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i12+2] = nodes[1]-xTetrahedra<T>::m_startNode; } if ( xMath::dot( x[nodes[0]]-mid, n1 ) < 0 ) { elems[i12+3] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+4] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i12+5] = nodes[3]-xTetrahedra<T>::m_startNode; } else { elems[i12+3] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+4] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i12+5] = nodes[2]-xTetrahedra<T>::m_startNode; } if ( xMath::dot( x[nodes[0]]-mid, n2 ) < 0 ) { elems[i12+6] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+7] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i12+8] = nodes[1]-xTetrahedra<T>::m_startNode; } else { elems[i12+6] = nodes[0]-xTetrahedra<T>::m_startNode; elems[i12+7] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i12+8] = nodes[3]-xTetrahedra<T>::m_startNode; } if ( xMath::dot( x[nodes[1]]-mid, n3 ) < 0 ) { elems[i12+9] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i12+10] = nodes[3]-xTetrahedra<T>::m_startNode; elems[i12+11] = nodes[2]-xTetrahedra<T>::m_startNode; } else { elems[i12+9] = nodes[1]-xTetrahedra<T>::m_startNode; elems[i12+10] = nodes[2]-xTetrahedra<T>::m_startNode; elems[i12+11] = nodes[3]-xTetrahedra<T>::m_startNode; } } } protected: int width, height, depth; void vCreateElements(std::vector< xMath::Vector3 >& x0); }; #endif // _TET_ROD_H_
a66d4f92a9288dbc3954c497f9df85b70d1ad3f5
6ad0eb96903b34cea56b2e769ef5da0de6b84eed
/include/UserInterfaceOptions.h
f6f26df13e0e33e0a7cc5388239bc6845d27c1b0
[ "Beerware" ]
permissive
F1ll3r/rollenspiel
44f6ea82db108d32efd141d3c4d74da7a4757cd6
7a786fc2282d126c5974bf11708079e63b21ecb9
refs/heads/master
2016-09-06T14:57:33.695795
2010-12-22T21:02:05
2010-12-22T21:02:05
603,338
1
0
null
null
null
null
UTF-8
C++
false
false
1,154
h
UserInterfaceOptions.h
/* * UserInterfaceOptions.h * * Created on: 25.05.2010 * Author: F1ll3r */ #ifndef USERINTERFACEOPTIONS_H_ #define USERINTERFACEOPTIONS_H_ #include "UserInterfaceManager.h" enum UI_GUI_Element_Options{ UI_GUI_Element_Apply =200, UI_GUI_Element_Close, UI_GUI_Element_Save, UI_GUI_Element_Resolution, UI_GUI_Element_Resolution_Text, UI_GUI_Element_Depth, UI_GUI_Element_Depth_Text, UI_GUI_Element_Fullscreen, UI_GUI_Element_Fullscreen_Text, UI_GUI_Element_Vsync, UI_GUI_Element_Vsync_Text, UI_GUI_Element_Grass, UI_GUI_Element_Grass_Text, UI_GUI_Element_Filtering, UI_GUI_Element_Filtering_Text, UI_GUI_Element_Anti_Aliasing, UI_GUI_Element_Anti_Aliasing_Text, UI_GUI_Element_Shadow, UI_GUI_Element_Shadow_Text }; class UserInterfaceOptions: public UserInterfaceManager { private: bool setSettings(Settings s); Settings getSettings(); irr::gui::IGUIWindow* window; public: void draw(); bool OnEvent(const irr::SEvent& event); UserInterfaceOptions(Game* game,UserInterfaceManager* UI_Manager); void createButtons(); void deleteButtons(); virtual ~UserInterfaceOptions(); }; #endif /* USERINTERFACEOPTIONS_H_ */
4990afcd0cec5bc6f7550face0fddf97277367bf
78da2c3fc16fb25587576c406b101a7e07e35c6a
/src/interfaces.hh
3d11414b118454b5d6a9628d28782356a9336429
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
amoe/figshare-uploader
a0ff57710a2c4fce9efa46705b7aed01781e2118
6a2c32c8521891e7f5e37670e7adb37dafbda3da
refs/heads/master
2023-06-23T02:32:02.736670
2023-06-13T07:04:08
2023-06-13T07:04:08
113,032,906
7
1
Apache-2.0
2022-09-23T16:24:49
2017-12-04T11:13:08
C++
UTF-8
C++
false
false
2,659
hh
interfaces.hh
#ifndef INTERFACES_HH #define INTERFACES_HH #include <string> #include <vector> #include "progress_reporter.hh" #include "mapping_types.hh" #include "domain_dto.hh" #include "converter_registry.hh" using std::string; using std::vector; class View { public: virtual string getSelectedFile() = 0; virtual string getToken() = 0; virtual void reportError(string errorText) = 0; virtual void addLog(string logText) = 0; virtual bool showFileDialog() = 0; virtual void setProgressReporter(ViewProgressAdapter* reporter) = 0; virtual void showAboutDialog() = 0; virtual void showSettingsDialog( vector<string> headerFields, const MappingScheme& fieldMappings, const ConverterRegistry& converterRegistry ) = 0; virtual void setSourceFile(string sourceFile) = 0; virtual void setToken(string newToken) = 0; virtual void setAvailableEncoders(vector<FieldEncoder>& availableEncoders) = 0; virtual void infoBox(string message) = 0; virtual void forceRefreshFieldMappings() = 0; }; class Presenter { public: virtual void startUpload() = 0; virtual void uploadFinished(string value) = 0; virtual void setView(View* view) = 0; virtual void fatalError(string what) = 0; virtual void pickFile() = 0; virtual void initializeView() = 0; virtual void showAboutDialog() = 0; virtual void showSettingsDialog() = 0; virtual void fileConfirmed(string fileName) = 0; virtual void settingsConfirmed() = 0; virtual void saveFieldMappings(string outputPath) = 0; virtual void loadFieldMappings(string inputPath) = 0; virtual void fieldEncoderConfigurationDialogConfirmed( domain::FieldEncoderListOperation dto ) = 0; virtual void onMappingEncoderSetOperation( domain::MappingEncoderSetOperation dto ) = 0; }; class Model { public: virtual void setSourceFile(string newSourceFile) = 0; virtual vector<FieldEncoder>& getAvailableEncoders() = 0; virtual void bindRow(int excelRow, int fieldEncoderIndex) = 0; virtual void setHeaderFields(vector<string> headerFields) = 0; virtual void dumpMappingScheme() const = 0; virtual void addFieldEncoder(FieldEncoder f) = 0; virtual void replaceFieldEncoder(int index, FieldEncoder f) = 0; virtual void replaceFieldMappings(MappingScheme newMappingScheme) = 0; virtual const MappingScheme& getFieldMappings() const = 0; virtual const vector<string> getHeaderFields() const = 0; virtual const optional<string> getSourceFile() const = 0; virtual const ConverterRegistry& getConverterRegistry() const = 0; }; #endif // INTERFACES_HH
e9949db83daaf20900ae7cbaa23ae89422e65f8d
56a77194fc0cd6087b0c2ca1fb6dc0de64b8a58a
/applications/LinearSolversApplication/custom_decompositions/eigen_dense_column_pivoting_householder_qr_decomposition.h
fafa1322fefb90843de4de90cc6eb69f2252661b
[ "BSD-3-Clause" ]
permissive
KratosMultiphysics/Kratos
82b902a2266625b25f17239b42da958611a4b9c5
366949ec4e3651702edc6ac3061d2988f10dd271
refs/heads/master
2023-08-30T20:31:37.818693
2023-08-30T18:01:01
2023-08-30T18:01:01
81,815,495
994
285
NOASSERTION
2023-09-14T13:22:43
2017-02-13T10:58:24
C++
UTF-8
C++
false
false
8,158
h
eigen_dense_column_pivoting_householder_qr_decomposition.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Ruben Zorrilla // #if !defined(KRATOS_EIGEN_DENSE_COLUMN_PIVOTING_HOUSEHOLDER_QR_H_INCLUDED) #define KRATOS_EIGEN_DENSE_COLUMN_PIVOTING_HOUSEHOLDER_QR_H_INCLUDED // External includes #include <Eigen/QR> // Project includes #include "includes/define.h" #include "linear_solvers_define.h" #include "utilities/dense_qr_decomposition.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ template<class TDenseSpace> class EigenDenseColumnPivotingHouseholderQRDecomposition : public DenseQRDecomposition<TDenseSpace> { public: ///@name Type Definitions ///@{ /// Definition of the shared pointer of the class KRATOS_CLASS_POINTER_DEFINITION(EigenDenseColumnPivotingHouseholderQRDecomposition); typedef typename TDenseSpace::DataType DataType; typedef typename TDenseSpace::VectorType VectorType; typedef typename TDenseSpace::MatrixType MatrixType; using EigenVector = Kratos::EigenDynamicVector<DataType>; using EigenMatrix = Kratos::EigenDynamicMatrix<DataType>; ///@} ///@name Life Cycle ///@{ EigenDenseColumnPivotingHouseholderQRDecomposition() = default; ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ static std::string Name() { return "dense_column_pivoting_householder_qr_decomposition"; } void Compute(MatrixType& rInputMatrix) override { // Householder QR requires m >= n const std::size_t m = rInputMatrix.size1(); const std::size_t n = rInputMatrix.size2(); KRATOS_ERROR_IF(m < n) << "Householder QR decomposition requires m >= n. Input matrix size is (" << m << "," << n << ")." << std::endl; // Compute the Householder QR decomposition // Note that the QR is computed when constructing the pointer Eigen::Map<EigenMatrix> eigen_input_matrix_map(rInputMatrix.data().begin(), m, n); mpColPivHouseholderQR = Kratos::make_unique<Eigen::ColPivHouseholderQR<Eigen::Ref<EigenMatrix>>>(eigen_input_matrix_map); } void Compute( MatrixType& rInputMatrix, MatrixType& rMatrixQ, MatrixType& rMatrixR) override { Compute(rInputMatrix); MatrixQ(rMatrixQ); MatrixR(rMatrixR); } void Solve( MatrixType& rB, MatrixType& rX) const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'Solve'." << std::endl; // Check output matrix size std::size_t n = rB.size2(); const std::size_t rank = Rank(); if (rX.size1() != rank || rX.size2() != n) { rX.resize(rank,n,false); } // Solve the problem Ax = b Eigen::Map<EigenMatrix> eigen_x_map(rX.data().begin(), rank, n); Eigen::Map<EigenMatrix> eigen_rhs_map(rB.data().begin(), rB.size1(), n); eigen_x_map = mpColPivHouseholderQR->solve(eigen_rhs_map); } void Solve( const VectorType& rB, VectorType& rX) const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'Solve'." << std::endl; // Check output matrix size const std::size_t rank = Rank(); if (rX.size() != rank) { rX.resize(rank,false); } // Solve the problem Ax = b Eigen::Map<EigenMatrix> eigen_x_map(rX.data().begin(), rank, 1); Eigen::Map<EigenMatrix> eigen_rhs_map(const_cast<VectorType&>(rB).data().begin(), rB.size(), 1); eigen_x_map = mpColPivHouseholderQR->solve(eigen_rhs_map); } void MatrixQ(MatrixType& rMatrixQ) const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'MatrixQ'." << std::endl; // Set the thin Q to be returned const std::size_t Q_rows = mpColPivHouseholderQR->householderQ().rows(); const std::size_t rank = Rank(); if (rMatrixQ.size1() != Q_rows || rMatrixQ.size2() != rank) { rMatrixQ.resize(Q_rows,rank,false); } // Get the thin unitary matrix Q from the complete one // Note that Eigen stores it not as matrix type but as a sequence of Householder transformations (householderQ()) Eigen::Map<EigenMatrix> thin_Q(rMatrixQ.data().begin(), Q_rows, rank); thin_Q = EigenMatrix::Identity(Q_rows,rank); thin_Q = mpColPivHouseholderQR->householderQ() * thin_Q; } void MatrixR(MatrixType& rMatrixR) const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'MatrixR'." << std::endl; // Set the matrix R to be returned const std::size_t rank = Rank(); if (rMatrixR.size1() != rank || rMatrixR.size2() != rank) { rMatrixR.resize(rank,rank,false); } // Get the upper triangular matrix // Note that we specify Eigen to return the upper triangular part as the bottom part are auxiliary internal values Eigen::Map<EigenMatrix> matrix_R_map(rMatrixR.data().begin(), rank, rank); matrix_R_map = mpColPivHouseholderQR->matrixR().topLeftCorner(rank, rank).template triangularView<Eigen::Upper>(); } void MatrixP(MatrixType& rMatrixP) const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'MatrixP'." << std::endl; // Get the permutation matrix const auto& r_P = mpColPivHouseholderQR->colsPermutation(); const std::size_t m = r_P.rows(); const std::size_t n = r_P.cols(); // Output the permutation matrix if (rMatrixP.size1() != m || rMatrixP.size2() != n) { rMatrixP.resize(m,n,false); } Eigen::Map<EigenMatrix> matrix_P_map(rMatrixP.data().begin(), m, n); matrix_P_map = r_P; } std::size_t Rank() const override { // Check that QR decomposition has been already computed KRATOS_ERROR_IF(!mpColPivHouseholderQR) << "QR decomposition not computed yet. Please call 'Compute' before 'Rank'." << std::endl; return mpColPivHouseholderQR->rank(); } void PrintInfo(std::ostream &rOStream) const override { rOStream << "EigenDecomposition <" << Name() << "> finished."; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ ///@} private: ///@name Private static Member Variables ///@{ ///@} ///@name Private member Variables ///@{ std::unique_ptr<Eigen::ColPivHouseholderQR<Eigen::Ref<EigenMatrix>>> mpColPivHouseholderQR = std::unique_ptr<Eigen::ColPivHouseholderQR<Eigen::Ref<EigenMatrix>>>(nullptr); ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Private LifeCycle ///@{ ///@} ///@name Unaccessible methods ///@{ ///@} }; ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } // namespace Kratos #endif // defined(KRATOS_EIGEN_DENSE_COLUMN_PIVOTING_HOUSEHOLDER_QR_H_INCLUDED)
4e58c0ec083f144b500340f0fa0ff70b5f4f7eec
5f2e5c68b7819dc24c200921b19936edabeb3c30
/FinalProject/FinalProject.cpp
de4be78c58fd3c5b0340943c33f4949c5f1ac45d
[]
no_license
EmperorMoose/CSCE-240
8c165582dd4c09f4b59f1eab7f79f8a37e532d28
3ad6b87e509995f771e9c16c6e65cb1146c9c684
refs/heads/master
2021-01-13T04:13:31.616835
2016-12-31T05:29:32
2016-12-31T05:29:32
77,493,041
0
0
null
null
null
null
UTF-8
C++
false
false
1,434
cpp
FinalProject.cpp
// FinalProject.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include "Gene.h" #include "Sequence.h" int main(int argc, char* argv[]) { //NOTES: Is the sequence on each line, prefaced by the ID? or are they seperate lines? //Everything below reads in and assigns the file to file_contents //*************************************************************** //ifstream geneFile; //geneFile.open(argv[1]); //string str; //string file_contents; int lines = 2; //this counts up the lines in the file //while (getline(geneFile, str)) //{ // lines++; //} string *file_contents; //file_contents = new string[lines]; file_contents = new string[2]; file_contents[0] = "TAACGATGCAACAGACGACTATACTAACTTCTCTGGGCCTTGATCACTAAACCGGATTGCTCACTGAGGCAAGACCATATCATACCCGAGATATAGCTGA"; file_contents[1] = "TTTCCCGCGTACATGTGTGAACCCGGCTGCCTTTGCTTGCGGTCGGGTTGGCTTTTACATTTGGTAGCACTAACGATGCAACAGACGACTATACTAACTT"; Gene *list; list = new Gene[lines]; Sequence sequence; int overlap = 5; for (int i = 0; i < 2;i++) { list[i] = *new Gene(file_contents[i], overlap); } /* for (int i = 0; i < list[0].len; i++) { cout << list[0].at(i); } */ for (int i = 0; i < 2;i++) { cout << i; //if (list[i + 1].doesExist()) //{ cout << "here"; list[i+1].compare(list[i], overlap, sequence); //} } sequence.show(); //delete[] file_contents; }
945a610ad64b02daa893cc95736e7436c3803186
d507b2c5eec7d46ce147dba1e65cf965a66b88d2
/Snark_News/2020/Round_2/A.cpp
16edb775cc1339b8673fd80b70096f8500c52c9c
[]
no_license
mohamedsobhi777/CompetitiveProgramming
e5875d23bdb9e0407d125fc421e269637e62627c
9b2ec961313064545682de3c460feed4d326920a
refs/heads/master
2022-09-28T06:41:30.120246
2022-09-12T09:28:21
2022-09-12T09:28:21
240,776,156
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
A.cpp
#include <bits/stdc++.h> #define vi vector<int> #define vii vector<pair<int, int>> #define pii pair<int, int> #define pll pair<ll, ll> #define loop(_) for (int __ = 0; __ < (_); ++__) #define forn(i, n) for (int i = 0; i < n; ++i) using namespace std; using ll = long long; using ld = long double; const int N = 1e6 + 7; const ll mod = 1e9 + 7; const ll inf = 2e18; auto ra = [] {char *p = new char ; delete p ; return ll(p) ; }; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count() * (ra() | 1)); int n; ll a[N]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); // freopen("in.in", "r", stdin); cin >> n; ll ans = 0; ll lhs = 0, rhs = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; rhs += a[i]; } for (int i = 0; i < n; ++i) { rhs -= a[i]; lhs += 1ll * a[i] * a[i]; ans = max(ans, 1ll * lhs * rhs); } cout << ans; return 0; }
4b25bab84f938da1f70515264423203ec0d6448d
642742cd1138f8e0fd9bb19271af676d1ae5facc
/core/basics/Observable.h
00b8ed055410211b6d726cb152989783ae8e1687
[]
no_license
cvjena/nice-core
d64f3b1b873047eb383ad116323f3f8617978886
d9578e23f5f9818e7c777f6976eab535b74dc62f
refs/heads/master
2021-01-20T05:32:01.068843
2019-02-01T16:17:13
2019-02-01T16:17:13
3,012,683
4
4
null
2018-10-22T20:37:52
2011-12-19T15:01:13
C++
UTF-8
C++
false
false
812
h
Observable.h
#ifndef _OBSERVABLE_FBASICS_H #define _OBSERVABLE_FBASICS_H #include <vector> #include <core/basics/Observer.h> namespace NICE { /** * Observable as in Observer-pattern. * * @author Ferid Bajramovic (ferid [dot] bajramovic [at] informatik [dot] uni-jena [dot] de) */ class Observable { public: //! notify all observers void notifyObservers(); /** * Add an Observer (Ownership NOT taken.) */ inline void addObserver(Observer* observer) { observers.push_back(observer); observer->setObserved(this); } /** * Remove an Observer. * @note If the Observer has been added multiple times, * all entries will be removed. */ void removeObserver(Observer* observer); private: std::vector<Observer*> observers; }; } // namespace #endif // _OBSERVABLE_FBASICS_H
be771b09fce6bad0bf1758d59fc7bfc2c8d36644
e42a3b348c78e3c90db1e8a5863152fe5b62746f
/cc/lib/cr/msgs/CRterminal.cc
7ee17127a6e5a6b2e79e8c8d4d0dfa5a482e991f
[]
no_license
wanziforever/hap
0532ff73106fc6d79a6c72a41fdf21f9085fb502
f981ea9a946fdb8453b4c277117836901d1abfaa
refs/heads/master
2020-04-14T22:38:22.070094
2015-01-20T00:14:24
2015-01-20T00:14:24
14,736,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,808
cc
CRterminal.cc
/* ** File ID: @(#): <MID19366 () - 08/17/02, 29.1.1.1> ** ** File: MID19366 ** Release: 29.1.1.1 ** Date: 08/21/02 ** Time: 19:40:13 ** Newest applied delta: 08/17/02 ** ** DESCRIPTION: ** ** OWNER: ** Roger McKee ** ** NOTES: ** */ #ifdef CC //IBM JGH 05/09/06 change path #ifdef __linux #include <termio.h> #else #include <sys/termio.h> #endif #else #include <sys/ttychars.h> #endif #include "cc/cr/hdr/CRterminal.H" #include "cc/hdr/misc/GLasync.H" CRwindow* CRtermController::curWindow = NULL; CRterminal* CRtermController::curTerminal = NULL; void CRtermController::setCurTerminal(CRterminal* term) { curTerminal = term; } void CRtermController::beep() { curTerminal->beep(); } void CRtermController::refresh() { curTerminal->refresh(); } CRwindow* CRtermController::activate(CRwindow* win) { CRwindow* retval = curWindow; if (curWindow) { if (curWindow == win) return NULL; curWindow->deactivate(); } curWindow = win; if (win) win->activate(); return retval; } void CRtermController::setVideoAtts(CRcolor fc, CRcolor bc, Bool flash, Bool underline, Bool graphic, CRintensity intensity) { if (curTerminal) curTerminal->setVideoAtts(fc, bc, flash, underline, graphic, intensity); } CRterminal::CRterminal() { curUnderline = NO; curGraphic = NO; curFlash = NO; } CRterminal::~CRterminal() { } void CRterminal::shutDown() { CRtermController::activate(NULL); } void CRterminal::refresh() { GLFFLUSH(stdout); } void CRterminal::beep() { //IBM JGH 05/09/06 use the quoted G for linux #ifdef __linux GLPUTCHAR(CTRL('G')); #else #ifdef _SVR4 GLPUTCHAR(CTRL('G')); #else GLPUTCHAR(CTRL(G)); #endif #endif } void CRterminal::setFkey(int /*fkeynum*/, const char* /*label*/, const char* /*value*/) { }
192d83947f0417093a0f231a9333c848f6a4a2bd
f76639427ccd2e6950aba5e25f2fed1878661e5f
/AAX_SDK_2p3p2/ExamplePlugIns/DemoGain_GUIExtensions/Source/GUI/DemoGain_String.cpp
c0df6ea322b4ee187f1c832f3d9a27febfb4d98a
[]
no_license
sadisticaudio/SDKs
f5e21caf67eb9b99db6677a7c3b1f58739922cdd
b56f6c506a0e93817dd2decd5f214061dae43dc4
refs/heads/main
2023-06-16T14:34:30.783603
2021-07-11T02:13:56
2021-07-11T02:13:56
384,839,826
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
cpp
DemoGain_String.cpp
/*================================================================================================*/ /* * Copyright 2009-2015 by Avid Technology, Inc. * All rights reserved. * * CONFIDENTIAL: This document contains confidential information. Do not * read or examine this document unless you are an Avid Technology employee * or have signed a non-disclosure agreement with Avid Technology which protects * the confidentiality of this document. DO NOT DISCLOSE ANY INFORMATION * CONTAINED IN THIS DOCUMENT TO ANY THIRD-PARTY WITHOUT THE PRIOR WRITTEN CONSENT * OF Avid Technology, INC. */ /*================================================================================================*/ #include "DemoGain_String.h" DemoGain_String::DemoGain_String() : mString("") { } uint32_t DemoGain_String::Length () const { return uint32_t(mString.length()); } uint32_t DemoGain_String::MaxLength () const { return kMaxStringLength; } const char * DemoGain_String::Get () const { return mString.c_str(); } void DemoGain_String::Set ( const char * iString ) { mString = iString; } AAX_IString & DemoGain_String::operator=(const AAX_IString & iOther) { mString = iOther.Get(); return *this; } AAX_IString & DemoGain_String::operator=(const char * iString) { mString = iString; return *this; }
c4f3745c384cb09a953824483d24c3b621f0b73c
8369afd6d25415bf47a870de2c4a87b0833c630e
/pass/pass.cpp
ef2e009e6468fbb0c629afd9f7ea8c47c5dc0724
[]
no_license
Babak-khezri/university.cpp
eaeb999081d4e4e01a26b63b2ce81ea2e9392248
779dcf958e6e739643d908b0486cf324830e6bc6
refs/heads/master
2020-12-27T10:14:52.034137
2020-02-03T01:41:23
2020-02-03T01:41:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
783
cpp
pass.cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> #define max 50 char user[max], pas[max]; void Enter(); void join(); int main(){ printf("1_Enter \n2_join\n"); int x; scanf("%d",&x); switch(x){ case 1: getchar(); Enter(); break; case 2: join(); break; } return 0; } void Enter(){ system("cls"); char u[max], p[max]; printf("Enter your usename: "); gets(u); //getchar(); printf("Enter your basword: "); gets(p); //getchar(); if(!(strcmp(u,user))&&!(strcmp(p,pas))) printf("you are in"); else printf("wrong username or pasword") ; } void join(){ system("cls"); printf("enter username: "); getchar(); gets(user); printf("Enter pasword : "); gets(pas); /*printf("press any key to go back to Enter page:"); getchar();*/ Enter(); }
f5a3dedac9e812920f58549547225d41a7d3fb74
dbd1cd64d92d75464c1baccfe604a378da5c4850
/zad1.2-benchmark/src/kontener.cpp
6dea63b6f578d84817cc36a67433fe731fd050b5
[]
no_license
200403/Pamsi_lab
f4419629339000bf9ad17a767b56b9628587a5f9
132a159d29f7d92b29d78d2b98405d64e272bad1
refs/heads/master
2020-04-06T03:40:59.672455
2014-05-28T19:45:12
2014-05-28T19:45:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
kontener.cpp
#include "kontener.hh" #include <iostream> #include <fstream> #include <assert.h> using namespace std; /*! * \brief metoda wczytuje dane do tablicy z pliku * * Format danych w pliku jest nastepujacy: * pierwszy wiersz - ilosc elementow, a nastepnie w kolumnie kolejne wartosci tablicy. * \param nazwaPliku - nazwa pliku do otwarcia * \return void */ void Kontener::wczytajDane(string nazwaPliku){ dane.clear(); ifstream plik; plik.open(nazwaPliku.c_str(), ios::in); plik >> rozmiar; while( !plik.eof()){ int element; plik >> element; dane.push_back(element); } assert(rozmiar==dane.size()); plik.close(); } void Kontener::zamien_elementy(unsigned int i, unsigned int j){ int temp; assert(i<=rozmiar-1 && j<=rozmiar-1); temp=dane[i]; dane[i]=dane[j]; dane[j]=temp; } void Kontener::odwroc_kolejnosc(){ vector <int> temp; for(unsigned int i=0; i<rozmiar;i++){ temp.push_back(dane[rozmiar-1-i]); } dane=temp; } void Kontener::dodaj_element(int e){ dane.push_back(e); rozmiar++; } void Kontener::dodaj_elementy(Kontener tab){ unsigned int i; for(i=0; i<tab.rozmiar; i++){ dane.push_back(tab.dane[i]); } rozmiar+=i; } int & Kontener::operator [](int index){ return dane[index]; } Kontener& Kontener::operator + (Kontener tab){ dodaj_elementy(tab); return *this; } Kontener& Kontener::operator = (Kontener tab){ dane=tab.wez_dane(); rozmiar=tab.wez_rozmiar(); return *this; } bool Kontener::operator == (Kontener tab){ if (rozmiar!=tab.wez_rozmiar()) return false; else{ for(unsigned int i=0; i<rozmiar; i++){ if(dane[i]!=tab[i]) return false; } } return true; } ostream & operator << (ostream& out, Kontener Tab){ out << "rozmiar: " << Tab.wez_rozmiar() << endl; for(unsigned int i=0; i<Tab.wez_rozmiar(); i++){ out << Tab[i] << endl; } return out; }
f4f48dce4567d84287e96669729fbb3d5097c3f8
2f9a425e8f5d034da4d35c9f941ff609cb232883
/poj/3417/POJ_3417_2797633_AC_1030MS_24496K.cpp
bdb85a6329b7f8c410df97fe15283de09ec1352e
[]
no_license
wangyongliang/nova
baac90cd8e7bdb03c6c5916fbab9675dabf49af5
86b00b1a12f1cc6291635f31a33e791f6fb19d1a
refs/heads/master
2022-02-18T05:35:02.447764
2019-09-08T02:22:06
2019-09-08T02:22:06
10,247,347
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
cpp
POJ_3417_2797633_AC_1030MS_24496K.cpp
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; #define size 100100 vector <int> a[size]; int b[size]; int n,cnt,m; int A[size*2],B[size*2]; int R[size]; bool flag[size]; int M[size*2][20]; __int64 ans; void dfs(int deep,int i,int j) { A[cnt]=deep; B[cnt]=i; R[i]=cnt; cnt++; vector<int >::iterator it; for(it=a[i].begin();it!=a[i].end();it++) { if(*it!=j) { dfs(deep+1,*it,i); A[cnt]=deep; B[cnt]=i; cnt++; } } } void Init_LCA_RMQ() { int i,j; cnt=0; dfs(0,1,0); for (i=0; i<cnt; i++) M[i][0] = i; for (j=1; (1<<j)<=cnt; j++) { for (i=0; i+(1<<j)-1<cnt; i++) { if (A[M[i][j-1]] > A[M[i+(1<<(j-1))][j-1]]) M[i][j] = M[i+(1<<(j-1))][j-1]; else M[i][j] = M[i][j-1]; } } } void f(int i,int j) { vector<int> ::iterator it; flag[i]=0; for(it=a[i].begin();it!=a[i].end();it++) { if(j!=*it) { f(*it,i); } } for(it=a[i].begin();it!=a[i].end();it++) { if(*it!=j) b[i]+=b[*it]; } if(b[i]==0) ans+=m; else if(b[i]==1) ans++; } int RMQ(int i, int j) { int k = 0; while ((1<<(k+1)) < (j-i+1)) k++; if (A[M[i][k]] > A[M[j-(1<<k)+1][k]]) return B[M[j-(1<<k)+1][k]]; else return B[M[i][k]]; } int main() { int i,j,k,p; while(scanf("%d%d",&n,&m)!=EOF) { for(k=0;k<=n;k++) { a[k].clear(); flag[k]=1;b[k]=0; } for(k=1;k<n;k++) { scanf("%d%d",&i,&j); a[i].push_back(j); a[j].push_back(i); } Init_LCA_RMQ(); p=m; while(p--) { scanf("%d%d",&i,&j); if(i==j) continue; if(R[i]>R[j]) swap(i,j); k=RMQ(R[i],R[j]); b[i]++; b[j]++; b[k]-=2; } ans=0; f(1,0); ans-=m; printf("%I64d\n",ans); } return 0; }
217b992006f27548539dea3d4fd000a82e1289fc
ca16b7fe65bee3ecee61435746aba6d3d29fff9e
/Fast Modular Exponentiation/main.cpp
3cc41bc3bf79d3cd512badb24dd2919d8a49b7b0
[]
no_license
DivyanshSinha/Competitive-Programing
c28bfd850e2fc4cb48fa8d7e7b6a9bd96308ef8c
1643b45e80dc48ca93a4f2d9396945f551a1abc0
refs/heads/main
2023-04-02T00:38:53.757272
2021-03-29T17:56:00
2021-03-29T17:56:00
345,370,353
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
main.cpp
#include <iostream> using namespace std; int fastExpo(int a , long long n , int mod) { if(n==0) return 1; if(n%2==0) return fastExpo((1LL*a*a)%mod,n/2,mod); return (1LL*a*fastExpo(a,n-1,mod))%mod; } int main() { int a,n,mod; cout<<"Enter base: "; cin>>a; cout<<"Enter exponent: "; cin>>n; cout<<"Enter mod: "; cin>>mod; cout<<fastExpo(a,n,mod); return 0; }
7040def8562b8037cc5de31f3fbd51c0500a8a84
513fc79b95b81899f7b9d2eb41724c1a2f8b4fe0
/v1/fonts/makefont.cpp
97af383c4db106f14e1d839f5a6ed893d2be9e8f
[]
no_license
escargames/escarlib
3fe2a5f3f02f96c4e1a8fe97b7228032ed31ab90
a0402aef8fac84ec918e048e88827903ceb41783
refs/heads/master
2020-05-17T14:01:49.520742
2020-04-12T19:25:00
2020-04-18T10:11:25
183,752,825
0
0
null
null
null
null
UTF-8
C++
false
false
783
cpp
makefont.cpp
#include <lol/engine.h> int main(int, char **argv) { lol::image img; img.load(argv[1]); auto size = img.size(); lol::array2d<lol::vec4> &data = img.lock2d<lol::PixelFormat::RGBA_F32>(); std::vector<int> accum; for (int i = 0; i < size.x; ++i) { int val = 0; for (int j = 0; j < size.y; ++j) if (lol::dot(data[i][j].rgb, lol::vec3(1.)) < 0.01) val += 1 << j; accum.push_back(val); if (i + 1 == size.x || (data[i + 1][0].r > 0.8 && data[i + 1][0].g < 0.2)) { printf(" [\"?\"]={"); for (auto n : accum) printf("%d,", n); printf("},\n"); accum.clear(); ++i; } } img.unlock2d(data); }
cfe407f91bcbf36e83068a3d46febb9e11ecf0a9
e62c565406a06075891598b173d5fabfb0107335
/include/otm/Matrix.hpp
e3a78e9457230ebdb96ccb010be3a568420422dc
[ "BSD-2-Clause" ]
permissive
Othereum/otm
2bf35fca82d527d05b51468d957c409f6303544e
75a800c2c5e3351b8068c6417d176a5943c6af27
refs/heads/master
2022-12-25T02:04:40.641582
2020-10-08T08:22:20
2020-10-08T08:22:20
256,718,533
5
1
null
null
null
null
UTF-8
C++
false
false
13,351
hpp
Matrix.hpp
#pragma once #include "Vector.hpp" namespace otm { namespace detail { template <class T, size_t R, size_t C> struct MatrixBase { }; template <class T, size_t L> struct MatrixBase<T, L, L> { static const Matrix<T, L, L> identity; constexpr void Transpose() noexcept; // Matrix with ones on the main diagonal and zeros elsewhere static constexpr Matrix<T, L, L> Identity() noexcept; // Matrix that assigned other matrix to the identity matrix // Efficient version (a little :D) template <class T2, size_t L2> static constexpr Matrix<T, L, L> Identity(const Matrix<T2, L2, L2>& other) noexcept; // Matrix that assigned other matrix to the identity matrix with offset template <class T2, size_t R2, size_t C2> static constexpr Matrix<T, L, L> Identity(const Matrix<T2, R2, C2>& other, const Vector<ptrdiff_t, 2>& offset = {}) noexcept; }; } template <class T, size_t R, size_t C> struct Matrix : detail::MatrixBase<T, R, C> { using value_type = Vector<T, C>; using size_type = size_t; using difference_type = ptrdiff_t; using reference = Vector<T, C>&; using const_reference = const Vector<T, C>&; using pointer = Vector<T, C>*; using const_pointer = const Vector<T, C>*; using iterator = Vector<T, C>*; using const_iterator = const Vector<T, C>*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static const Matrix zero; [[nodiscard]] static constexpr Matrix Zero() noexcept { return {}; } constexpr Matrix() noexcept = default; constexpr Matrix(All, T x) noexcept { for (auto& v : arr) for (auto& c : v) c = x; } template <class T2, size_t R2, size_t C2> explicit constexpr Matrix(const Matrix<T2, R2, C2>& other) { Assign(other); } template <class T2, size_t R2, size_t C2> constexpr Matrix(const Matrix<T2, R2, C2>& other, const Vector<ptrdiff_t, 2>& offset) { Assign(other, offset); } explicit constexpr Matrix(T x) noexcept { Assign({x}); } template <class... Args> constexpr Matrix(T x, T y, Args ... args) noexcept { static_assert(sizeof...(Args) + 2 <= R * C, "Too many arguments"); Assign({x, y, static_cast<T>(args)...}); } template <class Fn, std::enable_if_t<std::is_invocable_r_v<T, Fn>, int> = 0> explicit constexpr Matrix(Fn fn) noexcept(std::is_nothrow_invocable_v<Fn>) { for (auto& v : arr) v.Transform([&](auto&&...) { return fn(); }); } /** * \brief Assign elements of other matrix to this. The value of the unassigned elements does not change. * \note Does nothing if offset is out of range */ template <class T2, size_t R2, size_t C2> constexpr void Assign(const Matrix<T2, R2, C2>& other, const Vector<ptrdiff_t, 2>& offset = {}) noexcept { if (offset[1] >= 0) { const auto size = Min(R - Min(R, static_cast<size_t>(offset[1])), R2); for (size_t i = 0; i < size; ++i) (*this)[i + offset[1]].Assign(other[i], offset[0]); } else { const auto size = Min(R, R2 - Min(R2, static_cast<size_t>(-offset[1]))); for (size_t i = 0; i < size; ++i) (*this)[i].Assign(other[i - offset[1]], offset[0]); } } /** * \brief Assign elements from initializer list. The value of the unassigned elements does not change. */ constexpr void Assign(std::initializer_list<T> list) noexcept { auto it = list.begin(); for (size_t i = 0; i < R && it != list.end(); ++i) for (size_t j = 0; j < C && it != list.end(); ++j) arr[i][j] = *it++; } template <class T2> constexpr bool operator==(const Matrix<T2, R, C>& b) const noexcept { static_assert(!(std::is_floating_point_v<T> || std::is_floating_point_v<T2>), "Can't compare equality between floating point types. Use IsNearlyEqual() instead."); for (size_t i = 0; i < R; ++i) if (Row(i) != b[i]) return false; return true; } template <class T2> constexpr bool operator!=(const Matrix<T2, R, C>& b) const noexcept { return !(*this == b); } template <class T2, size_t R2, size_t C2> constexpr bool operator==(const Matrix<T2, R2, C2>&) const noexcept { return false; } template <class T2, size_t R2, size_t C2> constexpr bool operator!=(const Matrix<T2, R2, C2>&) const noexcept { return true; } constexpr auto& operator[](size_t i) noexcept { assert(i < R); return arr[i]; } constexpr auto& operator[](size_t i) const noexcept { assert(i < R); return arr[i]; } [[nodiscard]] constexpr auto& Row(size_t i) { if (i >= R) OutOfRange(); return arr[i]; } [[nodiscard]] constexpr auto& Row(size_t i) const { if (i >= R) OutOfRange(); return arr[i]; } template <size_t L> [[nodiscard]] constexpr Vector<T, L> Row(size_t i) const { if (i >= R) OutOfRange(); return Vector<T, L>{arr[i]}; } template <size_t L = R> [[nodiscard]] constexpr auto Col(size_t c) const { if (c >= C) OutOfRange(); Vector<T, L> v; for (size_t r = 0; r < Min(L, R); ++r) v[r] = arr[r][c]; return v; } [[nodiscard]] constexpr auto& AsVectors() noexcept { return arr; } [[nodiscard]] constexpr auto& AsVectors() const noexcept { return arr; } [[nodiscard]] auto& AsFlatArr() noexcept { return reinterpret_cast<T(&)[R * C]>(arr); } [[nodiscard]] auto& AsFlatArr() const noexcept { return reinterpret_cast<const T(&)[R * C]>(arr); } constexpr Matrix operator+(const Matrix& b) const noexcept { auto c = *this; return c += b; } constexpr Matrix& operator+=(const Matrix& b) noexcept { for (auto i = 0; i < R; ++i) arr[i] += b[i]; return *this; } constexpr Matrix operator-(const Matrix& b) const noexcept { auto c = *this; return c -= b; } constexpr Matrix& operator-=(const Matrix& b) noexcept { for (auto i = 0; i < R; ++i) arr[i] -= b[i]; return *this; } constexpr Matrix operator*(T f) const noexcept { auto c = *this; return c *= f; } constexpr Matrix& operator*=(T f) noexcept { for (auto i = 0; i < R; ++i) arr[i] *= f; return *this; } constexpr Matrix operator/(T f) const noexcept { auto c = *this; return c /= f; } constexpr Matrix& operator/=(T f) noexcept { for (auto i = 0; i < R; ++i) arr[i] /= f; return *this; } template <class T2, size_t C2> constexpr Matrix<std::common_type_t<T, T2>, R, C2> operator*(const Matrix<T2, C, C2>& b) const noexcept { Matrix<std::common_type_t<T, T2>, R, C2> c; for (size_t i = 0; i < R; ++i) for (size_t j = 0; j < C2; ++j) c[i][j] = Row(i) | b.Col(j); return c; } constexpr Matrix& operator*=(const Matrix& b) noexcept { return *this = *this * b; } [[nodiscard]] constexpr Matrix<T, C, R> Transposed() const noexcept { Matrix<T, C, R> t; for (auto i = 0; i < R; ++i) for (auto j = 0; j < C; ++j) t[j][i] = arr[i][j]; return t; } [[nodiscard]] constexpr T Det() const noexcept { static_assert(R == C); if constexpr (R == 1) { return arr[0][0]; } else { auto plus = true; T det = 0; for (size_t i = 0; i < R; ++i) { const auto x = arr[i][R - 1] * Slice(i, R - 1).Det(); if (plus) det += x; else det -= x; plus = !plus; } return det; } } [[nodiscard]] constexpr std::optional<Matrix> Inv() const noexcept { static_assert(R == C); static_assert(std::is_floating_point_v<T>); const auto det = Det(); if (IsNearlyZero(det)) return {}; Matrix inv; for (size_t i = 0; i < R; ++i) { for (size_t j = 0; j < C; ++j) { inv[i][j] = Slice(j, i).Det() / det; if ((i + j) % 2 == 0) inv[i][j] = -inv[i][j]; } } return inv; } [[nodiscard]] constexpr Matrix<T, R - 1, C - 1> Slice(const size_t y, const size_t x) const noexcept { Matrix<T, R - 1, C - 1> m; size_t i = 0; for (; i < y; ++i) { size_t j = 0; for (; j < x; ++j) m[i][j] = arr[i][j]; for (++j; j < C; ++j) m[i][j - 1] = arr[i][j]; } for (++i; i < R; ++i) { size_t j = 0; for (; j < x; ++j) m[i - 1][j] = arr[i][j]; for (++j; j < C; ++j) m[i - 1][j - 1] = arr[i][j]; } return m; } [[nodiscard]] constexpr iterator begin() noexcept { return arr; } [[nodiscard]] constexpr const_iterator begin() const noexcept { return arr; } [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return arr; } [[nodiscard]] constexpr iterator end() noexcept { return arr + R; } [[nodiscard]] constexpr const_iterator end() const noexcept { return arr + R; } [[nodiscard]] constexpr const_iterator cend() const noexcept { return arr + R; } [[nodiscard]] constexpr reverse_iterator rbegin() noexcept { return reverse_iterator{end()}; } [[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{end()}; } [[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{cend()}; } [[nodiscard]] constexpr reverse_iterator rend() noexcept { return reverse_iterator{begin()}; } [[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return const_reverse_iterator{begin()}; } [[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator{cbegin()}; } private: [[noreturn]] static void OutOfRange() { throw std::out_of_range{"Matrix out of range"}; } Vector<T, C> arr[R]; }; template <class T, size_t R, size_t C, class F, std::enable_if_t<std::is_convertible_v<F, T>, int> = 0> constexpr auto operator*(F f, const Matrix<T, R, C>& m) noexcept { return m * f; } template <class T, size_t R, size_t C> std::ostream& operator<<(std::ostream& os, const Matrix<T, R, C>& m) { os << m[0]; for (size_t i = 1; i < R; ++i) os << '\n' << m[i]; return os; } namespace detail { template <class T, size_t L> constexpr void MatrixBase<T, L, L>::Transpose() noexcept { auto& self = static_cast<Matrix<T, L, L>&>(*this); for (size_t i = 0; i < L; ++i) for (size_t j = 0; j < L; ++j) { using std::swap; swap(self[j][i], self[i][j]); } } template <class T, size_t L> constexpr Matrix<T, L, L> MatrixBase<T, L, L>::Identity() noexcept { Matrix<T, L, L> matrix; for (size_t i = 0; i < L; ++i) matrix[i][i] = 1; return matrix; } template <class T, size_t L> template <class T2, size_t L2> constexpr Matrix<T, L, L> MatrixBase<T, L, L>::Identity(const Matrix<T2, L2, L2>& other) noexcept { Matrix<T, L, L> m{other}; for (auto i = L2; i < L; ++i) m[i][i] = 1; return m; } template <class T, size_t L> template <class T2, size_t R2, size_t C2> constexpr Matrix<T, L, L> MatrixBase<T, L, L>::Identity(const Matrix<T2, R2, C2>& other, const Vector<ptrdiff_t, 2>& offset) noexcept { auto m = Identity(); m.Assign(other, offset); return m; } } template <class T, size_t L> constexpr Matrix<T, 1, L> Vector<T, L>::ToRowMatrix() const noexcept { Matrix<T, 1, L> m; for (size_t i = 0; i < L; ++i) m[0][i] = (*this)[i]; return m; } template <class T, size_t L> constexpr Matrix<T, L, 1> Vector<T, L>::ToColMatrix() const noexcept { Matrix<T, L, 1> m; for (size_t i = 0; i < L; ++i) m[i][0] = (*this)[i]; return m; } template <class T, size_t L> inline const Matrix<T, L, L> detail::MatrixBase<T, L, L>::identity = Identity(); template <class T, size_t R, size_t C> inline const Matrix<T, R, C> Matrix<T, R, C>::zero = Zero(); }
2b83df37b048ce5abb959c152e1e4b38925cc2c8
bdfe9048a46f2bc44b8f7ac64eddee64501cae8a
/src/Nodes/NodePrimaryExpr.cpp
f2cfc798963d4204f9cc4b2cabc7fde44dfbacf4
[ "MIT" ]
permissive
kirarpit/compiler-construction
80a438fc0469d716b7a64c6218d2b913b292375e
36bd47d40a934e8ff87bf58a9e7049f644169f2f
refs/heads/master
2021-03-22T03:46:42.392533
2018-11-03T23:09:39
2018-11-03T23:09:39
121,824,786
0
0
null
null
null
null
UTF-8
C++
false
false
1,649
cpp
NodePrimaryExpr.cpp
#include <AllNodeHeaders.h> Node* NodePrimaryExpr::parse(CompilerState &cs) { Lexer &lex = cs.lexer; Logger::logParseEntry(__CLASS_NAME__, lex.peek()); bool errorFlag = false; Node *primaryExpr = new NodePrimaryExpr(); if (lex.peek().type == TT_ID) { Token id = lex.read(); primaryExpr->addNode(new TerminalNode(id)); primaryExpr->assignable(); if (!cs.lastBlock->getST()->isDef) { if (!cs.lastBlock->getST()->insertOrUpdateVar(cs, id)) { errorFlag = true; } } } else if (lex.peek().type == TT_NUM) { primaryExpr->addNode(new TerminalNode(lex.read())); } else if (lex.peek().value == TokenTable::TS[TN_opnpar]) { Logger::logTerminal(lex.peek()); lex.read(); Node *expr = NodeExpr::parse(cs); if (expr) { primaryExpr->addNode(expr); if (expr->isAssignable) primaryExpr->assignable(); if (lex.peek().value == TokenTable::TS[TN_clspar]) { Logger::logTerminal(lex.peek()); lex.read(); } else { errorFlag = true; cs.es.reportError(cs, "expecting ')'"); } } else { errorFlag = true; } } else { errorFlag = true; cs.es.reportError(cs, "expecting ID or a Num"); } if (errorFlag) { delete primaryExpr; return NULL; } Logger::logParseExit(__CLASS_NAME__, lex.peek()); return primaryExpr; } void NodePrimaryExpr::walk(CompilerState &cs) { Logger::logWalkEntry(__CLASS_NAME__, this); smartWalk(cs); Logger::logWalkExit(__CLASS_NAME__, this); } Register NodePrimaryExpr::genCode(CompilerState &cs, CodeGenArgs cg) { Logger::logGenCodeEntry(__CLASS_NAME__, this); Logger::logGenCodeExit(__CLASS_NAME__, this); return children[0]->genCode(cs, cg); }
822564ff45728a3d77de43d285f66e2d45427099
44c24b25be46851e372438aec35b03955e3df136
/update_k_neighbors.h
1c68760625449d3980514bd8f1466422655251ac
[]
no_license
roksanaShimu/Probabilistic-Roadmap
ef34eb6713517138b7058ed8e6faffea347f0d19
5aeef17de1b98906e7699684f7b41e125ff11e7d
refs/heads/main
2023-03-05T12:21:41.159901
2021-02-11T08:53:53
2021-02-11T08:53:53
337,905,799
0
0
null
null
null
null
UTF-8
C++
false
false
3,280
h
update_k_neighbors.h
#ifndef update_k_neighbors #define update_k_neighbors #include <stdint.h> #include<vector> #include "predefined_variables.h" #include "milestones.h" using namespace std; bool path_can_be_build(local_planner_node* A, local_planner_node* B, vector<Sphere> obstacles){ Sphere local_sample[9]; int i=0; int j; for(float t=0.1;t<1;t=t+0.1){ //cout<<t<< " "<<i<<endl; local_sample[i].p.x=A->p.x+(B->p.x-A->p.x)*t; local_sample[i].p.y=A->p.y+(B->p.y-A->p.y)*t; local_sample[i].p.z=A->p.z+(B->p.z-A->p.z)*t; local_sample[i].radius=UAV_radius; i++; } for(i=0;i<9;i++){ for(j=0;j<number_of_obstacles ;j++){ if(doesItCollide(local_sample[i].p, obstacles[j])){ //cout<<"collides with obstacle x: "<<obstacles[j].p.x<<" y: "<<obstacles[j].p.y<<" z: "<<obstacles[j].p.z<<" radius: "<<obstacles[j].radius<<" and the UAV location is x: "<< local_sample[i].p.x<<" y: "<<local_sample[i].p.y<<" z: "<<local_sample[i].p.z<<endl<<endl; return false; } } } return true; } float calculate_distance(local_planner_node* A, local_planner_node* B){ return sqrt( (A->p.x-B->p.x)*(A->p.x-B->p.x) + (A->p.y-B->p.y)*(A->p.y-B->p.y) +(A->p.z-B->p.z)*(A->p.z-B->p.z) ); } void get_nodes(vector<local_planner_node*>& S, int i, int start_index, int end_index, vector<Sphere> obstacles){ //boundary conditions if(start_index <0 || end_index>S.size()-1)return; if(start_index> end_index)return; //end of boundary conditions typedef pair<local_planner_node*, float> apair; for(int j=start_index; j<=end_index; j++){ if (path_can_be_build(S[i], S[j], obstacles)){ S[i]->knn.push_back(apair(S[j], calculate_distance(S[i],S[j]) )); } } } void update_kth_neighbors(vector<local_planner_node*>& sample_local_planner_node, vector<Sphere> obstacles){ if(sample_local_planner_node.size()<= number_of_elements_for_knn){ cout<<"Error: the number of neighbors for knn is higher than the sample nodes" <<endl; return; } int m=sample_local_planner_node.size()-1; int n=number_of_elements_for_knn; //number_of_elements_for_knn is multiple of 4. so number_of_elements_for_knn is always divisible by 2 for(int i=0;i<=m;i++){ if(i<(n/2)){ //not enough elements at the begining get_nodes(sample_local_planner_node, i, 0, i-1, obstacles); get_nodes(sample_local_planner_node, i, i+1, n, obstacles); }else if((m-i)<(n/2)){ //not enough elements at the end get_nodes(sample_local_planner_node, i, m-n, i-1, obstacles); get_nodes(sample_local_planner_node, i, i+1, m, obstacles); }else{ get_nodes(sample_local_planner_node, i, i-(n/2), i-1, obstacles); get_nodes(sample_local_planner_node, i, i+1, i+(n/2), obstacles); } } } void print_neighbors_update(vector<local_planner_node*> sample_local_planner_node){ for(int i =0; i<sample_local_planner_node.size();i++){ cout<<"i= "<<i<<" x= "<<sample_local_planner_node[i]->p.x<<" y= "<<sample_local_planner_node[i]->p.y<<" z= "<<sample_local_planner_node[i]->p.z<<" no of neighbors= "<<sample_local_planner_node[i]->knn.size()<<endl; for(int j=0; j<sample_local_planner_node[i]->knn.size(); j++){ cout<<sample_local_planner_node[i]->knn[j].first->index<<", "<<sample_local_planner_node[i]->knn[j].second<<endl; } cout<<endl; } } #endif
a6544c4a08194b1f91c50908d89a66cd21346e31
165be8367f5753b03fae11430b1c3ebf48aa834a
/tools/train/source/models/MobilenetV2.hpp
88e95e7490118804a9eb493148be125a158a164a
[ "Apache-2.0" ]
permissive
alibaba/MNN
f21b31e3c62d9ba1070c2e4e931fd9220611307c
c442ff39ec9a6a99c28bddd465d8074a7b5c1cca
refs/heads/master
2023-09-01T18:26:42.533902
2023-08-22T11:16:44
2023-08-22T11:16:44
181,436,799
8,383
1,789
null
2023-09-07T02:01:43
2019-04-15T07:40:18
C++
UTF-8
C++
false
false
1,158
hpp
MobilenetV2.hpp
// // MobilenetV2.hpp // MNN // // Created by MNN on 2020/01/08. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef MobilenetV2_hpp #define MobilenetV2_hpp #include "Initializer.hpp" #include <vector> #include "MobilenetUtils.hpp" #include <MNN/expr/Module.hpp> #include "NN.hpp" #include <algorithm> namespace MNN { namespace Train { namespace Model { class MNN_PUBLIC MobilenetV2 : public Express::Module { public: // use tensorflow numClasses = 1001, which label 0 means outlier of the original 1000 classes // so you maybe need to add 1 to your true labels, if you are testing with ImageNet dataset MobilenetV2(int numClasses = 1001, float widthMult = 1.0f, int divisor = 8); virtual std::vector<Express::VARP> onForward(const std::vector<Express::VARP> &inputs) override; std::shared_ptr<Express::Module> firstConv; std::vector<std::shared_ptr<Express::Module> > bottleNeckBlocks; std::shared_ptr<Express::Module> lastConv; std::shared_ptr<Express::Module> dropout; std::shared_ptr<Express::Module> fc; }; } // namespace Model } // namespace Train } // namespace MNN #endif // MobilenetV2_hpp
43b6c7e8af86ad6d9747327d9ea89966cbc712ee
1197ff17a68feee28c6664b7b5be918de3dbb8da
/1203.SortItemsbyGroupsRespectingDependencies.cpp
31a9559f89a47b653ea21b3b40dde7038b6547e1
[]
no_license
dushyant-goel/leetcode
1151bf4cf69f63f3b0b1d5cf48cdd22f1d58c799
de5c061a0b0de70a2934a3a22931e491767d17b3
refs/heads/main
2023-06-24T10:03:24.965677
2021-07-27T14:50:31
2021-07-27T14:50:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,608
cpp
1203.SortItemsbyGroupsRespectingDependencies.cpp
class Solution { public: vector<int> visited; bool dfs(int i, vector<int> &order, vector<vector<int>> &edgeList) { if (visited[i] == 1) return true; else if (visited[i] == 2) return false; bool hasCycle; visited[i] = 1; for (int j = 0; j < edgeList[i].size(); j++) { if ((hasCycle = dfs(edgeList[i][j], order, edgeList))) { return true; } } order.push_back(i); visited[i] = 2; return false; } vector<int> topologicalSort(vector<vector<int>> &edgeList, vector<int> &vertexList) { vector<int> order; bool hasCycle = false; for (int i : vertexList) { if ((hasCycle = dfs(i, order, edgeList))) { cout << "flag"; return vector<int>{}; } } return order; } vector<int> sortItems(int n, int m, vector<int> &group, vector<vector<int>> &beforeItems) { vector<vector<int>> groupItem(m); for (int i = 0; i < n; i++) { if (group[i] == -1) { group[i] = m++; groupItem.push_back(vector<int>{i}); } else { groupItem[group[i]].push_back(i); } } vector<vector<int>> groupEdge(m); vector<int> groupVertex; int u, v; for (int i = 0; i < n; i++) { u = group[i]; for (int j = 0; j < beforeItems[i].size(); j++) { v = group[beforeItems[i][j]]; if (u != v) { groupEdge[u].push_back(v); } } } vector<int> t; for (int i = 0; i < m; i++) { t.push_back(i); } visited.resize(m, 0); vector<int> groupOrder = topologicalSort(groupEdge, t); if (groupOrder.empty()) { return groupOrder; } visited.clear(); visited.resize(n, 0); vector<int> itemOrder; for (int i = 0; i < m; i++) { if (groupItem[groupOrder[i]].empty()) continue; vector<int> temp = topologicalSort(beforeItems, groupItem[groupOrder[i]]); if (temp.empty()) { return temp; } itemOrder.insert(itemOrder.end(), temp.begin(), temp.end()); } return itemOrder; } };
f1a06925f46ae1681f499b69445a7d31a435ffd0
9587f5e6384bf4c76c77709882f4f15e59869c97
/ProjPad/EditContainer.cpp
02fc1c814451eca4b38954e842ae19b532fe15ec
[ "MIT" ]
permissive
sergrt/ProjPad
8fd3dae40ea016c11863a9acee1d4175e6d85216
59a26e75aa1e2077cf68df55eac0837679d90fb1
refs/heads/master
2018-09-27T03:23:37.237272
2018-06-09T10:56:00
2018-06-09T10:56:14
116,811,314
0
0
MIT
2018-06-08T12:05:21
2018-01-09T12:07:18
C++
UTF-8
C++
false
false
4,382
cpp
EditContainer.cpp
#include "stdafx.h" #include "EditContainer.h" #include <QGridLayout> #include <QScrollBar> EditContainer::EditContainer(int id) : attached_{ false } { setProperty("id", QVariant::fromValue(id)); setLayout(new QGridLayout()); upperEdit_ = new QTextEdit; lowerEdit_ = new QTextEdit; splitter_ = new QSplitter(); splitter_->setOrientation(Qt::Vertical); splitter_->addWidget(upperEdit_); splitter_->addWidget(lowerEdit_); splitter_->setSizes({ 0,10 }); layout()->addWidget(splitter_); layout()->setMargin(2); connect(upperEdit_, &QTextEdit::textChanged, this, &EditContainer::upperTextChanged); connect(lowerEdit_, &QTextEdit::textChanged, this, &EditContainer::lowerTextChanged); } EditContainer::~EditContainer() { delete splitter_; // splitter will delete its children automatically } void EditContainer::setText(const std::string& text) const { const QString qtext = QString::fromStdString(text); upperEdit_->setText(qtext); // changing of upperEdit_ will cause changing of lower text automatically, so no need to call it explicitly //lowerEdit_->setText(qtext); } void EditContainer::upperTextChanged() { syncTexts(upperEdit_, lowerEdit_); emit textChanged(property("id").toInt(), upperEdit_->toPlainText().toStdString()); } void EditContainer::lowerTextChanged() { syncTexts(lowerEdit_, upperEdit_); emit textChanged(property("id").toInt(), lowerEdit_->toPlainText().toStdString()); } void EditContainer::syncTexts(QTextEdit* initiator, QTextEdit* receiver) const { receiver->blockSignals(true); // prevent circular chainging const auto s = storeScrollPosAndCursorPos(receiver); receiver->setText(initiator->toPlainText()); restoreScrollPosAndCursorPos(receiver, s); receiver->blockSignals(false); } std::pair<CursorPos, ScrollPos> EditContainer::storeScrollPosAndCursorPos(QTextEdit* w) const { const QTextCursor receiverCursorOld = w->textCursor(); const int cursorPos = receiverCursorOld.position(); const int scrollPos = w->verticalScrollBar()->value(); return std::make_pair(CursorPos(cursorPos), ScrollPos(scrollPos)); } void EditContainer::restoreScrollPosAndCursorPos(QTextEdit* w, std::pair<CursorPos, ScrollPos> pos) const { QTextCursor receiverCursorNew = w->textCursor(); receiverCursorNew.setPosition(pos.first.get()); w->setTextCursor(receiverCursorNew); w->verticalScrollBar()->setValue(pos.second.get()); } int EditContainer::id() const { return property("id").toInt(); } QList<int> EditContainer::splitterPos() const { return splitter_->sizes(); } ScrollPos EditContainer::upperVScrollPos() const { return ScrollPos(upperEdit_->verticalScrollBar()->value()); } ScrollPos EditContainer::upperHScrollPos() const { return ScrollPos(upperEdit_->horizontalScrollBar()->value()); } CursorPos EditContainer::upperCursorPos() const { return CursorPos(upperEdit_->textCursor().position()); } ScrollPos EditContainer::lowerVScrollPos() const { return ScrollPos(lowerEdit_->verticalScrollBar()->value()); } ScrollPos EditContainer::lowerHScrollPos() const { return ScrollPos(lowerEdit_->horizontalScrollBar()->value()); } CursorPos EditContainer::lowerCursorPos() const { return CursorPos(lowerEdit_->textCursor().position()); } void EditContainer::setSplitterPos(const QList<int>& pos) { splitter_->setSizes(pos); } void EditContainer::setUpperVScrollPos(ScrollPos pos) { upperEdit_->verticalScrollBar()->setValue(pos.get()); } void EditContainer::setUpperHScrollPos(ScrollPos pos) { upperEdit_->horizontalScrollBar()->setValue(pos.get()); } void EditContainer::setUpperCursorPos(CursorPos pos) { QTextCursor textCursor = upperEdit_->textCursor(); textCursor.setPosition(pos.get()); upperEdit_->setTextCursor(textCursor); } void EditContainer::setLowerVScrollPos(ScrollPos pos) { lowerEdit_->verticalScrollBar()->setValue(pos.get()); } void EditContainer::setLowerHScrollPos(ScrollPos pos) { lowerEdit_->horizontalScrollBar()->setValue(pos.get()); } void EditContainer::setLowerCursorPos(CursorPos pos) { QTextCursor textCursor = lowerEdit_->textCursor(); textCursor.setPosition(pos.get()); lowerEdit_->setTextCursor(textCursor); }
6498894c4a3817392e974d9bb3595810797a853b
52adb01da994852256c8899dc0d6c7938b335edb
/source/girgs/include/girgs/BitManipulationBMI2.inl
aabaad11406212a36f6e05fce1a632ea01307ce9
[ "MIT" ]
permissive
chistopher/girgs
fc858a1a8d931386e8e20d7671c8eba97d8fd9ea
32916f7b9f8903f1d6ea37259b490bedb5d85928
refs/heads/master
2022-08-21T22:50:50.717150
2022-07-05T16:29:46
2022-07-05T16:29:46
165,020,603
18
4
MIT
2021-12-15T09:19:48
2019-01-10T08:25:52
Jupyter Notebook
UTF-8
C++
false
false
930
inl
BitManipulationBMI2.inl
#pragma once #include <immintrin.h> namespace girgs { namespace BitManipulationDetails { namespace BMI2 { template <unsigned D> struct Implementation { static constexpr unsigned kDimensions = D; static uint32_t deposit(const std::array<uint32_t, D>& coords) noexcept { uint32_t result = 0; constexpr auto mask = BitPattern<D, uint32_t>::kEveryDthBit; for(unsigned i=0; i < D; ++i) { result |= _pdep_u32(coords[i], mask << i); } return result; } static std::array<uint32_t, kDimensions> extract(uint32_t cell) noexcept { std::array<uint32_t, D> result; for(int i = 0; i < D; ++i) result[i] = _pext_u32(cell, BitPattern<D, uint32_t>::kEveryDthBit << i); return result; } static std::string name() { return "BMI2"; } }; } // namespace BMI2 } // namespace BitManipulationDetails } // namespace girgs
f07e550c3e8ceffe192f99d19a6121f432978fca
a5f3b0001cdb692aeffc444a16f79a0c4422b9d0
/main/svl/qa/complex/ConfigItems/helper/HistoryOptTest.cxx
2b7f01cb22ee03ffbe5845763f9e6e9ce035aa7b
[ "Apache-2.0", "CPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive", "Zlib", "LZMA-exception", "LGPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-philippe-de-muyter", "OFL-1.1", "LGPL-2.1-only", "MPL-1.1", "X11", "LGPL-2.1-or-later", "GPL-2.0-only", "OpenSSL", "LicenseRef-scancode-cpl-0.5", "GPL-1.0-or-later", "NPL-1.1", "MIT", "MPL-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference", "MPL-1.0", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSL-1.0", "LicenseRef-scancode-docbook", "LicenseRef-scancode-mit-old-style", "Python-2.0", "BSD-3-Clause", "IJG", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later", "LGPL-2.0-only", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "BSD-2-Clause", "Autoconf-exception-generic", "PSF-2.0", "NTP", "LicenseRef-scancode-python-cwi", "Afmparse", "W3C", "W3C-19980720", "curl", "LicenseRef-scancode-x11-xconsortium-veillard", "Bitstream-Vera", "HPND-sell-variant", "ICU" ]
permissive
apache/openoffice
b9518e36d784898c6c2ea3ebd44458a5e47825bb
681286523c50f34f13f05f7b87ce0c70e28295de
refs/heads/trunk
2023-08-30T15:25:48.357535
2023-08-28T19:50:26
2023-08-28T19:50:26
14,357,669
907
379
Apache-2.0
2023-08-16T20:49:37
2013-11-13T08:00:13
C++
UTF-8
C++
false
false
27,651
cxx
HistoryOptTest.cxx
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include "HistoryOptTest.hxx" #include <unotools/historyoptions_const.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <comphelper/configurationhelper.hxx> #include <comphelper/sequenceashashmap.hxx> #include <unotools/processfactory.hxx> namespace css = ::com::sun::star; //============================================================================= static const ::rtl::OUString MESSAGE_CLEAR_FAILED = ::rtl::OUString::createFromAscii("Clearing the list failed."); static const ::rtl::OUString MESSAGE_SETSIZE_FAILED = ::rtl::OUString::createFromAscii("Setting a new size for a list failed."); static const ::rtl::OUString MESSAGE_MISS_HISTORY = ::rtl::OUString::createFromAscii("Could not get config access to history list inside config."); static const ::rtl::OUString MESSAGE_MISS_ITEMLIST = ::rtl::OUString::createFromAscii("Could not get config access to item list inside config."); static const ::rtl::OUString MESSAGE_MISS_ORDERLIST = ::rtl::OUString::createFromAscii("Could not get config access to order list inside config."); static const ::rtl::OUString MESSAGE_MISS_ITEM = ::rtl::OUString::createFromAscii("Could not locate item."); static const ::rtl::OUString MESSAGE_UNEXPECTED_ITEM = ::rtl::OUString::createFromAscii("Found an unexpected item."); static const ::rtl::OUString MESSAGE_WRONG_ORDER = ::rtl::OUString::createFromAscii("Wrong order in history list."); //============================================================================= HistoryOptTest::HistoryOptTest() : m_aConfigItem ( ) , m_eList (ePICKLIST) , m_xHistoriesXCU( ) , m_xCommonXCU ( ) { } //============================================================================= HistoryOptTest::~HistoryOptTest() { m_xHistoriesXCU.clear(); m_xCommonXCU.clear(); } //============================================================================= void HistoryOptTest::checkPicklist() { impl_testHistory(ePICKLIST, 4); } //============================================================================= void HistoryOptTest::checkURLHistory() { impl_testHistory(eHISTORY, 10); } //============================================================================= void HistoryOptTest::checkHelpBookmarks() { impl_testHistory(eHELPBOOKMARKS, 100); } //============================================================================= void HistoryOptTest::impl_testHistory(EHistoryType eHistory , ::sal_Int32 nMaxItems) { try { m_eList = eHistory; ::sal_Int32 c = nMaxItems; ::sal_Int32 i = 0; impl_clearList( ); impl_setSize (c); // a) fill list completely and check if all items could be really created. // But dont check its order here! Because every new item will change that order. for (i=0; i<c; ++i) { impl_appendItem(i); if ( ! impl_existsItem(i)) throw css::uno::Exception(MESSAGE_MISS_ITEM, 0); } // b) Check order of all items in list now. // It must be reverse to the item number ... // item max = index 0 // item max-1 = index 1 // ... for (i=0; i<c; ++i) { ::sal_Int32 nExpectedIndex = (c-1)-i; if ( ! impl_existsItemAtIndex(i, nExpectedIndex)) throw css::uno::Exception(MESSAGE_WRONG_ORDER, 0); } // c) increase prio of "first" item so it will switch // to "second" and "second" will switch to "first" :-) // Check also if all other items was not touched. ::sal_Int32 nFirstItem = (c-1); ::sal_Int32 nSecondItem = (c-2); impl_appendItem(nSecondItem); if ( ( ! impl_existsItemAtIndex(nSecondItem, 0)) || ( ! impl_existsItemAtIndex(nFirstItem , 1)) ) throw css::uno::Exception(MESSAGE_WRONG_ORDER, 0); for (i=0; i<nSecondItem; ++i) { ::sal_Int32 nExpectedIndex = (c-1)-i; if ( ! impl_existsItemAtIndex(i, nExpectedIndex)) throw css::uno::Exception(MESSAGE_WRONG_ORDER, 0); } // d) Check if appending new items will destroy the oldest one. ::sal_Int32 nNewestItem = c; ::sal_Int32 nOldestItem = 0; impl_appendItem(nNewestItem); if ( ! impl_existsItemAtIndex(nNewestItem, 0)) throw css::uno::Exception(MESSAGE_WRONG_ORDER, 0); if (impl_existsItem(nOldestItem)) throw css::uno::Exception(MESSAGE_UNEXPECTED_ITEM, 0); // e) Check if decreasing list size will remove oldest items. // Note: impl_setSize() will make sure that 3 items exists only. // Otherwise it throws an exception. If we further check // positions of three items no further items must be checked. // They can't exists :-) ::sal_Int32 nNewSize = 3; impl_setSize(nNewSize); if ( ( ! impl_existsItemAtIndex(nNewestItem, 0)) || ( ! impl_existsItemAtIndex(nSecondItem, 1)) || ( ! impl_existsItemAtIndex(nFirstItem , 2)) ) throw css::uno::Exception(MESSAGE_WRONG_ORDER, 0); // finally we should try to clean up all used structures so the same office can be used // without problems :-) impl_clearList(); } catch (const css::uno::Exception& ex) { impl_clearList(); throw ex; } } //============================================================================= void HistoryOptTest::impl_clearList() { m_aConfigItem.Clear(m_eList); ::sal_Int32 nCount = m_aConfigItem.GetList(m_eList).getLength(); if (nCount != 0) throw css::uno::Exception(MESSAGE_CLEAR_FAILED, 0); css::uno::Reference< css::container::XNameAccess > xList; xList = impl_getItemList(); nCount = xList->getElementNames().getLength(); if (nCount != 0) throw css::uno::Exception(MESSAGE_CLEAR_FAILED, 0); xList = impl_getOrderList(); nCount = xList->getElementNames().getLength(); if (nCount != 0) throw css::uno::Exception(MESSAGE_CLEAR_FAILED, 0); } //============================================================================= void HistoryOptTest::impl_setSize(::sal_Int32 nSize) { m_aConfigItem.SetSize (m_eList, nSize); // a) size info returned by GetSize() means "MaxSize" // so it must match exactly ! ::sal_Int32 nCheck = m_aConfigItem.GetSize(m_eList); if (nCheck != nSize) throw css::uno::Exception(MESSAGE_SETSIZE_FAILED, 0); // b) current size of used XCU lists reflects the current state of // history list and not max size. So it can be less then size ! css::uno::Reference< css::container::XNameAccess > xList; xList = impl_getItemList(); nCheck = xList->getElementNames().getLength(); if (nCheck > nSize) throw css::uno::Exception(MESSAGE_SETSIZE_FAILED, 0); xList = impl_getOrderList(); nCheck = xList->getElementNames().getLength(); if (nCheck > nSize) throw css::uno::Exception(MESSAGE_SETSIZE_FAILED, 0); } //============================================================================= void HistoryOptTest::impl_appendItem(::sal_Int32 nItem) { const ::rtl::OUString sURL = impl_createItemURL (nItem); const ::rtl::OUString sTitle = impl_createItemTitle (nItem); const ::rtl::OUString sPassword = impl_createItemPassword(nItem); m_aConfigItem.AppendItem(m_eList, sURL, ::rtl::OUString(), sTitle, sPassword); } //============================================================================= ::rtl::OUString HistoryOptTest::impl_createItemURL(::sal_Int32 nItem) { ::rtl::OUStringBuffer sURL(256); sURL.appendAscii("file:///ooo_api_test/non_existing_test_url_"); sURL.append ((::sal_Int32)nItem ); sURL.appendAscii(".odt" ); return sURL.makeStringAndClear(); } //============================================================================= ::rtl::OUString HistoryOptTest::impl_createItemTitle(::sal_Int32 nItem) { ::rtl::OUStringBuffer sTitle(256); sTitle.appendAscii("Non Existing Test Item Nr "); sTitle.append ((::sal_Int32)nItem ); return sTitle.makeStringAndClear(); } //============================================================================= ::rtl::OUString HistoryOptTest::impl_createItemPassword(::sal_Int32 nItem) { ::rtl::OUStringBuffer sPassword(256); sPassword.appendAscii("Password_" ); sPassword.append ((::sal_Int32)nItem); return sPassword.makeStringAndClear(); } //============================================================================= ::sal_Bool HistoryOptTest::impl_existsItem(::sal_Int32 nItem) { const ::rtl::OUString sURL = impl_createItemURL(nItem); const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > lItems = m_aConfigItem.GetList(m_eList); const ::sal_Int32 c = lItems.getLength (); ::sal_Int32 i = 0; ::sal_Bool bFound = sal_False; for (i=0; i<c; ++i) { const ::comphelper::SequenceAsHashMap aItem(lItems[i]); const ::rtl::OUString& sCheck = aItem.getUnpackedValueOrDefault(s_sURL, ::rtl::OUString()); bFound = sCheck.equals(sURL); if (bFound) break; } if ( ! bFound) return sal_False; bFound = sal_False; try { css::uno::Reference< css::container::XNameAccess > xItemList = impl_getItemList(); css::uno::Reference< css::container::XNameAccess > xItem ; xItemList->getByName(sURL) >>= xItem; bFound = xItem.is(); } catch(const css::container::NoSuchElementException&) {} return bFound; } //============================================================================= ::sal_Bool HistoryOptTest::impl_existsItemAtIndex(::sal_Int32 nItem , ::sal_Int32 nIndex) { const ::rtl::OUString sURL = impl_createItemURL(nItem); const css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > lItems = m_aConfigItem.GetList(m_eList); const ::sal_Int32 c = lItems.getLength (); ::sal_Bool bFound = sal_False; if (nIndex >= c) return sal_False; const ::comphelper::SequenceAsHashMap aItem(lItems[nIndex]); ::rtl::OUString sCheck = aItem.getUnpackedValueOrDefault(s_sURL, ::rtl::OUString()); bFound = sCheck.equals(sURL); if ( ! bFound) return sal_False; bFound = sal_False; try { css::uno::Reference< css::container::XNameAccess > xItemList = impl_getItemList(); css::uno::Reference< css::container::XNameAccess > xItem ; xItemList->getByName(sURL) >>= xItem; bFound = xItem.is(); } catch(const css::container::NoSuchElementException&) {} if ( ! bFound) return sal_False; bFound = sal_False; try { const ::rtl::OUString sOrder = ::rtl::OUString::valueOf(nIndex); css::uno::Reference< css::container::XNameAccess > xOrderList = impl_getOrderList(); css::uno::Reference< css::container::XNameAccess > xOrder ; xOrderList->getByName(sOrder) >>= xOrder; if (xOrder.is()) { xOrder->getByName(s_sHistoryItemRef) >>= sCheck; bFound = sCheck.equals(sURL); } } catch(const css::container::NoSuchElementException&) {} return bFound; } //============================================================================= css::uno::Reference< css::container::XNameAccess > HistoryOptTest::impl_getItemList() { css::uno::Reference< css::container::XNameAccess > xHistory = impl_getNewHistory(); css::uno::Reference< css::container::XNameAccess > xList ; xHistory->getByName (s_sItemList) >>= xList; if ( ! xList.is()) throw css::uno::Exception(MESSAGE_MISS_ITEMLIST, 0); return xList; } //============================================================================= css::uno::Reference< css::container::XNameAccess > HistoryOptTest::impl_getOrderList() { css::uno::Reference< css::container::XNameAccess > xHistory = impl_getNewHistory(); css::uno::Reference< css::container::XNameAccess > xList ; xHistory->getByName (s_sOrderList) >>= xList; if ( ! xList.is()) throw css::uno::Exception(MESSAGE_MISS_ORDERLIST, 0); return xList; } //============================================================================= css::uno::Reference< css::container::XNameAccess > HistoryOptTest::impl_getNewHistory() { if ( ! m_xHistoriesXCU.is()) { m_xHistoriesXCU = css::uno::Reference< css::container::XNameAccess >( ::comphelper::ConfigurationHelper::openConfig( ::utl::getProcessServiceFactory(), s_sHistories, ::comphelper::ConfigurationHelper::E_STANDARD), css::uno::UNO_QUERY_THROW); } css::uno::Reference< css::container::XNameAccess > xHistory; switch (m_eList) { case ePICKLIST : m_xHistoriesXCU->getByName(s_sPickList) >>= xHistory; break; case eHISTORY : m_xHistoriesXCU->getByName(s_sURLHistory) >>= xHistory; break; case eHELPBOOKMARKS : m_xHistoriesXCU->getByName(s_sHelpBookmarks) >>= xHistory; break; } if ( ! xHistory.is()) throw css::uno::Exception(MESSAGE_MISS_HISTORY, 0); return xHistory; } //============================================================================= css::uno::Reference< css::container::XNameAccess > HistoryOptTest::impl_getOldHistory() { if ( ! m_xCommonXCU.is()) { m_xCommonXCU = css::uno::Reference< css::container::XNameAccess >( ::comphelper::ConfigurationHelper::openConfig( ::utl::getProcessServiceFactory(), s_sCommonHistory, ::comphelper::ConfigurationHelper::E_STANDARD), css::uno::UNO_QUERY_THROW); } css::uno::Reference< css::container::XNameAccess > xHistory; switch (m_eList) { case ePICKLIST : m_xCommonXCU->getByName(s_sPickList) >>= xHistory; break; case eHISTORY : m_xCommonXCU->getByName(s_sURLHistory) >>= xHistory; break; case eHELPBOOKMARKS : m_xCommonXCU->getByName(s_sHelpBookmarks) >>= xHistory; break; } if ( ! xHistory.is()) throw css::uno::Exception(MESSAGE_MISS_HISTORY, 0); return xHistory; } /* //============================================================================= // clear the list in XML directly when using the new Histories.xcs void HistoryOptTest::impl_clearList(const ::rtl::OUString& sList) { css::uno::Reference< css::container::XNameAccess > xListAccess; css::uno::Reference< css::container::XNameContainer > xItemOrder; css::uno::Reference< css::beans::XPropertySet > xFirstItem; css::uno::Sequence< ::rtl::OUString > sFileList; if (sList.equalsAscii("PickList")) m_xCfg->getByName(s_sPickList) >>= xListAccess; else if (sList.equalsAscii("URLHistory")) m_xCfg->getByName(s_sURLHistory) >>= xListAccess; else if (sList.equalsAscii("HelpBookmarks")) m_xCfg->getByName(s_sHelpBookmarks) >>= xListAccess; if (xListAccess.is()) { xListAccess->getByName(s_sItemList) >>= xItemOrder ; sFileList = xItemOrder->getElementNames(); for(sal_Int32 i=0; i<sFileList.getLength(); ++i) xItemOrder->removeByName(sFileList[i]); xListAccess->getByName(s_sOrderList) >>= xItemOrder ; sFileList = xItemOrder->getElementNames(); for(sal_Int32 j=0; j<sFileList.getLength(); ++j) xItemOrder->removeByName(sFileList[j]); xFirstItem = css::uno::Reference< css::beans::XPropertySet >(xListAccess, css::uno::UNO_QUERY); xFirstItem->setPropertyValue( s_sFirstItem, css::uno::makeAny((sal_Int32)0) ); ::comphelper::ConfigurationHelper::flush(m_xCfg); } } //============================================================================= // use configuration API (not ConfigItem!) to verify the results within XML ! sal_Bool HistoryOptTest::impl_isListEmpty(const ::rtl::OUString& sList) { css::uno::Reference< css::container::XNameAccess > xListAccess; css::uno::Reference< css::container::XNameAccess > xItemList; css::uno::Reference< css::container::XNameAccess > xOrderList; sal_Bool bRet = sal_True; if (sList.equalsAscii("PickList")) m_xCfg->getByName(s_sPickList) >>= xListAccess; else if (sList.equalsAscii("URLHistory")) m_xCfg->getByName(s_sURLHistory) >>= xListAccess; else if (sList.equalsAscii("HelpBookmarks")) m_xCfg->getByName(s_sHelpBookmarks) >>= xListAccess; if (xListAccess.is()) { xListAccess->getByName(s_sItemList) >>= xItemList; xListAccess->getByName(s_sOrderList) >>= xOrderList; css::uno::Sequence< ::rtl::OUString > sItemList = xItemList->getElementNames(); css::uno::Sequence< ::rtl::OUString > sOrderList = xOrderList->getElementNames(); if (sItemList.getLength()!=0 || sOrderList.getLength()!=0) bRet = sal_False; } return bRet; } //============================================================================= // append a item: use configuration API (not ConfigItem!) to verify the results within XML ! void HistoryOptTest::impl_appendItem(const ::rtl::OUString& sList) {//to do... } //============================================================================= // test SvtHistoryOptions::GetSize() void HistoryOptTest::impl_checkGetSize(const ::rtl::OUString& sList) { css::uno::Reference< css::beans::XPropertySet > xSet(m_xCommonXCU, css::uno::UNO_QUERY); sal_uInt32 nSize = 0; sal_uInt32 nSize_ = 0; if (sList.equalsAscii("PickList")) { nSize = aHistoryOpt.GetSize(ePICKLIST); xSet->setPropertyValue(s_sPickListSize, css::uno::makeAny(nSize+1)); ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); nSize_ = aHistoryOpt.GetSize(ePICKLIST); if (nSize_ == nSize) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetSize(ePICKLIST) error!")), 0); } else if (sList.equalsAscii("URLHistory")) { nSize = aHistoryOpt.GetSize(eHISTORY); xSet->setPropertyValue(s_sURLHistorySize, css::uno::makeAny(nSize+1)); ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); nSize_ = aHistoryOpt.GetSize(eHISTORY); if (nSize_ == nSize) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetSize(eHISTORY) error!")), 0); } else if (sList.equalsAscii("HelpBookmarks")) { nSize = aHistoryOpt.GetSize(eHELPBOOKMARKS); xSet->setPropertyValue(s_sHelpBookmarksSize, css::uno::makeAny(nSize+1)); ::comphelper::ConfigurationHelper::flush(m_xCommonXCU); nSize_ = aHistoryOpt.GetSize(eHELPBOOKMARKS); if (nSize_ == nSize) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetSize(eHELPBOOKMARKS) error!")), 0); } } //============================================================================= // test SvtHistoryOptions::SetSize() void HistoryOptTest::impl_checkSetSize(const ::rtl::OUString& sList) { css::uno::Reference< css::beans::XPropertySet > xSet(m_xCommonXCU, css::uno::UNO_QUERY); sal_uInt32 nSize = 0; sal_uInt32 nSize_ = 0; if (sList.equalsAscii("PickList")) { xSet->getPropertyValue(s_sPickListSize) >>= nSize; aHistoryOpt.SetSize(ePICKLIST, (nSize+1)); xSet->getPropertyValue(s_sPickListSize) >>= nSize_; if (nSize_ == nSize) //old config item will throw error throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SetSize(ePICKLIST) error!")), 0); } else if (sList.equalsAscii("URLHistory")) { xSet->getPropertyValue(s_sURLHistorySize) >>= nSize; aHistoryOpt.SetSize(eHISTORY, (nSize+1)); xSet->getPropertyValue(s_sURLHistorySize) >>= nSize_; if (nSize_ == nSize) //old config item will throw error throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SetSize(eHISTORY) error!")), 0); } else if (sList.equalsAscii("HelpBookmarks")) { xSet->getPropertyValue(s_sHelpBookmarksSize) >>= nSize; aHistoryOpt.SetSize(eHELPBOOKMARKS, (nSize+1)); xSet->getPropertyValue(s_sHelpBookmarksSize) >>= nSize_; if (nSize_ == nSize) //old config item will throw error throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SetSize(eHELPBOOKMARKS) error!")), 0); } } //============================================================================= // test SvtHistoryOptions::Clear() void HistoryOptTest::impl_checkClear(const ::rtl::OUString& sList) { if (sList.equalsAscii("PickList")) { aHistoryOpt.Clear(ePICKLIST); if ( !impl_isListEmpty(s_sPickList) ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Clear(ePICKLIST) error!")), 0); } else if (sList.equalsAscii("URLHistory")) { aHistoryOpt.Clear(eHISTORY); if ( !impl_isListEmpty(s_sURLHistory) ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Clear(eHISTORY) error!")), 0); } else if (sList.equalsAscii("HelpBookmarks")) { aHistoryOpt.Clear(eHELPBOOKMARKS); if ( !impl_isListEmpty(s_sHelpBookmarks) ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Clear(eHELPBOOKMARKS) error!")), 0); } } //============================================================================= // test SvtHistoryOptions::GetList() void HistoryOptTest::impl_checkGetList(const ::rtl::OUString& sList) { if (sList.equalsAscii("PickList")) { impl_clearList(s_sPickList); aHistoryOpt.AppendItem( ePICKLIST , ::rtl::OUString::createFromAscii("file:///c/test1"), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aHistoryList = aHistoryOpt.GetList( ePICKLIST ); if ( aHistoryList.getLength()==0 ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetList(ePICKLIST) error!")), 0); } else if (sList.equalsAscii("URLHistory")) { impl_clearList(s_sURLHistory); aHistoryOpt.AppendItem( eHISTORY , ::rtl::OUString::createFromAscii("file:///c/test1"), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aHistoryList = aHistoryOpt.GetList( eHISTORY ); if ( aHistoryList.getLength()==0 ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetList(eHISTORY) error!")), 0); } else if (sList.equalsAscii("HelpBookmarks")) { impl_clearList(s_sHelpBookmarks); aHistoryOpt.AppendItem( eHELPBOOKMARKS , ::rtl::OUString::createFromAscii("file:///c/test1"), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); css::uno::Sequence< css::uno::Sequence< css::beans::PropertyValue > > aHistoryList = aHistoryOpt.GetList( eHELPBOOKMARKS ); if ( aHistoryList.getLength()==0 ) throw css::uno::RuntimeException( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GetList(eHELPBOOKMARKS) error!")), 0); } } void HistoryOptTest::impl_checkAppendItem(const ::rtl::OUString& sList) { if (sList.equalsAscii("PickList")) { impl_clearList(s_sPickList); sal_Int32 nListSize = aHistoryOpt.GetSize(ePICKLIST); for (sal_Int32 i=0; i<nListSize; ++i) aHistoryOpt.AppendItem( ePICKLIST , ::rtl::OUString::valueOf(i), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); aHistoryOpt.AppendItem( ePICKLIST , ::rtl::OUString::valueOf(nListSize), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); } else if (sList.equalsAscii("URLHistory")) { impl_clearList(s_sURLHistory); sal_Int32 nListSize = aHistoryOpt.GetSize(eHISTORY); for (sal_Int32 i=0; i<nListSize; ++i) aHistoryOpt.AppendItem( eHISTORY , ::rtl::OUString::valueOf(i), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); aHistoryOpt.AppendItem( eHISTORY , ::rtl::OUString::valueOf(nListSize), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii(""), ::rtl::OUString::createFromAscii("") ); } else if (sList.equalsAscii("HelpBookmarks")) { //impl_clearList(s_sHelpBookmarks); //sal_Int32 nListSize = aHistoryOpt.GetSize(eHELPBOOKMARKS); //for (sal_Int32 i=0; i<nListSize; ++i) // aHistoryOpt.AppendItem( eHELPBOOKMARKS , // ::rtl::OUString::valueOf(i), // ::rtl::OUString::createFromAscii(""), // ::rtl::OUString::createFromAscii(""), // ::rtl::OUString::createFromAscii("") ); //aHistoryOpt.AppendItem( eHELPBOOKMARKS , // ::rtl::OUString::valueOf(nListSize), // ::rtl::OUString::createFromAscii(""), // ::rtl::OUString::createFromAscii(""), // ::rtl::OUString::createFromAscii("") ); } } //============================================================================= void HistoryOptTest::impl_checkPicklist() { impl_checkGetSize(s_sPickList); impl_checkSetSize(s_sPickList); impl_checkClear(s_sPickList); impl_checkGetList(s_sPickList); impl_checkAppendItem(s_sPickList); } //============================================================================= void HistoryOptTest::impl_checkURLHistory() { impl_checkGetSize(s_sURLHistory); impl_checkSetSize(s_sURLHistory); impl_checkClear(s_sURLHistory); impl_checkGetList(s_sURLHistory); impl_checkAppendItem(s_sURLHistory); } //============================================================================= void HistoryOptTest::impl_checkHelpBookmarks() { impl_checkGetSize(s_sHelpBookmarks); impl_checkSetSize(s_sHelpBookmarks); impl_checkClear(s_sHelpBookmarks); impl_checkGetList(s_sHelpBookmarks); impl_checkAppendItem(s_sHelpBookmarks); } */
694917446ff22ebce66378cf6b00cee6710cc9df
1dc3bdf2c7fe34519f30dad775587ad212903abe
/pieces/Queen.cpp
9e84f9d42c8d2d832357bd0074ac849868783cef
[]
no_license
GarrettFaucher/Chess-Graphics
225d586bdda6bd3845e04533ee4110ee27d2c31c
84b27b1f79ce685aab8d8b93369d07f47321e334
refs/heads/master
2022-04-08T10:29:27.724697
2020-02-07T21:40:22
2020-02-07T21:40:22
221,319,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
cpp
Queen.cpp
#include "Queen.h" Queen::Queen(){ type = QUEEN; team = BLACK; alive = true; x = 0; y = 0; findValidMoves(); } Queen::Queen(faction team, bool alive, int x, int y){ this->type = QUEEN; this->team = team; this->alive = alive; this->x = x; this->y = y; findValidMoves(); } bool Queen::validMove(int boardIndex) { int x = indexToX(boardIndex); int y = indexToY(boardIndex); int deltaX = x - this->x; int deltaY = y - this->y; if (((x == this->x || y == this->y) || ( deltaX == deltaY) || ( deltaX == -deltaY) || (-deltaX == deltaY) || (-deltaX == -deltaY)) && (x != this->x || y != this->y)) { return true; } return false; } void Queen::draw() { Quad r; if(team == BLACK){ r = Quad({0,0,0},{(getX()*100)+50, (getY()*100)+50}, 50, 50); r.draw(); glColor3f(1,1,1); } else{ r = Quad({1,1,1},{(getX()*100)+50, (getY()*100)+50}, 50, 50); r.draw(); glColor3f(0,0,0); } std::string label = "Queen"; glRasterPos2i(getX()*100 + 30 ,getY()*100 +50); for (const char &letter : label) { glutBitmapCharacter(GLUT_BITMAP_8_BY_13, letter); } }
98c520a21827cebcddb42cf3b0da7c0d6da9f108
cb9535a1dfea27158430d25aab71f4b903968386
/code/util/config.cpp
03609e62fed35787454f63f975ddd2a29497a4db
[]
no_license
uhacz/bitbox
0d87a54faa4bf175a2fdb591c4ea5f71935c67fb
63b4038a1b8cf05968c55ad11b25344fff44aba5
refs/heads/master
2021-01-23T09:40:25.289880
2017-09-09T18:15:06
2017-09-09T18:15:06
32,782,269
0
0
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
config.cpp
#include "config.h" #include <util/type.h> #include <util/debug.h> #include <util/memory.h> #include <libconfig/libconfig.h> struct bxConfig_Global { config_t _cfg; bxConfig_Global(){} config_t* config() { return &_cfg; } }; static bxConfig_Global* __cfg = 0; namespace bxConfig { int global_init( const char* cfgFilename ) { SYS_ASSERT( __cfg == 0 ); __cfg = BX_NEW( bxDefaultAllocator(), bxConfig_Global ); config_init( __cfg->config() ); //int ierr = config_read_file( __cfg->config(), "global.cfg" ); int ierr = config_read_file( __cfg->config(), cfgFilename ); if ( ierr == CONFIG_FALSE ) { BX_DELETE0( bxDefaultAllocator(), __cfg ); return -1; } return 0; } void global_deinit() { if ( !__cfg ) return; config_destroy( __cfg->config() ); BX_DELETE0( bxDefaultAllocator(), __cfg ); } const char* global_string( const char* name ) { const char* result = 0; config_lookup_string( __cfg->config(), name, &result ); return result; } int global_int( const char* name, int defaultValue ) { int result = defaultValue; config_lookup_int( __cfg->config(), name, &result ); return result; } float global_float( const char* name, float defaultValue ) { double result = defaultValue; config_lookup_float( __cfg->config(), name, &result ); return (float)result; } }
7afa66972dca00781b993d550cb00c8eafeeeefe
5e92e07317363aea17d008181406fffa3afaaa59
/libviews/callview.cpp
b0a4006cf45f80abc242c482e940a3894295ffe8
[ "CC0-1.0" ]
permissive
KDE/kcachegrind
ac6265ae1faf5c379f989e0892942009e02aafb6
8e06118fe2d0496aee579bbc04fb5062a87ebb07
refs/heads/master
2023-08-05T07:55:25.715063
2023-08-03T02:20:03
2023-08-03T02:20:03
42,722,999
338
41
NOASSERTION
2020-12-24T13:17:30
2015-09-18T13:10:44
C++
UTF-8
C++
false
false
9,360
cpp
callview.cpp
/* This file is part of KCachegrind. SPDX-FileCopyrightText: 2003-2016 Josef Weidendorfer <Josef.Weidendorfer@gmx.de> SPDX-License-Identifier: GPL-2.0-only */ /* * Call Views */ #include "callview.h" #include <QAction> #include <QMenu> #include <QTreeWidget> #include <QHeaderView> #include <QKeyEvent> #include "globalconfig.h" #include "callitem.h" // // CallView // CallView::CallView(bool showCallers, TraceItemView* parentView, QWidget* parent) : QTreeWidget(parent), TraceItemView(parentView) { _showCallers = showCallers; QStringList headerLabels; headerLabels << tr( "Cost" ) << tr( "Cost per call" ) << tr( "Cost 2" ) << tr( "Cost 2 per call" ) << tr( "Count" ) << ((_showCallers) ? tr( "Caller" ) : tr( "Callee" )); setHeaderLabels(headerLabels); // forbid scaling icon pixmaps to smaller size setIconSize(QSize(99,99)); setAllColumnsShowFocus(true); setRootIsDecorated(false); setUniformRowHeights(true); // sorting will be enabled after refresh() sortByColumn(0, Qt::DescendingOrder); setMinimumHeight(50); this->setWhatsThis( whatsThis() ); connect( this, &QTreeWidget::currentItemChanged, this, &CallView::selectedSlot ); setContextMenuPolicy(Qt::CustomContextMenu); connect( this, &QWidget::customContextMenuRequested, this, &CallView::context); connect(this, &QTreeWidget::itemDoubleClicked, this, &CallView::activatedSlot); connect(header(), &QHeaderView::sectionClicked, this, &CallView::headerClicked); } QString CallView::whatsThis() const { return _showCallers ? tr( "<b>List of direct Callers</b>" "<p>This list shows all functions calling the " "current selected one directly, together with " "a call count and the cost spent in the current " "selected function while being called from the " "function from the list.</p>" "<p>An icon instead of an inclusive cost specifies " "that this is a call inside of a recursive cycle. " "An inclusive cost makes no sense here.</p>" "<p>Selecting a function makes it the current selected " "one of this information panel. " "If there are two panels (Split mode), the " "function of the other panel is changed instead.</p>") : tr( "<b>List of direct Callees</b>" "<p>This list shows all functions called by the " "current selected one directly, together with " "a call count and the cost spent in this function " "while being called from the selected function.</p>" "<p>Selecting a function makes it the current selected " "one of this information panel. " "If there are two panels (Split mode), the " "function of the other panel is changed instead.</p>"); } void CallView::context(const QPoint & p) { QMenu popup; // p is in local coordinates int col = columnAt(p.x()); QTreeWidgetItem* i = itemAt(p); TraceCall* c = i ? ((CallItem*) i)->call() : nullptr; TraceFunction *f = nullptr, *cycle = nullptr; QAction* activateFunctionAction = nullptr; QAction* activateCycleAction = nullptr; if (c) { QString name = _showCallers ? c->callerName(true) : c->calledName(true); f = _showCallers ? c->caller(true) : c->called(true); cycle = f->cycle(); QString menuText = tr("Go to '%1'").arg(GlobalConfig::shortenSymbol(name)); activateFunctionAction = popup.addAction(menuText); if (cycle) { name = GlobalConfig::shortenSymbol(cycle->prettyName()); QString menuText = tr("Go to '%1'").arg(name); activateCycleAction = popup.addAction(menuText); } popup.addSeparator(); } // add menu items to select event type if column displays cost for a type if (col < 4) { addEventTypeMenu(&popup); popup.addSeparator(); } addGoMenu(&popup); QAction* a = popup.exec(mapToGlobal(p + QPoint(0,header()->height()))); if (a == activateFunctionAction) TraceItemView::activated(f); else if (a == activateCycleAction) TraceItemView::activated(cycle); } void CallView::selectedSlot(QTreeWidgetItem * i, QTreeWidgetItem *) { if (!i) return; TraceCall* c = ((CallItem*) i)->call(); // Should we skip cycles here? CostItem* f = _showCallers ? c->caller(false) : c->called(false); _selectedItem = f; selected(f); } void CallView::activatedSlot(QTreeWidgetItem* i,int) { if (!i) return; TraceCall* c = ((CallItem*) i)->call(); // skip cycles: use the context menu to get to the cycle... CostItem* f = _showCallers ? c->caller(true) : c->called(true); TraceItemView::activated(f); } void CallView::headerClicked(int col) { // name columns should be sortable in both ways if (col == 5) return; // all others only descending sortByColumn(col, Qt::DescendingOrder); } void CallView::keyPressEvent(QKeyEvent* event) { QTreeWidgetItem *item = currentItem(); if (item && ((event->key() == Qt::Key_Return) || (event->key() == Qt::Key_Space))) { TraceCall* c = ((CallItem*) item)->call(); CostItem* f = _showCallers ? c->caller(false) : c->called(false); TraceItemView::activated(f); } QTreeView::keyPressEvent(event); } CostItem* CallView::canShow(CostItem* i) { ProfileContext::Type t = i ? i->type() : ProfileContext::InvalidType; switch(t) { case ProfileContext::Function: case ProfileContext::FunctionCycle: return i; default: break; } return nullptr; } void CallView::doUpdate(int changeType, bool) { // Special case ? if (changeType == selectedItemChanged) { if (!_selectedItem) { clearSelection(); return; } CallItem* ci = (CallItem*) currentItem(); TraceCall* c; CostItem* ti; if (ci) { c = ci->call(); ti = _showCallers ? c->caller() : c->called(); if (ti == _selectedItem) return; } QTreeWidgetItem *item = nullptr; for (int i=0; i<topLevelItemCount();i++) { item = topLevelItem(i); c = ((CallItem*) item)->call(); ti = _showCallers ? c->caller() : c->called(); if (ti == _selectedItem) { scrollToItem(item); setCurrentItem(item); break; } } if (!item && ci) clearSelection(); return; } if (changeType == groupTypeChanged) { QTreeWidgetItem *item; for (int i=0; i<topLevelItemCount(); i++){ item = topLevelItem(i); ((CallItem*)item)->updateGroup(); } return; } refresh(); } void CallView::refresh() { clear(); setColumnHidden(2, (_eventType2 == nullptr)); setColumnHidden(3, (_eventType2 == nullptr)); if (_eventType) { headerItem()->setText(0, _eventType->name()); headerItem()->setText(1, tr("%1 per call").arg(_eventType->name())); } if (_eventType2) { headerItem()->setText(2, _eventType2->name()); headerItem()->setText(3, tr("%1 per call").arg(_eventType2->name())); } if (!_data || !_activeItem) return; TraceFunction* f = activeFunction(); if (!f) return; // In the call lists, we skip cycles to show the real call relations TraceCallList l = _showCallers ? f->callers(true) : f->callings(true); QList<QTreeWidgetItem*> items; foreach(TraceCall* call, l) if (call->subCost(_eventType)>0) items.append(new CallItem(this, nullptr, call)); // when inserting, switch off sorting for performance reason setSortingEnabled(false); addTopLevelItems(items); setSortingEnabled(true); // enabling sorting switches on the indicator, but we want it off header()->setSortIndicatorShown(false); // resize to content now (section size still can be interactively changed) setCostColumnWidths(); } void CallView::setCostColumnWidths() { // first columns 0 + 2 resizeColumnToContents(0); if (_eventType2) { setColumnHidden(2, false); resizeColumnToContents(2); } else { setColumnHidden(2, true); } // then "per call" columns if (_data->maxCallCount() == 0) { // hide "per call" columns and call count column setColumnHidden(1, true); setColumnHidden(3, true); setColumnHidden(4, true); } else { setColumnHidden(1, false); resizeColumnToContents(1); if (_eventType2) { setColumnHidden(3, false); resizeColumnToContents(3); } else setColumnHidden(3, true); setColumnHidden(4, false); resizeColumnToContents(4); } } #include "moc_callview.cpp"
5df1673415c364c9d532bf468ad838c5de5e8ddf
f65abbd28d767d42698e03493f44087cb801e985
/Library/PhoenixLibrary/Source/Graphics/Mesh/Win/DirectX11/MeshDX11.h
9398b2352215b2d422a47d720eb9c092175f79ee
[]
no_license
01kim/GameIndustryEngine
e1d5dfeb7793951f1e6bf689e0472ef957102f7c
e4442da876e6ec896c61b24db13d43ebebaf19a1
refs/heads/master
2023-06-12T18:51:47.122226
2021-07-08T11:03:59
2021-07-08T11:03:59
381,909,971
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,369
h
MeshDX11.h
#pragma once #include <d3d11.h> #include "Phoenix/Graphics/Buffer.h" #include "./Mesh/Win/Mesh.h" namespace Phoenix { namespace Graphics { //**************************************************************************** // DirectX11版メッシュ操作オブジェクト //**************************************************************************** class MeshDX11 final : public Mesh { private: struct VertexBuffer { std::unique_ptr<IBuffer> buffer = nullptr; UINT stride = 0; }; struct IndexBuffer { std::unique_ptr<IBuffer> buffer = nullptr; DXGI_FORMAT dxgiFormat = {}; }; private: VertexBuffer vertexBuffers[(int)VertexBufferKind::TypeNum]; IndexBuffer indexBuffers; public: MeshDX11() {} ~MeshDX11() override { Finalize(); } public: // 初期化 bool Initialize(IDevice* device, const MeshDesc& desc) override; // 終了化 void Finalize() override; // 描画 void Draw(IDevice* device, VertexBufferKind vbKind[], u32 kindNum, u32 start, u32 count, PrimitiveTopology primitiveTopology) override; private: template<typename T> bool BuildVertexBuffer(IDevice* device, VertexBufferKind kind, T* data, u32 vertexCount); template<typename T> bool BuildIndexBuffer(IDevice* device, T* data, u32 indexCount); }; } // namespace Graphics } // namespace Phoenix
bff61d7880ced428a8f2a2948cf6913e51d99efc
7c9ea05f3852066ed01f14498b7f5d47af3bb157
/Client/Scene.h
c80ea2903dbcbfa5a028af6a33a4fb4331537ea8
[]
no_license
OverFace/MapleStory
0b73faaea2cabd373c0e2ab4f529225d5441e93d
51c6bfbeef1efb70a30d5050ed557459ee68292a
refs/heads/master
2021-01-01T06:27:11.858829
2017-11-07T02:14:20
2017-11-07T02:14:20
97,424,364
0
1
null
2017-08-15T11:54:13
2017-07-17T01:51:29
C
UTF-8
C++
false
false
223
h
Scene.h
#pragma once class CScene { public: CScene(void); virtual ~CScene(void); public: virtual void Initialize(void)PURE; virtual int Update(void)PURE; virtual void Render(HDC _dc)PURE; virtual void Release(void)PURE; };
ee44f900e9b110faf0331f0aef5b40ba84857fb6
35701a648c65aab3011a523fd35cc10b1e753b6a
/第8周实验课实验/八MFC一4/八MFC一4/MyDlg.cpp
ba3605bc59d1df1beb0f7c07dd4ad3ddc59fb9b9
[]
no_license
Mutiyu/YML
9fe15d809021796c34a59446caf011b73eef12f7
24991754e212a9580a6b817fc00a092fd63d02a4
refs/heads/master
2022-11-11T18:09:07.096657
2020-07-03T15:34:02
2020-07-03T15:34:02
268,554,710
0
0
null
null
null
null
GB18030
C++
false
false
1,168
cpp
MyDlg.cpp
// MyDlg.cpp : 实现文件 // #include "stdafx.h" #include "八MFC一4.h" #include "MyDlg.h" #include "afxdialogex.h" // MyDlg 对话框 IMPLEMENT_DYNAMIC(MyDlg, CDialogEx) MyDlg::MyDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_DIALOG1, pParent) , s1(_T("")) , x(0) , s3(_T("")) { } MyDlg::~MyDlg() { } void MyDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, s1); DDX_Text(pDX, IDC_EDIT2, x); DDX_Text(pDX, IDC_EDIT3, s3); } BEGIN_MESSAGE_MAP(MyDlg, CDialogEx) ON_EN_CHANGE(IDC_EDIT2, &MyDlg::OnEnChangeEdit2) ON_BN_CLICKED(IDC_BUTTON1, &MyDlg::OnBnClickedButton1) END_MESSAGE_MAP() // MyDlg 消息处理程序 void MyDlg::OnEnChangeEdit2() { // TODO: 如果该控件是 RICHEDIT 控件,它将不 // 发送此通知,除非重写 CDialogEx::OnInitDialog() // 函数并调用 CRichEditCtrl().SetEventMask(), // 同时将 ENM_CHANGE 标志“或”运算到掩码中。 // TODO: 在此添加控件通知处理程序代码 } void MyDlg::OnBnClickedButton1() { this->UpdateData(true); CString s2; int X = x; s2.Format(_T("%d"), X); s3 = s1 +s2; this->UpdateData(false); }
43659675b4c0381721612beb20cf2100103d7b85
12b379faa59d827f9b502e312987a25de2d43e12
/media_driver/linux/gen11/ddi/media_sysinfo_g11.cpp
56da3519fd3847b039dae38e82ab9af9d0fee44a
[ "BSD-3-Clause", "MIT" ]
permissive
Jaly314/media-driver
9041f952ff1590c1b345ecdb9da41998f5267adf
6f37735ea7c44f733e0ae028213689d1c1031264
refs/heads/master
2020-03-28T22:21:35.827872
2018-09-17T07:04:45
2018-09-17T07:10:01
149,226,591
1
0
null
2018-09-18T03:59:44
2018-09-18T03:59:44
null
UTF-8
C++
false
false
7,026
cpp
media_sysinfo_g11.cpp
/* * Copyright (c) 2018, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file media_sysinfo_g11.cpp //! #include "igfxfmid.h" #include "linux_system_info.h" #include "skuwa_factory.h" #include "linux_skuwa_debug.h" #include "linux_media_skuwa.h" #include "linux_shadow_skuwa.h" //extern template class DeviceInfoFactory<GfxDeviceInfo>; typedef DeviceInfoFactory<GfxDeviceInfo> base_fact; #define GEN11_THREADS_PER_EU 7 static bool InitIclShadowSku(struct GfxDeviceInfo *devInfo, SHADOW_MEDIA_FEATURE_TABLE *skuTable, struct LinuxDriverInfo *drvInfo) { if ((devInfo == nullptr) || (skuTable == nullptr) || (drvInfo == nullptr)) { DEVINFO_ERROR("null ptr is passed\n"); return false; } skuTable->FtrVERing = 0; if (drvInfo->hasVebox) { skuTable->FtrVERing = 1; } skuTable->FtrVcs2 = 0; skuTable->FtrULT = 0; skuTable->FtrPPGTT = 1; skuTable->FtrIA32eGfxPTEs = 1; skuTable->FtrDisplayYTiling = 1; skuTable->FtrEDram = devInfo->hasERAM; return true; } static bool InitIclShadowWa(struct GfxDeviceInfo *devInfo, SHADOW_MEDIA_WA_TABLE *waTable, struct LinuxDriverInfo *drvInfo) { if ((devInfo == nullptr) || (waTable == nullptr) || (drvInfo == nullptr)) { DEVINFO_ERROR("null ptr is passed\n"); return false; } /* by default PPGTT is enabled */ waTable->WaForceGlobalGTT = 0; if (drvInfo->hasPpgtt == 0) { waTable->WaForceGlobalGTT = 1; } waTable->WaDisregardPlatformChecks = 1; waTable->Wa4kAlignUVOffsetNV12LinearSurface = 1; return true; } static bool InitIcllpMediaSysInfo(struct GfxDeviceInfo *devInfo, MEDIA_GT_SYSTEM_INFO *sysInfo) { if ((devInfo == nullptr) || (sysInfo == nullptr)) { DEVINFO_ERROR("null ptr is passed\n"); return false; } if (!sysInfo->SliceCount) { sysInfo->SliceCount = devInfo->SliceCount; } if (!sysInfo->SubSliceCount) { sysInfo->SubSliceCount = devInfo->SubSliceCount; } if (!sysInfo->EUCount) { sysInfo->EUCount = devInfo->EUCount; } sysInfo->L3CacheSizeInKb = devInfo->L3CacheSizeInKb; sysInfo->L3BankCount = devInfo->L3BankCount; /* default two VDBox are enabled */ sysInfo->VDBoxInfo.Instances.Bits.VDBox0Enabled = 1; sysInfo->VDBoxInfo.Instances.Bits.VDBox1Enabled = 0; sysInfo->VEBoxInfo.Instances.Bits.VEBox0Enabled = 1; sysInfo->MaxEuPerSubSlice = devInfo->MaxEuPerSubSlice; sysInfo->MaxSlicesSupported = sysInfo->SliceCount; sysInfo->MaxSubSlicesSupported = sysInfo->SubSliceCount; sysInfo->VEBoxInfo.NumberOfVEBoxEnabled = 1; sysInfo->VDBoxInfo.NumberOfVDBoxEnabled = 1; sysInfo->ThreadCount = sysInfo->EUCount * GEN11_THREADS_PER_EU; sysInfo->VEBoxInfo.IsValid = true; sysInfo->VDBoxInfo.IsValid = true; /* the GMM doesn't care the real size of ERAM/LLC. Instead it is used to * indicate whether the LLC/ERAM exists */ if (devInfo->hasERAM) { // 64M sysInfo->EdramSizeInKb = 64 * 1024; } if (devInfo->hasLLC) { // 2M sysInfo->LLCCacheSizeInKb = 2 * 1024; } return true; } static struct GfxDeviceInfo icllpGt1Info = { .platformType = PLATFORM_MOBILE, .productFamily = IGFX_ICELAKE_LP, .displayFamily = IGFX_GEN11_CORE, .renderFamily = IGFX_GEN11_CORE, .eGTType = GTTYPE_GT1, .L3CacheSizeInKb = 2304, .L3BankCount = 6, .EUCount = 48, .SliceCount = 1, .SubSliceCount = 6, .MaxEuPerSubSlice = 8, .isLCIA = 0, .hasLLC = 1, .hasERAM = 0, .InitMediaSysInfo = InitIcllpMediaSysInfo, .InitShadowSku = InitIclShadowSku, .InitShadowWa = InitIclShadowWa, }; static struct GfxDeviceInfo icllpGt05Info = { .platformType = PLATFORM_MOBILE, .productFamily = IGFX_ICELAKE_LP, .displayFamily = IGFX_GEN11_CORE, .renderFamily = IGFX_GEN11_CORE, .eGTType = GTTYPE_GT1, .L3CacheSizeInKb = 2304, .L3BankCount = 6, .EUCount = 8, .SliceCount = 1, .SubSliceCount = 1, .MaxEuPerSubSlice = 8, .isLCIA = 0, .hasLLC = 1, .hasERAM = 0, .InitMediaSysInfo = InitIcllpMediaSysInfo, .InitShadowSku = InitIclShadowSku, .InitShadowWa = InitIclShadowWa, }; static struct GfxDeviceInfo icllpGt2Info = { .platformType = PLATFORM_MOBILE, .productFamily = IGFX_ICELAKE_LP, .displayFamily = IGFX_GEN11_CORE, .renderFamily = IGFX_GEN11_CORE, .eGTType = GTTYPE_GT2, .L3CacheSizeInKb = 3072, .L3BankCount = 8, .EUCount = 64, .SliceCount = 1, .SubSliceCount = 8, .MaxEuPerSubSlice = 8, .isLCIA = 0, .hasLLC = 1, .hasERAM = 0, .InitMediaSysInfo = InitIcllpMediaSysInfo, .InitShadowSku = InitIclShadowSku, .InitShadowWa = InitIclShadowWa, }; static bool icllpDeviceff05 = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0xff05, &icllpGt1Info); static bool icllpDevice8a51 = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a51, &icllpGt2Info); static bool icllpDevice8a52 = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a52, &icllpGt2Info); static bool icllpDevice8a5d = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a5d, &icllpGt1Info); static bool icllpDevice8a5c = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a5c, &icllpGt1Info); static bool icllpDevice8a5b = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a5b, &icllpGt1Info); static bool icllpDevice8a5a = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a5a, &icllpGt1Info); static bool icllpDevice8a71 = DeviceInfoFactory<GfxDeviceInfo>:: RegisterDevice(0x8a71, &icllpGt05Info);
1b2d6dcadea26c9657a901de03a81e8814ae7388
d0fbe5fdc9889d05bf06a6e785c2cf0cfbea68c5
/csrc/utils.cc
8fe4d5f27beec2406c5144f681cc0d7f4867c8bc
[]
no_license
vssousa/python-cspade
cb8b9b428568408bfe28317e5106a29923099a63
e3af0ff86934457b0cbbca5d32f973ca86ead7fa
refs/heads/master
2020-04-10T18:01:24.268726
2018-12-02T17:10:07
2018-12-02T17:10:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
130
cc
utils.cc
#include "utils.h" #include <sstream> using std::ostringstream; ostringstream logger; ostringstream mined; ostringstream memlog;
66ee6a647114e64ee2959831d577fda6aaf950bf
d020f624a375fc51f79fd5eabb87bc00e3e75854
/#620 div2/C.cc
d5b50dd596073caf6ca323a0ef49544eb87bfd42
[]
no_license
thirtiseven/CF
50649e51ebeb183e26606e31ac7d141b08f2044c
21ea775563643b8e4d35a97c4d9c80323bb5717b
refs/heads/master
2023-07-23T22:53:01.822563
2023-07-06T15:58:37
2023-07-06T15:58:37
88,733,957
1
0
null
null
null
null
UTF-8
C++
false
false
863
cc
C.cc
#include <iostream> #include <tuple> #include <algorithm> int n, m, q; struct customer{ int a, b, c; }cus[102]; bool cmp(customer x, customer y) { return x.a < y.a; } int main(int argc, char *argv[]) { std::ios::sync_with_stdio(false); std::cin.tie(0); std::cin >> q; while (q--) { std::cin >> n >> m; cus[0].a = 0; for (int i = 1; i <= n; i++) { std::cin >> cus[i].a >> cus[i].b >> cus[i].c; } std::sort(cus+1, cus+n+1, cmp); int upper = m, lower = m; bool yes = 1; for (int i = 1; i <= n; i++) { upper += (cus[i].a-cus[i-1].a); lower -= (cus[i].a-cus[i-1].a); if (upper >= cus[i].b && lower <= cus[i].c) { upper = std::min(upper, cus[i].c); lower = std::max(lower, cus[i].b); } else { yes = 0; break; } // std::cout << lower << ' ' << upper << '\n'; } std::cout << (yes?"YES\n":"NO\n"); } }
a0a278a8179477dec9d144a2f81abb59843ef430
83010fe0442b0cf6f7260ee71a452d087f328a5d
/kdist.cpp
0d319e29d2402c378e12a9ea7acb2d21083b98c9
[]
no_license
samkumartp/Competitive-programming-problems
d6b32233d36dbd91fe5c78d2f4b4e37afcfe67df
399d966d5e77aae4c3823405e3989b4e1b1bbea5
refs/heads/master
2020-04-08T11:54:06.225640
2017-09-17T16:25:35
2017-09-17T16:25:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,646
cpp
kdist.cpp
# include <bits/stdc++.h> # define NR 200005 using namespace std; ifstream f("kdist.in"); ofstream g("kdist.out"); vector <int> v[NR], store[NR]; struct elem { int x, t1, t2; }aux[NR], E; struct elem2 { int k, niv; }RMQ[20][2*NR]; int i,j,n,m,x,y,K,Rt1,Rt2,VV,k,W,t1,t2; int H[NR], R[NR], ap[NR], lg[2*NR], Col[NR], niv[NR], poz[NR]; long long sol; void DFS (int k, int nivel) { ap[k]=1; niv[k]=nivel; ++VV; poz[k]=VV; RMQ[0][VV].k=k; RMQ[0][VV].niv=nivel; store[Col[k]].push_back(k); for (auto x: v[k]) { if (! ap[x]) { DFS (x, nivel+1); ++VV; RMQ[0][VV].k=k; RMQ[0][VV].niv=nivel; } } } void logaritmi () { for (int i=2; i<=VV; ++i) lg[i]=lg[i/2] + 1; } void rmq () { for (int i=1; i<=lg[VV]; ++i) for (int j=1; j<=VV - (1<<(i-1))+1; ++j) if (RMQ[i-1][j].niv < RMQ[i-1][j+(1<<(i-1))].niv) RMQ[i][j]=RMQ[i-1][j]; else RMQ[i][j]=RMQ[i-1][j+(1<<(i-1))]; } int lca (int X, int Y) { int ci, cs, LG; ci=poz[X]; cs=poz[Y]; if (ci > cs) swap(ci, cs); LG=lg[cs-ci+1]; if (RMQ[LG][ci].niv < RMQ[LG][cs-(1<<LG)+1].niv) return RMQ[LG][ci].k; else return RMQ[LG][cs-(1<<LG)+1].k; } bool cmp (elem x, elem y) { return niv[x.x] > niv[y.x]; } void initPadure () { for (int i=1; i<=n; ++i) R[i]=i, H[i]=1; } int radacina (int k) { while (R[k]!=k) k=R[k]; return k; } void unite (int X, int Y) { if (H[X] > H[Y]) R[Y]=X, H[X]+=H[Y]; else R[X]=Y, H[Y]+=H[X]; } int main () { f>>n>>K; for (i=1; i<n; ++i) { f>>x>>y; v[x].push_back(y); v[y].push_back(x); } for (i=1; i<=n; ++i) f>>Col[i]; DFS (1, 1); logaritmi (); rmq(); initPadure(); for (k=1; k<=K; ++k) { //pentru fiecare culoare if (store[k].size()==1) { g<<"0\n"; continue; } sol=0; W=0; for (auto x: store[k]) // inaltimile initiale sol=sol + 1LL*(store[k].size()-1)*niv[x]; for (i=1; i<store[k].size(); ++i) { // fac lca-urile x=lca (store[k][i], store[k][i-1]); E.x=x; E.t1=store[k][i-1]; E.t2=store[k][i]; aux[++W]=E; } sort (aux+1, aux+W+1, cmp); for (i=1; i<=W; ++i) { x=aux[i].x; t1=aux[i].t1; t2=aux[i].t2; Rt1=radacina(t1); Rt2=radacina(t2); sol=sol - 1LL * 2 * niv[x] * H[Rt1] * H[Rt2]; unite (Rt1, Rt2); } g<<sol<<"\n"; } return 0; }
f8371036ea4d176d6197beb1ae828220a053e942
eb31d986eb055daba38c8dad981f17f477476a61
/valt_csere_kul.cpp
5b0a328dfaba927119d10f593bc8882d39e109b8
[]
no_license
gyorfi-daniel/bev_prog
9accb00df4fa0ee829e70256de712c82b9ac1bbc
5765b042a8d5fb266eb7a359ec4483f314a8bf59
refs/heads/master
2020-03-29T14:25:18.796128
2018-11-21T11:39:10
2018-11-21T11:39:10
150,016,151
0
0
null
null
null
null
UTF-8
C++
false
false
216
cpp
valt_csere_kul.cpp
#include "std_lib_facilities.h" int main() { int a=7; int b=1; cout << "A kezdő érték: a=" << a << ",b=" << b <<'\n'; a=a+b; b=a-b; a=a-b; cout << "A csere utáni érték: a=" << a << ",b=" << b <<'\n'; }
4a46c31107958aa6f608a7afc5f5b9670de5e89a
eead9dcd8d0ea54bb876a6082c612838610513e3
/P294FlipGameII.cpp
39f37fdce770f90effc76e28257637b22a94df37
[]
no_license
ysonggit/leetcode-cpp
df8e4d58b52ce66dd5d603a003cca102e9bcfb2b
3daf0ab175d2d877828b3b258a4bba538ce03797
refs/heads/master
2021-01-10T21:16:01.706172
2020-09-30T13:56:43
2020-09-30T13:56:43
41,328,961
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
P294FlipGameII.cpp
class Solution { public: // can optimize solution with memorization // or DP (Sprague-Grundy Theorem) https://leetcode.com/discuss/64344/theory-matters-from-backtracking-128ms-to-dp-0ms bool canWin(string s) { int n = s.length(); if(n<2) return false; for(int i=0; i<n-1; i++){ if(s[i]==s[i+1] && s[i]=='+'){ string next = s.substr(0, i) + "--" + s.substr(i+2); if(!canWin(next)){ return true; } } } return false; } };
6452c46ae66236945da6dd747950ac4e9f8b7308
b2571f919ae552c4dff006be9c825184d272dd75
/uri/1045.cpp
bc0bd78687934c404783f4471b813eb50c882f46
[]
no_license
juanplopes/icpc
22877ca4ebf67138750f53293ee9af341c21ec40
3e65ffe9f59973714ff25f3f9bb061b98455f781
refs/heads/master
2020-12-25T17:35:04.254195
2017-10-27T23:53:25
2017-10-27T23:53:25
2,492,274
121
44
null
null
null
null
UTF-8
C++
false
false
821
cpp
1045.cpp
//1045 //Triangle Types //Misc;Beginner #include <iomanip> #include <algorithm> #include <iostream> using namespace std; double V[3]; int main() { while(cin >> V[0] >> V[1] >> V[2]) { sort(V, V+3, greater<double>()); if (V[0] > V[1] + V[2]) cout << "NAO FORMA TRIANGULO" << endl; if (V[0]*V[0] == V[1]*V[1] + V[2]*V[2]) cout << "TRIANGULO RETANGULO" << endl; if (V[0]*V[0] > V[1]*V[1] + V[2]*V[2]) cout << "TRIANGULO OBTUSANGULO" << endl; if (V[0]*V[0] < V[1]*V[1] + V[2]*V[2]) cout << "TRIANGULO ACUTANGULO" << endl; if (V[0] == V[1] && V[1] == V[2]) cout << "TRIANGULO EQUILATERO" << endl; if (V[0] == V[1] ^ V[1] == V[2] ^ V[0] == V[2]) cout << "TRIANGULO ISOSCELES" << endl; } }
5b0aeaab415c54495943a3224b7936dd062de648
c5d137fe433357e37020281923ed845a38057b83
/main.cpp
90063577e4fd44b12a7f4fbe0f004c04d2dd8b00
[]
no_license
spidey/3DSEncode
ab1ee7a924fe8bc784214ea453790f249461fa39
64023ff3039475fe1908450383f4f14befabf923
refs/heads/master
2021-01-01T10:13:39.799628
2014-02-14T02:12:29
2014-02-14T02:12:29
2,960,263
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
main.cpp
#include <QtGui/QApplication> #include "Q3DSEncode.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Q3DSEncode w; w.show(); return app.exec(); }
fd93545af57099b6cdd75e50d4c037aba45b2507
94e5a9e157d3520374d95c43fe6fec97f1fc3c9b
/Light OJ/1316.cpp
33d1e7b06e7e9200a357c7cb77ac45854ef6774f
[ "MIT" ]
permissive
dipta007/Competitive-Programming
0127c550ad523884a84eb3ea333d08de8b4ba528
998d47f08984703c5b415b98365ddbc84ad289c4
refs/heads/master
2021-01-21T14:06:40.082553
2020-07-06T17:40:46
2020-07-06T17:40:46
54,851,014
8
4
null
2020-05-02T13:14:41
2016-03-27T22:30:02
C++
UTF-8
C++
false
false
7,249
cpp
1316.cpp
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iomanip> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; const double EPS = 1e-9; const int INF = 1000000; const double PI=acos(-1.0); #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long #define POPCOUNT __builtin_popcount #define POPCOUNTLL __builtin_popcountll #define RIGHTMOST __builtin_ctzll #define LEFTMOST(x) (63-__builtin_clzll((x))) template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #define dipta00 #ifdef dipta0 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; ///****************** template ends here **************** // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out int n,m,s; int shop[22]; pii dp[16][(1<<15)+4]; bool vis[16][(1<<15)+4]; int adj[22][22]; int strt, endd; pii min(pii &a, pii &b) { if(a.ff > b.ff) return a; if(a.ff == b.ff) { if(a.ss <= b.ss) return a; return b; } return b; } pii add(pii &a, pii &b) { pii tmp; tmp.ff = a.ff + b.ff; tmp.ss = a.ss + b.ss; debug(a.ff, a.ss, b.ff, b.ss, tmp.ff, tmp.ss); return tmp; } pii call(int in, int mask) { if(bitCount(mask) == s) { if(adj[in][endd] >= INF) return MP(-INF, INF); return MP(0, adj[in][endd]); } pii &ret = dp[in][mask]; if(vis[in][mask]) return ret; vis[in][mask] = 1; ret = MP(0, adj[in][endd]); if(adj[in][endd] >= INF) ret = MP(-INF, INF); FOR(i,0,s-1) { if(bitCheck(mask, i) == 0 && adj[in][i] < INF) { pii a = MP(1, adj[in][i]); pii b = call(i, bitOn(mask, i) ); pii p = add( a , b ); ret = min(ret, p); // debug(adj[shop[in]][shop[i]], ret.ff, ret.ss) } } return ret; } #define mx 510 vector<int> g[mx],cost[mx]; struct node { int u,w; node(int a,int b){u=a;w=b;} bool operator< (const node &p)const {return w > p.w;} }; int d[mx]; int djkstra(int n, int de) { for(int i=0;i<mx;i++)d[i]=INF; priority_queue<node> q; q.push(node(n,0)); d[n]=0; while(!q.empty()) { node top=q.top();q.pop(); int u=top.u; if(u == de) return d[de]; for(int i=0;i<(int)g[u].size();i++) { int v=g[u][i]; if(cost[u][i] + d[u] < d[v]) { d[v]=cost[u][i] + d[u]; q.push(node(v,d[v])); } } } return d[de]; } int main() { #ifdef dipta007 //READ("in.txt"); //WRITE("out.txt"); #endif // dipta007 // ios_base::sync_with_stdio(0);cin.tie(0); int t; getI(t); FOR(ci,1,t) { getIII(n,m,s); FOR(i,0,n) g[i].clear(); FOR(i,0,n) cost[i].clear(); FOR(i,0, s-1) { getI(shop[i]); } FOR(i,0,n) FOR(j,0,n) adj[i][j] = INF; FOR(i,0,n) adj[i][i] = 0; FOR(i,1,m) { int u,v,w; getIII(u,v,w); g[u].PB(v); cost[u].PB(w); } FOR(i,0,s-1) { FOR(j,0, s-1) { adj[i][j] = djkstra(shop[i], shop[j]); } } strt = s, endd = s+1; FOR(i,0,s-1) { adj[strt][i] = djkstra(0, shop[i]); adj[i][endd] = djkstra(shop[i], n-1); } adj[strt][endd] = djkstra(0, n-1); printf("Case %d: ", ci); if(adj[strt][endd] >= INF) { printf("Impossible\n"); continue; } CLR(vis); pii res = MP(0, adj[strt][endd]); int mask = 0; FOR(i,0,s-1) { if(adj[strt][i] == INF) continue; pii a = MP(1, adj[strt][i]); pii b = call(i, bitOn(mask, i) ); pii p = add( a , b ); res = min(res, p ); } printf("%d %d\n", res.ff, res.ss); } return 0; }
12efd401a0335fd56f111b2d3ce4ef53ee03ba57
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/4e/8ebaca07830965/main.cpp
0798c1b1920b9f52b387cae5d3435a8b368225d5
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
main.cpp
#include <string> #include <iostream> #include <bitset> #include <climits> using namespace std; template<typename T> void show_binrep(const T& a) { const char* beg = reinterpret_cast<const char*>(&a); const char* end = beg + sizeof(a); while(beg != end) std::cout << std::bitset<CHAR_BIT>(*beg++) << ' '; std::cout << '\n'; } int main() { char a; a = -58; show_binrep(a); string SS; // C++ STL string SS = "pippo"; cout << SS << endl; cout << "this is the binary representation of the string: " << SS << endl; show_binrep(SS); }
afe9c5cad5ed4aac9c68865707cd150c60239736
b495209212ba745251914fee2ba6aebf90932b44
/src/ChatManager.h
0d538ec03e28d774ecc0f5d0761f1f93dd29654e
[]
no_license
knetikmedia/knetikcloud-tizen-client
21e1d9a0f98ca275f372af05dfb699adf46b7679
28be72af9caa0980570ff20fc798bdcf67b5550a
refs/heads/master
2021-01-13T13:34:44.915887
2018-03-14T16:05:13
2018-03-14T16:05:13
76,421,710
0
0
null
null
null
null
UTF-8
C++
false
false
15,364
h
ChatManager.h
#ifndef _ChatManager_H_ #define _ChatManager_H_ #include <string> #include <cstring> #include <list> #include <glib.h> #include "ChatBlacklistResource.h" #include "ChatMessageResource.h" #include "PageResource«ChatMessageResource».h" #include "PageResource«ChatUserThreadResource».h" #include "Result.h" #include "Error.h" /** \defgroup Operations API Endpoints * Classes containing all the functions for calling API endpoints * */ namespace Tizen{ namespace ArtikCloud { /** \addtogroup Chat Chat * \ingroup Operations * @{ */ class ChatManager { public: ChatManager(); virtual ~ChatManager(); /*! \brief Acknowledge number of messages in a thread. *Synchronous* * * <b>Permissions Needed:</b> owner * \param id The thread id *Required* * \param readCount The amount of messages read * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool acknowledgeChatMessageSync(char * accessToken, std::string id, int readCount, void(* handler)(Error, void* ) , void* userData); /*! \brief Acknowledge number of messages in a thread. *Asynchronous* * * <b>Permissions Needed:</b> owner * \param id The thread id *Required* * \param readCount The amount of messages read * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool acknowledgeChatMessageAsync(char * accessToken, std::string id, int readCount, void(* handler)(Error, void* ) , void* userData); /*! \brief Add a user to a chat message blacklist. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param blacklistedUserId The user id to blacklist *Required* * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool addChatMessageBlacklistSync(char * accessToken, int blacklistedUserId, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Add a user to a chat message blacklist. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param blacklistedUserId The user id to blacklist *Required* * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool addChatMessageBlacklistAsync(char * accessToken, int blacklistedUserId, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Delete a message. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The message id *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool deleteChatMessageSync(char * accessToken, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Delete a message. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The message id *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool deleteChatMessageAsync(char * accessToken, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Edit your message. *Synchronous* * * <b>Permissions Needed:</b> owner * \param id The message id *Required* * \param chatMessageResource The chat message resource * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool editChatMessageSync(char * accessToken, std::string id, ChatMessageResource chatMessageResource, void(* handler)(Error, void* ) , void* userData); /*! \brief Edit your message. *Asynchronous* * * <b>Permissions Needed:</b> owner * \param id The message id *Required* * \param chatMessageResource The chat message resource * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool editChatMessageAsync(char * accessToken, std::string id, ChatMessageResource chatMessageResource, void(* handler)(Error, void* ) , void* userData); /*! \brief Get a message. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The message id *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatMessageSync(char * accessToken, std::string id, void(* handler)(ChatMessageResource, Error, void* ) , void* userData); /*! \brief Get a message. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The message id *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatMessageAsync(char * accessToken, std::string id, void(* handler)(ChatMessageResource, Error, void* ) , void* userData); /*! \brief Get a list of blocked users for chat messaging. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatMessageBlacklistSync(char * accessToken, std::string id, void(* handler)(std::list<ChatBlacklistResource>, Error, void* ) , void* userData); /*! \brief Get a list of blocked users for chat messaging. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatMessageBlacklistAsync(char * accessToken, std::string id, void(* handler)(std::list<ChatBlacklistResource>, Error, void* ) , void* userData); /*! \brief List your threads. *Synchronous* * * <b>Permissions Needed:</b> owner * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatThreadsSync(char * accessToken, int size, int page, std::string order, void(* handler)(PageResource«ChatUserThreadResource», Error, void* ) , void* userData); /*! \brief List your threads. *Asynchronous* * * <b>Permissions Needed:</b> owner * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getChatThreadsAsync(char * accessToken, int size, int page, std::string order, void(* handler)(PageResource«ChatUserThreadResource», Error, void* ) , void* userData); /*! \brief List messages with a user. *Synchronous* * * <b>Permissions Needed:</b> owner * \param id The user id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getDirectMessagesSync(char * accessToken, int id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief List messages with a user. *Asynchronous* * * <b>Permissions Needed:</b> owner * \param id The user id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getDirectMessagesAsync(char * accessToken, int id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief List messages in a thread. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The thread id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getThreadMessagesSync(char * accessToken, std::string id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief List messages in a thread. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The thread id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getThreadMessagesAsync(char * accessToken, std::string id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief List messages in a topic. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The topic id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getTopicMessagesSync(char * accessToken, std::string id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief List messages in a topic. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param id The topic id *Required* * \param size The number of objects returned per page * \param page The number of the page returned * \param order A comma separated list of sorting requirements in priority order, each entry matching PROPERTY_NAME:[ASC|DESC] * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool getTopicMessagesAsync(char * accessToken, std::string id, int size, int page, std::string order, void(* handler)(PageResource«ChatMessageResource», Error, void* ) , void* userData); /*! \brief Remove a user from a blacklist. *Synchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param blacklistedUserId The user id to blacklist *Required* * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool removeChatBlacklistSync(char * accessToken, int blacklistedUserId, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Remove a user from a blacklist. *Asynchronous* * * <b>Permissions Needed:</b> CHAT_ADMIN or owner * \param blacklistedUserId The user id to blacklist *Required* * \param id The user id or 'me' *Required* * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool removeChatBlacklistAsync(char * accessToken, int blacklistedUserId, std::string id, void(* handler)(Error, void* ) , void* userData); /*! \brief Send a message. *Synchronous* * * <b>Permissions Needed:</b> ANY * \param chatMessageResource The chat message resource * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool sendChatMessageSync(char * accessToken, ChatMessageResource chatMessageResource, void(* handler)(ChatMessageResource, Error, void* ) , void* userData); /*! \brief Send a message. *Asynchronous* * * <b>Permissions Needed:</b> ANY * \param chatMessageResource The chat message resource * \param handler The callback function to be invoked on completion. *Required* * \param accessToken The Authorization token. *Required* * \param userData The user data to be passed to the callback function. */ bool sendChatMessageAsync(char * accessToken, ChatMessageResource chatMessageResource, void(* handler)(ChatMessageResource, Error, void* ) , void* userData); static std::string getBasePath() { return "https://jsapi-integration.us-east-1.elasticbeanstalk.com"; } }; /** @}*/ } } #endif /* ChatManager_H_ */
ca161134ca2e5a6e395af365bd70671d64a48351
7f74bc0d683edc3da4c3541e5fdd1e5f77494927
/Phases/2/VirtualMachine.h
e74a1cc5d151a04194a23e5bb73662531171e549
[]
no_license
xCAMELZx/CSE460
3e2c3c9669be618997fe8402064a28666070a1bc
e7000c6fa7c9e12164b4c22734569d942f1696cd
refs/heads/master
2020-03-29T23:12:31.910025
2018-11-02T00:46:47
2018-11-02T00:46:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
VirtualMachine.h
/* Yousef Jarrar, Nicholas Chiodini CSE 460 Dr. Z Due Date: October 15th, 2018 Description: Virtual Machine Header File. A constructer is used to define functions like memory size, register size, base, limit, program counter, instruction register, stack point and getting the clock time */ #ifndef VIRTUALMACHINE_H #define VIRTUALMACHINE_H #include <fstream> #include <vector> using namespace std; class OS; class VirtualMachine { //Constructors for VM int msize; //memory size int rsize; //register size int pc, ir, sr, sp, clock; int msp; // minimal stack pointer, needed for stat vector<int> mem; vector<int> r; int base, limit; public: VirtualMachine(): msize(256), rsize(4), clock(0) { // Size of Memory = 256 //Register from r[0]-r[3] || Initialize clock to 0 mem.resize(msize); r.resize(rsize); } void run(int); int get_clock(); friend class OS; }; // VirtualMachine #endif
589897c86be05229db82e770f88274ea34804ddb
6cb34f254a0ffbd87ab8e945452903079a00f0e9
/src/Game.cpp
b9bfd87a90edc6bb7c908215764af3695a463225
[]
no_license
brasthm/Mouse-n-Music
7200bca7f8da094255525560f90c722f34563cfa
617aa030a8d9f37d93498e27d3e5c21b24e8f572
refs/heads/master
2020-03-31T06:35:07.553897
2018-10-14T17:05:56
2018-10-14T17:05:56
151,987,616
0
0
null
null
null
null
UTF-8
C++
false
false
5,669
cpp
Game.cpp
#include "Game.h" #include <iostream> Game::Game() { // Load Background textBackground_.loadFromFile(IMG_PATH + "bg.png"); background_.setTexture(textBackground_); // Load Cursor textCursor_.loadFromFile(IMG_PATH + "cursor.png"); cursor_.setTexture(textCursor_); cursor_.setOrigin(32, 32); // Load Sections textSections_.resize(NB_SECTIONS); sections_.resize(NB_SECTIONS); for (int i = 0; i < NB_SECTIONS; i++) { textSections_[i].loadFromFile(IMG_PATH + "section" + std::to_string(i + 1) + ".png"); sections_[i].setTexture(textSections_[i]); } // Load Font neig_.loadFromFile(FONT_PATH + "neig.otf"); scoreText_.setFont(neig_); scoreText_.setOutlineThickness(5); scoreText_.setOutlineColor(sf::Color::Black); scoreText_.setFillColor(sf::Color::White); scoreText_.setCharacterSize(50); // Start Clock clock_.restart(); songTime_ = sf::Time::Zero; } float Game::getAngle() { sf::Vector2f reference(REFERENCE_X, REFERENCE_Y); sf::Vector2f hyp = mousePosition_ - reference; return atan2(hyp.y, hyp.x) * 180 / PI + 180; } float Game::getDistance() { sf::Vector2f reference(REFERENCE_X, REFERENCE_Y); sf::Vector2f hyp = mousePosition_ - reference; return sqrt(hyp.x*hyp.x + hyp.y*hyp.y); } void Game::drawCursor(sf::RenderWindow & window) { cursor_.setPosition(mousePosition_); window.draw(cursor_); } void Game::drawSection(sf::RenderWindow & window) { if (section_ != -1) window.draw(sections_[section_]); } void Game::update(sf::RenderWindow &window, FMOD::System *soundSystem) { elapsedTime_ = clock_.getElapsedTime(); if (isPlaying_) { unsigned int songPosition; channel_->getPosition(&songPosition, FMOD_TIMEUNIT_MS); songTime_ = sf::milliseconds(songPosition); } else if (!isPlaying_ && songTime_ > sf::Time::Zero) { soundSystem->playSound(song_, 0, false, &channel_); isPlaying_ = true; } else songTime_ += elapsedTime_; clock_.restart(); section_ = -1; mousePosition_ = sf::Vector2f(sf::Mouse::getPosition(window)); if (getDistance() >= REFERENCE_MARGIN) { float angle = getAngle(); for (int i = 0; i <= NB_SECTIONS; i++) { if (angle < i * 180 / NB_SECTIONS) { section_ = i - 1; break; } } } for (int i = current_; i < notes_.size(); i++) { int status = notes_[i].update(songTime_, elapsedTime_, section_); if (status == 1) { int s = notes_[i].getScore(); current_++; score_ += s; if (s == 0) { popups_.emplace_back(neig_, "Miss", sf::Color(244, 101, 101), notes_[i].getSection()); score_.incMiss(); } else if (s <= 40) { popups_.emplace_back(neig_, "Bad", sf::Color(244, 146, 101), notes_[i].getSection()); score_.incBad(); } else if (s <= 70) { popups_.emplace_back(neig_, "Ok", sf::Color(101, 144, 226), notes_[i].getSection()); score_.incOk(); } else if (s <= 90) { popups_.emplace_back(neig_, "Good", sf::Color(155, 244, 101), notes_[i].getSection()); score_.incGood(); } else { popups_.emplace_back(neig_, "Perfect", sf::Color(217, 101, 244), notes_[i].getSection()); score_.incPerfect(); } } } for (int i = 0; i < popups_.size(); i++) { if (popups_[i].isDead()) { popups_[i] = popups_.back(); popups_.pop_back(); } } scoreText_.setString(std::to_string(score_.getScore())); } void Game::draw(sf::RenderWindow & window) { window.clear(sf::Color(200,200,200)); drawSection(window); for (int i = 0; i < notes_.size(); i++) notes_[i].draw(window); window.draw(background_); scoreText_.setPosition((WINDOW_W - scoreText_.getGlobalBounds().width) / 2, REFERENCE_Y - 100); window.draw(scoreText_); for (int i = 0; i < popups_.size(); i++) popups_[i].draw(window, elapsedTime_); drawCursor(window); window.display(); } void Game::generateNotes(std::string mapFile) { std::ifstream fichier(MUSIC_PATH + "/" + mapFile + "/" + mapFile + ".mnm"); std::string buffer = ""; // Read Song Name std::getline(fichier, buffer); songName_ = Utils::splitString(buffer, '=').back(); // Read Song Composer std::getline(fichier, buffer); songComposer_ = Utils::splitString(buffer, '=').back(); // Read Song Location std::getline(fichier, buffer); songPath_ = MUSIC_PATH + "/" + mapFile + "/" + Utils::splitString(buffer, '=').back(); // Read Offset std::getline(fichier, buffer); // Read BPM std::getline(fichier, buffer); // Read Length std::getline(fichier, buffer); // Read DATA std::getline(fichier, buffer); while (std::getline(fichier, buffer)) { auto data = Utils::splitString(buffer, ' '); notes_.emplace_back(sf::seconds(std::stof(data[0])), sf::seconds(std::stof(data[1])), std::stoi(data[2]), std::stoi(data[3])); } fichier.close(); } void Game::play(sf::RenderWindow & window, FMOD::System *soundSystem, std::string filePath) { srand(time(NULL)); generateNotes(filePath); // Load Song soundSystem->createStream(songPath_.c_str(), FMOD_2D | FMOD_CREATESTREAM, 0, &song_); if (notes_.front().getStartTime().asSeconds() < NOTE_START_DISTANCE / notes_.front().getSpeed()) songTime_ = -(sf::seconds(NOTE_START_DISTANCE / notes_.front().getSpeed()) - notes_.front().getStartTime()); bool songIsOver = false; clock_.restart(); while (window.isOpen() && !songIsOver) { if (isPlaying_) { channel_->isPlaying(&songIsOver); songIsOver = !songIsOver; } sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } update(window, soundSystem); draw(window); sf::sleep(sf::milliseconds(1)); } song_->release(); score_.drawConsole(filePath); } Game::~Game() { }
46cc736dc9d0f54e797ad4ceea48ac43e8a722df
94531d8f6d9f562c28b07ba765d4efb70b2c3fe8
/copy_of_serijski_port1.ino
10cf940ee5cbb11231a810dea42dd62b860158ce
[]
no_license
ledjoburazeru/RSZDMK_ZAD2
280438b1e25058e0bdd03e13f31d242661abe815
a57f39efd06e07f7d755d1c319f5a7dd3eb446c6
refs/heads/master
2022-09-07T16:56:19.403975
2020-05-30T09:36:38
2020-05-30T09:36:38
268,049,569
0
0
null
null
null
null
UTF-8
C++
false
false
3,913
ino
copy_of_serijski_port1.ino
#include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <util/delay.h> #define BR_KORISNIKA 10 char korisnici[BR_KORISNIKA][32] = { "Marko Markovic", "Milan He", "Nikola Nikolic", "Nikola Simic", "Sinisa Nikolic", "Petar Rodic", "Zoran Kalezic", "Pera Peric", "Marko Nikolic", "Boris Arsic" }; char PIN[BR_KORISNIKA][5] = {"5346", "2133", "7445", "8756","3333","4444","5555","6666","7777", "7435"}; //Velicina prijemnog bafera (mora biti 2^n) #define USART_RX_BUFFER_SIZE 64 char Rx_Buffer[USART_RX_BUFFER_SIZE]; //prijemni FIFO bafer volatile unsigned char Rx_Buffer_Size = 0; //broj karaktera u prijemnom baferu volatile unsigned char Rx_Buffer_First = 0; volatile unsigned char Rx_Buffer_Last = 0; ISR(USART_RX_vect) { Rx_Buffer[Rx_Buffer_Last++] = UDR0; //ucitavanje primljenog karaktera Rx_Buffer_Last &= USART_RX_BUFFER_SIZE - 1; //povratak na pocetak u slucaju prekoracenja if (Rx_Buffer_Size < USART_RX_BUFFER_SIZE) Rx_Buffer_Size++; //inkrement brojaca primljenih karaktera } void usartInit(unsigned long baud) { UCSR0A = 0x00; //inicijalizacija indikatora //U2Xn = 0: onemogucena dvostruka brzina //MPCMn = 0: onemogucen multiprocesorski rezim UCSR0B = 0x98; //RXCIEn = 1: dozvola prekida izavanog okoncanjem prijema //RXENn = 1: dozvola prijema //TXENn = 1: dozvola slanja UCSR0C = 0x06; //UMSELn[1:0] = 00: asinroni rezim //UPMn[1:0] = 00: bit pariteta se ne koristi //USBSn = 0: koristi se jedan stop bit //UCSzn[2:0] = 011: 8bitni prenos UBRR0 = F_CPU / (16 * baud) - 1; sei(); //I = 1 (dozvola prekida) } unsigned char usartAvailable() { return Rx_Buffer_Size; //ocitavanje broja karaktera u prijemnom baferu } void usartPutChar(char c) { while(!(UCSR0A & 0x20)); //ceka da se setuje UDREn (indikacija da je predajni bafer prazan) UDR0 = c; //upis karaktera u predajni bafer } void usartPutString(char *s) { while(*s != 0) //petlja se izvrsava do nailaska na nul-terminator { usartPutChar(*s); //slanje tekuceg karaktera s++; //azuriranje pokazivaca na tekuci karakter } } void usartPutString_P(const char *s) { while (1) { char c = pgm_read_byte(s++); //citanje sledeceg karaktera iz programske memorije if (c == '\0') //izlazak iz petlje u slucaju return; //nailaska na terminator usartPutChar(c); //slanje karaktera } } char usartGetChar() { char c; if (!Rx_Buffer_Size) //bafer je prazan? return -1; c = Rx_Buffer[Rx_Buffer_First++]; //citanje karaktera iz prijemnog bafera Rx_Buffer_First &= USART_RX_BUFFER_SIZE - 1; //povratak na pocetak u slucaju prekoracenja Rx_Buffer_Size--; //dekrement brojaca karaktera u prijemnom baferu return c; } unsigned char usartGetString(char *s) { unsigned char len = 0; while(Rx_Buffer_Size) //ima karaktera u faferu? s[len++] = usartGetChar(); //ucitavanje novog karaktera s[len] = 0; //terminacija stringa return len; //vraca broj ocitanih karaktera } int main() { usartInit(9600); while(1) { usartPutString("Unesite ime i prezime\r\n"); char str[32]; while (!usartAvailable()); _delay_ms(50); usartGetString(str); for(int i=0;i<BR_KORISNIKA;i++) { if(strcmp(str,korisnici[i])==0) { usartPutString("Odobreno, uneti pin:\r\n"); char pin[5]; for(int j=0;j<5;j++) { while(!usartAvailable()); pin[j]=usartGetChar(); usartPutChar('*'); } usartPutChar('\n'); strcpy(PIN[i],pin); usartPutString(PIN[i]); usartPutChar('\n'); } } } return 0; }
487bfb808e611de6d3228b94f3d2d420c8daa8f4
da1500e0d3040497614d5327d2461a22e934b4d8
/net/third_party/quic/core/crypto/crypto_server_config_protobuf.h
ed201439126b95b5bee1d5ea4c619dfb3aef99a8
[ "BSD-3-Clause" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
3,679
h
crypto_server_config_protobuf.h
// Copyright (c) 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 NET_THIRD_PARTY_QUIC_CORE_CRYPTO_CRYPTO_SERVER_CONFIG_PROTOBUF_H_ #define NET_THIRD_PARTY_QUIC_CORE_CRYPTO_CRYPTO_SERVER_CONFIG_PROTOBUF_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include "base/logging.h" #include "base/macros.h" #include "net/third_party/quic/core/crypto/crypto_protocol.h" #include "net/third_party/quic/platform/api/quic_export.h" #include "net/third_party/quic/platform/api/quic_string_piece.h" namespace quic { // QuicServerConfigProtobuf contains QUIC server config block and the private // keys needed to prove ownership. // TODO(rch): sync with server more rationally. class QUIC_EXPORT_PRIVATE QuicServerConfigProtobuf { public: // PrivateKey contains a QUIC tag of a key exchange algorithm and a // serialised private key for that algorithm. The format of the serialised // private key is specific to the algorithm in question. class QUIC_EXPORT_PRIVATE PrivateKey { public: QuicTag tag() const { return tag_; } void set_tag(QuicTag tag) { tag_ = tag; } std::string private_key() const { return private_key_; } void set_private_key(const std::string& key) { private_key_ = key; } private: QuicTag tag_; std::string private_key_; }; QuicServerConfigProtobuf(); ~QuicServerConfigProtobuf(); size_t key_size() const { return keys_.size(); } const PrivateKey& key(size_t i) const { DCHECK_GT(keys_.size(), i); return *keys_[i].get(); } std::string config() const { return config_; } void set_config(QuicStringPiece config) { config.CopyToString(&config_); } QuicServerConfigProtobuf::PrivateKey* add_key() { keys_.push_back(std::make_unique<PrivateKey>()); return keys_.back().get(); } void clear_key() { keys_.clear(); } bool has_primary_time() const { return primary_time_ > 0; } int64_t primary_time() const { return primary_time_; } void set_primary_time(int64_t primary_time) { primary_time_ = primary_time; } bool has_priority() const { return priority_ > 0; } uint64_t priority() const { return priority_; } void set_priority(int64_t priority) { priority_ = priority; } bool has_source_address_token_secret_override() const { return !source_address_token_secret_override_.empty(); } std::string source_address_token_secret_override() const { return source_address_token_secret_override_; } void set_source_address_token_secret_override( QuicStringPiece source_address_token_secret_override) { source_address_token_secret_override.CopyToString( &source_address_token_secret_override_); } private: std::vector<std::unique_ptr<PrivateKey>> keys_; // config_ is a serialised config in QUIC wire format. std::string config_; // primary_time_ contains a UNIX epoch seconds value that indicates when this // config should become primary. int64_t primary_time_; // Relative priority of this config vs other configs with the same // primary time. For use as a secondary sort key when selecting the // primary config. uint64_t priority_; // Optional override to the secret used to box/unbox source address // tokens when talking to clients that select this server config. // It can be of any length as it is fed into a KDF before use. std::string source_address_token_secret_override_; DISALLOW_COPY_AND_ASSIGN(QuicServerConfigProtobuf); }; } // namespace quic #endif // NET_THIRD_PARTY_QUIC_CORE_CRYPTO_CRYPTO_SERVER_CONFIG_PROTOBUF_H_
4a37316851a28df17d0d3a6280f5a708bb2396e4
03db02dfd69267e9974f0d975c1af8077f32d566
/dfg/randAll.hpp
97a4b7244f11cd2f427c0846eddc5f67319f83f8
[ "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-public-domain" ]
permissive
kluge/dfglib
930b90b7444d480a3f9d75375c4b33c9aafb51a6
be351899feea8dd3fa978f1a5fd99c5cecd4f497
refs/heads/master
2020-09-07T04:43:30.728355
2019-11-09T12:05:49
2019-11-09T12:05:49
220,658,736
0
0
null
2019-11-09T15:03:18
2019-11-09T15:03:18
null
UTF-8
C++
false
false
37
hpp
randAll.hpp
#pragma once #include "rand.hpp"
20cd74b6da94a91f03caf82dcf8b5206b75b6300
8fe458ccb4aa7d875138c0d68b37eca5e02b191f
/NT-Template/ntechnium/libNtechnium/Geometry/ntMeshPts.h
0d29a53269c9dcfdb002e392c9f41a9a6bc64a65
[]
no_license
jwarton/N-Technium-Libs
786cc8358827a566908266bbeff88175fbf941ad
8733436bb9936bde482c96a4f44c79d8030b6657
refs/heads/master
2020-12-09T11:13:26.445865
2017-08-30T14:29:52
2017-08-30T14:29:52
44,542,206
0
0
null
null
null
null
UTF-8
C++
false
false
3,315
h
ntMeshPts.h
/////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// ntMeshPts.h // openGl scratch libs /////////////////// // Mesh Class from explicit point list /////////////////// // created by James Warton on 04/05/2014 /////////////////// /////////////////////////////////////////////////////////////////// #ifndef MESH_PTS_JPW_NTECHNIUM #define MESH_PTS_JPW_NTECHNIUM #include <iostream> #include <vector> #include "ntBaseShape.h" #include "ntMatrix4.h" #include "ntBasePhysics.h" using namespace std; namespace jpw{ class ntMeshPts; typedef ntMeshPts MeshPts; class ntMeshPts : public BaseShape { private: void init(); int U; int V; std::vector <Vec3*>* vecsV = new vector<Vec3*>(); std::vector <Vec3*>* vecsN = new vector<Vec3*>(); public: using BaseShape::BaseShape;///may not be required /////////////////////////////////////////////////////////// ////////////////////////////////////////////// CONSTRUCTORS ntMeshPts(); ntMeshPts(std::vector<ntVec3*>* vecsPtr); ntMeshPts(std::vector<ntVec3*>* vecsPtr, int U, int V); void update(); ///TODO void display(); void display_verts(); void display_verts(float dim); void display_norms(); void display_norms(float len); void display_edges(); void display_edges(float w); std::vector<ntVec3*>* getVecs(); /////////////////////////////////////////////////////////// //////////////////////////////////////// PHYSICS OPERATIONS bool enablePhysics = false; //unique constructor enables physics std::vector <Particle*> particles; //node with particle dynamics std::vector <Spring*> springs; //branch with spring dynamics void addPhysics(bool enable); void addSpring(Particle* p0, Particle* p1); std::vector<Particle*>* getParticles(); std::vector<Spring*>* getSprings(); /////////////////////////////////////////////////////////// /////////////////////////////////////////// MESH OPERATIONS ///TODO FUNCTIONALITY void displayQuad(); void relax(); void subdivide(enum MeshType); enum MeshType { CATMULL_CLARK, MID_EDGE, VERT_CENTROID, }; }; } inline std::vector<ntVec3*>* ntMeshPts::getVecs() { std::vector<ntVec3*>* vecsPtr = &vecs; return vecsPtr; } inline std::vector<Particle*>* ntMeshPts::getParticles(){ std::vector<Particle*>* particlePtrs = &particles; return particlePtrs; } inline std::vector<Spring*>* ntMeshPts::getSprings() { std::vector<Spring*>* springPtrs = &springs; return springPtrs; } #endif /// This would create a COPY of the vector // that would be local to this function's scope //void tester(std::vector<Item*>); // This would use a reference to the vector // this reference could be modified in the // tester function /// This does NOT involve a second copy of the vector ///void tester(std::vector<Item*>&); // This would use a const-reference to the vector // this reference could NOT be modified in the // tester function /// This does NOT involve a second copy of the vector //void tester(const std::vector<Item*>&); // This would use a pointer to the vector /// This does NOT involve a second copy of the vector // caveat: use of raw pointers can be dangerous and // should be avoided for non-trivial cases if possible //void tester(std::vector<Item*>*);
93908c17059c1a98239ecca3d2b1c93c714bf3d6
9d9f8e888b08e34f774f596c3121ad8666ba9302
/Include/PhysicsEngine/AxisAlignedBoundingBox.hpp
4833e46965af27b12e7ec9103d444c88c531012e
[]
no_license
TommyRadan/Labyrinth
756075d1269275895d76476c380a826d88437937
b50018678c55d2d7c702cd7b8b28d91bc89ddc99
refs/heads/master
2021-09-03T20:13:59.785249
2018-01-11T17:16:17
2018-01-11T17:16:17
109,323,828
1
0
null
2017-11-04T19:31:09
2017-11-02T22:07:20
C++
UTF-8
C++
false
false
327
hpp
AxisAlignedBoundingBox.hpp
#pragma once #include <glm.hpp> namespace PhysicsEngine { struct AxisAlignedBoundingBox { AxisAlignedBoundingBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); const bool IsInCollision(glm::vec3 point); private: float m_MinX, m_MaxX; float m_MinY, m_MaxY; float m_MinZ, m_MaxZ; }; }
f0ecf1a2584b8880f636dcb0fde50900e7d3353e
44ffe14c37baf3b16932c00677d8b35575f32755
/src/xtopcom/xdata/src/xdatautil.cpp
a9db9c5c4e8bc74efe7d4045b2ad871f82e2e3e1
[]
no_license
telosprotocol/TOP-chain
199fca0a71c439a8c18ba31f16641c639575ea29
1f168664d1eb4175df8f1596e81acd127112414a
refs/heads/master
2023-07-25T01:24:34.437043
2023-06-05T01:28:24
2023-06-05T01:28:24
312,178,439
13
46
null
2023-07-18T01:09:29
2020-11-12T05:38:44
C++
UTF-8
C++
false
false
1,896
cpp
xdatautil.cpp
// Copyright (c) 2017-2018 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include <vector> #include <assert.h> #include <cinttypes> #include "xbase/xint.h" #include "xbase/xmem.h" #include "xbase/xutl.h" // TODO(jimmy) #include "xbase/xvledger.h" #include "xdata/xdatautil.h" #include "xdata/xblock.h" #include "xdata/xnative_contract_address.h" namespace top { namespace data { using base::xstring_utl; std::string xdatautil::serialize_owner_str(const std::string & prefix, uint32_t table_id) { return base::xvaccount_t::make_account_address(prefix, (uint16_t)table_id); } bool xdatautil::deserialize_owner_str(const std::string & address, std::string & prefix, uint32_t & table_id) { uint16_t subaddr{0xFFFF}; // TODO: jimmy, bypass release compiling error auto ret = base::xvaccount_t::get_prefix_subaddr_from_account(address, prefix, subaddr); table_id = subaddr; return ret; } bool xdatautil::extract_table_id_from_address(const std::string & address, uint32_t & table_id) { std::string prefix; return deserialize_owner_str(address, prefix, table_id); } bool xdatautil::extract_parts(const std::string& address, std::string& base_addr, uint32_t& table_id) { if (address == sys_drand_addr) return false; return deserialize_owner_str(address, base_addr, table_id); } std::string xdatautil::base_addr(std::string const& address) { std::string base_addr{""}; uint32_t table_id{0}; extract_parts(address, base_addr, table_id); return base_addr; } std::string xdatautil::xip_to_hex(const xvip2_t & xip) { char data[33] = {0}; snprintf(data, 33, "%" PRIx64 ":%" PRIx64, xip.high_addr, xip.low_addr); return std::string(data); } } // namespace data } // namespace top
06d560a1f4c6d1cceebabc8b954c6dfd11e278cd
2cbee1cb5a4b52ec20f362250b0252e7fcf2bdd0
/Lists-Iterators/lists/node_sequence.h
c3fb1e40f8608587b7b21641d79fcc7279762137
[]
no_license
j84guo/dsaai-cpp
a1b9c261da6a585bc5495bd0b5f84bf573169ea3
4ecddfacfcdb79e56f3a5667083cf60e05695dcb
refs/heads/master
2020-03-18T17:45:09.089392
2018-11-19T06:58:26
2018-11-19T06:58:26
135,048,441
1
0
null
null
null
null
UTF-8
C++
false
false
692
h
node_sequence.h
#ifndef NODE_SEQUENCE_H #define NODE_SEQUENCE_H #include "node_list.h" #include <iostream> using std::cout; using std::endl; template <typename E> class NodeSequence : public NodeList<E>{ public: E& atIndex(int i) const; int indexOf(const typename NodeList<E>::Iterator& p) const; }; template <typename E> E& NodeSequence<E>::atIndex(int i) const{ typename NodeList<E>::Iterator p = this->begin(); for(int j=0; j<i; ++j){ ++p; } return *p; } template <typename E> int NodeSequence<E>::indexOf(const typename NodeList<E>::Iterator& p) const{ typename NodeList<E>::Iterator a = this->begin(); int j = 0; while(a != p){ ++a; ++j; } return j; } #endif
3176f1e8d13bddcacaf7d706f2797d52bbc6fc37
3672eb1395ecadb9f5ce0ba81d7bd2de26f9875b
/mcu/Sources/middleware/SPM/spm_info.inc
7e035cabe8a9628ff38ca2ac1727b36ada8da9b8
[]
no_license
lzxcvbnm11/EP21H-
d45bcecc46d3e7937995ad02898502854a86162a
81a01135c0a4ac2db375a6e831107323f2a1ae96
refs/heads/master
2020-04-05T11:05:36.928799
2018-11-09T06:47:53
2018-11-09T06:47:53
156,821,907
0
0
null
null
null
null
UTF-8
C++
false
false
1,193
inc
spm_info.inc
/***************************************************************************** * Copyright (C) 2018 ShenZhen Yeedon Media co.,LTD. All rights reserved. * * File Name : spm_info.inc * Description : including DIIC driver header files. * Author: qq * Date: 2018-06-07 ******************************************************************************/ /* check of multiple include */ #ifndef _SPM_INFO_INC_ #define _SPM_INFO_INC_ /* Files for including */ #include <hidef.h> #include "derivative.h" #include "yd_typedefs.h" #include "spm_cfg.h" #include "spm_private.h" #include "spm_public.h" #include "diic_public.h" #include "dgpio_public.h" #endif /* _SPM_INFO_INC_ */ /*=========================================================================== * File Revision History(bottom to top:first revision to last revision) *============================================================================ * $Log:$ * * Rev: Userid: Date: Description *-------- ---------- --------- ------------------------------ * * V1.0 qq 2018-6-7 Initial * *===========================================================================*/
91a657b8c050273be2ec3e6a33dc64eee2d31f35
9de3293e4c22fcaf4682babf67f7a4ab21f91098
/05-most-recent-out/shared/src/mro.cc
f6ce7937739724889aa693da6667690bdbef329b
[ "MIT" ]
permissive
timmerov/aggiornamento
1c3404a64f4b2cc02b4d2df92f68eee4379af201
d6af5c42d96522f6987c4b7c05a9421177504bcd
refs/heads/master
2020-12-25T14:48:12.778909
2017-06-29T22:05:44
2017-06-29T22:05:44
67,525,837
1
0
null
null
null
null
UTF-8
C++
false
false
5,272
cc
mro.cc
/* Copyright (C) 2012-2016 tim cotter. All rights reserved. */ /** most recent out example. mro implementation. assumes: single producer, single consumer. long ago this was called a triple buffer. however that term is now confused with a fifo with three buffers. cause microsoft. sigh. so now i use the term most-recent-out buffer. which uses three buffers. unlike a fifo, data is not guaranteed to be delivered. unlike a fifo, put cannot fail and cannot block the producer. like a fifo, get optionally blocks the consumer. producer thread and consumer thread. the producer produces data and cannot be blocked. it must always have somewhere to put the latest data. the consumer consumes data as soon as it is available. if the consumer is consuming data faster than the producer is producing it, the consumer may optionally block waiting for the producer to produce data. if the producer is producing data faster than the consumer can consume it, the not-latest data is discarded. the producer gets empty buffers. and puts full buffers. neither of these operations block the producer. the consumer gets full buffers. the consumer puts empty buffers. get optionally blocks. put never blocks. real world use case: suppose you're decoding video at 60 fps. but playing it back at 24 fps. you can't block the decoder or it will fall behind. you must decode every frame. therefore you must discard some of the decoded frames. the easy way is to put all frames into an mro. **/ #include <aggiornamento/aggiornamento.h> #include <aggiornamento/string.h> #include <container/mro.h> #include <condition_variable> #include <mutex> // use an anonymous namespace to avoid name collisions at link time. namespace { enum { kEmpty, kFilling, kFull, kEmptying }; class MroImpl : public Mro { public: MroImpl() noexcept { data_[0] = nullptr; } MroImpl(const MroImpl &) = delete; virtual ~MroImpl() noexcept { delete[] data_[0]; } int size_ = 0; int state_[3]; char *data_[3]; std::mutex mutex_; std::condition_variable cv_; }; } Mro::Mro() noexcept : agm::Container("MostRecentOut") { } Mro::~Mro() noexcept { } Mro *Mro::create( int size ) noexcept { auto impl = new(std::nothrow) MroImpl; auto stride = (size + 15) / 16 * 16; auto size3 = 3*stride; impl->size_ = size; impl->state_[0] = kEmpty; impl->state_[1] = kEmpty; impl->state_[2] = kEmpty; impl->data_[0] = new(std::nothrow) char[size3]; impl->data_[1] = impl->data_[0] + stride; impl->data_[2] = impl->data_[1] + stride; return impl; } /* returns the size of the buffer. */ int Mro::getSize() noexcept { auto impl = (MroImpl *) this; return impl->size_; } /* returns an empty buffer. marks it "filling". */ char *Mro::getEmpty() noexcept { auto impl = (MroImpl *) this; char *ptr = nullptr; { std::unique_lock<std::mutex> lock(impl->mutex_); for (auto n = 0; n < 3; ++n) { if (impl->state_[n] == kEmpty) { impl->state_[n] = kFilling; ptr = impl->data_[n]; break; } } } return ptr; } /* full buffers are marked empty. changes filling buffers to full. signals the consumer thread. */ void Mro::putFull() noexcept { auto impl = (MroImpl *) this; { std::unique_lock<std::mutex> lock(impl->mutex_); for (auto n = 0; n < 3; ++n) { auto state = impl->state_[n]; if (state == kFull) { impl->state_[n] = kEmpty; } if (state == kFilling) { impl->state_[n] = kFull; } } } impl->cv_.notify_one(); } /* gets a full buffer. marks it "emptying". returns null if no buffer is full. */ char *Mro::getFull() noexcept { auto impl = (MroImpl *) this; char *ptr = nullptr; { std::unique_lock<std::mutex> lock(impl->mutex_); for (auto n = 0; n < 3; ++n) { if (impl->state_[n] == kFull) { impl->state_[n] = kEmptying; ptr = impl->data_[n]; break; } } } return ptr; } /* gets a full buffer. marks it "emptying". blocks if no buffer is full until a full buffer is put. */ char *Mro::getFullWait() noexcept { auto impl = (MroImpl *) this; char *ptr = nullptr; { std::unique_lock<std::mutex> lock(impl->mutex_); for(;;) { for (auto n = 0; n < 3; ++n) { if (impl->state_[n] == kFull) { impl->state_[n] = kEmptying; ptr = impl->data_[n]; break; } } if (ptr) { break; } impl->cv_.wait(lock); } } return ptr; } /* changes emptying buffers to empty. */ void Mro::putEmpty() noexcept { auto impl = (MroImpl *) this; { std::unique_lock<std::mutex> lock(impl->mutex_); for (auto n = 0; n < 3; ++n) { if (impl->state_[n] == kEmptying) { impl->state_[n] = kEmpty; } } } }
9fb8c208235ab8e61b5e717a609927b31dcdfbd8
e153f1c20a0f8d8dceddb7e17f3700d8fc9d6f20
/AppFrame/source/Application/ApplicationBase.h
18ecc9d94352101c664a4aa57fadefde55767ea5
[]
no_license
Matsu-Td/TensionBlower
71c7f970f3decea097f2d9e91aa9edeb7d8ea9ba
f3b08c4ad842afd9e12019c778f5aa8e32feff50
refs/heads/master
2023-04-24T09:42:10.870235
2021-05-18T15:56:22
2021-05-18T15:56:22
356,140,957
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,665
h
ApplicationBase.h
/** * @file ApplicationBase.h * @brief アプリケーション基底クラス * * @author matsuo tadahiko * @date 2020/12/18 */ #include "dxlib.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include "../Mode//ModeServer.h" #include "EffekseerForDXLib.h" namespace appframe { /** * @brief アプリケーション基底クラス */ class ApplicationBase { public: ApplicationBase(); virtual ~ApplicationBase(); /** * @brief 初期化 * @param hInstance WinMain関数の第一引数 * @return 処理の成否 */ virtual bool Initialize(HINSTANCE hInstance); /** * @brief 解放 * @return 処理の成否 */ virtual bool Terminate(); /** * @brief フレーム処理:入力 * @return 処理の成否 */ virtual bool Input(); /** * @brief フレーム処理:計算 * @return 処理の成否 */ virtual bool Process(); /** * @brief フレーム処理:描画 * @return 処理の成否 */ virtual bool Render(); /** * @brief ウィンドウモード、フルスクリーンモードの設定を行う * @return true */ virtual bool AppWindowed() { return true; } /** * @brief 表示するウィンドウの横幅 * @return サイズ */ virtual int DispSizeW() { return 640; } /** * @brief 表示するウィンドウの縦幅 * @return サイズ */ virtual int DispSizeH() { return 480; } /** * @brief インスタンスを取得 * @return ApplicationBaseのインスタンス */ static ApplicationBase* GetInstance() { return _pInstance; } /** * @brief キー入力情報取得 * @return キー入力情報 */ virtual int GetKey() { return _key; } /** * @brief キーのトリガ情報取得 * @return キーのトリガ情報 */ virtual int GetKeyTrg() { return _keyTrg; } /** * @brief DINPUTコントローラー入力情報取得 * @return DINPUTコントローラー入力情報 */ virtual DINPUT_JOYSTATE GetDInputState() { return _dInput; } /** * @brief ゲーム終了フラグを返す * @return ゲーム終了フラグ */ bool GameEndFlag() const { return _gameEnd; } /** * @brief ゲーム終了フラグを立てる */ void IsGameEnd() { _gameEnd = true; } protected: static ApplicationBase* _pInstance; std::unique_ptr<mode::ModeServer> _serverMode; int _key; // キー入力情報 int _keyTrg; // キー入力のトリガ情報 DINPUT_JOYSTATE _dInput; // DINPUTコントローラーの入力情報 bool _gameEnd = false; // ゲーム終了フラグ }; }
2e20bca398cb8342b81946dc4426d395e45684b3
b5e06773a21efb3be2372c9cede361c5240ae954
/HW4/core/test2.cpp
6873ac440ac6c68f308c7c69084a49c2af51c418
[]
no_license
WU-TING-HSUAN/NTUT-EE-ACV
3ab38ef4d3a0c19e265a50dbfd19ac651bbd5f3f
f23dbb737f5a6a13fc363f3068665d14e77a1b1d
refs/heads/main
2023-02-26T11:34:56.195504
2021-02-04T10:18:03
2021-02-04T10:18:03
333,695,095
0
0
null
null
null
null
BIG5
C++
false
false
4,915
cpp
test2.cpp
#include <opencv2/core/utility.hpp> #include <opencv2/tracking/tracking.hpp> #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <cstring> #include<fstream> #include <time.h> using namespace std; using namespace cv; int max(int a, int b); int min(int a, int b); void total(double a); int IOU_total[10]; int main(int argc, char** argv) { fstream file; char buffer[200]; char* pStart = buffer; clock_t t1, t2; // typedef time_t long; double IOU, overlap_x_max, overlap_y_max,overlap_x_min, overlap_y_min,interArea,groudtruthArea, trackArea; char* pEnd; char* pEnd_1; char* pEnd_2; char ad[128] = { 0 }; int count = 0; int dx = 0; float PDF[10]; float CDF[10]; // declares all required variables Mat CDFMat = Mat::zeros(500,500, CV_8UC1); Mat frame; // create a tracker object Ptr<Tracker> tracker = TrackerMedianFlow::create(); // set input video // std::string video = argv[1]; VideoCapture cap("1.avi"); // get bounding box cap >> frame; Rect2d roi(422, 131, 60, 64); /* Rect2d roi(512,120,80,102);*/ //BONIUS Rect2d roi_truth; printf("Start the tracking process, press ESC to quit.\n"); file.open("GroundTruth_1.txt", ios::in); //file.open("GroundTruth_2.txt", ios::in);//BONIUS int i = 1; tracker->init(frame, roi); if (!file) cout << "無法開啟檔案!\n"; else { file.getline(buffer, sizeof(buffer)); file.getline(buffer, sizeof(buffer));//BONUIS需要把這行關掉 do { t1 = clock(); file.getline(buffer, sizeof(buffer)); int d1, d2, d3, d4; d1 = strtod(buffer, &pEnd); d2 = strtod(pEnd, &pEnd_1); d3 = strtod(pEnd_1, &pEnd_2); d4 = strtod(pEnd_2, NULL); // get frame from the video cap >> frame; // stop the program if no more images if (frame.rows == 0 || frame.cols == 0) break; // update the tracking result tracker->update(frame,roi); // draw the tracked object rectangle(frame, roi, Scalar(255, 0, 0), 2, 1); roi_truth = Rect2d(d1,d2,d3,d4); rectangle(frame, roi_truth, Scalar(0, 0, 255), 2); // show image with the tracked object imshow("tracker", frame); t2 = clock(); overlap_x_max = max(d1, roi.x); overlap_y_max = max(d2, roi.y); overlap_x_min = min(d1+d3, roi.x+roi.height); overlap_y_min = min(d2+d4, roi.y+roi.width); interArea = (overlap_x_min - overlap_x_max + 1) * (overlap_y_min - overlap_y_max + 1); trackArea = roi.height * roi.width; groudtruthArea = d3 * d4 ; IOU = interArea / float(trackArea + groudtruthArea - interArea); /* printf("%f\n", IOU);*/ total(IOU); printf("Average computational time per frame:%f\n",(t2 - t1) / (double)(CLOCKS_PER_SEC)); //quit on ESC button i = i + 1; /*if (i == 30) { sprintf_s(ad, "C:\\Users\\xie\\source\\repos\\Project3\\Project3\\pic3\\test%d.jpg", ++dx); imwrite(ad, frame); i = 0; }*/ if (waitKey(1) == 27)break; } while (!file.eof()); file.close(); } for (int i = 0; i < 10; i++) { count += IOU_total[i]; } for (int i = 0; i < 10; i++) { PDF[i]= IOU_total[i]/(float)count; } for (int i = 0; i < 10; i++) { float cdf = 0; for (int j = 0; j <= i; j++) { cdf += PDF[j]; } CDF[i] = cdf; } for (int i = 0; i < 9; i++) { line(CDFMat, Point(50*i,500-500* CDF[i]), Point(50*(i+1),500-500* CDF[i+1]), Scalar(255)); } imshow("CDF", CDFMat); waitKey(0); } int max(int a, int b) { if (a > b) return a; else return b; } int min(int a, int b) { if (a > b) return b; else return a; } void total(double a){ if (0.9 <= a < 1) { IOU_total[9] += 1; } if (0.8 <= a < 0.9) { IOU_total[8] += 1; } if (0.7 <= a < 0.8) { IOU_total[7] += 1; } if (0.6 <= a < 0.7) { IOU_total[6] += 1; } if (0.5 <= a < 0.6) { IOU_total[5] += 1; } if (0.4 <= a < 0.5) { IOU_total[4] += 1; } if (0.3 <= a < 0.4) { IOU_total[3] += 1; } if (0.2 <= a < 0.3) { IOU_total[2] += 1; if (0.1 <= a < 0.2) { IOU_total[1] += 1; } if (0 <= a < 0.1) { IOU_total[0] += 1; } } }
007ce5eb37da302e125590f1097a08ac291ca1a3
e91f0624b1615f7a6fcc089daf568f18d9a98ed1
/data/tplcache/d9a360db880665a0f4b8a089eff5e876.inc
a453ba5c89919c3b1a6f40d8fdaab567b8aa8661
[]
no_license
kanbei001/kbetyy_com
cbe1970c4b3951329e0d024d6ad7d0999cbf9800
880c7f78ad9c6a1dd2cc2c5245ef0f1d2f7f6520
refs/heads/master
2021-09-08T10:57:08.888585
2018-03-09T08:19:10
2018-03-09T08:19:10
124,475,174
0
0
null
null
null
null
UTF-8
C++
false
false
34
inc
d9a360db880665a0f4b8a089eff5e876.inc
/uploads/171118/1-1G11Q125533L.jpg
698f0f12338f801965930f205dde36c786e1a0e0
22b24b43b398f766c293c24ddba47017150be29b
/src/gameObject.h
daa15c0b92f66e3d93a64fc699952dc3fb5372d3
[]
no_license
adrianmisko/opengl-liquor-store
f72eaa411efa7256fddd8d93189f2f05431d0fd9
516fb3415e5123dd77fc9767f753fda100175283
refs/heads/master
2020-05-01T19:15:42.196825
2019-05-22T18:42:53
2019-05-22T18:42:53
177,643,992
0
0
null
null
null
null
UTF-8
C++
false
false
811
h
gameObject.h
#pragma once #include "resources.h" #include "model.h" #include "shader.h" #include "dynamicsWorld.h" #include <fstream> #include <string> struct GameObject { int ID; btScalar mass; float modelMatrix[16]; std::string type; btCollisionShape* collisionShape; btRigidBody* rigidBody; btMotionState* motionState; Model* model; Shader* shader; GameObject(int ID, float mass, const std::string& type, const std::string& shader, btTransform& trans, Resources& res, DynamicsWorld& dynamicsWorld); GameObject(int ID, float mass, const std::string& type, const std::string& shader, Resources& res, DynamicsWorld& dynamicsWorld); void updateModelMatrix(); void draw(glm::mat4& view, glm::mat4& projection); bool operator==(int oID); bool operator==(const GameObject& go); };
fec1912658b20826943c10bfc2ef011fb4af3546
6bb4b9b79dd9b6ba96091f5f4344ca060d09f2aa
/AP-flightgear-interpreter/Parser.cpp
cc5c721e5055b5a51b2512c1b1515eea833d6053
[]
no_license
orsanawwad/APEX
84304558236a4525a70afa6d1233787c75df5f53
980b714e144f4b90c8fd1241f9cd6eae3e6bfcab
refs/heads/master
2020-09-21T20:49:28.385061
2019-11-30T16:44:08
2019-11-30T16:44:08
224,924,776
1
0
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
Parser.cpp
#include "Parser.h" #include "OpenServerCommand.h" #include "DefineVarCommand.h" #include "ConnectCommand.h" #include "LoopCommand.h" #include "IfCommand.h" #include "DBEngine.h" #include "iostream" #define PRINT_UNKNOWN_COMMAND_ERROR "Syntax Error: Unknown command '" << *lexerIteratorBegin << "'" << std::endl; Parser::Parser() {} /** * Given a vector, prepare 2 iterators (begin,end), check current begin and pass it to its own command * if it not a command try to evaluate it * * The way this works is by taking 2 iterators, and pass them to each command, and let the commands deal with them. * * @param lexerOutput */ void Parser::parse(std::vector<std::string> lexerOutput) { std::unordered_map<std::string, Command *> commands = DBEngine::getInstance().get()->getCommandTable(); std::vector<std::string>::iterator lexerIteratorBegin; std::vector<std::string>::iterator lexerIteratorEnd; lexerIteratorBegin = lexerOutput.begin(); lexerIteratorEnd = lexerOutput.end(); while (lexerIteratorBegin != lexerOutput.end()) { if (commands.find(*lexerIteratorBegin) == commands.end()) { if (DBEngine::getInstance().get()->symbolExist(*lexerIteratorBegin)) { DefineVarCommand::getInstance().get()->execute(lexerIteratorBegin, lexerIteratorEnd); } else { if (*lexerIteratorBegin == "") { break; } std::cout << PRINT_UNKNOWN_COMMAND_ERROR; break; } } else { commands[*lexerIteratorBegin]->execute(lexerIteratorBegin, lexerIteratorEnd); } } }
ae62ad7458321d421c219b9df082f26f17e1212c
ea8cfcb7536c6575ca723e916fab6913e2ce6171
/target_sum_01_k_snap.cpp
52e60d60f3a09c7a2164581016d21aa0eb3f768b
[]
no_license
AmanMSHRA/Solved-challanges-
cb057d6a596354ed183675595b7a98a40071a92d
839e2e98dfbd30d85ed110dda4bac2136573938e
refs/heads/main
2023-02-21T06:31:02.095502
2021-01-22T09:47:23
2021-01-22T09:47:23
331,866,132
1
0
null
null
null
null
UTF-8
C++
false
false
1,089
cpp
target_sum_01_k_snap.cpp
#include<bits/stdc++.h> using namespace std; int target_sum_01_ksnap(int arr[],int n,int t,int sum) { if(sum==n && t==0) { return 1; } else if( sum > n) { return 0; } else{ //cout<<t<<endl; return target_sum_01_ksnap(arr,n,t+arr[sum],sum+1) + target_sum_01_ksnap(arr,n,t-arr[sum],sum+1); } } int main() { int arr[] = {1,1,1,1,1}; int t = 3; int n = sizeof(arr)/sizeof(arr[0]); int sum = 0; sum = target_sum_01_ksnap(arr,n,t,sum); cout<<sum<<endl; return 0; }
d5e9a0726c7f5f6cf0b2cd314059a2fe2cb13780
03462a00d09c7f9a7e82ffb8ff125c1d9266e846
/Quadtree.cpp
e412ceb76cf82da3f9c9192c26cf4c2a6d8a9aac
[]
no_license
lucipher128/QuadTree
3d80bc0cbe5c28593fbe7a3f9c7bf3d3a6d2ed9e
f598b52f5ff77e98d391687b332a63ae0538a0e6
refs/heads/master
2020-12-04T23:15:17.375356
2020-01-20T19:51:43
2020-01-20T19:51:43
231,932,501
0
0
null
null
null
null
UTF-8
C++
false
false
3,952
cpp
Quadtree.cpp
#include"QuadTree.h" //============================================================================ //===============================POINTS ====================================== Point::Point(float x, float y) { this->x = x; this->y = y; } float Point::GetX() { return this->x; } float Point::GetY() { return this->y; } //============================================================================== //===========================RECTANGLE========================================== Rectangle::Rectangle(float x, float y, float w, float h) { this->x = x; this->y =y; this->w = w; this->h = h; } Rectangle::~Rectangle() { } float Rectangle::GetX() { return this->x; } float Rectangle::GetY() { return this->y; } float Rectangle::GetW() { return this->w; } float Rectangle::GetH() { return this->h; } bool Rectangle::contains(Point p) { float x = this->GetX(); float y = this->GetY(); float w = this->GetW(); float h = this->GetH(); if ( p.GetX() > x && p.GetX() < x+w&& p.GetY() > y && p.GetY() < y+h) { return true; } return false; } //============================================================================== //===========================QUADTREE========================================== QuadTree::QuadTree(Rectangle rec, int capacity ,const char* name ) { this->rec = rec; this->capacity = capacity; this->nbPoints = 0; this->divided = false; this->name = name; } QuadTree::~QuadTree() { delete this->ne; delete this->se; delete this->nw; delete this->sw; } void QuadTree::SubDivide() { if (this->nbPoints < this->capacity) { //std::cout << "added" << std::endl; return; } else { //std::cout << "dividing "<< this->name<< std::endl; float x = this->rec.GetX(); float y = this->rec.GetY(); float w = this->rec.GetW(); float h = this->rec.GetH(); Rectangle northwest(x , y ,w/2 ,h/2); nw = new QuadTree(northwest, this->capacity,"nw"); Rectangle northeast(x+w/2 , y , w / 2, h / 2); ne = new QuadTree(northeast, this->capacity,"ne"); Rectangle southwest(x , y+h/2, w / 2, h / 2); sw = new QuadTree(southwest, this->capacity,"sw"); Rectangle southeast(x+w/2,y+h/2, w / 2, h / 2); se = new QuadTree(southeast, this->capacity,"se"); this->divided = true; } } void QuadTree::Insert(Point p ) { if (!this->rec.contains(p)) { return; } if (this->nbPoints < this->capacity) { this->points[this->nbPoints] = p; (this->nbPoints) = (this->nbPoints) + 1; } else { if (!this->divided) { this->SubDivide(); } this->ne->Insert(p); this->nw->Insert(p); this->se->Insert(p); this->sw->Insert(p); } } void QuadTree::Insert(Point p,std::string __VERSION) { if (!this->rec.contains(p)) { return; } if (this->nbPoints < this->capacity) { this->points[this->nbPoints] = p; (this->nbPoints) = (this->nbPoints) + 1; std::cout << "inserted" << std::endl; } else { if (!this->divided) { this->SubDivide(); } this->ne->Insert(p); this->nw->Insert(p); this->se->Insert(p); this->sw->Insert(p); } } void QuadTree::search( Point search[10] , Point P) { if (!(this->rec).contains(P)) { return; } if (this->divided) { ne->search(search, P); nw->search(search, P); se->search(search, P); sw->search(search, P); } else { for (int i = 0; i < 10; i++) { search[i] = this->points[i]; } } } void QuadTree::draw(SDL_Window* win, SDL_Renderer* ren) { SDL_Rect rectangle = { (int)this->rec.GetX(), (int)this->rec.GetY(), (int)this->rec.GetW(), (int)this->rec.GetH() };; SDL_SetRenderDrawColor(ren, 255, 0, 0, 255); SDL_RenderDrawRect(ren,&rectangle); for (int i = 0; i < 10; i++) { SDL_SetRenderDrawColor(ren, 255, 255, 255, 255); SDL_RenderDrawPoint(ren, this->points[i].GetX(), this->points[i].GetY()); } if (this->divided) { ne->draw(win, ren); nw->draw(win, ren); se->draw(win, ren); sw->draw(win, ren); } }
2492eb403476a2eb39f30f4a5fae3d87b322c730
54340ace4df01915fe66cc628e7f6e0b0db80422
/ledgerview.cpp
6547025e453631d3a97875ff9ddbfc7d4964a2e2
[]
no_license
probonopd/Accounting
324eb1f951752aa0364e71010d7ee7e58e7f533c
4fc5e4601790d54e5bd3882852709f30d63513e3
refs/heads/master
2021-01-20T22:51:55.444009
2016-09-12T15:40:54
2016-09-12T15:41:27
68,156,424
1
0
null
2016-09-13T23:43:13
2016-09-13T23:43:12
C++
UTF-8
C++
false
false
7,795
cpp
ledgerview.cpp
#include "ledgerview.h" #include "ledgerdelegate.h" #include "ledgervheader.h" #include "commands.h" #include <QKeyEvent> #include <QKeySequence> #include <QMimeData> LedgerView::LedgerView(QWidget *parent) : QTableView(parent) { horizontalHeader()->setSectionsMovable(true); setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); setVerticalHeader(new LedgerVHeader); QAbstractItemDelegate* d = itemDelegate(); setItemDelegate(new LedgerDelegate); delete d; setSortingEnabled(true); setAcceptDrops(true); actionInsertRowAbove = new QAction(tr("Insert Empty Row &Above"),this); actionInsertRowBelow = new QAction(tr("Insert Empty Row &Below"),this); actionMoveRowUp = new QAction(tr("Move Current Row U&p"), this); actionMoveRowDown = new QAction(tr("Move Current Row &Down"), this); actionDeleteRow = new QAction(tr("De&lete Current Row"), this); actionInsertRowAbove->setShortcut(QKeySequence::fromString("Ctrl+Alt+Up")); actionInsertRowBelow->setShortcut(QKeySequence::fromString("Ctrl+Alt+Down")); actionMoveRowUp ->setShortcut(QKeySequence::fromString("Ctrl+Shift+Up")); actionMoveRowDown ->setShortcut(QKeySequence::fromString("Ctrl+Shift+Down")); actionDeleteRow ->setShortcut(QKeySequence::fromString("Ctrl+Delete")); actionInsertRowAbove->setShortcutContext(Qt::WindowShortcut); actionInsertRowBelow->setShortcutContext(Qt::WindowShortcut); actionMoveRowUp ->setShortcutContext(Qt::WindowShortcut); actionMoveRowDown ->setShortcutContext(Qt::WindowShortcut); actionDeleteRow ->setShortcutContext(Qt::WindowShortcut); connect(actionInsertRowAbove,&QAction::triggered, this,&LedgerView::insertRowAbove); connect(actionInsertRowBelow,&QAction::triggered, this,&LedgerView::insertRowBelow); connect(actionMoveRowUp ,&QAction::triggered, this,&LedgerView::moveCurrentRowUp); connect(actionMoveRowDown ,&QAction::triggered, this,&LedgerView::moveCurrentRowDown); connect(actionDeleteRow ,&QAction::triggered, this,&LedgerView::deleteCurrentRow); } void LedgerView::setLedger(Ledger * ledger) { this->ledger = ledger; QItemSelectionModel* m = selectionModel(); setModel(ledger); delete m; if( ledger && ledger->isValidFile() && ledger->columnCount()==Ledger::NCOL ){ setColumnWidth(Ledger::COL_DATE, 120); setColumnWidth(Ledger::COL_DESCRIP,200); setColumnWidth(Ledger::COL_PRICE, 125); setColumnWidth(Ledger::COL_CATEG, 110); setEditTriggers(DoubleClicked|EditKeyPressed|AnyKeyPressed); } else{ resizeColumnsToContents(); setEditTriggers(NoEditTriggers); } manageActions();\ if(ledger){ connect(ledger,&QAbstractItemModel::rowsRemoved, this,&LedgerView::manageActions); connect(ledger,&QAbstractItemModel::rowsInserted, this,&LedgerView::manageActions); connect(ledger,&QAbstractItemModel::rowsMoved, this,&LedgerView::manageActions); connect(ledger,&QAbstractItemModel::layoutChanged,this,&LedgerView::manageActions); connect(ledger,&QObject::destroyed, this,&LedgerView::manageActions); } } QList<QAction*> LedgerView::rowActions() { QList<QAction*> actions; actions << actionInsertRowAbove; actions << actionInsertRowBelow; actions << actionMoveRowUp; actions << actionMoveRowDown; actions << actionDeleteRow; return actions; } void LedgerView::insertRowAbove() { if( !model() || !currentIndex().isValid() ) return; int currentRow = currentIndex().row(); ledger->undoStack->push(new AddRow(currentRow,ledger)); } void LedgerView::insertRowBelow() { if( !model() || !currentIndex().isValid() ) return; int currentRow = currentIndex().row(); ledger->undoStack->push(new AddRow(currentRow+1,ledger)); } void LedgerView::moveCurrentRowUp() { if( !model() || !currentIndex().isValid() ) return; int currentRow = currentIndex().row(); int currentCol = currentIndex().column(); if( currentRow <= 0 ) return; ledger->undoStack->push(new MoveRow(currentRow,currentRow-1,ledger)); QModelIndex index = model()->index(currentRow-1,currentCol); setCurrentIndex(index); selectionModel()->select(index,QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows); } void LedgerView::moveCurrentRowDown() { if( !model() || !currentIndex().isValid() ) return; int currentRow = currentIndex().row(); int currentCol = currentIndex().column(); if( currentRow >= model()->rowCount()-1 ) return; ledger->undoStack->push(new MoveRow(currentRow,currentRow+1,ledger)); QModelIndex index = model()->index(currentRow+1,currentCol); setCurrentIndex(index); selectionModel()->select(index,QItemSelectionModel::ClearAndSelect|QItemSelectionModel::Rows); } void LedgerView::deleteCurrentRow() { if( !model() || !currentIndex().isValid() ) return; int currentRow = currentIndex().row(); int currentCol = currentIndex().column(); QAbstractItemModel* mod = model(); if( mod->rowCount()==1 && ledger->isEmptyRow(currentRow) ) return; ledger->undoStack->push(new DeleteRow(currentRow,ledger)); QModelIndex index; if( currentRow < mod->rowCount() ) index = mod->index(currentRow,currentCol); else if( currentRow > 0 ) index = mod->index(currentRow-1,currentCol); selectionModel()->setCurrentIndex(index,QItemSelectionModel::Current); } void LedgerView::currentChanged(const QModelIndex &current, const QModelIndex &previous) { QAbstractItemView::currentChanged(current,previous); manageActions(); } void LedgerView::manageActions() { if(!currentIndex().isValid() || !model()){ actionInsertRowAbove->setEnabled(false); actionInsertRowBelow->setEnabled(false); actionMoveRowUp ->setEnabled(false); actionMoveRowDown ->setEnabled(false); actionDeleteRow ->setEnabled(false); return; } actionInsertRowAbove->setEnabled(true); actionInsertRowBelow->setEnabled(true); if(currentIndex().row()==0) actionMoveRowUp->setEnabled(false); else actionMoveRowUp->setEnabled(true); if(currentIndex().row()==model()->rowCount()-1) actionMoveRowDown->setEnabled(false); else actionMoveRowDown->setEnabled(true); if( model()->rowCount()==1 && ledger->isEmptyRow(currentIndex().row()) ) actionDeleteRow->setEnabled(false); else actionDeleteRow->setEnabled(true); } void LedgerView::keyPressEvent(QKeyEvent *event) { if( event->key()==Qt::Key_Delete && (event->modifiers()&(~Qt::KeypadModifier))==0 ) { QModelIndexList selected = selectedIndexes(); bool empty = true; foreach (const QModelIndex & index, selected) if(!model()->data(index,Qt::EditRole).isNull()) empty = false; if(!empty) ledger->undoStack->push(new DeleteItems(selected,ledger)); } QAbstractItemView::keyPressEvent(event); } void LedgerView::dragEnterEvent(QDragEnterEvent *event) { if(event->mimeData()->hasUrls() && event->proposedAction()==Qt::CopyAction) event->accept(); else QTableView::dragEnterEvent(event); } void LedgerView::dragMoveEvent(QDragMoveEvent *event) { if(event->mimeData()->hasUrls() && event->proposedAction()==Qt::CopyAction) event->acceptProposedAction(); else QTableView::dragMoveEvent(event); } void LedgerView::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls() && event->proposedAction()==Qt::CopyAction){ QList<QUrl> urls = event->mimeData()->urls(); emit filesDropped(urls); } else QTableView::dropEvent(event); }
625e2bcc674ce96e552684a659e1343ae2d40160
238165028f560e39a5fa795a0d3b1d9e6d34ba11
/MyPDE/src/ElasticityCrackOpening2D.cpp
f029f2f7d532a7adc1c7b61dcf2b45989450657d
[]
no_license
pmueller2/NuToApps
3b1d41b34cc3267f270fd20311543ec0751e96e2
b09cb916ed510d79df99c85666a0b0b9a1bf6608
refs/heads/master
2018-12-18T08:58:14.402501
2018-09-14T12:28:47
2018-09-14T12:28:47
125,864,845
0
0
null
null
null
null
UTF-8
C++
false
false
7,299
cpp
ElasticityCrackOpening2D.cpp
#include "nuto/mechanics/mesh/MeshFemDofConvert.h" #include "nuto/mechanics/mesh/MeshGmsh.h" #include "nuto/mechanics/integrationtypes/IntegrationCompanion.h" #include "nuto/mechanics/interpolation/InterpolationQuadLobatto.h" #include "nuto/mechanics/constitutive/LinearElastic.h" #include "nuto/mechanics/integrands/DynamicMomentumBalance.h" #include "nuto/mechanics/tools/CellStorage.h" #include "nuto/mechanics/cell/SimpleAssembler.h" #include "nuto/mechanics/dofs/DofNumbering.h" #include "nuto/visualize/AverageHandler.h" #include "nuto/visualize/Visualizer.h" #include "nuto/mechanics/constraints/ConstraintCompanion.h" #include "nuto/mechanics/constraints/Constraints.h" #include "../../MyTimeIntegration/NY4NoVelocity.h" #include "../../NuToHelpers/ConstraintsHelper.h" #include <iostream> using namespace NuTo; double smearedStepFunction(double t, double tau) { double ot = M_PI * t / tau; if (ot > M_PI) return 1.; if (ot < 0.) return 0.; return 0.5 * (1. - cos(ot)); } /* Rectangular domain, linear isotropic homogeneous elasticity * Crack opening */ int main(int argc, char *argv[]) { // ********************************* // Geometry parameter // ********************************* MeshGmsh gmsh("Crack2D_2.msh"); MeshFem &mesh = gmsh.GetMeshFEM(); auto bottom = gmsh.GetPhysicalGroup("Bottom"); auto left = gmsh.GetPhysicalGroup("Left"); auto crack = gmsh.GetPhysicalGroup("Crack"); auto domain = gmsh.GetPhysicalGroup("Domain"); // *********************************** // Dofs, Interpolation // *********************************** double tau = 0.2e-6; double stepSize = 0.006e-6; int numSteps = 30000; double E = 200.0e9; double nu = 0.3; double rho = 8000.; Eigen::Vector2d crackLoad(-1., 0.); DofType dof1("Displacements", 2); Laws::LinearElastic<2> steel(E, nu); // 2D default: plane stress Integrands::DynamicMomentumBalance<2> pde(dof1, steel, rho); int order = 3; auto &ipol = mesh.CreateInterpolation(InterpolationQuadLobatto(order)); AddDofInterpolation(&mesh, dof1, ipol); mesh.AllocateDofInstances(dof1, 2); // *********************************** // Set up integration, add cells // *********************************** int integrationOrder = order + 1; // Domain cells auto domainIntType = CreateLobattoIntegrationType( domain.begin()->DofElement(dof1).GetShape(), integrationOrder); CellStorage domainCells; auto domainCellGroup = domainCells.AddCells(domain, *domainIntType); // Boundary cells auto boundaryIntType = CreateLobattoIntegrationType( crack.begin()->DofElement(dof1).GetShape(), integrationOrder); CellStorage crackCells; auto crackCellGroup = crackCells.AddCells(crack, *boundaryIntType); // ****************************** // Set Dirichlet boundary // ****************************** Group<NodeSimple> bottomNodes = GetNodes(bottom, dof1); Group<NodeSimple> leftNodes = GetNodes(left, dof1); Constraint::Constraints constraints; constraints.Add(dof1, Constraint::Component(bottomNodes, {eDirection::Y})); constraints.Add(dof1, Constraint::Component(leftNodes, {eDirection::X})); // ************************************ // Assemble constant mass matrix // ************************************ DofInfo dofInfo = DofNumbering::Build(mesh.NodesTotal(dof1), dof1, constraints); Eigen::SparseMatrix<double> cmat = constraints.BuildConstraintMatrix(dof1, dofInfo.numIndependentDofs[dof1]); SimpleAssembler asmbl = SimpleAssembler(dofInfo); auto lumpedMassMx = asmbl.BuildDiagonallyLumpedMatrix( domainCellGroup, {dof1}, [&](const CellIpData &cipd) { return pde.Hessian2(cipd); }); auto mJ = lumpedMassMx.J[dof1]; auto mK = lumpedMassMx.K[dof1]; Eigen::SparseMatrix<double> massModifier = cmat.transpose() * mK.asDiagonal() * cmat; Eigen::VectorXd massMxMod = mJ + massModifier.diagonal(); // *********************************** // Assemble stiffness matrix // *********************************** GlobalDofMatrixSparse stiffnessMx = asmbl.BuildMatrix(domainCellGroup, {dof1}, [&](const CellIpData &cipd) { return pde.Hessian0(cipd, 0.); }); // Compute modified stiffness matrix auto kJJ = stiffnessMx.JJ(dof1, dof1); auto kJK = stiffnessMx.JK(dof1, dof1); auto kKJ = stiffnessMx.KJ(dof1, dof1); auto kKK = stiffnessMx.KK(dof1, dof1); Eigen::SparseMatrix<double> stiffnessMxMod = kJJ - cmat.transpose() * kKJ - kJK * cmat + cmat.transpose() * kKK * cmat; // ********************************* // Visualize // ********************************* auto visualizeResult = [&](std::string filename) { NuTo::Visualize::Visualizer visualize(domainCellGroup, NuTo::Visualize::AverageHandler()); visualize.DofValues(dof1); visualize.WriteVtuFile(filename + ".vtu"); }; // *********************************** // Solve // *********************************** NuTo::TimeIntegration::NY4NoVelocity<Eigen::VectorXd> ti; double t = 0.; Eigen::VectorXd femResult(dofInfo.numIndependentDofs[dof1] + dofInfo.numDependentDofs[dof1]); // Set initial data Eigen::VectorXd w0(dofInfo.numIndependentDofs[dof1]); Eigen::VectorXd v0(dofInfo.numIndependentDofs[dof1]); w0.setZero(); v0.setZero(); auto MergeResult = [&mesh, &dof1](Eigen::VectorXd femResult) { for (auto &node : mesh.NodesTotal(dof1)) { for (int component = 0; component < dof1.GetNum(); component++) { int dofNr = node.GetDofNumber(component); node.SetValue(component, femResult[dofNr]); } }; }; auto state = std::make_pair(w0, v0); auto crackLoadFunc = [&](const CellIpData &cipd, double tt) { Eigen::MatrixXd N = cipd.N(dof1); DofVector<double> loadLocal; Eigen::Vector2d normalTraction = crackLoad * smearedStepFunction(tt, tau); loadLocal[dof1] = N.transpose() * normalTraction; return loadLocal; }; auto eq = [&](const Eigen::VectorXd &w, Eigen::VectorXd &d2wdt2, double t) { // Compute load GlobalDofVector boundaryLoad = asmbl.BuildVector(crackCellGroup, {dof1}, [&](const CellIpData cipd) { return crackLoadFunc(cipd, t); }); // Include constraints auto fJ = boundaryLoad.J[dof1]; auto fK = boundaryLoad.K[dof1]; auto b = constraints.GetRhs(dof1, t); Eigen::VectorXd loadVectorMod = fJ - cmat.transpose() * fK; loadVectorMod -= (kJK * b - cmat.transpose() * kKK * b); Eigen::VectorXd tmp = (-stiffnessMxMod * w + loadVectorMod); d2wdt2 = (tmp.array() / massMxMod.array()).matrix(); }; int plotcounter = 1; for (int i = 0; i < numSteps; i++) { t = i * stepSize; state = ti.DoStep(eq, state.first, state.second, t, stepSize); femResult.head(dofInfo.numIndependentDofs[dof1]) = state.first; // Compute Dependent Dofs femResult.tail(dofInfo.numDependentDofs[dof1]) = -cmat * state.first + constraints.GetRhs(dof1, (i + 1) * stepSize); std::cout << i + 1 << std::endl; if ((i * 100) % numSteps == 0) { MergeResult(femResult); visualizeResult("Crack2DNormalLoad_" + std::to_string(plotcounter)); plotcounter++; } } }
bd620c0c9a5904ec0920f4fbc4744a1710504450
b715ec24c6bbf40935b8d09f30ab49af7e601f5a
/src/Camera.h
3210163e9104c232031c901ab67a7377aae94939
[]
no_license
alban-s/raytracing
0fa9b8d9df6b7eaef020078225a565daa4252132
38ccffa6ac1be97750c6f6d5ec04bc487a08eb57
refs/heads/master
2023-03-25T05:01:59.316959
2021-01-14T22:25:03
2021-01-14T22:25:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
607
h
Camera.h
// // Created by constantin on 12/09/2020. // #ifndef RAYTRACING_CAMERA_H #define RAYTRACING_CAMERA_H #include "Vector.h" #include "Matrix4x4.h" ///\brief Classe de la camera class Camera { public: Position origin; static float fov; static Matrix4x4 cameraToWorld; ///\brief Regle la camera ///\param from : position de la camera ///\param to : endroit visé par la camera ///\param dir : Indique le haut de la scène static Matrix4x4 lookAt(const Vector3<float> & from, const Vector3<float> & to,const Vector3f & dir=Vector3f(0,1,0)); }; #endif //RAYTRACING_CAMERA_H
bbc9c206a0ba30560d73e886617de9e259d51fd6
d00807fe7b2c6c9b71f64788d9ff9ac53da57133
/page_builder/js_polygon.hpp
c797830a1120eec923a7caaab81985be31862d12
[]
no_license
olegh/chm
ee234f42c2ac102974144d8d37ffceb660f0c874
de254ce41f9f39dc75693efd2a7144317dce4266
refs/heads/master
2021-01-19T00:08:36.756994
2013-07-14T17:46:32
2013-07-14T17:46:32
1,481,914
1
0
null
null
null
null
UTF-8
C++
false
false
2,094
hpp
js_polygon.hpp
#if !defined( BA669AA0_EF10_4a56_B5DA_90FF38383232 ) # define BA669AA0_EF10_4a56_B5DA_90FF38383232 #include <string> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <boost/cstdint.hpp> #include <boost/lexical_cast.hpp> #include <boost/iterator/filter_iterator.hpp> #include <boost/foreach.hpp> #include "common/ptree_helpers.hpp" #include "common/named_properties.hpp" #include "page_builder/js_simple_objects.hpp" namespace chm{ template<class Ptree> struct basic_js_polygon { typedef js_simple_objects js_so; typedef basic_js_polygon<Ptree> this_type; basic_js_polygon( const Ptree& ptree ) : ptree_( ptree ) {} std::string operator()() { const std::string colorPath = props::polygon::color::relative(); return "gr.fillPolygon( " + js_so::jsColor( ptree_.template get<boost::uint32_t>(colorPath)) + ", " + jsArray() + " );\n" + "gr.drawPolygon( " + js_so::jsPen() + ", " + jsArray() + " );\n"; } private: std::string jsArray() { const std::string pointPath = props::polygon::point::relative(); std::string result = "new Array( "; std::for_each( make_begin_filter_const(pointPath, ptree_), make_end_filter_const(ptree_), boost::bind(&this_type::addPoint, boost::ref(result), _1)); result.erase( -- -- result.end() ); return result += ")"; } static void addPoint( std::string& result, const typename Ptree::value_type& pair ) { const std::string x = props::polygon::point::x::relative(); const std::string y = props::polygon::point::y::relative(); const Ptree& point = pair.second; result += js_so::jsPoint( point.template get<boost::uint32_t>(x), point.template get<boost::uint32_t>(y) ) + ", "; } Ptree ptree_; }; //struct js_polygon_creater typedef basic_js_polygon<boost::property_tree::iptree> js_polygon; } //namespace chm{ #endif //#if !defined( BA669AA0_EF10_4a56_B5DA_90FF38383232 )
0aabd1031ba774a14b803c0a801146b3b4d396e6
3630a2ec288d62d74f9018720a1e804ffc039fdf
/ABC/ABC150/c.cpp
40a2dc25a80dfaea24e50ced01d4ba22c2bb8093
[]
no_license
kant/AtCoder
8f8970d46fb415983927b2626a34cf3a3c81e090
b9910f20980243f1d40c18c8f16e258c3e6e968f
refs/heads/master
2022-12-10T10:15:43.200914
2020-02-17T07:23:46
2020-02-17T07:23:46
292,367,026
0
0
null
2020-09-02T18:45:51
2020-09-02T18:45:50
null
UTF-8
C++
false
false
1,144
cpp
c.cpp
#include <bits/stdc++.h> using namespace std; int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; vector<int> P(n), Q(n); for(int i = 0; i < n; i++){ cin >> P[i]; } for(int i = 0; i < n; i++){ cin >> Q[i]; } vector<int> A(n); for(int i = 0; i < n; i++){ A[i] = i + 1; } int ai = -1, bi = -1, cnt = 0; do{ if(ai == -1){ bool f = true; for(int i = 0; i < n; i++){ if(A[i] == P[i]); else{ f = false; break; } } if(f) ai = cnt; } if(bi == -1){ bool f = true; for(int i = 0; i < n; i++){ if(A[i] == Q[i]); else{ f = false; break; } } if(f) bi = cnt; } if(ai != -1 and bi != -1){ break; } cnt++; }while(next_permutation(A.begin(), A.end())); cout << abs(ai - bi) << endl; return 0; }
71d9a81642cf9ed41423cedc9dd88368ca38949a
b9c64f2110438454173b1086c39f34283fda23ab
/cracking_the_coding_interview/1_5_one_away.cpp
489a7cd7f078488b041ed45fc2e0916b7cc92d64
[]
no_license
jmeadows4/coding_problems
1f759bae731cc939dd0265e720454e232aa40d90
f81971b7ff04149fb6b61ccf0ba778863c2682bd
refs/heads/master
2022-09-30T03:12:02.908759
2020-06-06T05:28:30
2020-06-06T05:28:30
269,868,877
0
0
null
null
null
null
UTF-8
C++
false
false
1,694
cpp
1_5_one_away.cpp
#include<iostream> #include<string> #include<unordered_map> #include<cstdlib> using namespace std; /* check if a string is one operation away from another string. operations you can preform: * add a character * remove a character * swap a character */ bool one_away(string s1, string s2){ int size; //if they are the same size, only a swap would work if(s1.size() == s2.size()){ bool swapped = false; size = s1.size(); for(int i = 0; i < size; i++){ if(s1[i] != s2[i]){ if(swapped){ return false; } else{ swapped = true; } } } } else{ //if there is more than a 2 character difference between the strings, nothing can be done if(abs(int(s1.size() - s2.size())) > 2){ return false; } //else, the difference between the strings is 1. //make it easier by naming the strings by size string bigger, smaller; if(s1.size() > s2.size()){ bigger = s1; smaller = s2; } else{ bigger = s2; smaller = s1; } //doesn't make a difference whether we insert or remove bool removed = false; int big_it = 0; for(int small_it = 0; small_it < smaller.size(); small_it++){ if(bigger[big_it] != smaller[small_it]){ if(removed){ return false; } else{ removed = true; } small_it -= 1; } big_it += 1; } } return true; } int main(){ string s1, s2; getline(cin, s1); getline(cin, s2); bool ans = one_away(s1, s2); if(ans){ cout << "They are one away!" << endl; } else{ cout << "They are not one away." << endl; } return 0; }
32a50697a6c200e14b8d4b7e84806d21a6e04008
f5c0d5ea5d659bf4bde7e0b025022b59fd521d3b
/cpp/agrecacao_e_composicao/exemplo_1/telefone.cc
38dd90c7c414aa752b99a51a27bf0e066c85a5fc
[]
no_license
hazylua/pt-br
d611b23aa8e280b12ac9132c6e158abb47e8bea3
101ac756e6a1b879e222573aaa29e8220cdf907e
refs/heads/master
2022-03-10T14:25:29.371088
2019-02-27T13:00:51
2019-02-27T13:00:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
240
cc
telefone.cc
#include "telefone.h" Telefone::Telefone (const string &ddd, const string &num_tel) { this->ddd = ddd; this->num_tel = num_tel; } string Telefone::getDdd () { return ddd; } string Telefone::getNumTel () { return num_tel; }
45f7a3fb586ff39a58992c707cb0aa34a7ae10c1
1ee92455b7a146626fafd765e0fd7934b69e08eb
/FAIRELCT.cpp
533c29801ab037042bd033ae5249177c0ba53d99
[]
no_license
SasmalUdayaditya/Codechef_Problems
eab99dabd077496b187514acc448e21cfb2c9651
38f303130a4f51de8b0dfefe75550d4adf5d36c4
refs/heads/main
2023-03-07T15:19:21.197902
2021-02-21T16:14:04
2021-02-21T16:14:04
302,969,800
4
0
null
null
null
null
UTF-8
C++
false
false
985
cpp
FAIRELCT.cpp
//j2infy Codechef-Long Jan-21 #include<bits/stdc++.h> #define IOS ios_base::sync_with_stdio(false); cin.tie(NULL); #define ll long long int using namespace std; ll CalcSum(ll a[],ll n) { ll sum=0; for(ll i=0;i<n;i++) sum+=a[i]; return sum; } int main(void) { IOS; int t; cin>>t; while(t--) { ll n,m; cin>>n>>m; ll jhon[n],jack[m]; ll sumjhon=0,sumjack=0; for(int i=0;i<n;i++) { cin>>jhon[i]; sumjhon+=jhon[i]; } for(int i=0;i<m;i++) { cin>>jack[i]; sumjack+=jack[i]; } int count=0,flag=0; if(sumjhon > sumjack) count=0; else { sort(jhon,jhon+n); sort(jack,jack+m); int i=m-1; count = 1; while(count) { swap(jhon[(count-1)%n],jack[i]); int jh = CalcSum(jhon,n); int ja = CalcSum(jack,m); i--; if(jh > ja) break; else if((jh<=ja)&&i==0) { count = -1; break; } count++; } } cout<<count<<"\n"; } return 0; }
f3bfa35070cb40d15c5ecc24b3509ec976e4cc37
005f320c33d4218054a18e90cb7b574b9a7d5f4c
/VbCodeConstant.h
9474c541eba6bee31cd8a2a17408b08db4a865d8
[]
no_license
jmfb/ConvertVb6ToCs
7652c96df56c45ceb3f3e2846df9b63517be050b
a14322dd4df61b90a9ab2c8a04f7744ae6769f55
refs/heads/master
2021-01-10T09:55:00.631698
2016-04-12T01:25:18
2016-04-12T01:25:18
54,246,525
4
0
null
null
null
null
UTF-8
C++
false
false
780
h
VbCodeConstant.h
#pragma once #include "VbCodeValue.h" #include "VbCodeWriter.h" #include <iostream> class VbCodeConstant { public: VbCodeConstant(bool isPublic, const std::string& name, const VbCodeValue& value) : isPublic(isPublic), name(name), value(value) { } void WriteClassCs(std::ostream& out) const { out << " " << (isPublic ? "public" : "private") << " const "; value.WriteTypeCs(out); out << " " << name << " = "; value.WriteValueCs(out); out << ";" << std::endl; } void WriteLocalCs(VbCodeWriter& writer) const { writer.StartLine(); writer.out << "const "; value.WriteTypeCs(writer.out); writer.out << " " << name << " = "; value.WriteValueCs(writer.out); writer.out << ";" << std::endl; } bool isPublic; std::string name; VbCodeValue value; };
c0ab284117eec6fc9134227bd055eec59a0b0b65
d10f93fc85ea3b2e1faf81cededeb65b9f006d1b
/src/Triangle.cpp
b661bca2733cf1f23079d794e194a8bd7c060b84
[]
no_license
carl2g/Raytracer
0d45e36fc373d96ee4c617aa6269a4a303110072
8f7541251f6a7798964bf1906c90506c53ff79e0
refs/heads/master
2023-03-14T14:39:33.537095
2021-03-14T16:15:34
2021-03-14T16:15:34
135,750,579
0
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
Triangle.cpp
/* * @Author: carl de gentile * @Date: 2018-07-02 11:22:15 * @Last Modified by: carl de gentile * @Last Modified time: 2018-07-02 11:23:27 */ #include "Triangle.hpp" #include <math.h> Triangle::Triangle(const Vec3<double> &a, const Vec3<double> &b, const Vec3<double> &c, const Color &color) : Obj(color), _a(a), _b(b), _c(c) {} double Triangle::intersect(const Vec3<double> &origin, const Vec3<double> &rd) { auto &&norm_vec = (_b - _a).cross(_c - _a); double dot1 = norm_vec.dot(origin - _c); double dot3 = norm_vec.dot(rd); if (dot3 == 0.0) { return (-1); } double t = -dot1 / dot3; auto &&g = origin + rd * t; double bac = (_b-_a).getAngle(_c-_a); double bag = (_b-_a).getAngle(g-_a); if (bac < bag) { return (-1); } double acb = (_a-_c).getAngle(_b-_c); double acg = (_a-_c).getAngle(g-_c); if (acb < acg) { return (-1); } double cba = (_c-_b).getAngle(_a-_b); double cbg = (_c-_b).getAngle(g-_b); if (cba < cbg) { return (-1); } return (t); } std::unique_ptr<Vec3<double>> Triangle::getNormalVect(const Vec3<double> &origin) const { return std::unique_ptr<Vec3<double>> ( new Vec3<double>( (origin - _a).cross(origin - _b).normalized() ) ); }
9825fe22c153047e1abc05a318a50cb5485e774d
6d4299ea826239093a91ff56c2399f66f76cc72a
/Visual Studio 2017/Projects/baekjun/baekjun/3062.cpp
13db99ac05ac58fc6493cca670663fd915bace32
[]
no_license
kongyi123/Algorithms
3eba88cff7dfb36fb4c7f3dc03800640b685801b
302750036b06cd6ead374d034d29a1144f190979
refs/heads/master
2022-06-18T07:23:35.652041
2022-05-29T16:07:56
2022-05-29T16:07:56
142,523,662
3
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
3062.cpp
#include <stdio.h> int inv(int a) { int t2 = 0; while (a) { t2 = t2 * 10 + a % 10; a = a / 10; } return t2; } int main(void) { int n; int data; fscanf(stdin, "%d", &n); for (int i = 1;i <= n;i ++) { fscanf(stdin, "%d", &data); int t = data, t2; t2 = inv(data) + data; if (t2 == inv(t2)) { fprintf(stdout, "YES\n"); } else fprintf(stdout, "NO\n"); } return 0; }
2560bc488a7c07653703a05fbd19824b722a7f0c
e6b695c9b0ab3eca8f5424c80db936e6e3f7be72
/appinfo.h
b4a310792a32e7d0b9e20a4b0e2c7f85630e2f30
[]
no_license
DriftMind/NTUMEMSOpenVPN
a9bba50db42542423b1736a65911f9d4d6e9099e
7964c4be8cfddfb403fa00e2f3b14eec6d3f8e60
refs/heads/master
2021-01-11T14:45:25.102786
2014-06-09T15:35:42
2014-06-09T15:35:42
null
0
0
null
null
null
null
MacCentralEurope
C++
false
false
516
h
appinfo.h
#ifndef APPINFO_H #define APPINFO_H #include <QtGui> namespace Ui { class appInfo; } // Die Appinfo wird nun eine Singleton-Klasse // Zudem ist der Name von appInfo auf AppInfo // zwecks Nomenklatur gešndert. class AppInfo : public QDialog { Q_OBJECT public: static AppInfo *getInstance (); ~AppInfo(); protected: void changeEvent(QEvent *e); private: static AppInfo* mInst; Ui::appInfo *m_ui; AppInfo(); private slots: void on_cmdClose_clicked(); }; #endif // APPINFO_H
a1e4189b89c45c2d187994fe4a8edadf02cc501d
125eb97cbfbcea24a6578550c9a3a0db9c447b27
/include/http/Cookie.h
7f3ae54a81d5ff2f9116dfccb769cdd9320a3132
[]
no_license
Anarion-zuo/AnMVC
13b00485a4c962bda09761137b15e23839a9afef
dd28b6ee98b8dd6e3d9bfa0dc3adec1e840ae765
refs/heads/master
2021-05-23T08:22:49.952044
2020-05-15T05:38:28
2020-05-15T05:38:28
253,196,088
0
0
null
null
null
null
UTF-8
C++
false
false
412
h
Cookie.h
// // Created by anarion on 5/1/20. // #ifndef MYMVC_COOKIE_H #define MYMVC_COOKIE_H #include <container/Map/HashMap.hpp> #include <container/SString.h> namespace anarion { class Cookie { protected: HashMap<SString, SString> _map; public: void put(SString key, SString val); HashMap<SString, SString>::iterator get(const SString &key); }; } #endif //MYMVC_COOKIE_H
07c3787556dc4baf836d40bfa12182dee87d26d2
6b550d3d0b182bcddda1f0a175d6b6cd07b60fb3
/logdevice/common/settings/ClientReadStreamFailureDetectorSettings.h
f5cea22eb7231f851e5a5af88ad3f5518339e978
[ "BSD-3-Clause" ]
permissive
Rachelmorrell/LogDevice
5bd04f7ab0bdf9cc6e5b2da4a4b51210cdc9a4c8
3a8d800033fada47d878b64533afdf41dc79e057
refs/heads/master
2021-06-24T09:10:20.240011
2020-04-21T14:10:52
2020-04-21T14:13:09
157,563,026
1
0
NOASSERTION
2020-04-21T19:20:55
2018-11-14T14:43:33
C++
UTF-8
C++
false
false
1,546
h
ClientReadStreamFailureDetectorSettings.h
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include "logdevice/common/util.h" namespace facebook { namespace logdevice { struct ClientReadStreamFailureDetectorSettings { // Duration to use for the moving average. std::chrono::seconds moving_avg_duration; // Define the required margin of the outlier detection algorithm. For // instance a required marginn of 5 means that a shard will be considered // outlier only if it's 500% slower than the average of the other shards. // This parameter changes adaptively in order to avoid too many rewinds. float required_margin; // Rate at which we decrease the required margin as we complete windows // without a rewind. Defined in terms of units / 1s. For instance a value of // 0.25 means we will substract 0.25 to the required margin for every second // spent reading. float required_margin_decrease_rate; // Define how long a shard should remain in the outlier list after it has // been detected slow. This duration is adaptive. chrono_expbackoff_t<std::chrono::seconds> outlier_duration; // Rate at which we decrease the time after which we'll try to reinstate an // outlier in the read set. This rate gets applied when a shard is not // detected an outlier. float outlier_duration_decrease_rate; }; }} // namespace facebook::logdevice
b45cfe9127301342b842fe847463ae4358364bd6
3b40374043ee732d8e45bac5711f56b9146b347f
/12/copy.cpp
377986d0273f931c4f9eef02995b8a0e2bee193f
[]
no_license
hpsdy/c-plus
01e2681ddd410a0f71a93e183d610a355d461313
9077aff1c62136281777a0e03ab2981aa0330fbe
refs/heads/master
2021-01-24T04:08:09.042744
2018-11-03T04:13:07
2018-11-03T04:13:07
122,922,744
0
3
null
null
null
null
UTF-8
C++
false
false
1,329
cpp
copy.cpp
#include<iostream> #include<string> #include<memory> #include<stdexcept> using namespace std; struct cn{ cn(){ cout<<"default construct"<<endl; }; cn(string pstr){ str = pstr; cout<<"user construct"<<endl; } cn(cn &p){ cout<<"copy construct"<<endl; } ~cn(){ cout<<"default destory:"<<str<<endl; } void pt(){ cout<<str<<endl; } void operator=(const cn &p){ cout<<"=="<<endl; } private: string str="default"; }; int main(){ { cn obj; cout<<"===="<<endl; cn obj1(obj); cout<<"===="<<endl; cn obj2 = obj; cout<<"===="<<endl; obj1=obj2; cout<<"===="<<endl; cn o1("one1"); cn o2("one2"); cn o3("one3"); } { cout<<"+++++++++++++++"<<endl; shared_ptr<cn> p(new cn); cout<<p.use_count()<<endl; shared_ptr<cn> q(p); cout<<q.use_count()<<endl; cn *obj = new cn("qinhan"); p.reset(obj); cout<<q.use_count()<<endl; p->pt(); p.reset(); cout<<p<<endl; } { cout<<"+++++++++++++++"<<endl; unique_ptr<cn> up(new cn("unique")); cout<<up.get()<<endl; auto p = up.release(); cout<<p<<endl; cout<<up.get()<<endl; } { cout<<"+++++++++++++++"<<endl; string *str = new string("中国人民万岁"); try{ throw runtime_error("some error"); delete str; }catch(runtime_error e){ cout<<e.what()<<endl; } cout<<*str<<endl; } return 0; }
eedf95be8d2e4e7650515af4081dd3ee9262244e
b24747bb1237595e7a0e33b7cf75804545862513
/Operation.h
6637df2c3cc5004aa5895b4e014ee98b51817037
[ "MIT" ]
permissive
leti9005/prog_2.7.2
51f863b4614c008bffb531cd077bc74d54266741
6fa17fa361dc955aab1c740b978c0ae551b6d738
refs/heads/master
2022-09-06T22:54:54.996212
2020-05-28T18:59:18
2020-05-28T18:59:18
267,671,198
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
Operation.h
#ifndef KURS_SEM2_OPERATION_H #define KURS_SEM2_OPERATION_H #include <string> #include <iostream> #include "GenericList.h" class Operation { unsigned int _book; unsigned int _reader; unsigned int _date; public: Operation(); Operation(unsigned _book, unsigned _reader, unsigned _date); static Operation *from_raw_string(const std::string &line); unsigned int get_book() const; unsigned int get_reader() const; unsigned int get_date() const; }; #endif //KURS_SEM2_OPERATION_H
3991712892aaf7100309ddf09e31b4694bfaec01
d86cf8e5ed4612166c0b10e71b46d397f885bf46
/src/Board.h
9d329e9c6af4ebf721f60443c536713b40633b28
[]
no_license
JALB91/mthree
1a9b80411a924192de1010509a3a462bd6a1492c
0f9fcbf20cc2d0015f9acd94b5cb3993920d49c2
refs/heads/master
2020-03-17T19:11:31.894193
2018-05-19T10:37:40
2018-05-19T10:39:20
133,849,047
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
Board.h
#ifndef BOARD_H #define BOARD_H #include <map> #include <cstdint> #include "Pos.h" #include "Tile.h" namespace mthree { class Board { public: Board(const std::map<BoardPos, Tile>& tilesMap); ~Board(); inline const std::map<BoardPos, Tile>& getTilesMap() const { return this->tilesMap; } inline const uint8_t getHeight() const { return this->height; } inline const uint8_t getWidth() const { return this->width; } bool hasTile(const BoardPos& pos) const; protected: private: std::map<BoardPos, Tile> tilesMap; uint8_t height = 0; uint8_t width = 0; }; } // namespace mthree #endif /* BOARD_H */
6f357c0a2347ca69bf4eee46658f8e7f2a6da94b
129b771015af7daf37c03c3b5a3740758a3aabe6
/tools/don_segmentation.cpp
3f5cfd3f5df29da9a79c4246cab82c73acea6578
[]
no_license
18670025215/pcl_tools
54747146f678e7aedb90662904b34d9253f8712d
06057597b89a721e825b3f5059641b13acf64d1f
refs/heads/master
2020-04-02T17:01:53.418877
2018-10-24T07:59:37
2018-10-24T07:59:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,219
cpp
don_segmentation.cpp
// // Created by robosense on 2018-1-4 // /** * @file don_segmentation.cpp * Difference of Normals Example for PCL Segmentation Tutorials. * * @author Yani Ioannou * @date 2012-09-24 */ #include <pcl/common/random.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/features/don.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/filters/conditional_removal.h> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/search/kdtree.h> #include <pcl/search/organized.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/visualization/pcl_visualizer.h> #include <string> using namespace pcl; using namespace pcl::io; using namespace pcl::console; using namespace std; double threshold = 0.2; void printHelp(int, char** argv) { print_error("Syntax is: %s input_normal_small.pcd input_normal_small.pcd " "<options> [optional_arguments]\n", argv[0]); print_info(" where options are:\n"); print_info(" -threshold X = threshold for DoN magnitude " "(default: "); print_value("%f", threshold); print_info(")\n"); } int main(int argc, char* argv[]) { if (argc < 3) { printHelp(argc, argv); exit(EXIT_FAILURE); } parse_argument(argc, argv, "-threshold", threshold); pcl::PointCloud<PointNormal>::Ptr normals_small_scale(new pcl::PointCloud<PointNormal>); pcl::PointCloud<PointNormal>::Ptr normals_large_scale(new pcl::PointCloud<PointNormal>); if (pcl::io::loadPCDFile<PointNormal>(argv[1], *normals_small_scale) == -1) { std::cout << "Cloud reading failed." << std::endl; return (-1); } if (pcl::io::loadPCDFile<PointNormal>(argv[2], *normals_large_scale) == -1) { std::cout << "Cloud reading failed." << std::endl; return (-1); } // Create output cloud for DoN results PointCloud<PointNormal>::Ptr doncloud(new pcl::PointCloud<PointNormal>); copyPointCloud<PointNormal, PointNormal>(*normals_small_scale, *doncloud); cout << "Calculating DoN... " << endl; // Create DoN operator pcl::DifferenceOfNormalsEstimation<PointNormal, PointNormal, PointNormal> don; don.setInputCloud(normals_small_scale); don.setNormalScaleLarge(normals_large_scale); don.setNormalScaleSmall(normals_small_scale); if (!don.initCompute()) { std::cerr << "Error: Could not intialize DoN feature operator" << std::endl; exit(EXIT_FAILURE); } // Compute DoN don.computeFeature(*doncloud); // Save DoN features pcl::PCDWriter writer; writer.write<pcl::PointNormal>("don.pcd", *doncloud, false); pcl::PointCloud<PointNormal>::Ptr doncloud_filtered(new pcl::PointCloud<PointNormal>), doncloud_remove(new pcl::PointCloud<PointNormal>); for (auto p : *doncloud) { if (p.curvature <= threshold) { doncloud_filtered->push_back(p); } else { doncloud_remove->push_back(p); } } std::cout << "Filtered Pointcloud: " << doncloud->points.size() << " data points." << std::endl; writer.write<pcl::PointNormal>("don_filtered.pcd", *doncloud_filtered, false); writer.write<pcl::PointNormal>("doncloud_remove.pcd", *doncloud_remove, false); }
bbbfca162f731dea9040e9958efbc74fab1261cb
3b131bdc0ed040f5435614ba6b63e0d0b0ae86ea
/include/emp/base/_assert_macros.hpp
8a402a6658d56afe7edd47c0fd019c348f3653a0
[]
no_license
emilydolson/Empirical
c2fd46f47d732b72c62eed62c0d73ed651775537
8a661a67b2132b46b77b2870bbdc5bcd07368e28
refs/heads/master
2021-12-25T04:13:39.968957
2021-10-11T17:57:42
2021-10-11T17:57:42
58,516,662
1
1
null
2018-10-08T17:47:30
2016-05-11T05:29:01
C++
UTF-8
C++
false
false
3,207
hpp
_assert_macros.hpp
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2021. * * @file _assert_macros.hpp * @brief Helper macros for building proper assert commands. * @note Status: RELEASE * */ #ifndef EMP_ASSERT_MACROS_HPP #define EMP_ASSERT_MACROS_HPP /// Basic elper macros... #define emp_assert_STRINGIFY(...) emp_assert_STRINGIFY_IMPL(__VA_ARGS__) #define emp_assert_STRINGIFY_IMPL(...) #__VA_ARGS__ #define emp_assert_TO_PAIR(X) emp_assert_STRINGIFY(X) , X #define emp_assert_GET_ARG_1(a, ...) a #define emp_assert_GET_ARG_21(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t, u, ...) u #define emp_assert_MERGE(A, B) A ## B #define emp_assert_ASSEMBLE(BASE, ARG_COUNT, ...) emp_assert_MERGE(BASE, ARG_COUNT) (__VA_ARGS__) /// returns the number of arguments in the __VA_ARGS__; cap of 20! #define emp_assert_COUNT_ARGS(...) emp_assert_GET_ARG_21(__VA_ARGS__, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) /// Converts all macro arguments to pairs of arguments with both string names and values. #define emp_assert_TO_PAIRS(...) emp_assert_ASSEMBLE(emp_assert_TO_PAIRS, emp_assert_COUNT_ARGS(__VA_ARGS__), __VA_ARGS__) #define emp_assert_TO_PAIRS1(X) emp_assert_TO_PAIR(X) #define emp_assert_TO_PAIRS2(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS1(__VA_ARGS__) #define emp_assert_TO_PAIRS3(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS2(__VA_ARGS__) #define emp_assert_TO_PAIRS4(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS3(__VA_ARGS__) #define emp_assert_TO_PAIRS5(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS4(__VA_ARGS__) #define emp_assert_TO_PAIRS6(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS5(__VA_ARGS__) #define emp_assert_TO_PAIRS7(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS6(__VA_ARGS__) #define emp_assert_TO_PAIRS8(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS7(__VA_ARGS__) #define emp_assert_TO_PAIRS9(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS8(__VA_ARGS__) #define emp_assert_TO_PAIRS10(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS9(__VA_ARGS__) #define emp_assert_TO_PAIRS11(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS10(__VA_ARGS__) #define emp_assert_TO_PAIRS12(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS11(__VA_ARGS__) #define emp_assert_TO_PAIRS13(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS12(__VA_ARGS__) #define emp_assert_TO_PAIRS14(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS13(__VA_ARGS__) #define emp_assert_TO_PAIRS15(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS14(__VA_ARGS__) #define emp_assert_TO_PAIRS16(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS15(__VA_ARGS__) #define emp_assert_TO_PAIRS17(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS16(__VA_ARGS__) #define emp_assert_TO_PAIRS18(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS17(__VA_ARGS__) #define emp_assert_TO_PAIRS19(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS18(__VA_ARGS__) #define emp_assert_TO_PAIRS20(X, ...) emp_assert_TO_PAIR(X) , emp_assert_TO_PAIRS19(__VA_ARGS__) #endif // #ifdef EMP_ASSERT_MACROS_HPP
66d88392a1e155007d0665306774b332009273b3
02cd7f9dc74a9a5d38759affc34a5001eb27a830
/MapTool/D3D_base/cRay.h
d9abad8a47448ebd337772267b249c6dddf2ddba
[]
no_license
di9208/wow_2
3083a7ab205e4b0ee0dd96bd32e1af4fdfb73f20
9a941b1ed1982570d8bd23d52df6483fc7d6a51a
refs/heads/master
2021-05-03T17:40:36.547556
2018-02-14T13:36:32
2018-02-14T13:36:32
120,443,697
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
cRay.h
#pragma once class cRay { private: SYNTHESIZE(D3DXVECTOR3, m_vPos,Pos); SYNTHESIZE(D3DXVECTOR3 ,m_vDir,Dir); SYNTHESIZE(D3DXVECTOR3, m_vNDir, NDir); float t; float a; public: cRay(); ~cRay(); static cRay RayAtViewSpace(int nScreenX, int nScreenY); static cRay RayAtWorldSpace(int nScreenX, int nScreenY); bool IsPicked(ST_SPHERE* pS); bool IsPicked(D3DXVECTOR3 v0, D3DXVECTOR3 v1, D3DXVECTOR3 v2, D3DXVECTOR3& dis); };
76814822ef18ce56ff069bada29f97e19908b6b5
5c176fb35c7f24229657e78014ad151f0bf49880
/CrazyQueue.cpp
e8dc7423366fc8874667df34a5f8ef02b401e1e3
[]
no_license
YangKai-NEU/algorithms
e3caac49d6e30bdcbe3268ad16e797167a03f5eb
308f0f3434392b294747099626c42b963e0ebfef
refs/heads/master
2021-01-22T07:42:30.083682
2017-09-04T02:55:18
2017-09-04T02:55:18
102,311,499
0
0
null
null
null
null
GB18030
C++
false
false
2,261
cpp
CrazyQueue.cpp
/* 小易老师是非常严厉的,它会要求所有学生在进入教室前都排成一列,并且他要求学生按照身高不递减的顺序排列。有一次,n个学生在列队的时候,小易老师正好去卫生间了。学生们终于有机会反击了,于是学生们决定来一次疯狂的队列,他们定义一个队列的疯狂值为每对相邻排列学生身高差的绝对值总和。由于按照身高顺序排列的队列的疯狂值是最小的,他们当然决定按照疯狂值最大的顺序来进行列队。现在给出n个学生的身高,请计算出这些学生列队的最大可能的疯狂值。小易老师回来一定会气得半死。 输入描述: 输入包括两行,第一行一个整数n(1 ≤ n ≤ 50),表示学生的人数 第二行为n个整数h[i](1 ≤ h[i] ≤ 1000),表示每个学生的身高 输出描述: 输出一个整数,表示n个学生列队可以获得的最大的疯狂值。 如样例所示: 当队列排列顺序是: 25-10-40-5-25, 身高差绝对值的总和为15+30+35+20=100。 这是最大的疯狂值了。 输入例子1: 5 5 10 25 40 25 输出例子1: 100 */ #include <vector> #include <iostream> #include <algorithm> #include <cmath> using namespace std; int maxv(vector<int> &s,int left){ int c=0; for(int i=1;i<s.size();i++){ c+=abs(s[i]-s[i-1]); } if(left==-1){ return c; } int tmp=c+(abs(s[0]-left)<abs(s[s.size()-1]-left)?abs(s[s.size()-1]-left):abs(s[0]-left)); for(int i=1;i<s.size();i++){ int t=c-abs(s[i]-s[i-1])+abs(s[i]-left)+abs(s[i-1]-left); tmp=tmp>t?tmp:t; } return tmp; } int process(vector<int> &s){ vector<int> t; sort(s.begin(),s.end()); while(s.size()>1){ if(s.size()>=2){ if(t.size()==0){ t.push_back(s[0]); t.push_back(s[s.size()-1]); }else{ if(t[0]>t[t.size()-1]){ t.push_back(s[s.size()-1]); t.insert(t.begin(),s[0]); }else{ t.push_back(s[0]); t.insert(t.begin(),s[s.size()-1]); } } s.erase(s.begin()); s.pop_back(); }else{ break; } } if(s.size()==1){ return maxv(t,s[0]); }else{ return maxv(t,-1); } } int main(int argc, char *argv[]) { int n; vector<int> s; cin>>n; for(int i=0;i<n;i++){ int t; cin>>t; s.push_back(t); } cout<<process(s)<<endl; return 0; }
44094675eb90a3da7b7e8e625cef2e761962384f
3765be4ab5d4d7829a22208118b255e2c5cc8251
/task 115.cpp
f42e93cc4a7a745c53c9dcfec03ad4c7a34ff54c
[]
no_license
omirzakye/practice-new-
b84449a1020f63d9123d92781c3a6e1039531460
a40239aca410784e595b5f416a9f952329dc5900
refs/heads/master
2020-09-13T02:06:57.501921
2019-11-22T07:25:01
2019-11-22T07:25:01
222,629,232
0
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
task 115.cpp
#include<iostream> using namespace std; int main() { for(int i=1; i<=10; i++) { for(int j=1; j<=10; j++) { cout<<i<<" * "<<j<<" = "<<i*j<<endl; } cout<<endl; } }
399f27aa77a954cdc2e46ee24c0f9bc59fd4fd62
32c07d976d327888d9eee1365592617ba67c1932
/Item.h
425b4d42aa52b2ade457ef7035e91b7244c3dc4d
[]
no_license
MaxJameson/Takeaway
1843b4bf395e335d0cf0776c8549f9949d8b89da
4eef695109d2c0e07a22d169887a27f71c6d1947
refs/heads/main
2023-03-28T04:28:33.982726
2021-03-25T15:31:16
2021-03-25T15:31:16
351,482,357
0
0
null
null
null
null
UTF-8
C++
false
false
912
h
Item.h
/* ------------------------------------------------------ CMP2801M: Advanced Programming *Title : takeaway *Form : Item.h *Use : Header file for Item class *Creator : Max Jameson *Student ID : 19702735 ------------------------------------------------------ */ #pragma once #include <vector> #include <iostream> using namespace std; class Item { public: //Constructor that creates item Item(vector<string> itemData); //Returns items type string getType(); //Returns items price double getPrice(); //Returns items name string getName(); //returns string of item details virtual string toString(); protected: Item (); //Stores Item type string itemType; //Stores item name string name; //Stores price of iem string price; //Stores Items calories string calories; };
033f63fc6526b4f9497d732ff5cae438fd219974
7f25ac596812ed201f289248de52d8d616d81b93
/haihongS/2016/05/2016_05_14.cpp
ec05a6943c8a55fe0fca3e2339704c08242b4185
[]
no_license
AplusB/ACEveryDay
dc6ff890f9926d328b95ff536abf6510cef57eb7
e958245213dcdba8c7134259a831bde8b3d511bb
refs/heads/master
2021-01-23T22:15:34.946922
2018-04-07T01:45:20
2018-04-07T01:45:20
58,846,919
25
49
null
2016-07-14T10:38:25
2016-05-15T06:08:55
C++
UTF-8
C++
false
false
2,407
cpp
2016_05_14.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; const int maxn=4000009; struct II { int v; int next[26]; } tree[maxn]; char op[20],ans[40]; int loca; int insert_word(); int creat_node(int s); int searchit(); int del(); int main() { int n; while(~scanf("%d",&n)) { loca=1; for(int i=0; i<26; i++) tree[0].next[i]=-1; tree[0].v=0; while(n--) { scanf("%s",op); scanf("%s",ans); if(op[0]=='i') insert_word(); else if(op[0]=='s') { int tmp=searchit(); if(tmp) printf("Yes\n"); else printf("No\n"); } else if(op[0]=='d') del(); /* for(int i=0;i<loca;i++) { printf("%d-%d: ",i,tree[i].v); for(int j=0;j<26;j++) { if(tree[i].next[j]!=-1) printf(" %d",j); } printf("\n"); } */ } } return 0; } int del() { int len=strlen(ans); int p=0; for(int i=0; i<len; i++) { int tmp=ans[i]-'a'; if(tree[p].next[tmp]==-1) return 0; p=tree[p].next[tmp]; } int tmp=tree[p].v; p=0; int last=p; for(int i=0; i<len; i++) { p=tree[p].next[ans[i]-'a']; tree[p].v-=tmp; if(tree[p].v==0) { tree[last].next[ans[i]-'a']=-1;return 0; } last=p; } tree[last].next[ans[len-1]-'a']=-1; return 0; } int searchit() { int len=strlen(ans); int p=0; for(int i=0; i<len; i++) { int tmp=ans[i]-'a'; if(tree[p].next[tmp]==-1) return 0; p=tree[p].next[tmp]; } return 1; } int creat_node(int s) { tree[s].v=0; for(int i=0; i<26; i++) tree[s].next[i]=-1; return 0; } int insert_word() { int len=strlen(ans); int p=0; tree[0].v++; for(int i=0; i<len; i++) { int tmp=ans[i]-'a'; if(tree[p].next[tmp]==-1) { creat_node(loca); tree[p].next[tmp]=loca; p=loca; loca++; } else { p=tree[p].next[tmp]; } tree[p].v++; } return 0; }
338c0c25ddea798347ca59cf4d227cde2bd62fc2
d77d11ece3b3241e7660005a8d499955dcac35b4
/c++/Patterns/Creational/Abstract Factory/Factory2.cpp
61c4a77d42cb0908ffbce7c094f147502a0df763
[]
no_license
dshevchyk/interviewbit
aa8c98159bd66c1589f9f9de7debed2894ed572a
8dcb6362f3927b8795b428811b5e230f0209893c
refs/heads/master
2020-03-23T16:26:06.457563
2018-08-12T11:10:02
2018-08-12T11:10:02
141,809,218
0
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
Factory2.cpp
// // Factory2.cpp // Interviewbit // // Created by Shevchyk Dmytro on 05.08.2018. // Copyright © 2018 Shevchyk Dmytro. All rights reserved. // #include "Factory2.hpp" #include "ConcreteObjectA2.hpp" #include "ConcreteObjectB2.hpp" using std::make_shared; shared_ptr<AbstractObjectA> Factory2::createObjectA() const { return make_shared<ConcreteObjectA2>(); } shared_ptr<AbstractObjectB> Factory2::createObjectB() const { return make_shared<ConcreteObjectB2>(); }
144a9c7e08977d1975d55882060ff7f15cb72f4a
5e4e015bcf88951ae1a15e05fbab3237ec08194e
/program-2-spr19-haydendillon/Scanner.cpp
90bb8a68c6aad2412922a8ee45093a504e402c62
[]
no_license
HaydenRoeder1/CS240-Data-Structures-and-Algorithms-
de0ef068bd6a7f864e56cf2f79ef73ef03363037
e7ab3aaf6d50b016c133e9063f1b22f22d1a9250
refs/heads/master
2020-06-23T20:10:02.270546
2019-07-25T02:26:26
2019-07-25T02:26:26
198,740,407
0
0
null
null
null
null
UTF-8
C++
false
false
861
cpp
Scanner.cpp
#include "Scanner.h" #include <vector> #include "Planet.h" Scanner::Scanner(std::vector<Planet> planetList){ Heap<Planet> h(planetList); planets = h;//? } std::vector<Planet> Scanner::scan(unsigned int num_planets){ if(num_planets > (unsigned int) planets.size()){ num_planets = (unsigned int) planets.size(); } std::vector<Planet> scanned; for(int i = 0; i < num_planets; i++){ Planet curPlanet = planets.getPriority(); double randChange = (rand() % 2); if(randChange == 0){ randChange = -1; }else{ randChange = 1; } if(curPlanet.getProbability() != 0 && curPlanet.getProbability() != 100) curPlanet.refine(randChange); scanned.push_back(curPlanet); } return scanned; } void Scanner::addPlanet(Planet p){ planets.addElement(p); } Heap<Planet> Scanner::getHeap(){ return planets; //? }
15d34d9cc2bdfeb7dc196314a4345ba78d18fb6d
552c39141dab7cbc0c34245000291a46cdb41495
/lte_enb/src/tenb_commonplatform/software/apps/fap/management/oam/led-management/LedBehaviourInterface.h
911eaab02a0ac7f8697533f3445b722dd27bfb4f
[]
no_license
cmjeong/rashmi_oai_epc
a0d6c19d12b292e4da5d34b409c63e3dec28bd20
6ec1784eb786ab6faa4f7c4f1c76cc23438c5b90
refs/heads/master
2021-04-06T01:48:10.060300
2017-08-10T02:04:34
2017-08-10T02:04:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
h
LedBehaviourInterface.h
/////////////////////////////////////////////////////////////////////////////// // // LedBehaviourInterface.h // // Interface for LedBehaviour // // Copyright radisys Limited // /////////////////////////////////////////////////////////////////////////////// #ifndef __LedBehaviourInterface_h_ #define __LedBehaviourInterface_h_ /////////////////////////////////////////////////////////////////////////////// // Local Includes /////////////////////////////////////////////////////////////////////////////// #include <messaging/messages/oam/LedInfo.h> using namespace std; /////////////////////////////////////////////////////////////////////////////// // Functions / Classes /////////////////////////////////////////////////////////////////////////////// /* Following interface exists to future-proof customisation of LED patterns. * It allows decoupling from the MIB. */ //TODO: maybe this interface should be combined with SetLedInterface class LedBehaviourInterface { public: virtual ~LedBehaviourInterface() {}; /* This function loads a default Map of event - pattern * to be used to activate a specific LED behaviour in response of some event * (example: event: location acquired / pattern: location led turn to solid green. * Map contains enabled event types and corresponding patterns */ virtual void LoadDefaultMap(map<LedEvent, LedMap> &) = 0; }; #endif
c4ddb77e575789105ca6f05b1634d555c86f941b
dc0c9ea3fa7498b0552b5f0cdd121489404cb07a
/codeforces/matrix exponentiation contest/F.cpp
a02e515318741860aa6bd3c0e2e37173929b26ec
[]
no_license
alaneos777/club
226e7e86983da7f87d87efbfd47d42326872dd25
47da01e884d6324aa1c9f701d6f70b8b978a0e18
refs/heads/master
2023-08-05T02:43:33.428365
2023-07-29T02:43:58
2023-07-29T02:43:58
143,675,419
2
2
null
null
null
null
UTF-8
C++
false
false
1,106
cpp
F.cpp
#include <bits/stdc++.h> using namespace std; using ld = long double; using lli = int64_t; using vec = vector<lli>; using mat = vector<vec>; const lli inf = numeric_limits<lli>::max(); mat operator*(const mat & a, const mat & b){ int n = a.size(); mat c(n, vec(n, inf)); for(int k = 0; k < n; ++k){ for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ if(a[i][k] != inf && b[k][j] != inf){ c[i][j] = min(c[i][j], a[i][k] + b[k][j]); } } } } return c; } mat power(mat a, lli b){ int n = a.size(); mat ans(n, vec(n, inf)); for(int i = 0; i < n; ++i) ans[i][i] = 0; while(b){ if(b & 1) ans = ans * a; b >>= 1; a = a * a; } return ans; } int main(){ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m; lli k; cin >> n >> m >> k; mat adj(n, vec(n, inf)); while(m--){ int u, v; lli c; cin >> u >> v >> c; adj[u-1][v-1] = c; } adj = power(adj, k); lli ans = inf; for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ ans = min(ans, adj[i][j]); } } if(ans == inf) cout << "IMPOSSIBLE\n"; else cout << ans << "\n"; return 0; }
efb53fc33ad02c652c03145e410231b03bd8890c
8e4837e6b99ab0bb9151b0f4c28281603bfc21b8
/progs/fitLSSTspectra.cc
ac39a158117e2c79b411c3524d515920b1c7003e
[]
no_license
alexabate/DirectSim
d35fb25b092fb72fe30a9c1f7bbcb8bf34a4ca9c
7a58bd5c3e8b05d80cec4c731aeae447bc8842f6
refs/heads/master
2021-01-21T05:00:53.250943
2016-07-01T21:54:35
2016-07-01T21:54:35
8,280,620
1
1
null
null
null
null
UTF-8
C++
false
false
7,676
cc
fitLSSTspectra.cc
#include <iostream> #include <fstream> #include <string> #include <math.h> #include <typeinfo> // sophya libraries //#include "histinit.h" #include "machdefs.h" #include "sopnamsp.h" #include "fiosinit.h" #include "mydefrg.h" #include "hpoly.h" //#include "genericfunc.h" #include "constcosmo.h" #include "cosmocalcs.h" #include "igm.h" #include "mydefrg.h" #include "sedfilter.h" #include "simdata.h" void usage(void); void usage(void) { cout << endl<<" Usage: fitLSSTspectra [...options...]" << endl<<endl; cout << " -o OUTFILEROOT "<<endl; cout << endl; } int main(int narg, char* arg[]) { cout << " ==== fitLSSTspectra.cc program ==== "<<endl; // make sure SOPHYA modules are initialized SophyaInit(); FitsIOServerInit(); cout<<endl<<endl; //--- decoding command line arguments string outfileroot = "output/fitLSSTspectra"; //--- decoding command line arguments cout << " ==== decoding command line arguments ===="<<endl; char c; while((c = getopt(narg,arg,"ho:")) != -1) { switch (c) { case 'o' : outfileroot = optarg; outfileroot = "output/" + outfileroot; break; case 'h' : default : usage(); return -1; } } //-- end command line arguments cout << " Output to be written to files beginning "<< outfileroot <<endl; cout << endl; int rc = 1; try { // exception handling try bloc at top level ifstream inp; ofstream outp; string outfile; cout <<" Reading in SED libraries "<<endl; string sedFile; // Wavelength range and resolution of SEDs double lmin=1e-7, lmax=1e-6; int nl=3000; double dl = (lmax - lmin)/(nl -1); // Load in CWWK SEDs sedFile = "CWWKSB.list"; ReadSedList readCWWK(sedFile); readCWWK.readSeds(lmin,lmax); vector<SED*> sedCWWK=readCWWK.getSedArray(); string sedLoc = readCWWK.getSedDirEnviromentVar(); vector<string> sedFilenames=readCWWK.returnSedFilenames(); int nCWWK = readCWWK.getNSed(); cout << " "<< nCWWK <<" CWWK seds "<<endl; // Load in LSST SEDs sedFile = "LSST.list"; ReadSedList readLSST(sedFile); readLSST.readSeds(lmin,lmax); vector<SED*> sedLSST=readLSST.getSedArray(); int nLSST = readLSST.getNSed(); cout << " "<< nLSST <<" LSST seds "<<endl; cout << endl; // Find normalization values of the SEDs double lamNorm = 5500e-10; cout << " Normalizing spectra to 1 at "<< lamNorm*1e10 <<" angstroms "<<endl; vector<double> normCWWK; for (int i=0; i<nCWWK; i++) { double val = sedCWWK[i]->returnFlux(lamNorm); normCWWK.push_back(val); } vector<double> normLSST; for (int i=0; i<nLSST; i++) { double val = sedLSST[i]->returnFlux(lamNorm); normLSST.push_back(val); } cout << endl; // Open file to write to outfile = outfileroot + "_fitvalues.txt"; outp.open(outfile.c_str()); // Fit SEDs to each other vector<int> bestFitSpectra; for (int i=0; i<nLSST; i++) { // loop over LSST SEDs cout <<" On LSST sed "<< i+1 <<" of "<< nLSST; vector<double> fitValues; for (int j=0; j<nCWWK; j++) { // for each CWWKSB SED double sum = 0; for (int il=0; il<nl; il++) { double lam = lmin + il*dl; double sCWWK = (sedCWWK[j]->returnFlux(lam))/normCWWK[j]; double sLSST = (sedLSST[i]->returnFlux(lam))/normLSST[i]; sum += (sCWWK-sLSST)*(sCWWK-sLSST); // Chi-square type fit } fitValues.push_back(sum); } for (int j=0; j<nCWWK; j++) outp << fitValues[j] <<" "; outp << endl; // find CWWKSB SED with smallest chi-square value (this is the best fit!) int iElement; findMinimumPosition(fitValues, iElement); bestFitSpectra.push_back(iElement); cout <<", best fit CWWK spectrum: "<< iElement <<endl; } outp.close(); cout << endl; double eps = 1e-6; TArray<double> newSEDs; sa_size_t ndim = 2; sa_size_t mydim[ndim]; mydim[0] = nl; mydim[1] = nCWWK + 1; newSEDs.SetSize(ndim,mydim); outfile = outfileroot + "_newSEDs.txt"; outp.open(outfile.c_str()); for (int il=0; il<nl; il++) { double lam = lmin + il*dl; outp << lam <<" "; newSEDs(il,0) = lam; int cntTot = 0; for (int i=0; i<nCWWK; i++) { // loop over each CWWKSB SED int iWant = i; int cnt = 0; double sumSEDvals = 0, sumSEDvalsSq = 0; for (int j=0; j<nLSST; j++) { int iValue = bestFitSpectra[j]; // Find all LSST SEDs that had this CWWKSB SED as the best fit, // and average them together if ( abs(iWant - iValue)<eps ) { double val = (sedLSST[j]->returnFlux(lam)); sumSEDvals += val; sumSEDvalsSq += val*val; cnt++; } } //cout <<" "<< cnt <<" LSST spectra have a best-fit CWWK = "<<iWant<<endl; cntTot += cnt; double sedVal = sumSEDvals/cnt; double sedVar = sumSEDvalsSq/cnt - sedVal*sedVal; outp << sedVal <<" "<< sedVar << " "; newSEDs(il,i+1) = sedVal; }// end loop over CWWK SEDs outp << endl; if (cntTot!=nLSST) throw ParmError("ERROR! best-fit SED numbers don't add up"); }// end loop over wavelengths outp.close(); cout << endl; // Write these new spectra to files cout <<" Writing the new spectra to files: "<<endl; for (int i=0; i<nCWWK; i++) { outfile = sedLoc+"/"+sedFilenames[i]+".lsst"; cout <<" "<<outfile<<endl; outp.open(outfile.c_str()); for (int il=0; il<nl; il++) outp << newSEDs(il,0) <<" "<<newSEDs(il,i+1) << endl; outp.close(); } cout << endl; // Write these new spectra to files cout <<" Writing the new spectra to files BPZ style: "<<endl; cout <<" (wavelength is in angstroms and filename ends in .sed)"<<endl; for (int i=0; i<nCWWK; i++) { outfile = sedLoc+"/"+sedFilenames[i]+".lsst.sed"; cout <<" "<<outfile<<endl; outp.open(outfile.c_str()); for (int il=0; il<nl; il++) outp << newSEDs(il,0)*1e10 <<" "<<newSEDs(il,i+1) << endl; outp.close(); } cout << endl; outfile = sedLoc+"/LSSTshort.list"; cout <<" Writing a new spectra list file "<< outfile << endl; outp.open(outfile.c_str()); for (int i=0; i<nCWWK; i++) outp << sedFilenames[i]+".lsst" << endl; outp.close(); cout << endl; } // End of try bloc catch (PThrowable & exc) { // catching SOPHYA exceptions cerr << " fitLSSTspectra.cc: Catched Exception (PThrowable)" << (string)typeid(exc).name() << "\n...exc.Msg= " << exc.Msg() << endl; rc = 99; } catch (std::exception & e) { // catching standard C++ exceptions cerr << " fitLSSTspectra.cc: Catched std::exception " << " - what()= " << e.what() << endl; rc = 98; } catch (...) { // catching other exceptions cerr << " fitLSSTspectra.cc: some other exception (...) was caught ! " << endl; rc = 97; } cout << " ==== End of fitLSSTspectra.cc program Rc= " << rc << endl; return rc; }
5cd1453dc35de0f978d472e89794738d2df3667f
0d037ab7b4d6138e0da6006b535d3d5bbf502bb6
/src/Vertex.cpp
9c0b946ce798cc18850363a5f0358f83289b8fd9
[]
no_license
Solek798/GeometryEngine
a394bac19d2a7af8101ea814a76eaee016c27c64
414019b6f443341e15cd0deed6188ea779f529f4
refs/heads/master
2022-11-05T20:21:13.099875
2020-06-19T14:43:40
2020-06-19T14:43:40
269,660,758
1
0
null
null
null
null
UTF-8
C++
false
false
1,247
cpp
Vertex.cpp
// // Created by felix on 10.06.20. // #include "Vertex.h" geo::Vertex::Vertex() : position(0, 0) { } geo::Vertex::Vertex(glm::vec2 position, glm::vec2 uv) : position(position) , uv(uv) { } geo::Vertex::Vertex(float x, float y, float u, float v) : position(x, y) , uv(u, v) { } VkVertexInputBindingDescription geo::Vertex::getInputBindingDescription() { VkVertexInputBindingDescription inputBindingDescription; inputBindingDescription.binding = 0; inputBindingDescription.stride = sizeof(Vertex); inputBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return inputBindingDescription; } const sp<std::vector<VkVertexInputAttributeDescription>> geo::Vertex::getInputAttributeDescription() { auto descriptions = std::make_shared<std::vector<VkVertexInputAttributeDescription>>(2); descriptions->at(0).location = 0; descriptions->at(0).binding = 0; descriptions->at(0).format = VK_FORMAT_R32G32_SFLOAT; descriptions->at(0).offset = offsetof(Vertex, position); descriptions->at(1).location = 1; descriptions->at(1).binding = 0; descriptions->at(1).format = VK_FORMAT_R32G32_SFLOAT; descriptions->at(1).offset = offsetof(Vertex, uv); return descriptions; }
8d51be1aa126042f3703ad3329a941d1bbf55c27
91c8570f4499a17fb2de5048c66060fc1fc4bfcf
/leetcodeInXcode/Solution/Trapping Rain Water.h
79db580d6425941ec3571428b728fc23f44381b4
[ "MIT" ]
permissive
thats2ez/leetcode-in-Xcode
7b47d2b1e56dc5a6c03f058dcf3ac6484df2f9bc
6a9cd577276908d1186002d8c365ad2fe84347f0
refs/heads/master
2016-09-06T13:26:01.523326
2015-08-21T06:34:02
2015-08-21T06:34:02
25,959,127
1
1
null
null
null
null
UTF-8
C++
false
false
837
h
Trapping Rain Water.h
// // Trapping Rain Water.h // leetcodeInXcode // // Created by Kaiqi on 2/14/15. // Copyright (c) 2015 edu.self. All rights reserved. // class Solution { public: int trap(int A[], int n) { if (n == 0) return 0; // search for highest bar int high = 0; for (int i = 0; i < n; i++) { if (A[i] > A[high]) { high = i; } } int water = 0; // left part int left_high = 0; for (int i = 0; i < high; i++) { left_high = max(left_high, A[i]); water += left_high - A[i]; } // right part int right_high = 0; for (int i = n - 1; i > high; i--) { right_high = max(right_high, A[i]); water += right_high - A[i]; } return water; } };
f38fc0537043c7933a383ff43e135509eb8877b3
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/content/renderer/media/stream/media_stream_constraints_util_audio.cc
e5d1dd41c418f8273c615c1bca622e80c89fed12
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
34,469
cc
media_stream_constraints_util_audio.cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/stream/media_stream_constraints_util_audio.h" #include <algorithm> #include <cmath> #include <tuple> #include <utility> #include <vector> #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "content/common/media/media_stream_controls.h" #include "content/public/common/content_features.h" #include "content/renderer/media/stream/media_stream_audio_source.h" #include "content/renderer/media/stream/media_stream_constraints_util.h" #include "content/renderer/media/stream/media_stream_constraints_util_sets.h" #include "content/renderer/media/stream/media_stream_video_source.h" #include "content/renderer/media/stream/processed_local_audio_source.h" #include "media/audio/audio_features.h" #include "media/base/audio_parameters.h" #include "media/base/limits.h" #include "third_party/blink/public/platform/web_media_constraints.h" #include "third_party/blink/public/platform/web_string.h" namespace content { using EchoCancellationType = AudioProcessingProperties::EchoCancellationType; using ConstraintSet = blink::WebMediaTrackConstraintSet; using StringConstraint = blink::StringConstraint; using BooleanConstraint = blink::BooleanConstraint; namespace { template <class T> using DiscreteSet = media_constraints::DiscreteSet<T>; // The presence of a MediaStreamAudioSource object indicates whether the source // in question is currently in use, or not. This convenience enum helps identify // whether a source is available and if so whether has audio processing enabled // or disabled. enum class SourceType { kNoSource, kUnprocessedSource, kProcessedSource }; // This class encapsulates two values that together build up the score of each // processed candidate. // - Fitness, similarly defined by the W3C specification // (https://w3c.github.io/mediacapture-main/#dfn-fitness-distance); // - Distance from the default device ID. // // Differently from the definition in the W3C specification, the present // algorithm maximizes the score. struct Score { public: explicit Score(double fitness, bool is_default_device_id = false) { score = std::make_tuple(fitness, is_default_device_id); } bool operator<(const Score& other) const { return score < other.score; } Score& operator+=(const Score& other) { std::get<0>(score) += std::get<0>(other.score); std::get<1>(score) |= std::get<1>(other.score); return *this; } std::tuple<double, bool> score; }; // Selects the best value from the nonempty |set|, subject to |constraint|. The // only decision criteria is equality to |constraint.Ideal()|. If there is no // single best value in |set|, returns nullopt. base::Optional<bool> SelectOptionalBool( const DiscreteSet<bool>& set, const blink::BooleanConstraint& constraint) { DCHECK(!set.IsEmpty()); if (constraint.HasIdeal() && set.Contains(constraint.Ideal())) return constraint.Ideal(); if (set.is_universal()) return base::Optional<bool>(); DCHECK_EQ(set.elements().size(), 1U); return set.FirstElement(); } // Container for each independent boolean constrainable property. class BooleanContainer { public: BooleanContainer(DiscreteSet<bool> allowed_values = DiscreteSet<bool>()) : allowed_values_(std::move(allowed_values)) {} const char* ApplyConstraintSet(const BooleanConstraint& constraint) { allowed_values_ = allowed_values_.Intersection( media_constraints::BoolSetFromConstraint(constraint)); return allowed_values_.IsEmpty() ? constraint.GetName() : nullptr; } std::tuple<double, bool> SelectSettingsAndScore( const BooleanConstraint& constraint, bool default_setting) const { DCHECK(!IsEmpty()); if (constraint.HasIdeal() && allowed_values_.Contains(constraint.Ideal())) return std::make_tuple(1.0, constraint.Ideal()); if (allowed_values_.is_universal()) return std::make_tuple(0.0, default_setting); DCHECK_EQ(allowed_values_.elements().size(), 1U); return std::make_tuple(0.0, allowed_values_.FirstElement()); } bool IsEmpty() const { return allowed_values_.IsEmpty(); } private: DiscreteSet<bool> allowed_values_; }; // Container for each independent string constrainable property. class StringContainer { public: explicit StringContainer( DiscreteSet<std::string> allowed_values = DiscreteSet<std::string>()) : allowed_values_(std::move(allowed_values)) {} const char* ApplyConstraintSet(const StringConstraint& constraint) { allowed_values_ = allowed_values_.Intersection( media_constraints::StringSetFromConstraint(constraint)); return allowed_values_.IsEmpty() ? constraint.GetName() : nullptr; } // Selects the best value from the nonempty |allowed_values_|, subject to // |constraint_set.*constraint_member_| and determines the associated fitness. // The first selection criteria is inclusion in the constraint's ideal value, // followed by equality to |default_value|. There is always a single best // value. std::tuple<double, std::string> SelectSettingsAndScore( const StringConstraint& constraint, std::string default_setting) const { DCHECK(!IsEmpty()); if (constraint.HasIdeal()) { for (const blink::WebString& ideal_candidate : constraint.Ideal()) { std::string candidate = ideal_candidate.Utf8(); if (allowed_values_.Contains(candidate)) return std::make_tuple(1.0, candidate); } } std::string setting = allowed_values_.Contains(default_setting) ? default_setting : allowed_values_.FirstElement(); return std::make_tuple(0.0, setting); } bool IsEmpty() const { return allowed_values_.IsEmpty(); } private: DiscreteSet<std::string> allowed_values_; }; // Container to manage the properties related to echo cancellation: // echoCancellation, googEchoCancellation and echoCancellationType. class EchoCancellationContainer { public: EchoCancellationContainer(SourceType source_type, bool is_device_capture, media::AudioParameters parameters, AudioProcessingProperties properties) : parameters_(parameters), is_device_capture_(is_device_capture) { if (source_type == SourceType::kNoSource) { ec_type_allowed_values_ = GetEchoCancellationTypesFromParameters(parameters); return; } ec_allowed_values_ = DiscreteSet<bool>({IsEchoCancellationEnabled( properties, parameters.effects(), source_type == SourceType::kProcessedSource)}); goog_ec_allowed_values_ = ec_allowed_values_; auto type = ToBlinkEchoCancellationType(properties.echo_cancellation_type); ec_type_allowed_values_ = type ? DiscreteSet<std::string>({*type}) : DiscreteSet<std::string>(); } const char* ApplyConstraintSet(const ConstraintSet& constraint_set) { ec_allowed_values_ = ec_allowed_values_.Intersection( media_constraints::BoolSetFromConstraint( constraint_set.echo_cancellation)); if (ec_allowed_values_.IsEmpty()) return constraint_set.echo_cancellation.GetName(); goog_ec_allowed_values_ = goog_ec_allowed_values_.Intersection( media_constraints::BoolSetFromConstraint( constraint_set.goog_echo_cancellation)); if (goog_ec_allowed_values_.IsEmpty()) return constraint_set.goog_echo_cancellation.GetName(); // Make sure that the results from googEchoCancellation and echoCancellation // constraints do not contradict each other. auto ec_intersection = ec_allowed_values_.Intersection(goog_ec_allowed_values_); if (ec_intersection.IsEmpty()) return constraint_set.echo_cancellation.GetName(); ec_type_allowed_values_ = ec_type_allowed_values_.Intersection( media_constraints::StringSetFromConstraint( constraint_set.echo_cancellation_type)); if (ec_type_allowed_values_.IsEmpty()) return constraint_set.echo_cancellation_type.GetName(); // If the echoCancellation constraint is not true, the type set should not // have explicit elements, otherwise the two constraints would contradict // each other. if (!ec_allowed_values_.Contains(true) && constraint_set.echo_cancellation_type.HasExact()) { return constraint_set.echo_cancellation_type.GetName(); } return nullptr; } std::tuple<double, EchoCancellationType> SelectSettingsAndScore( const ConstraintSet& constraint_set) const { DCHECK(!IsEmpty()); double fitness = 0.0; EchoCancellationType echo_cancellation_type = EchoCancellationType::kEchoCancellationDisabled; if (ShouldUseEchoCancellation(constraint_set.echo_cancellation, constraint_set.goog_echo_cancellation)) { std::tie(echo_cancellation_type, fitness) = SelectEchoCancellationTypeAndFitness( constraint_set.echo_cancellation_type); } return std::make_tuple(fitness, echo_cancellation_type); } bool IsEmpty() const { return ec_allowed_values_.IsEmpty() || goog_ec_allowed_values_.IsEmpty() || ec_type_allowed_values_.IsEmpty(); } // Audio-processing properties are disabled by default for content capture, // or if the |echo_cancellation| constraint is false. void UpdateDefaultValues( const BooleanConstraint& echo_cancellation_constraint, AudioProcessingProperties* properties) const { auto echo_cancellation = SelectOptionalBool(ec_allowed_values_, echo_cancellation_constraint); bool default_audio_processing_value = true; if (!is_device_capture_ || (echo_cancellation && !*echo_cancellation)) default_audio_processing_value = false; properties->goog_audio_mirroring &= default_audio_processing_value; properties->goog_auto_gain_control &= default_audio_processing_value; properties->goog_experimental_echo_cancellation &= default_audio_processing_value; properties->goog_typing_noise_detection &= default_audio_processing_value; properties->goog_noise_suppression &= default_audio_processing_value; properties->goog_experimental_noise_suppression &= default_audio_processing_value; properties->goog_highpass_filter &= default_audio_processing_value; properties->goog_experimental_auto_gain_control &= default_audio_processing_value; } private: static DiscreteSet<std::string> GetEchoCancellationTypesFromParameters( const media::AudioParameters& audio_parameters) { #if defined(OS_MACOSX) || defined(OS_CHROMEOS) // If force system echo cancellation feature is enabled: only expose that // type if available, otherwise expose no type. if (base::FeatureList::IsEnabled(features::kForceEnableSystemAec)) { std::vector<std::string> types; if (audio_parameters.effects() & (media::AudioParameters::EXPERIMENTAL_ECHO_CANCELLER | media::AudioParameters::ECHO_CANCELLER)) { types.push_back(blink::kEchoCancellationTypeSystem); } return DiscreteSet<std::string>(types); } #endif // defined(OS_MACOSX) || defined(OS_CHROMEOS) // The browser and AEC3 echo cancellers are always available. std::vector<std::string> types = {blink::kEchoCancellationTypeBrowser, blink::kEchoCancellationTypeAec3}; if (audio_parameters.effects() & (media::AudioParameters::EXPERIMENTAL_ECHO_CANCELLER | media::AudioParameters::ECHO_CANCELLER)) { // If the system/hardware supports echo cancellation, add it to the set. types.push_back(blink::kEchoCancellationTypeSystem); } return DiscreteSet<std::string>(types); } static bool IsEchoCancellationEnabled( const AudioProcessingProperties& properties, int effects, bool is_processed) { const bool system_echo_cancellation_available = (properties.echo_cancellation_type == EchoCancellationType::kEchoCancellationSystem || !is_processed) && effects & media::AudioParameters::ECHO_CANCELLER; const bool experimental_system_cancellation_available = properties.echo_cancellation_type == EchoCancellationType::kEchoCancellationSystem && effects & media::AudioParameters::EXPERIMENTAL_ECHO_CANCELLER; return properties.EchoCancellationIsWebRtcProvided() || system_echo_cancellation_available || experimental_system_cancellation_available; } bool ShouldUseEchoCancellation( const BooleanConstraint& echo_cancellation_constraint, const BooleanConstraint& goog_echo_cancellation_constraint) const { base::Optional<bool> ec = SelectOptionalBool(ec_allowed_values_, echo_cancellation_constraint); base::Optional<bool> goog_ec = SelectOptionalBool( goog_ec_allowed_values_, goog_echo_cancellation_constraint); if (ec) return *ec; if (goog_ec) return *goog_ec; // Echo cancellation is enabled by default for device capture and disabled // by default for content capture. return is_device_capture_; } std::tuple<EchoCancellationType, double> SelectEchoCancellationTypeAndFitness( const blink::StringConstraint& echo_cancellation_type) const { double fitness = 0.0; // Try to use an ideal candidate, if supplied. base::Optional<std::string> selected_type; if (echo_cancellation_type.HasIdeal()) { for (const auto& ideal : echo_cancellation_type.Ideal()) { std::string candidate = ideal.Utf8(); if (ec_type_allowed_values_.Contains(candidate)) { selected_type = candidate; fitness = 1.0; break; } } } // If no ideal, or none that worked, and the set contains only one value, // pick that. if (!selected_type) { if (!ec_type_allowed_values_.is_universal() && ec_type_allowed_values_.elements().size() == 1) { selected_type = ec_type_allowed_values_.FirstElement(); } } // Return type based on the selected type. if (selected_type == blink::kEchoCancellationTypeBrowser) { return std::make_tuple(EchoCancellationType::kEchoCancellationAec2, fitness); } else if (selected_type == blink::kEchoCancellationTypeAec3) { return std::make_tuple(EchoCancellationType::kEchoCancellationAec3, fitness); } else if (selected_type == blink::kEchoCancellationTypeSystem) { return std::make_tuple(EchoCancellationType::kEchoCancellationSystem, fitness); } // If no type has been selected, choose system if the device has the // ECHO_CANCELLER flag set. Never automatically enable an experimental // system echo canceller. if (parameters_.IsValid() && parameters_.effects() & media::AudioParameters::ECHO_CANCELLER) { return std::make_tuple(EchoCancellationType::kEchoCancellationSystem, fitness); } // Finally, choose the browser provided AEC2 or AEC3 based on an optional // override setting for AEC3 or feature. // In unit tests not creating a message filter, |aec_dump_message_filter| // will be null. We can just ignore that. Other unit tests and browser tests // ensure that we do get the filter when we should. base::Optional<bool> override_aec3; scoped_refptr<AecDumpMessageFilter> aec_dump_message_filter = AecDumpMessageFilter::Get(); if (aec_dump_message_filter) override_aec3 = aec_dump_message_filter->GetOverrideAec3(); const bool use_aec3 = override_aec3.value_or( base::FeatureList::IsEnabled(features::kWebRtcUseEchoCanceller3)); auto ec_type = use_aec3 ? EchoCancellationType::kEchoCancellationAec3 : EchoCancellationType::kEchoCancellationAec2; return std::make_tuple(ec_type, fitness); } base::Optional<std::string> ToBlinkEchoCancellationType( EchoCancellationType type) const { switch (type) { case EchoCancellationType::kEchoCancellationAec2: return blink::kEchoCancellationTypeBrowser; case EchoCancellationType::kEchoCancellationAec3: return blink::kEchoCancellationTypeAec3; case EchoCancellationType::kEchoCancellationSystem: return blink::kEchoCancellationTypeSystem; case EchoCancellationType::kEchoCancellationDisabled: return base::nullopt; } } DiscreteSet<bool> ec_allowed_values_; DiscreteSet<bool> goog_ec_allowed_values_; DiscreteSet<std::string> ec_type_allowed_values_; media::AudioParameters parameters_; bool is_device_capture_; }; // Container for the constrainable properties of a single audio device. class DeviceContainer { public: DeviceContainer(const AudioDeviceCaptureCapability& capability, bool is_device_capture) : parameters_(capability.Parameters()) { if (!capability.DeviceID().empty()) device_id_container_ = StringContainer(DiscreteSet<std::string>({capability.DeviceID()})); if (!capability.GroupID().empty()) group_id_container_ = StringContainer(DiscreteSet<std::string>({capability.GroupID()})); // If the device is in use, a source will be provided and all containers // must be initialized such that their only supported values correspond to // the source settings. Otherwise, the containers are initialized to contain // all possible values. SourceType source_type; AudioProcessingProperties properties; std::tie(source_type, properties) = InfoFromSource(capability.source()); echo_cancellation_container_ = EchoCancellationContainer( source_type, is_device_capture, parameters_, properties); if (source_type == SourceType::kNoSource) return; MediaStreamAudioSource* source = capability.source(); boolean_containers_[kHotwordEnabled] = BooleanContainer(DiscreteSet<bool>({source->hotword_enabled()})); boolean_containers_[kDisableLocalEcho] = BooleanContainer(DiscreteSet<bool>({source->disable_local_echo()})); boolean_containers_[kRenderToAssociatedSink] = BooleanContainer( DiscreteSet<bool>({source->RenderToAssociatedSinkEnabled()})); for (size_t i = kGoogAudioMirroring; i < kNumBooleanContainerIds; ++i) { auto& info = kBooleanPropertyContainerInfoMap[i]; boolean_containers_[info.index] = BooleanContainer( DiscreteSet<bool>({properties.*(info.property_member)})); } DCHECK(echo_cancellation_container_ != base::nullopt); DCHECK_EQ(boolean_containers_.size(), kNumBooleanContainerIds); #if DCHECK_IS_ON() for (const auto& container : boolean_containers_) DCHECK(!container.IsEmpty()); #endif } const char* ApplyConstraintSet(const ConstraintSet& constraint_set) { const char* failed_constraint_name; failed_constraint_name = device_id_container_.ApplyConstraintSet(constraint_set.device_id); if (failed_constraint_name != nullptr) return failed_constraint_name; failed_constraint_name = group_id_container_.ApplyConstraintSet(constraint_set.group_id); if (failed_constraint_name != nullptr) return failed_constraint_name; for (size_t i = 0; i < kNumBooleanContainerIds; ++i) { auto& info = kBooleanPropertyContainerInfoMap[i]; failed_constraint_name = boolean_containers_[info.index].ApplyConstraintSet( constraint_set.*(info.constraint_member)); if (failed_constraint_name != nullptr) return failed_constraint_name; } failed_constraint_name = echo_cancellation_container_->ApplyConstraintSet(constraint_set); if (failed_constraint_name != nullptr) return failed_constraint_name; return nullptr; } std::tuple<double, AudioCaptureSettings> SelectSettingsAndScore( const ConstraintSet& constraint_set, bool is_destkop_source, bool should_disable_hardware_noise_suppression, std::string default_device_id) const { DCHECK(!IsEmpty()); double score = 0.0; double sub_score = 0.0; std::string device_id; std::tie(sub_score, device_id) = device_id_container_.SelectSettingsAndScore(constraint_set.device_id, default_device_id); score += sub_score; std::tie(sub_score, std::ignore) = group_id_container_.SelectSettingsAndScore(constraint_set.group_id, std::string()); score += sub_score; bool hotword_enabled; std::tie(sub_score, hotword_enabled) = boolean_containers_[kHotwordEnabled].SelectSettingsAndScore( constraint_set.hotword_enabled, false); score += sub_score; bool disable_local_echo; std::tie(sub_score, disable_local_echo) = boolean_containers_[kDisableLocalEcho].SelectSettingsAndScore( constraint_set.disable_local_echo, !is_destkop_source); score += sub_score; bool render_to_associated_sink; std::tie(sub_score, render_to_associated_sink) = boolean_containers_[kRenderToAssociatedSink].SelectSettingsAndScore( constraint_set.render_to_associated_sink, false); score += sub_score; AudioProcessingProperties properties; std::tie(sub_score, properties.echo_cancellation_type) = echo_cancellation_container_->SelectSettingsAndScore(constraint_set); score += sub_score; // NOTE: audio-processing properties are disabled by default for content // capture, or if the |echo_cancellation| constraint is false. This function // call updates the default settings for such properties according to the // value obtained for the echo cancellation property. echo_cancellation_container_->UpdateDefaultValues( constraint_set.echo_cancellation, &properties); for (size_t i = kGoogAudioMirroring; i < kNumBooleanContainerIds; ++i) { auto& info = kBooleanPropertyContainerInfoMap[i]; std::tie(sub_score, properties.*(info.property_member)) = boolean_containers_[info.index].SelectSettingsAndScore( constraint_set.*(info.constraint_member), properties.*(info.property_member)); score += sub_score; } // NOTE: this is a special case required to support for conditional // constraint for echo cancellation type based on an experiment. properties.disable_hw_noise_suppression = should_disable_hardware_noise_suppression && properties.echo_cancellation_type == EchoCancellationType::kEchoCancellationDisabled; // The score at this point can be considered complete only when the settings // are compared against the default device id, which is used as arbitrator // in case multiple candidates are available. return std::make_tuple( score, AudioCaptureSettings(device_id, hotword_enabled, disable_local_echo, render_to_associated_sink, properties)); } // The DeviceContainer is considered empty if at least one of the // containers owned is empty. bool IsEmpty() const { DCHECK(!boolean_containers_.empty()); for (auto& container : boolean_containers_) { if (container.IsEmpty()) return true; } return device_id_container_.IsEmpty() || group_id_container_.IsEmpty() || echo_cancellation_container_->IsEmpty(); } std::tuple<SourceType, AudioProcessingProperties> InfoFromSource( MediaStreamAudioSource* source) { AudioProcessingProperties properties; SourceType source_type; ProcessedLocalAudioSource* processed_source = ProcessedLocalAudioSource::From(source); if (source == nullptr) { source_type = SourceType::kNoSource; } else if (processed_source == nullptr) { source_type = SourceType::kUnprocessedSource; properties.DisableDefaultProperties(); } else { source_type = SourceType::kProcessedSource; properties = processed_source->audio_processing_properties(); } return std::make_tuple(source_type, properties); } private: enum StringContainerId { kDeviceId, kGroupId, kNumStringContainerIds }; enum BooleanContainerId { kHotwordEnabled, kDisableLocalEcho, kRenderToAssociatedSink, // Audio processing properties indexes. kGoogAudioMirroring, kGoogAutoGainControl, kGoogExperimentalEchoCancellation, kGoogTypingNoiseDetection, kGoogNoiseSuppression, kGoogExperimentalNoiseSuppression, kGoogHighpassFilter, kGoogExperimentalAutoGainControl, kNumBooleanContainerIds }; // This struct groups related fields or entries from // AudioProcessingProperties, // SingleDeviceCandidateSet::bool_sets_ and blink::WebMediaTrackConstraintSet. struct BooleanPropertyContainerInfo { BooleanContainerId index; BooleanConstraint ConstraintSet::*constraint_member; bool AudioProcessingProperties::*property_member; }; static constexpr BooleanPropertyContainerInfo kBooleanPropertyContainerInfoMap[] = { {kHotwordEnabled, &ConstraintSet::hotword_enabled, nullptr}, {kDisableLocalEcho, &ConstraintSet::disable_local_echo, nullptr}, {kRenderToAssociatedSink, &ConstraintSet::render_to_associated_sink, nullptr}, {kGoogAudioMirroring, &ConstraintSet::goog_audio_mirroring, &AudioProcessingProperties::goog_audio_mirroring}, {kGoogAutoGainControl, &ConstraintSet::goog_auto_gain_control, &AudioProcessingProperties::goog_auto_gain_control}, {kGoogExperimentalEchoCancellation, &ConstraintSet::goog_experimental_echo_cancellation, &AudioProcessingProperties::goog_experimental_echo_cancellation}, {kGoogTypingNoiseDetection, &ConstraintSet::goog_typing_noise_detection, &AudioProcessingProperties::goog_typing_noise_detection}, {kGoogNoiseSuppression, &ConstraintSet::goog_noise_suppression, &AudioProcessingProperties::goog_noise_suppression}, {kGoogExperimentalNoiseSuppression, &ConstraintSet::goog_experimental_noise_suppression, &AudioProcessingProperties::goog_experimental_noise_suppression}, {kGoogHighpassFilter, &ConstraintSet::goog_highpass_filter, &AudioProcessingProperties::goog_highpass_filter}, {kGoogExperimentalAutoGainControl, &ConstraintSet::goog_experimental_auto_gain_control, &AudioProcessingProperties::goog_experimental_auto_gain_control}}; media::AudioParameters parameters_; StringContainer device_id_container_; StringContainer group_id_container_; std::array<BooleanContainer, kNumBooleanContainerIds> boolean_containers_; base::Optional<EchoCancellationContainer> echo_cancellation_container_; }; constexpr DeviceContainer::BooleanPropertyContainerInfo DeviceContainer::kBooleanPropertyContainerInfoMap[]; // This class represents a set of possible candidate settings. The // SelectSettings algorithm starts with a set containing all possible candidates // based on system/hardware capabilities and/or allowed values for supported // properties. The set is then reduced progressively as the basic and advanced // constraint sets are applied. In the end, if the set of candidates is empty, // SelectSettings fails. If not, the ideal values (if any) or tie breaker rules // are used to select the final settings based on the candidates that survived // the application of the constraint sets. This class is implemented as a // collection of more specific sets for the various supported properties. If any // of the specific sets is empty, the whole CandidatesContainer is considered // empty as well. class CandidatesContainer { public: CandidatesContainer(const AudioDeviceCaptureCapabilities& capabilities, std::string& media_stream_source, std::string& default_device_id) : default_device_id_(default_device_id) { for (const auto& capability : capabilities) { DeviceContainer device(capability, media_stream_source.empty()); if (!device.IsEmpty()) devices_.push_back(std::move(device)); } } const char* ApplyConstraintSet(const ConstraintSet& constraint_set) { const char* latest_failed_constraint_name = nullptr; for (auto it = devices_.begin(); it != devices_.end();) { DCHECK(!it->IsEmpty()); auto* failed_constraint_name = it->ApplyConstraintSet(constraint_set); if (failed_constraint_name) { latest_failed_constraint_name = failed_constraint_name; devices_.erase(it); } else { ++it; } } return IsEmpty() ? latest_failed_constraint_name : nullptr; } std::tuple<Score, AudioCaptureSettings> SelectSettingsAndScore( const ConstraintSet& constraint_set, bool is_desktop_source, bool should_disable_hardware_noise_suppression) const { DCHECK(!IsEmpty()); // Make a copy of the settings initially provided, to track the default // settings. AudioCaptureSettings best_settings; Score best_score(-1.0); for (const auto& candidate : devices_) { double fitness; AudioCaptureSettings settings; std::tie(fitness, settings) = candidate.SelectSettingsAndScore( constraint_set, is_desktop_source, should_disable_hardware_noise_suppression, default_device_id_); Score score(fitness, default_device_id_ == settings.device_id()); if (best_score < score) { best_score = score; best_settings = std::move(settings); } } return std::make_tuple(best_score, best_settings); } bool IsEmpty() const { return devices_.empty(); } private: std::string default_device_id_; std::vector<DeviceContainer> devices_; }; } // namespace AudioDeviceCaptureCapability::AudioDeviceCaptureCapability() : parameters_(media::AudioParameters::UnavailableDeviceParams()) {} AudioDeviceCaptureCapability::AudioDeviceCaptureCapability( MediaStreamAudioSource* source) : source_(source) {} AudioDeviceCaptureCapability::AudioDeviceCaptureCapability( std::string device_id, std::string group_id, const media::AudioParameters& parameters) : device_id_(std::move(device_id)), group_id_(std::move(group_id)), parameters_(parameters) { DCHECK(!device_id_.empty()); } AudioDeviceCaptureCapability::AudioDeviceCaptureCapability( const AudioDeviceCaptureCapability& other) = default; const std::string& AudioDeviceCaptureCapability::DeviceID() const { return source_ ? source_->device().id : device_id_; } const std::string& AudioDeviceCaptureCapability::GroupID() const { return source_ && source_->device().group_id ? *source_->device().group_id : group_id_; } const media::AudioParameters& AudioDeviceCaptureCapability::Parameters() const { return source_ ? source_->device().input : parameters_; } AudioCaptureSettings SelectSettingsAudioCapture( const AudioDeviceCaptureCapabilities& capabilities, const blink::WebMediaConstraints& constraints, bool should_disable_hardware_noise_suppression) { if (capabilities.empty()) return AudioCaptureSettings(); std::string media_stream_source = GetMediaStreamSource(constraints); std::string default_device_id; bool is_device_capture = media_stream_source.empty(); if (is_device_capture) default_device_id = capabilities.begin()->DeviceID(); CandidatesContainer candidates(capabilities, media_stream_source, default_device_id); if (candidates.IsEmpty()) return AudioCaptureSettings(); auto* failed_constraint_name = candidates.ApplyConstraintSet(constraints.Basic()); if (failed_constraint_name) return AudioCaptureSettings(failed_constraint_name); for (const auto& advanced_set : constraints.Advanced()) { CandidatesContainer copy = candidates; failed_constraint_name = candidates.ApplyConstraintSet(advanced_set); if (failed_constraint_name) candidates = std::move(copy); } DCHECK(!candidates.IsEmpty()); // Score is ignored as it is no longer needed. AudioCaptureSettings settings; std::tie(std::ignore, settings) = candidates.SelectSettingsAndScore( constraints.Basic(), media_stream_source == kMediaStreamSourceDesktop, should_disable_hardware_noise_suppression); return settings; } AudioCaptureSettings CONTENT_EXPORT SelectSettingsAudioCapture(MediaStreamAudioSource* source, const blink::WebMediaConstraints& constraints) { DCHECK(source); if (source->device().type != MEDIA_DEVICE_AUDIO_CAPTURE && source->device().type != MEDIA_GUM_TAB_AUDIO_CAPTURE && source->device().type != MEDIA_GUM_DESKTOP_AUDIO_CAPTURE) { return AudioCaptureSettings(); } std::string media_stream_source = GetMediaStreamSource(constraints); if (source->device().type == MEDIA_DEVICE_AUDIO_CAPTURE && !media_stream_source.empty()) { return AudioCaptureSettings( constraints.Basic().media_stream_source.GetName()); } if (source->device().type == MEDIA_GUM_TAB_AUDIO_CAPTURE && !media_stream_source.empty() && media_stream_source != kMediaStreamSourceTab) { return AudioCaptureSettings( constraints.Basic().media_stream_source.GetName()); } if (source->device().type == MEDIA_GUM_DESKTOP_AUDIO_CAPTURE && !media_stream_source.empty() && media_stream_source != kMediaStreamSourceSystem && media_stream_source != kMediaStreamSourceDesktop) { return AudioCaptureSettings( constraints.Basic().media_stream_source.GetName()); } AudioDeviceCaptureCapabilities capabilities = { AudioDeviceCaptureCapability(source)}; bool should_disable_hardware_noise_suppression = !(source->device().input.effects() & media::AudioParameters::NOISE_SUPPRESSION); return SelectSettingsAudioCapture(capabilities, constraints, should_disable_hardware_noise_suppression); } } // namespace content