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
569fb566736554a210786e6292de5ad2249248ed
ee027a6d4a551e92bd9c1d92ead359b0ed84b77a
/src/fixme.hpp
78eaa95dce23b6fea32c4df0475487ff764f6652
[ "ISC" ]
permissive
Surfndez/powerdxx
5989b2144f2aa108d046b676ea9d585f8a988616
3e9bbcd05f83fd0dcde5bbc08a065aa9118daed0
refs/heads/master
2020-03-23T16:00:47.117710
2017-11-20T18:18:05
2017-11-20T18:18:05
141,789,559
1
0
ISC
2018-07-21T07:04:45
2018-07-21T07:04:45
null
UTF-8
C++
false
false
615
hpp
fixme.hpp
/** \file * Implementations in the fixme namespace. */ #include <sstream> /* std::ostringstream */ #ifndef _POWERDXX_FIXME_HPP_ #define _POWERDXX_FIXME_HPP_ /** * Workarounds for compiler/library bugs. */ namespace fixme { /** * G++ 5.3 does not believe in std::to_string(). * * @tparam T * The argument type to convert * @param op * The argument to convert * @return * A string of the given argument */ template <typename T> inline std::string to_string(T const & op) { std::ostringstream result; result << op; return result.str(); } } /* namespace fixme */ #endif /* _POWERDXX_FIXME_HPP_ */
c9b115501520706431b5b565eaf2edae571d3093
594fc4eadeff6b0fabe9c2923b8b996d2b13dea1
/nudg++/trunk/Src/Codes3D/PoissonIPDG3D.cpp
96367adbf040e3db6deb4286c95c8245b4fb199c
[ "LGPL-3.0-only", "LGPL-2.1-or-later", "MIT" ]
permissive
AlbaraaKhayat/nodal-dg
506345d6a2e12c289c2965c1160118c3ea448ba3
28e43f41f0d55ff22ec543695d772a5f0ddae52d
refs/heads/master
2022-12-23T17:40:30.554978
2020-10-01T06:24:17
2020-10-01T06:24:17
268,416,765
0
0
MIT
2020-06-01T03:32:24
2020-06-01T03:32:24
null
UTF-8
C++
false
false
7,081
cpp
PoissonIPDG3D.cpp
// CurvedPoissonIPDG2D.m // function [OP,MM] = PoissonIPDG3D() // 2007/10/16 //--------------------------------------------------------- #include "NDGLib_headers.h" #include "NDG3D.h" #define NDG_New_CHOLINC 1 //--------------------------------------------------------- void NDG3D::PoissonIPDG3D(CSd& spOP, CSd& spMM) //--------------------------------------------------------- { // function [OP,MM] = PoissonIPDG3D() // // Purpose: Set up the discrete Poisson matrix directly // using LDG. The operator is set up in the weak form DVec faceR("faceR"), faceS("faceS"), faceT("faceT"); DMat V2D; IVec Fm("Fm"); IVec i1_Nfp = Range(1,Nfp); double opti1=0.0, opti2=0.0; int i=0; umLOG(1, "\n ==> {OP,MM} assembly: "); opti1 = timer.read(); // time assembly // build local face matrices DMat massEdge[5]; // = zeros(Np,Np,Nfaces); for (i=1; i<=Nfaces; ++i) { massEdge[i].resize(Np,Np); } // face mass matrix 1 Fm = Fmask(All,1); faceR=r(Fm); faceS=s(Fm); V2D = Vandermonde2D(N, faceR, faceS); massEdge[1](Fm,Fm) = inv(V2D*trans(V2D)); // face mass matrix 2 Fm = Fmask(All,2); faceR = r(Fm); faceT = t(Fm); V2D = Vandermonde2D(N, faceR, faceT); massEdge[2](Fm,Fm) = inv(V2D*trans(V2D)); // face mass matrix 3 Fm = Fmask(All,3); faceS = s(Fm); faceT = t(Fm); V2D = Vandermonde2D(N, faceS, faceT); massEdge[3](Fm,Fm) = inv(V2D*trans(V2D)); // face mass matrix 4 Fm = Fmask(All,4); faceS = s(Fm); faceT = t(Fm); V2D = Vandermonde2D(N, faceS, faceT); massEdge[4](Fm,Fm) = inv(V2D*trans(V2D)); // build local volume mass matrix MassMatrix = trans(invV)*invV; DMat Dx("Dx"),Dy("Dy"),Dz("Dz"), Dx2("Dx2"),Dy2("Dy2"),Dz2("Dz2"); DMat Dn1("Dn1"),Dn2("Dn2"), mmE("mmE"), OP11("OP11"), OP12("OP12"); DMat mmE_All_Fm1, mmE_Fm1_Fm1, Dn2_Fm2_All; IMat rows1,cols1,rows2,cols2; int k1=0,f1=0,k2=0,f2=0,id=0; Index1D entries, entriesMM, idsM; IVec fidM,vidM,Fm1,vidP,Fm2; double lnx=0.0,lny=0.0,lnz=0.0,lsJ=0.0,hinv=0.0,gtau=0.0; double N1N1 = double((N+1)*(N+1)); int NpNp = Np*Np; // build DG derivative matrices int max_OP = (K*Np*Np*(1+Nfaces)); int max_MM = (K*Np*Np); // "OP" triplets (i,j,x), extracted to {Ai,Aj,Ax} IVec OPi(max_OP), OPj(max_OP), Ai,Aj; DVec OPx(max_OP), Ax; // "MM" triplets (i,j,x) IVec MMi(max_MM), MMj(max_MM); DVec MMx(max_MM); IVec OnesNp = Ones(Np); // global node numbering entries.reset(1,NpNp); entriesMM.reset(1,NpNp); OP12.resize(Np,Np); for (k1=1; k1<=K; ++k1) { if (! (k1%250)) { umLOG(1, "%d, ",k1); } rows1 = outer( Range((k1-1)*Np+1,k1*Np), OnesNp ); cols1 = trans(rows1); // Build local operators Dx = rx(1,k1)*Dr + sx(1,k1)*Ds + tx(1,k1)*Dt; Dy = ry(1,k1)*Dr + sy(1,k1)*Ds + ty(1,k1)*Dt; Dz = rz(1,k1)*Dr + sz(1,k1)*Ds + tz(1,k1)*Dt; OP11 = J(1,k1)*(trans(Dx)*MassMatrix*Dx + trans(Dy)*MassMatrix*Dy + trans(Dz)*MassMatrix*Dz); // Build element-to-element parts of operator for (f1=1; f1<=Nfaces; ++f1) { k2 = EToE(k1,f1); f2 = EToF(k1,f1); rows2 = outer( Range((k2-1)*Np+1, k2*Np), OnesNp ); cols2 = trans(rows2); fidM = (k1-1)*Nfp*Nfaces + (f1-1)*Nfp + i1_Nfp; vidM = vmapM(fidM); Fm1 = mod(vidM-1,Np)+1; vidP = vmapP(fidM); Fm2 = mod(vidP-1,Np)+1; id = 1+(f1-1)*Nfp + (k1-1)*Nfp*Nfaces; lnx = nx(id); lny = ny(id); lnz = nz(id); lsJ = sJ(id); hinv = std::max(Fscale(id), Fscale(1+(f2-1)*Nfp, k2)); Dx2 = rx(1,k2)*Dr + sx(1,k2)*Ds + tx(1,k2)*Dt; Dy2 = ry(1,k2)*Dr + sy(1,k2)*Ds + ty(1,k2)*Dt; Dz2 = rz(1,k2)*Dr + sz(1,k2)*Ds + tz(1,k2)*Dt; Dn1 = lnx*Dx + lny*Dy + lnz*Dz; Dn2 = lnx*Dx2 + lny*Dy2 + lnz*Dz2; mmE = lsJ*massEdge[f1]; gtau = 2.0 * N1N1 * hinv; // set penalty scaling if (EToE(k1,f1)==k1) { OP11 += ( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE ); // ok } else { // interior face variational terms OP11 += 0.5*( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE ); // extract mapped regions: mmE_All_Fm1 = mmE(All,Fm1); mmE_Fm1_Fm1 = mmE(Fm1,Fm1); Dn2_Fm2_All = Dn2(Fm2,All); OP12 = 0.0; // reset to zero OP12(All,Fm2) = -0.5*( gtau*mmE_All_Fm1 ); OP12(Fm1,All) -= 0.5*( mmE_Fm1_Fm1*Dn2_Fm2_All ); //OP12(All,Fm2) -= 0.5*(-trans(Dn1)*mmE_All_Fm1 ); OP12(All,Fm2) += 0.5*( trans(Dn1)*mmE_All_Fm1 ); // load this set of triplets #if (1) OPi(entries)=rows1; OPj(entries)=cols2, OPx(entries)=OP12; entries += (NpNp); #else //########################################################### // load only the lower triangle (after droptol test?) sk=0; start=entries(1); for (int i=1; i<=NpNp; ++i) { eid = start+i; id=entries(eid); rid=rows1(i); cid=cols2(i); if (rows1(rid) >= cid) { // take lower triangle if ( fabs(OP12(id)) > 1e-15) { // drop small entries ++sk; OPi(id)=rid; OPj(id)=cid, OPx(id)=OP12(id); } } } entries += sk; //########################################################### #endif } } OPi(entries )=rows1; OPj(entries )=cols1, OPx(entries )=OP11; MMi(entriesMM)=rows1; MMj(entriesMM)=cols1; MMx(entriesMM)=J(1,k1)*MassMatrix; entries += (NpNp); entriesMM += (NpNp); } umLOG(1, "\n ==> {OP,MM} to sparse\n"); entries.reset(1, entries.hi()-Np*Np); // Extract triplets from the large buffers. Note: this // requires copying each array, and since these arrays // can be HUGE(!), we force immediate deallocation: Ai=OPi(entries); OPi.Free(); Aj=OPj(entries); OPj.Free(); Ax=OPx(entries); OPx.Free(); umLOG(1, " ==> triplets ready (OP) nnz = %10d\n", entries.hi()); // adjust triplet indices for 0-based sparse operators Ai -= 1; Aj -= 1; MMi -= 1; MMj -= 1; int npk=Np*K; #if defined(NDG_USE_CHOLMOD) || defined(NDG_New_CHOLINC) // load only the lower triangle tril(OP) free args? spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, false,1e-15, true); // {LT, false} -> TriL #else // select {upper,lower,both} triangles //spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, true,1e-15,true); // LT -> enforce symmetry //spOP.load(npk,npk, Ai,Aj,Ax, sp_All,true,1e-15,true); // All-> includes "noise" //spOP.load(npk,npk, Ai,Aj,Ax, sp_UT, false,1e-15,true); // UT -> triu(OP) only #endif Ai.Free(); Aj.Free(); Ax.Free(); umLOG(1, " ==> triplets ready (MM) nnz = %10d\n", entriesMM.hi()); //------------------------------------------------------- // The mass matrix operator will NOT be factorised, // Load ALL elements (both upper and lower triangles): //------------------------------------------------------- spMM.load(npk,npk, MMi,MMj,MMx, sp_All,false,1.00e-15,true); MMi.Free(); MMj.Free(); MMx.Free(); opti2 = timer.read(); // time assembly umLOG(1, " ==> {OP,MM} converted to csc. (%g secs)\n", opti2-opti1); }
36bc3110558e549b8dde8d9ed85580e476426c5f
0eaf1873b46076b485810621247968ddda034624
/libraries/Meeo/examples/NodeMCU/IPLocation/IPLocation.ino
e6c2010e389f3af1909ec5215a87074ae8902a1e
[ "MIT" ]
permissive
naveenneog/Arduino_Projects
d236df36377f08edb15c47dfe294e740c14110c2
bfc8ee57297499396d192b26164d02702bd50dc9
refs/heads/master
2022-04-24T11:10:31.560851
2020-04-23T08:35:36
2020-04-23T08:35:36
258,142,147
0
0
null
null
null
null
UTF-8
C++
false
false
3,442
ino
IPLocation.ino
/* IPLocation by Meeo This example will make use of Meeo. If you haven't already, visit Meeo at https://meeo.xyz and create an account. Then check how to get started with the Meeo library through https://github.com/meeo/meeo-arduino OTHER REQUIREMENTS Under Sketch > Include Library > Manage Libraries... Search and install the following: * ESP8266RestClient by fabianofranca * ArduinoJson by Benoit Blanchon Know your GPS location based on your IP address with ipapi.co! More details of the project here: https://medium.com/meeo/meeo-project-ip-location-4a81316c0b30 Copyright: Meeo Author: Terence Anton Dela Fuente License: MIT */ #include <Meeo.h> #include <RestClient.h> #include <ArduinoJson.h> // Uncomment if you wish to see the events on the Meeo dashboard // #define LOGGER_CHANNEL "logger" String nameSpace = "my_namespace"; String accessKey = "my_access_key"; String ssid = "MyWiFi"; String pass = "qwerty123"; String ipLocationChannel = "ip-location"; // ipapi.co will serve as our GPS tracker based on the current IP address of the // device RestClient client = RestClient("ipapi.co"); DynamicJsonBuffer jsonBuffer; unsigned long previous = 0; void setup() { Serial.begin(115200); Meeo.setEventHandler(meeoEventHandler); Meeo.setDataReceivedHandler(meeoDataHandler); Meeo.begin(nameSpace, accessKey, ssid, pass); #ifdef LOGGER_CHANNEL Meeo.setLoggerChannel(LOGGER_CHANNEL); #endif } void loop() { Meeo.run(); unsigned long now = millis(); // Check value every 10 seconds if (now - previous >= 10000) { previous = now; String response = ""; int statusCode = client.get("/json", &response); if (statusCode == 200) { // parse the response from request JsonObject& root = jsonBuffer.parseObject(response); float latitude = root[String("latitude")]; float longitude = root[String("longitude")]; String location = String(latitude, 6) + "," + String(longitude, 6); Meeo.publish(ipLocationChannel, location); #ifdef LOGGER_CHANNEL String tempCity = root[String("city")]; String tempRegion = root[String("region")]; String tempCountryName = root[String("country_name")]; String tempTimezone = root[String("timezone")]; String city = "[INFO] City: " + tempCity; String region = "[INFO] Region: " + tempRegion; String countryName = "[INFO] Country: " + tempCountryName; String timezone = "[INFO] Timezone: " + tempTimezone; Meeo.println(city); Meeo.println(region); Meeo.println(countryName); Meeo.println(timezone); #endif } } } void meeoDataHandler(String topic, String payload) { Serial.print(topic); Serial.print(": "); Serial.println(payload); } void meeoEventHandler(MeeoEventType event) { switch (event) { case WIFI_DISCONNECTED: Serial.println("Not Connected to WiFi"); break; case WIFI_CONNECTING: Serial.println("Connecting to WiFi"); break; case WIFI_CONNECTED: Serial.println("Connected to WiFi"); break; case MQ_DISCONNECTED: Serial.println("Not Connected to MQTT Server"); break; case MQ_CONNECTED: Serial.println("Connected to MQTT Server"); break; case MQ_BAD_CREDENTIALS: Serial.println("Bad Credentials"); break; case AP_MODE: Serial.println("AP Mode"); break; default: break; } }
e8ea59dfdcb5d7ec0a9ced12df3b8869bd830c34
20a87d95b777d01fc49b7479512d7725674980f3
/constants_io.hpp
ac33f302f80d2e9cdd986bbf1243c211f09db9d4
[ "MIT" ]
permissive
Megacrafter127/Atomaker
03169e1e3a84a0c38306617aa355b178e91ff4db
03956be5c249277fde40e2cc5c62b846b9aa7ed2
refs/heads/master
2023-02-26T03:39:17.341485
2021-02-03T04:09:09
2021-02-03T04:09:09
282,981,927
2
0
null
null
null
null
UTF-8
C++
false
false
934
hpp
constants_io.hpp
/* * constants_io.hpp * * Created on: 27.07.2020 * Author: Megacrafter127 */ #ifndef CONSTANTS_IO_HPP_ #define CONSTANTS_IO_HPP_ #include "constants.hpp" #include <cstdio> template<typename T> constexpr static const char constantFmt[]="\nm_e: %f\nm_p: %f\nm_n: %f\nh_bar: %f\nepsilon_0: %f\ne: %f\nc: %f"; template<> constexpr const char constantFmt<double>[]="\nm_e: %lf\nm_p: %lf\nm_n: %lf\nh_bar: %lf\nepsilon_0: %lf\ne: %lf\nc: %lf"; template<> constexpr const char constantFmt<long double>[]="\nm_e: %Lf\nm_p: %Lf\nm_n: %Lf\nh_bar: %Lf\nepsilon_0: %Lf\ne: %Lf\nc: %Lf"; template<typename T> int load_constants(constants<T> &c,FILE *f) { return fscanf(f,constantFmt<T>,&c.m_e,&c.m_p,&c.m_n,&c.h_bar,&c.epsilon_0,&c.e,&c.c); } template<typename T> int save_constants(const constants<T> &c,FILE *f) { return fprintf(f,constantFmt<T>,c.m_e,c.m_p,c.m_n,c.h_bar,c.epsilon_0,c.e,c.c); } #endif /* CONSTANTS_IO_HPP_ */
d8deefb12cd456ddc766e7b9daffb2249def49c6
114c19f73364c59832ee0cc3f3035659975b2a6b
/tictactoe.cpp
48f961ece5758df70ef5ad3feadba6a6f1b70e69
[]
no_license
parag1999/random-project
659281192978d2d4a17beced07c6fdbb41d2c56c
2f20ac7da8aaf56561f96f16ed8d4572cd4566dc
refs/heads/master
2021-04-06T20:02:48.328380
2018-03-15T19:38:08
2018-03-15T19:38:08
125,336,859
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
cpp
tictactoe.cpp
#include <iostream> #include <climits> using namespace std; int i,j,k; char arr[9]; void x(); void play(int counter); void display(); void check(); main () { display(); for(j=1;j<=9;j++) { if(k!=1) { play(j); check(); } } if(k!=1) cout<<"DRAW"<<endl; } void display() { for (i=0;i<9;i++) { arr[i]='0'+i; } cout<<" "<<arr[0]<<" |"<<arr[1]<<" |"<<arr[2]<<endl; cout<<" --"<<"|"<<"--"<<"|"<<"--"<<endl; cout<<" "<<arr[3]<<" |"<<arr[4]<<" |"<<arr[5]<<endl; cout<<" --"<<"|"<<"--"<<"|"<<"--"<<endl; cout<<" "<<arr[6]<<" |"<<arr[7]<<" |"<<arr[8]<<endl; } void play(int counter) { char ply = ' '; if(counter%2!=0) { ply='X'; } else { ply='O'; } cout<<endl; cout<<"enter position of " << ply <<endl; cin>>i; while(cin.fail()) { cin.clear();// to clear the character value cin.ignore(INT_MAX,'\n');//ignore and free the space assigning it to int cout<<"enter correctly my friend"<<endl; cin>>i; } while(arr[i]== (ply == 'X' ? 'O' : 'X') | i>8) { cout<<"invalid input "<<"enter the position of " << ply <<endl; cin>>i; } arr[i]=ply; cout<<endl; cout<<" "<<arr[0]<<" |"<<arr[1]<<" |"<<arr[2]<<endl; cout<<" --"<<"|"<<"--"<<"|"<<"--"<<endl; cout<<" "<<arr[3]<<" |"<<arr[4]<<" |"<<arr[5]<<endl; cout<<" --"<<"|"<<"--"<<"|"<<"--"<<endl; cout<<" "<<arr[6]<<" |"<<arr[7]<<" |"<<arr[8]<<endl; } void check() { for(i=0;i<=2;i++) { if((arr[i]=='X' && arr[i+3]=='X') && arr[i+6]=='X') { k=1; cout<<"player 1 wins"<<endl; } else if((arr[i]=='O' && arr[i+3]=='O') && arr[i+6]=='O') { k=1; cout<<"player 2 wins"<<endl; } } for(i=0;i<=6;i=i+3) { if((arr[i]=='X' && arr[i+1]=='X') && arr[i+2]=='X') { k=1; cout<<"player 1 wins"<<endl; } else if((arr[i]=='O' && arr[i+1]=='O') && arr[i+2]=='O') { k=1; cout<<"player 2 wins"<<endl;} } if((arr[0]=='X' && arr[4]=='X') && arr[8]=='X') { k=1; cout<<"player 1 wins"<<endl; } else if ((arr[0]=='O' && arr[4]=='O') && arr[8]=='O') { k=1; cout<<"player 2 wins"<<endl; } if((arr[2]=='X' && arr[4]=='X') && arr[6]=='X') { k=1; cout<<"player 1 wins"<<endl; } else if ((arr[2]=='O' && arr[4]=='O') && arr[6]=='O') { k=1; cout<<"player 2 wins"<<endl; } }
3a9fce8c685dda963eccbede63356fca01741f3e
16e54286bb66e4173f746936c829dda2c280ce68
/C/牛客网/客似云来.cpp
7eccad2ccd9fb65c6f2f72a1b27c437b6eb21d72
[]
no_license
569985011/Work-Space
653b932ada697d29178c2211a40d7de7650f9421
9afeb1846433d22514a0997b7a48254ce85f5009
refs/heads/master
2021-05-04T00:28:23.098655
2020-09-30T11:32:57
2020-09-30T11:32:57
71,839,693
0
0
null
null
null
null
GB18030
C++
false
false
599
cpp
客似云来.cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #define N int main(){ long long a[81],b[81],c[81]; a[1]=0;b[1]=0;c[1]=1; a[2]=0;b[2]=1;c[2]=0; a[3]=1;b[3]=0;c[3]=1; int min=3;int from ,to; while((scanf("%d%d",&from,&to))!=EOF){ if(to>min){//动态扩展,随着程序中验证的数据越来越多,数据库也就越来越完善 //相应的,后续我们就不用计算了。 for(int i=min+1;i<=to;i++){ a[i]=a[i-1]+b[i-1]; b[i]=c[i-1]; c[i]=a[i]; } } long long sum=0; for(int i=from;i<=to;i++){ sum+=a[i]+b[i]+c[i]; }printf("%lld\n",sum); } return 0; }
b7d77daa33b614399d8075f93623ff22f1c8a223
1ea4bcba5958b0d898b263dee4e2925670071df9
/scripting/javascript/bindings/generated/jsb_cocos2dx_extension_auto.hpp
a9730abf3fc81b5e281cc8021e16164bd66b3a9a
[ "MIT" ]
permissive
victorchan123/Dorothy
d4cff893fadd6232932c940cf10da67b5db8e65b
58b50c68ab4cdec6cc58205771776c7c150e898c
refs/heads/master
2021-01-16T22:09:08.243632
2013-05-03T14:23:33
2013-05-03T14:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,355
hpp
jsb_cocos2dx_extension_auto.hpp
#ifndef __jsb_cocos2dx_extension_h__ #define __jsb_cocos2dx_extension_h__ #include "jsapi.h" #include "jsfriendapi.h" extern JSClass *jsb_CCControl_class; extern JSObject *jsb_CCControl_prototype; JSBool js_cocos2dx_extension_CCControl_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCControl_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCControl(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCControl_setEnabled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_getState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_isOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_sendActionsForControlEvents(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_setSelected(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_getTouchLocation(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_isEnabled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_isTouchInside(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_setOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_needsLayout(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_hasVisibleParents(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_isSelected(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_init(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_setHighlighted(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_registerWithTouchDispatcher(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_isHighlighted(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControl_CCControl(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCScale9Sprite_class; extern JSObject *jsb_CCScale9Sprite_prototype; JSBool js_cocos2dx_extension_CCScale9Sprite_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCScale9Sprite_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCScale9Sprite(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCScale9Sprite_getCapInsets(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_updateWithBatchNode(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setInsetBottom(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_isOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_initWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setInsetTop(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_init(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setPreferredSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setSpriteFrame(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_initWithBatchNode(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getInsetBottom(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_resizableSpriteWithCapInsets(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setContentSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getInsetRight(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getOriginalSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_initWithFile(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getInsetTop(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setInsetLeft(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_initWithSpriteFrame(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getPreferredSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setCapInsets(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_getInsetLeft(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_setInsetRight(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_create(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_createWithSpriteFrameName(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_createWithSpriteFrame(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScale9Sprite_CCScale9Sprite(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCControlButton_class; extern JSObject *jsb_CCControlButton_prototype; JSBool js_cocos2dx_extension_CCControlButton_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCControlButton_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCControlButton(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCControlButton_setTitleColorDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_isPushed(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setSelected(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleLabel(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_ccTouchBegan(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleTTFSizeForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setAdjustBackgroundImage(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_ccTouchEnded(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setHighlighted(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setBackgroundSpriteDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setZoomOnTouchDown(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setLabelAnchorPoint(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_ccTouchCancelled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getLabelAnchorPoint(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_initWithBackgroundSprite(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleTTFSizeForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setOpacity(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_init(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleTTFForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setPreferredSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleLabelForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_ccTouchMoved(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getOpacity(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getCurrentTitleColor(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleColorDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setEnabled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getBackgroundSpriteForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getHorizontalOrigin(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setMargins(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_needsLayout(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_initWithTitleAndFontNameAndFontSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleBMFontForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleTTFForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getBackgroundSprite(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleColorForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_doesAdjustBackgroundImage(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setBackgroundSpriteFrameForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setBackgroundSpriteForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleLabelDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_initWithLabelAndBackgroundSprite(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleLabelDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleLabel(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getPreferredSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getVerticalMargin(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getBackgroundSpriteDispatchTable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleLabelForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getCurrentTitle(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleBMFontForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setTitleForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_setBackgroundSprite(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getZoomOnTouchDown(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_getTitleForState(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_create(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCControlButton_CCControlButton(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCScrollView_class; extern JSObject *jsb_CCScrollView_prototype; JSBool js_cocos2dx_extension_CCScrollView_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCScrollView_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCScrollView(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCScrollView_isClippingToBounds(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setContainer(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setContentOffsetInDuration(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setZoomScaleInDuration(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_addChild(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_ccTouchBegan(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getContainer(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_ccTouchEnded(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getDirection(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getZoomScale(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_updateInset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_initWithViewSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_pause(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setDirection(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setBounceable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setContentOffset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_isDragging(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_init(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_isBounceable(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getContentSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_ccTouchMoved(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setTouchEnabled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getContentOffset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_resume(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setClippingToBounds(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setViewSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_getViewSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_maxContainerOffset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setContentSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_isTouchMoved(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_isNodeVisible(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_ccTouchCancelled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_minContainerOffset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_registerWithTouchDispatcher(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_setZoomScale(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_create(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCScrollView_CCScrollView(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCTableViewCell_class; extern JSObject *jsb_CCTableViewCell_prototype; JSBool js_cocos2dx_extension_CCTableViewCell_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCTableViewCell_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCTableViewCell(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCTableViewCell_reset(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableViewCell_setIdx(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableViewCell_setObjectID(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableViewCell_getObjectID(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableViewCell_getIdx(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableViewCell_CCTableViewCell(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCTableView_class; extern JSObject *jsb_CCTableView_prototype; JSBool js_cocos2dx_extension_CCTableView_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCTableView_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCTableView(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCTableView_updateCellAtIndex(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_setVerticalFillOrder(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_scrollViewDidZoom(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_ccTouchBegan(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_getVerticalFillOrder(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_removeCellAtIndex(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_initWithViewSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_scrollViewDidScroll(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_reloadData(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_ccTouchCancelled(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_ccTouchEnded(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_ccTouchMoved(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView__updateContentSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_insertCellAtIndex(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_cellAtIndex(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_dequeueCell(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCTableView_CCTableView(JSContext *cx, uint32_t argc, jsval *vp); extern JSClass *jsb_CCEditBox_class; extern JSObject *jsb_CCEditBox_prototype; JSBool js_cocos2dx_extension_CCEditBox_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_extension_CCEditBox_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_extension_CCEditBox(JSContext *cx, JSObject *global); void register_all_cocos2dx_extension(JSContext* cx, JSObject* obj); JSBool js_cocos2dx_extension_CCEditBox_setAnchorPoint(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_getText(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setContentSize(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_getPlaceHolder(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setInputMode(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setPlaceholderFontColor(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setFontColor(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setPlaceholderFont(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_initWithSizeAndBackgroundSprite(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setPlaceHolder(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setPosition(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setReturnType(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_getMaxLength(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setInputFlag(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setText(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setMaxLength(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setFont(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_setVisible(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_create(JSContext *cx, uint32_t argc, jsval *vp); JSBool js_cocos2dx_extension_CCEditBox_CCEditBox(JSContext *cx, uint32_t argc, jsval *vp); #endif // __jsb_cocos2dx_extension_h__
716e3fc8619a04abfe31de462d0b48bf14e6c39b
c4c69e7c63bd338c369b348db69d8c074bdc6a48
/FinanceStaticLib/BinomialTree.h
91995c0d2b89d3c1f425d9413203db62324a2026
[]
no_license
Sledis/Joshi-on-C-
5b90960f310ad6dbd24780cc634d5385e1a2a787
d9f1f8eb5b7a22fb66edd6285a413ac482eff4cc
refs/heads/master
2020-07-13T01:04:43.223243
2019-09-23T13:53:58
2019-09-23T13:53:58
204,954,629
1
0
null
2019-09-22T20:35:52
2019-08-28T14:42:58
C++
UTF-8
C++
false
false
567
h
BinomialTree.h
#pragma once #include "TreeProduct.h" #include <vector> #include "Parameters.h" #include "Arrays.h" class SimpleBinomialTree { public: SimpleBinomialTree(double Spot_, const Parameters& r_, const Parameters& d_, double Volatility_, unsigned long Steps, double Time); double GetThePrice(const TreeProduct& TheProduct); protected: void BuildTree(); private: double Spot; Parameters r; Parameters d; double Volatility; unsigned long Steps; double Time; bool TreeBuilt; std::vector<std::vector<std::pair<double, double>>> TheTree; MJArray Discounts; };
7737bbeb63fbd9d20b9d3fc6a7e52ca7193aff85
2c97aabb4daad961f12f05a69a4001f2bc6d380b
/Server/REST_API.cpp
845d378185300516c9b118e251c1a5854e6c8c02
[]
no_license
dorinbotan/Greenhouse
de2128b3aa89206cfe7e069cbb3767e0859071e7
aea26101365c1ee4ced246b2e31aa2ac7803ac63
refs/heads/master
2021-09-03T14:46:45.159042
2018-01-09T21:37:19
2018-01-09T21:37:19
110,474,108
0
0
null
null
null
null
UTF-8
C++
false
false
11,304
cpp
REST_API.cpp
#include "REST_API.h" #include <QDebug> using QtJson::JsonObject; using QtJson::JsonArray; QString REST_API::processTemperature( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return temperature value responseBody = QString::number( greenhouse.getTemperature() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /temperature" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable automatic temperature control at given value greenhouse.setTemperature( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /temperature" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic temperature control (turn off heater) greenhouse.setAutoTemperature( false ); greenhouse.setHeater( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /temperature"; } return responseHeader + responseBody; } QString REST_API::processTemperatureMode( QHttpRequestHeader header ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return auto temperature value responseBody = QString::number( greenhouse.getAutoTemperature() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /temperature/mode" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Automaticaly maintain current temperature greenhouse.setAutoTemperature( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /temperature/mode"; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic temperature control greenhouse.setAutoTemperature( false ); greenhouse.setHeater( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /temperature/mode"; } return responseHeader + responseBody; } QString REST_API::processHumidity( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return humidity value responseBody = QString::number( greenhouse.getHumidity() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /humidity" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable automatic humidity control at given value greenhouse.setHumidity( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /humidity" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic humidity control (close the lid) greenhouse.setAutoHumidity( false ); greenhouse.setLid( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /humidity"; } return responseHeader + responseBody; } QString REST_API::processHumidityMode( QHttpRequestHeader header ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return auto humidity value responseBody = QString::number( greenhouse.getAutoHumidity() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /humidity/mode" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Automaticaly maintain current humidity greenhouse.setAutoHumidity( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /humidity"; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic humidity control greenhouse.setAutoHumidity( false ); greenhouse.setLid( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /humidity"; } return responseHeader + responseBody; } QString REST_API::processLight( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return light value responseBody = QString::number( greenhouse.getLight() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /light" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable automatic light control at given value greenhouse.setLight( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /light" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic light control (turn off lamp) greenhouse.setAutoLight( false ); greenhouse.setLamp( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /light"; } return responseHeader + responseBody; } QString REST_API::processLightMode( QHttpRequestHeader header ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return auto light value responseBody = QString::number( greenhouse.getAutoLight() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /light/mode" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Automaticaly maintain current light level greenhouse.setAutoLight( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /light/mode"; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable automatic light control greenhouse.setAutoLight( false ); greenhouse.setLamp( 0 ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /light/mode"; } return responseHeader + responseBody; } QString REST_API::processHeater( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return heater value responseBody = QString::number( greenhouse.getHeater() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /heater" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable manual temperature control and set heater to desired value greenhouse.setAutoTemperature( false ); greenhouse.setHeater( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /heater" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable manual temperature control and keep current temperature greenhouse.setAutoTemperature( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /heater"; } return responseHeader + responseBody; } QString REST_API::processLid( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return lid value responseBody = QString::number( greenhouse.getLid() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /lid" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable manual humidity control and set lid to desired value greenhouse.setAutoHumidity( false ); greenhouse.setLid( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /lid" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable manual humidity control and keep current humidity level greenhouse.setAutoHumidity( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /lid"; } return responseHeader + responseBody; } QString REST_API::processLamp( QHttpRequestHeader header, QString body ) { QString responseHeader = getResponseHeader( 404 ).toString(); QString responseBody; if( header.method().compare( "GET" ) == 0 ) { // Return lamp value responseBody = QString::number( greenhouse.getLamp() ); responseHeader = getResponseHeader( 200, responseBody.size(), mediaType.toMIME( "text/plain" ) ).toString(); qDebug() << "GET /lamp" << responseBody; } else if( header.method().compare( "POST" ) == 0 ) { // Enable manual light control and set lamp to desired value greenhouse.setAutoLight( false ); greenhouse.setLamp( body.toInt() ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "POST /lamp" << body; } else if( header.method().compare( "DELETE" ) == 0 ) { // Disable manual light control and keep current light level greenhouse.setAutoLight( true ); responseHeader = getResponseHeader( 200 ).toString(); qDebug() << "DELETE /lamp"; } return responseHeader + responseBody; } QHttpResponseHeader REST_API::getResponseHeader( quint16 responseCode, int contentLength, QString contentType ) { QHttpResponseHeader toReturn( responseCode ); if( !contentType.isEmpty() ) { toReturn.setContentType( contentType ); } toReturn.setContentLength( contentLength ); toReturn.setValue( "server", "BeagleBone Black Greenhouse" ); return toReturn; }
383a30d03c87e3bcb74bfec41d79c019e29b82ea
49398de1cdd551c3a168896929d5dc5b0197a4a4
/include/vulkan/internal/struct/VkSwapchain.hpp
89d1d3301fcd4102d4aeb13f064baa55cf4c223b
[ "Apache-2.0" ]
permissive
skyline-emu/vkhpp
9580b5ea039256bbf68c67e9197d2b3eab390cbe
a4b8f74942a932ea191dc95cc4a210fea524508f
refs/heads/master
2022-04-23T20:51:15.446022
2020-04-22T21:02:56
2020-04-22T21:03:01
257,965,208
2
1
null
null
null
null
UTF-8
C++
false
false
19,812
hpp
VkSwapchain.hpp
// Copyright (c) 2015-2019 The Khronos Group Inc. // // 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. // // ---- Exceptions to the Apache 2.0 License: ---- // // As an exception, if you use this Software to generate code and portions of // this Software are embedded into the generated code as a result, you may // redistribute such product without providing attribution as would otherwise // be required by Sections 4(a), 4(b) and 4(d) of the License. // // In addition, if you combine or link code generated by this Software with // software that is licensed under the GPLv2 or the LGPL v2.0 or 2.1 // ("`Combined Software`") and if a court of competent jurisdiction determines // that the patent provision (Section 3), the indemnity provision (Section 9) // or other Section of the License conflicts with the conditions of the // applicable GPL or LGPL license, you may retroactively and prospectively // choose to deem waived or otherwise exclude such Section(s) of the License, // but only in their entirety and only with respect to the Combined Software. // // This header is generated from the Khronos Vulkan XML API Registry. #pragma once #include "../handles.hpp" #include "VkAcquire.hpp" #include "VkAcceleration.hpp" #include "VkApplication.hpp" #include "VkInitialize.hpp" #include "VkAllocation.hpp" #include "VkExternal.hpp" #include "VkBind.hpp" #include "VkObject.hpp" #include "VkCooperative.hpp" #include "VkAndroid.hpp" #include "VkImport.hpp" #include "VkImage.hpp" #include "VkDescriptor.hpp" #include "VkBase.hpp" #include "VkAttachment.hpp" #include "VkBuffer.hpp" #include "VkFramebuffer.hpp" #include "VkCalibrated.hpp" #include "VkDevice.hpp" #include "VkSubresource.hpp" #include "VkCheckpoint.hpp" #include "VkConformance.hpp" #include "VkClear.hpp" #include "VkStream.hpp" #include "VkCmd.hpp" #include "VkCoarse.hpp" #include "VkExtension.hpp" #include "VkCommand.hpp" #include "VkFormat.hpp" #include "VkMetal.hpp" #include "VkComponent.hpp" #include "VkCopy.hpp" #include "VkCompute.hpp" #include "VkPast.hpp" #include "VkConditional.hpp" #include "VkMapped.hpp" #include "VkD3D.hpp" #include "VkDebug.hpp" #include "VkDedicated.hpp" #include "VkFence.hpp" #include "VkDispatch.hpp" #include "VkPipeline.hpp" #include "VkDraw.hpp" #include "VkDisplay.hpp" #include "VkDrm.hpp" #include "VkEvent.hpp" #include "VkExport.hpp" #include "VkRay.hpp" #include "VkExtent.hpp" #include "VkPerformance.hpp" #include "VkFilter.hpp" #include "VkRender.hpp" #include "VkGeometry.hpp" #include "VkGraphics.hpp" #include "VkHdr.hpp" #include "VkHeadless.hpp" #include "VkMultisample.hpp" #include "VkI.hpp" #include "VkIndirect.hpp" #include "VkInput.hpp" #include "VkOffset.hpp" #include "VkMemory.hpp" #include "VkInstance.hpp" #include "VkLayer.hpp" #include "VkMac.hpp" #include "VkPhysical.hpp" #include "VkPresent.hpp" #include "VkProtected.hpp" #include "VkPush.hpp" #include "VkQuery.hpp" #include "VkQueue.hpp" #include "VkRect.hpp" #include "VkRefresh.hpp" #include "VkSample.hpp" #include "VkSampler.hpp" #include "VkSemaphore.hpp" #include "VkShader.hpp" #include "VkShading.hpp" #include "VkShared.hpp" #include "VkSparse.hpp" #include "VkSpecialization.hpp" #include "VkStencil.hpp" #include "VkSubmit.hpp" #include "VkSubpass.hpp" #include "VkSurface.hpp" #include "VkSwapchain.hpp" namespace VULKAN_HPP_NAMESPACE { struct SwapchainCounterCreateInfoEXT { VULKAN_HPP_CONSTEXPR SwapchainCounterCreateInfoEXT( VULKAN_HPP_NAMESPACE::SurfaceCounterFlagsEXT surfaceCounters_ = {} ) VULKAN_HPP_NOEXCEPT : surfaceCounters( surfaceCounters_ ) {} VULKAN_HPP_CONSTEXPR SwapchainCounterCreateInfoEXT( SwapchainCounterCreateInfoEXT const& rhs ) VULKAN_HPP_NOEXCEPT : pNext( rhs.pNext ) , surfaceCounters( rhs.surfaceCounters ) {} SwapchainCounterCreateInfoEXT & operator=( SwapchainCounterCreateInfoEXT const & rhs ) VULKAN_HPP_NOEXCEPT { memcpy( &pNext, &rhs.pNext, sizeof( SwapchainCounterCreateInfoEXT ) - offsetof( SwapchainCounterCreateInfoEXT, pNext ) ); return *this; } SwapchainCounterCreateInfoEXT( VkSwapchainCounterCreateInfoEXT const & rhs ) VULKAN_HPP_NOEXCEPT { *this = rhs; } SwapchainCounterCreateInfoEXT& operator=( VkSwapchainCounterCreateInfoEXT const & rhs ) VULKAN_HPP_NOEXCEPT { *this = *reinterpret_cast<VULKAN_HPP_NAMESPACE::SwapchainCounterCreateInfoEXT const *>(&rhs); return *this; } SwapchainCounterCreateInfoEXT & setPNext( const void* pNext_ ) VULKAN_HPP_NOEXCEPT { pNext = pNext_; return *this; } SwapchainCounterCreateInfoEXT & setSurfaceCounters( VULKAN_HPP_NAMESPACE::SurfaceCounterFlagsEXT surfaceCounters_ ) VULKAN_HPP_NOEXCEPT { surfaceCounters = surfaceCounters_; return *this; } operator VkSwapchainCounterCreateInfoEXT const&() const VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<const VkSwapchainCounterCreateInfoEXT*>( this ); } operator VkSwapchainCounterCreateInfoEXT &() VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<VkSwapchainCounterCreateInfoEXT*>( this ); } #if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR) auto operator<=>( SwapchainCounterCreateInfoEXT const& ) const = default; #else bool operator==( SwapchainCounterCreateInfoEXT const& rhs ) const VULKAN_HPP_NOEXCEPT { return ( sType == rhs.sType ) && ( pNext == rhs.pNext ) && ( surfaceCounters == rhs.surfaceCounters ); } bool operator!=( SwapchainCounterCreateInfoEXT const& rhs ) const VULKAN_HPP_NOEXCEPT { return !operator==( rhs ); } #endif public: const VULKAN_HPP_NAMESPACE::StructureType sType = StructureType::eSwapchainCounterCreateInfoEXT; const void* pNext = {}; VULKAN_HPP_NAMESPACE::SurfaceCounterFlagsEXT surfaceCounters = {}; }; static_assert( sizeof( SwapchainCounterCreateInfoEXT ) == sizeof( VkSwapchainCounterCreateInfoEXT ), "struct and wrapper have different size!" ); static_assert( std::is_standard_layout<SwapchainCounterCreateInfoEXT>::value, "struct wrapper is not a standard layout!" ); struct SwapchainCreateInfoKHR { VULKAN_HPP_CONSTEXPR SwapchainCreateInfoKHR( VULKAN_HPP_NAMESPACE::SwapchainCreateFlagsKHR flags_ = {}, VULKAN_HPP_NAMESPACE::SurfaceKHR surface_ = {}, uint32_t minImageCount_ = {}, VULKAN_HPP_NAMESPACE::Format imageFormat_ = VULKAN_HPP_NAMESPACE::Format::eUndefined, VULKAN_HPP_NAMESPACE::ColorSpaceKHR imageColorSpace_ = VULKAN_HPP_NAMESPACE::ColorSpaceKHR::eSrgbNonlinear, VULKAN_HPP_NAMESPACE::Extent2D imageExtent_ = {}, uint32_t imageArrayLayers_ = {}, VULKAN_HPP_NAMESPACE::ImageUsageFlags imageUsage_ = {}, VULKAN_HPP_NAMESPACE::SharingMode imageSharingMode_ = VULKAN_HPP_NAMESPACE::SharingMode::eExclusive, uint32_t queueFamilyIndexCount_ = {}, const uint32_t* pQueueFamilyIndices_ = {}, VULKAN_HPP_NAMESPACE::SurfaceTransformFlagBitsKHR preTransform_ = VULKAN_HPP_NAMESPACE::SurfaceTransformFlagBitsKHR::eIdentity, VULKAN_HPP_NAMESPACE::CompositeAlphaFlagBitsKHR compositeAlpha_ = VULKAN_HPP_NAMESPACE::CompositeAlphaFlagBitsKHR::eOpaque, VULKAN_HPP_NAMESPACE::PresentModeKHR presentMode_ = VULKAN_HPP_NAMESPACE::PresentModeKHR::eImmediate, VULKAN_HPP_NAMESPACE::Bool32 clipped_ = {}, VULKAN_HPP_NAMESPACE::SwapchainKHR oldSwapchain_ = {} ) VULKAN_HPP_NOEXCEPT : flags( flags_ ) , surface( surface_ ) , minImageCount( minImageCount_ ) , imageFormat( imageFormat_ ) , imageColorSpace( imageColorSpace_ ) , imageExtent( imageExtent_ ) , imageArrayLayers( imageArrayLayers_ ) , imageUsage( imageUsage_ ) , imageSharingMode( imageSharingMode_ ) , queueFamilyIndexCount( queueFamilyIndexCount_ ) , pQueueFamilyIndices( pQueueFamilyIndices_ ) , preTransform( preTransform_ ) , compositeAlpha( compositeAlpha_ ) , presentMode( presentMode_ ) , clipped( clipped_ ) , oldSwapchain( oldSwapchain_ ) {} VULKAN_HPP_CONSTEXPR SwapchainCreateInfoKHR( SwapchainCreateInfoKHR const& rhs ) VULKAN_HPP_NOEXCEPT : pNext( rhs.pNext ) , flags( rhs.flags ) , surface( rhs.surface ) , minImageCount( rhs.minImageCount ) , imageFormat( rhs.imageFormat ) , imageColorSpace( rhs.imageColorSpace ) , imageExtent( rhs.imageExtent ) , imageArrayLayers( rhs.imageArrayLayers ) , imageUsage( rhs.imageUsage ) , imageSharingMode( rhs.imageSharingMode ) , queueFamilyIndexCount( rhs.queueFamilyIndexCount ) , pQueueFamilyIndices( rhs.pQueueFamilyIndices ) , preTransform( rhs.preTransform ) , compositeAlpha( rhs.compositeAlpha ) , presentMode( rhs.presentMode ) , clipped( rhs.clipped ) , oldSwapchain( rhs.oldSwapchain ) {} SwapchainCreateInfoKHR & operator=( SwapchainCreateInfoKHR const & rhs ) VULKAN_HPP_NOEXCEPT { memcpy( &pNext, &rhs.pNext, sizeof( SwapchainCreateInfoKHR ) - offsetof( SwapchainCreateInfoKHR, pNext ) ); return *this; } SwapchainCreateInfoKHR( VkSwapchainCreateInfoKHR const & rhs ) VULKAN_HPP_NOEXCEPT { *this = rhs; } SwapchainCreateInfoKHR& operator=( VkSwapchainCreateInfoKHR const & rhs ) VULKAN_HPP_NOEXCEPT { *this = *reinterpret_cast<VULKAN_HPP_NAMESPACE::SwapchainCreateInfoKHR const *>(&rhs); return *this; } SwapchainCreateInfoKHR & setPNext( const void* pNext_ ) VULKAN_HPP_NOEXCEPT { pNext = pNext_; return *this; } SwapchainCreateInfoKHR & setFlags( VULKAN_HPP_NAMESPACE::SwapchainCreateFlagsKHR flags_ ) VULKAN_HPP_NOEXCEPT { flags = flags_; return *this; } SwapchainCreateInfoKHR & setSurface( VULKAN_HPP_NAMESPACE::SurfaceKHR surface_ ) VULKAN_HPP_NOEXCEPT { surface = surface_; return *this; } SwapchainCreateInfoKHR & setMinImageCount( uint32_t minImageCount_ ) VULKAN_HPP_NOEXCEPT { minImageCount = minImageCount_; return *this; } SwapchainCreateInfoKHR & setImageFormat( VULKAN_HPP_NAMESPACE::Format imageFormat_ ) VULKAN_HPP_NOEXCEPT { imageFormat = imageFormat_; return *this; } SwapchainCreateInfoKHR & setImageColorSpace( VULKAN_HPP_NAMESPACE::ColorSpaceKHR imageColorSpace_ ) VULKAN_HPP_NOEXCEPT { imageColorSpace = imageColorSpace_; return *this; } SwapchainCreateInfoKHR & setImageExtent( VULKAN_HPP_NAMESPACE::Extent2D imageExtent_ ) VULKAN_HPP_NOEXCEPT { imageExtent = imageExtent_; return *this; } SwapchainCreateInfoKHR & setImageArrayLayers( uint32_t imageArrayLayers_ ) VULKAN_HPP_NOEXCEPT { imageArrayLayers = imageArrayLayers_; return *this; } SwapchainCreateInfoKHR & setImageUsage( VULKAN_HPP_NAMESPACE::ImageUsageFlags imageUsage_ ) VULKAN_HPP_NOEXCEPT { imageUsage = imageUsage_; return *this; } SwapchainCreateInfoKHR & setImageSharingMode( VULKAN_HPP_NAMESPACE::SharingMode imageSharingMode_ ) VULKAN_HPP_NOEXCEPT { imageSharingMode = imageSharingMode_; return *this; } SwapchainCreateInfoKHR & setQueueFamilyIndexCount( uint32_t queueFamilyIndexCount_ ) VULKAN_HPP_NOEXCEPT { queueFamilyIndexCount = queueFamilyIndexCount_; return *this; } SwapchainCreateInfoKHR & setPQueueFamilyIndices( const uint32_t* pQueueFamilyIndices_ ) VULKAN_HPP_NOEXCEPT { pQueueFamilyIndices = pQueueFamilyIndices_; return *this; } SwapchainCreateInfoKHR & setPreTransform( VULKAN_HPP_NAMESPACE::SurfaceTransformFlagBitsKHR preTransform_ ) VULKAN_HPP_NOEXCEPT { preTransform = preTransform_; return *this; } SwapchainCreateInfoKHR & setCompositeAlpha( VULKAN_HPP_NAMESPACE::CompositeAlphaFlagBitsKHR compositeAlpha_ ) VULKAN_HPP_NOEXCEPT { compositeAlpha = compositeAlpha_; return *this; } SwapchainCreateInfoKHR & setPresentMode( VULKAN_HPP_NAMESPACE::PresentModeKHR presentMode_ ) VULKAN_HPP_NOEXCEPT { presentMode = presentMode_; return *this; } SwapchainCreateInfoKHR & setClipped( VULKAN_HPP_NAMESPACE::Bool32 clipped_ ) VULKAN_HPP_NOEXCEPT { clipped = clipped_; return *this; } SwapchainCreateInfoKHR & setOldSwapchain( VULKAN_HPP_NAMESPACE::SwapchainKHR oldSwapchain_ ) VULKAN_HPP_NOEXCEPT { oldSwapchain = oldSwapchain_; return *this; } operator VkSwapchainCreateInfoKHR const&() const VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<const VkSwapchainCreateInfoKHR*>( this ); } operator VkSwapchainCreateInfoKHR &() VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<VkSwapchainCreateInfoKHR*>( this ); } #if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR) auto operator<=>( SwapchainCreateInfoKHR const& ) const = default; #else bool operator==( SwapchainCreateInfoKHR const& rhs ) const VULKAN_HPP_NOEXCEPT { return ( sType == rhs.sType ) && ( pNext == rhs.pNext ) && ( flags == rhs.flags ) && ( surface == rhs.surface ) && ( minImageCount == rhs.minImageCount ) && ( imageFormat == rhs.imageFormat ) && ( imageColorSpace == rhs.imageColorSpace ) && ( imageExtent == rhs.imageExtent ) && ( imageArrayLayers == rhs.imageArrayLayers ) && ( imageUsage == rhs.imageUsage ) && ( imageSharingMode == rhs.imageSharingMode ) && ( queueFamilyIndexCount == rhs.queueFamilyIndexCount ) && ( pQueueFamilyIndices == rhs.pQueueFamilyIndices ) && ( preTransform == rhs.preTransform ) && ( compositeAlpha == rhs.compositeAlpha ) && ( presentMode == rhs.presentMode ) && ( clipped == rhs.clipped ) && ( oldSwapchain == rhs.oldSwapchain ); } bool operator!=( SwapchainCreateInfoKHR const& rhs ) const VULKAN_HPP_NOEXCEPT { return !operator==( rhs ); } #endif public: const VULKAN_HPP_NAMESPACE::StructureType sType = StructureType::eSwapchainCreateInfoKHR; const void* pNext = {}; VULKAN_HPP_NAMESPACE::SwapchainCreateFlagsKHR flags = {}; VULKAN_HPP_NAMESPACE::SurfaceKHR surface = {}; uint32_t minImageCount = {}; VULKAN_HPP_NAMESPACE::Format imageFormat = VULKAN_HPP_NAMESPACE::Format::eUndefined; VULKAN_HPP_NAMESPACE::ColorSpaceKHR imageColorSpace = VULKAN_HPP_NAMESPACE::ColorSpaceKHR::eSrgbNonlinear; VULKAN_HPP_NAMESPACE::Extent2D imageExtent = {}; uint32_t imageArrayLayers = {}; VULKAN_HPP_NAMESPACE::ImageUsageFlags imageUsage = {}; VULKAN_HPP_NAMESPACE::SharingMode imageSharingMode = VULKAN_HPP_NAMESPACE::SharingMode::eExclusive; uint32_t queueFamilyIndexCount = {}; const uint32_t* pQueueFamilyIndices = {}; VULKAN_HPP_NAMESPACE::SurfaceTransformFlagBitsKHR preTransform = VULKAN_HPP_NAMESPACE::SurfaceTransformFlagBitsKHR::eIdentity; VULKAN_HPP_NAMESPACE::CompositeAlphaFlagBitsKHR compositeAlpha = VULKAN_HPP_NAMESPACE::CompositeAlphaFlagBitsKHR::eOpaque; VULKAN_HPP_NAMESPACE::PresentModeKHR presentMode = VULKAN_HPP_NAMESPACE::PresentModeKHR::eImmediate; VULKAN_HPP_NAMESPACE::Bool32 clipped = {}; VULKAN_HPP_NAMESPACE::SwapchainKHR oldSwapchain = {}; }; static_assert( sizeof( SwapchainCreateInfoKHR ) == sizeof( VkSwapchainCreateInfoKHR ), "struct and wrapper have different size!" ); static_assert( std::is_standard_layout<SwapchainCreateInfoKHR>::value, "struct wrapper is not a standard layout!" ); struct SwapchainDisplayNativeHdrCreateInfoAMD { VULKAN_HPP_CONSTEXPR SwapchainDisplayNativeHdrCreateInfoAMD( VULKAN_HPP_NAMESPACE::Bool32 localDimmingEnable_ = {} ) VULKAN_HPP_NOEXCEPT : localDimmingEnable( localDimmingEnable_ ) {} VULKAN_HPP_CONSTEXPR SwapchainDisplayNativeHdrCreateInfoAMD( SwapchainDisplayNativeHdrCreateInfoAMD const& rhs ) VULKAN_HPP_NOEXCEPT : pNext( rhs.pNext ) , localDimmingEnable( rhs.localDimmingEnable ) {} SwapchainDisplayNativeHdrCreateInfoAMD & operator=( SwapchainDisplayNativeHdrCreateInfoAMD const & rhs ) VULKAN_HPP_NOEXCEPT { memcpy( &pNext, &rhs.pNext, sizeof( SwapchainDisplayNativeHdrCreateInfoAMD ) - offsetof( SwapchainDisplayNativeHdrCreateInfoAMD, pNext ) ); return *this; } SwapchainDisplayNativeHdrCreateInfoAMD( VkSwapchainDisplayNativeHdrCreateInfoAMD const & rhs ) VULKAN_HPP_NOEXCEPT { *this = rhs; } SwapchainDisplayNativeHdrCreateInfoAMD& operator=( VkSwapchainDisplayNativeHdrCreateInfoAMD const & rhs ) VULKAN_HPP_NOEXCEPT { *this = *reinterpret_cast<VULKAN_HPP_NAMESPACE::SwapchainDisplayNativeHdrCreateInfoAMD const *>(&rhs); return *this; } SwapchainDisplayNativeHdrCreateInfoAMD & setPNext( const void* pNext_ ) VULKAN_HPP_NOEXCEPT { pNext = pNext_; return *this; } SwapchainDisplayNativeHdrCreateInfoAMD & setLocalDimmingEnable( VULKAN_HPP_NAMESPACE::Bool32 localDimmingEnable_ ) VULKAN_HPP_NOEXCEPT { localDimmingEnable = localDimmingEnable_; return *this; } operator VkSwapchainDisplayNativeHdrCreateInfoAMD const&() const VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<const VkSwapchainDisplayNativeHdrCreateInfoAMD*>( this ); } operator VkSwapchainDisplayNativeHdrCreateInfoAMD &() VULKAN_HPP_NOEXCEPT { return *reinterpret_cast<VkSwapchainDisplayNativeHdrCreateInfoAMD*>( this ); } #if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR) auto operator<=>( SwapchainDisplayNativeHdrCreateInfoAMD const& ) const = default; #else bool operator==( SwapchainDisplayNativeHdrCreateInfoAMD const& rhs ) const VULKAN_HPP_NOEXCEPT { return ( sType == rhs.sType ) && ( pNext == rhs.pNext ) && ( localDimmingEnable == rhs.localDimmingEnable ); } bool operator!=( SwapchainDisplayNativeHdrCreateInfoAMD const& rhs ) const VULKAN_HPP_NOEXCEPT { return !operator==( rhs ); } #endif public: const VULKAN_HPP_NAMESPACE::StructureType sType = StructureType::eSwapchainDisplayNativeHdrCreateInfoAMD; const void* pNext = {}; VULKAN_HPP_NAMESPACE::Bool32 localDimmingEnable = {}; }; static_assert( sizeof( SwapchainDisplayNativeHdrCreateInfoAMD ) == sizeof( VkSwapchainDisplayNativeHdrCreateInfoAMD ), "struct and wrapper have different size!" ); static_assert( std::is_standard_layout<SwapchainDisplayNativeHdrCreateInfoAMD>::value, "struct wrapper is not a standard layout!" ); } // namespace VULKAN_HPP_NAMESPACE
54ed83eb94788f3cfb1d41819597ce7accc195a1
8837bd83aa8373ac7c37628c0868ff6872f8c0aa
/distinctSubsequences.cpp
5ebd881fb2741fc6c44c93888ca4ad2e5a42fda4
[]
no_license
abhisehekkumr/DP
5fb86e04f5a8625ac0c1a634f6a9d6217dd7f866
5942921cbd37d26e1dad099b826851c81356cfc0
refs/heads/master
2022-02-05T19:23:08.344463
2019-08-08T17:53:19
2019-08-08T17:53:19
197,929,987
0
0
null
null
null
null
UTF-8
C++
false
false
853
cpp
distinctSubsequences.cpp
#include<iostream> #include<string> #include<unordered_map> using namespace std; void totalSubsequences(string str, unordered_map<string, int> &m, string ans = ""){ //std::cout << "ans : " << ans << '\n'; if(str.size() == 0) return; if(m.count(ans)) return; totalSubsequences(str.substr(1), m, ans + str[0]); totalSubsequences(str.substr(1), m,ans); m[ans + str[0]] = 1; m[ans] = 1; } int main(){ int t; cin >> t; while(t--){ string str; cin >> str; unordered_map<string,int> m; totalSubsequences(str, m); std::cout << m.size() << '\n'; /* unordered_map<string,int> :: iterator it; for(it = m.begin(); it != m.end(); it++) std::cout << it->first << '\n'; */ } }
2fc764fe08e0833754e1a34e96d87620b3cc5713
c39862dcbc5b9ad65f582752bcfd0c5eb9be463e
/dev/external/wxWidgets-3.1.0/include/wx/xrc/xh_toolb.h
e3f3f1416d57413c9bc61f4f7dd95c6e4b021c13
[ "MIT" ]
permissive
rexdex/recompiler
5f1138adf5d02a052c8b37c290296d5cf5faadc2
7cd1d5a33d6c02a13f972c6564550ea816fc8b5b
refs/heads/master
2023-08-16T16:24:37.810517
2022-02-12T21:20:21
2022-02-12T21:20:21
81,953,901
1,714
120
MIT
2022-02-12T21:20:22
2017-02-14T14:32:17
C++
UTF-8
C++
false
false
937
h
xh_toolb.h
///////////////////////////////////////////////////////////////////////////// // Name: wx/xrc/xh_toolb.h // Purpose: XML resource handler for wxToolBar // Author: Vaclav Slavik // Created: 2000/08/11 // Copyright: (c) 2000 Vaclav Slavik // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_XH_TOOLB_H_ #define _WX_XH_TOOLB_H_ #include "wx/xrc/xmlres.h" #if wxUSE_XRC && wxUSE_TOOLBAR class WXDLLIMPEXP_FWD_CORE wxToolBar; class WXDLLIMPEXP_XRC wxToolBarXmlHandler : public wxXmlResourceHandler { wxDECLARE_DYNAMIC_CLASS(wxToolBarXmlHandler); public: wxToolBarXmlHandler(); virtual wxObject *DoCreateResource() wxOVERRIDE; virtual bool CanHandle(wxXmlNode *node) wxOVERRIDE; private: bool m_isInside; wxToolBar *m_toolbar; wxSize m_toolSize; }; #endif // wxUSE_XRC && wxUSE_TOOLBAR #endif // _WX_XH_TOOLB_H_
a9dd3e3d5c3f2640a6080c4fa74845a87438fdd0
247aead7ae4d545b732babcaf8e2ab31e3ec4e3f
/methods/pw.cpp
d3ba3f4d3466054070f3843fdada8c42d3444238
[]
no_license
GaetanLhoest/FacadeClipper
787f1bcb5b35e72014d48a9169921138d23f4a74
ef31e0077b8169a9e98036729a0e6359f9a58c9c
refs/heads/master
2021-05-16T03:12:13.082129
2020-04-08T16:44:55
2020-04-08T16:44:55
40,994,763
0
0
null
null
null
null
UTF-8
C++
false
false
5,250
cpp
pw.cpp
#include "pw.h" #include <stdio.h> #include <sys/types.h> #include <sys/time.h> #include <time.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <mccodimage.h> #include <mcimage.h> #include <cccodimage.h> #include <lMSF.h> #include <MSF_RW.h> #include <powerwatsegm.h> #include <image_toolbox.h> #include <unistd.h> #include <argv.h> #include <iostream> #include <thread> using namespace cv; unsigned char * applyPowerWatershed(Mat &imageM, Mat &seedsM, short multipleseed){ unsigned char * image = imageM.data; int rs, cs, ds, N, M; struct xvimage * seeds = readimagecustom(seedsM.data, seedsM.rows, seedsM.cols); if (seeds == NULL) { fprintf(stderr, "msf_rw: readimage failed\n"); exit(1); } unsigned char * s = UCHARDATA(seeds); rs = rowsize(seeds); cs = colsize(seeds); ds = 1;//colsize(seeds); N = rs * cs * ds; M = ds*rs*(cs-1)+ds*(rs-1)*cs+(ds-1)*cs*rs; //number of edges uint32_t * weights = (uint32_t *)malloc(sizeof(uint32_t)*M); int ** edges; edges = (int**)malloc(2*sizeof(int*)); for(short i=0;i<2;i++) edges[i] = (int*)malloc(M*sizeof(int)); compute_edges(edges,rs, cs, ds); int * index_seeds = (int*)malloc(N*sizeof(int)); uint8_t * index_labels = (uint8_t*)malloc(N*sizeof(uint8_t)); int32_t nblabels, i,j; bool mult; if (multipleseed == 0) mult = false; else mult = true; //multilabel seed image j = 0; if (mult == true) { nblabels = 0; for (i=0;i<rs*cs*ds;i++) if(s[i]>0) { index_seeds[j]=i; index_labels[j]=s[i]; j++; if(s[i]>nblabels) nblabels = s[i]; } } else { nblabels=2; for (i=0;i<rs*cs*ds;i++) { if(s[i]>155) { index_seeds[j] = i; index_labels[j]=1; j++; } else if(s[i]<100) { index_seeds[j] = i; index_labels[j]=2; j++; } } } int size_seeds = j; freeimage(seeds); uint32_t * normal_weights ; uint32_t max_weight = 255; bool quicksort = false; int rows = imageM.rows; int cols = imageM.cols; normal_weights = color_standard_weights_PW_custom(image, weights, edges, index_seeds, size_seeds, &max_weight, quicksort, rows, cols); struct xvimage * img_proba; #ifndef SPEEDY img_proba = allocimage(NULL, rs, cs, ds, VFF_TYP_1_BYTE); #endif struct xvimage * outputcv = NULL; outputcv = PowerWatershed_q2(edges, weights, normal_weights,max_weight,index_seeds, index_labels, size_seeds,rs, cs, ds, nblabels, quicksort, img_proba); unsigned char *outputc = UCHARDATA(outputcv); return outputc; } void findPWMaskThreaded(Mat *tmpModified, Mat *MaskSeed) { int h = tmpModified->rows; int s[8]; int e[8]; int step = h/8; for (int i = 0; i < 8; i++){ s[i] = (i*step); e[i] = (i+1)*step; } e[7] = h; std::thread first(findPWMask, tmpModified, MaskSeed, s[0], e[0]); std::thread second(findPWMask, tmpModified, MaskSeed, s[1], e[1]); std::thread third(findPWMask, tmpModified, MaskSeed, s[2], e[2]); std::thread fourth(findPWMask, tmpModified, MaskSeed, s[3], e[3]); std::thread fifth(findPWMask, tmpModified, MaskSeed, s[4], e[4]); std::thread sixth(findPWMask, tmpModified, MaskSeed, s[5], e[5]); std::thread seventh(findPWMask, tmpModified, MaskSeed, s[6], e[6]); std::thread eighth(findPWMask, tmpModified, MaskSeed, s[7], e[7]); first.join(); second.join(); third.join(); fourth.join(); fifth.join(); sixth.join(); seventh.join(); eighth.join(); } void findPWMask(Mat *tmpModified, Mat *MaskSeed, int s, int e) { int sqsize = 15; int w = tmpModified->cols; int h = tmpModified->rows; int h1, h2; h1 = s; h2 = e; if (s == -1){ h1 = sqsize; h2 = h - sqsize; } if(s < sqsize and s != -1){ h1 = sqsize; } if(e > h - sqsize){ h2 = h-sqsize; } bool writeW, notwriteB; int index; unsigned short b, g, r; unsigned char *data = tmpModified->data; unsigned char *grey = MaskSeed->data; for (int i = h1; i < h2; i++){ for (int j = sqsize; j < w-sqsize; j++){ writeW = true; notwriteB = false; for (int k = i-sqsize; k <= i+sqsize; k++){ for (int l = j-sqsize; l <= j+sqsize; l++){ index = (k*w*3) + (3*l); b = data[index + 0]; g = data[index + 1]; r = data[index + 2]; if (!(b == 0 and g == 255 and r == 0)){ writeW = false; } if (b == 0 and g == 255 and r == 0){ notwriteB = true; } } } if (writeW){ grey[(w*i)+j] = 255; } if (!notwriteB){ grey[(w*i)+j] = 0; } } } }
635f2122d998849719932ae1fba29695d3ee6e98
5dbb5dda4cb89668111285976f2b34c8ed1447bb
/LaTeX/code/beaglebone/http.cpp
eed36da93ed8b0d4b37e6b4cb2d7545f43dc8a79
[]
no_license
BusoRN/MyThesis
47a2af06113786225426f67a86cbc20c54d2556a
dcf6799d1b0732d04f10d5dc19c7aeaa0d0f89c1
refs/heads/master
2021-01-22T02:49:20.341497
2015-03-19T10:55:31
2015-03-19T10:55:31
31,878,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,365
cpp
http.cpp
#include "http.h" void post_data_sensor(int type, float value){ CURL *curl; CURLcode res; /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, URL_POST.c_str()); /* Now specify the POST data */ std::ostringstream ss; ss << value; std::string s; if ( type == 0) s= POST_DATA_TEMPERATURE +(ss.str()); else if (type == 1) s= POST_DATA_PH +(ss.str()); else s= POST_DATA_BEATING + (ss.str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, s.c_str()); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); /* always cleanup */ curl_easy_cleanup(curl); } curl_global_cleanup(); }
0dff20c1241f749819bc7bf542dc1b2d672943a0
c2dbd667abeb1b37423f8eaee73bd395af290045
/Contest/Contest-E.cpp
14d8acb507652f90b0d73082db9e38a1f9930e1e
[]
no_license
BugMaker-Boyan/CS203-Sustech-DSAA
c925413cd5088f638bce051e5bb4d3e7f47e76e9
da258d960baed7e4d1b77bc3958fe58b76cedde1
refs/heads/master
2023-02-24T17:41:29.249361
2021-01-27T06:43:50
2021-01-27T06:43:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,191
cpp
Contest-E.cpp
//// //// Created by Boyan on 2021/1/2. //// //#include <iostream> //#include <cstring> //using namespace std; //typedef long long ll; //ll n,q,s,x,y; //#define fio ios::sync_with_stdio(false);istream::sync_with_stdio(false);ostream::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); // //ll number[10005]; //ll a[10005]; //ll copy_a[10005]; // //int main(){ // fio // cin>>n>>q; // for (int i = 1; i <= n ; ++i) { // cin>>number[i]; // } // a[1] = number[1]+number[2]; // a[n] = number[n-1]+number[n]; // for (int i = 2; i <= n-1 ; ++i) { // a[i] = number[i-1] + number[i] + number[i+1]; // } // for (int k = 0; k < q; ++k) { // memcpy(copy_a,a,sizeof a); // cin>>x>>y; // ll tot = 0; // for (int i = 1; i <=n ; ++i) { // if (copy_a[i]<x){ // ll inc = (x-copy_a[i]); // tot += inc; // copy_a[i] += inc; // copy_a[i+1] += inc; // copy_a[i+2] += inc; // } // } // if (tot > y){ // cout<<"No"<<endl; // }else{ // cout<<"Yes"<<endl; // } // } // // return 0; //}
8c4045885722655a32f3469fd79d0949169e1575
6136a66fb378a5dace4705fada2288c65cb03df8
/Assignments/Homework/Homework 2/mazequeue.cpp/mazequeue.cpp
a9c20637f24003842e18e339c86cf39df934cdd6
[]
no_license
ntjoar/CS32
a5360ddcd3742b0745f571c12aa42eb0a2764b39
7c8f8bfcf9ed21e85e7f499b8009ce3c6fa6fee6
refs/heads/master
2020-04-29T22:25:59.462504
2019-03-19T07:16:35
2019-03-19T07:16:35
176,434,010
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
cpp
mazequeue.cpp
// // main.cpp // mazequeue.cpp // // Created by Nathan Tjoar on 1/31/19. // Copyright © 2019 Nathan Tjoar. All rights reserved. // #include <iostream> #include <queue> using namespace std; class Coord { public: Coord(int rr, int cc) : m_r(rr), m_c(cc) {} int r() const { return m_r; } int c() const { return m_c; } private: int m_r; int m_c; }; bool pathExists(string maze[], int nRows, int nCols, int sr, int sc, int er, int ec); bool pathExists(string maze[], int nRows, int nCols, int sr, int sc, int er, int ec) { // Return true if there is a path from (sr,sc) to (er,ec) // through the maze; return false otherwise queue<Coord> cQueue; Coord start(sr, sc); cQueue.push(start); maze[sr][sc] = '*'; int row = sr; int col = sc; int i = 1; while(!cQueue.empty()) { start = cQueue.front(); row = start.r(); col = start.c(); cQueue.pop(); cout << i << ". (" << row << ", " << col << ")" << endl; i++; if(row == er && col == ec) return true; if(row != nRows - 1 && maze[row + 1][col] != 'X' && maze[row + 1][col] != '*') // Move South { Coord mv(row + 1, col); cQueue.push(mv); maze[row + 1][col] = '*'; } if(col != 0 && maze[row][col - 1] != 'X' && maze[row][col - 1] != '*') // Move West { Coord mv(row, col - 1); cQueue.push(mv); maze[row][col - 1] = '*'; } if(row != 0 && maze[row - 1][col] != 'X' && maze[row - 1][col] != '*') // Move North { Coord mv(row - 1, col); cQueue.push(mv); maze[row - 1][col] = '*'; } if(col != nCols - 1 && maze[row][col + 1] != 'X' && maze[row][col + 1] != '*') // Move East { Coord mv(row, col + 1); cQueue.push(mv); maze[row][col + 1] = '*'; } } return false; } int main() { string maze[10] = { "XXXXXXXXXX", "X....X...X", "X.XX.XX..X", "XXX....X.X", "X.XXX.XXXX", "X.X...X..X", "X...X.X..X", "XXXXX.X.XX", "X........X", "XXXXXXXXXX" }; if (pathExists(maze, 10,10, 3,5, 8,8)) cout << "Solvable!" << endl; else cout << "Out of luck!" << endl; }
cd98e19a2ec941ab2f1c68106be93d57e3a58959
303316f1105ab10d0978bab2731ee8d9ef0f7ee3
/module00/ex01/includes/map.h
872cb3748147372e2682c4f305dbbf3c0330fcdc
[]
no_license
AcensJJ/Piscine-CPP
db26bcc710ce916c3313e73f429dc8918b9f60d3
773d3614a2eb7bf9f1c3e2f5a31a07e5b1ee4c7e
refs/heads/master
2021-07-01T08:05:28.824226
2021-06-11T23:54:19
2021-06-11T23:54:19
241,883,493
0
3
null
null
null
null
UTF-8
C++
false
false
2,442
h
map.h
#ifndef MAP_H # define MAP_H # include <iostream> # include <string> # include <iomanip> class Contact { public: std::string getFirstName() const { return this->first_name; } void setFirstName(std::string value); std::string getLastName() const { return this->last_name; } void setLastName(std::string value); std::string getNickname() const { return this->nickname; } void setNickname(std::string value); std::string getLogin() const { return this->login; } void setLogin(std::string value); std::string getPostAddr() const { return this->postal_address; } void setPostAddr(std::string value); std::string getEmail() const { return this->email_address; } void setEmail(std::string value); std::string getPhone() const { return this->phone_number; } void setPhone(std::string value); std::string getBirthday() const { return this->birthday_date; } void setBirthday(std::string value); std::string getMeal() const { return this->favorite_meal; } void setMeal(std::string value); std::string getColor() const { return this->underwear_color; } void setColor(std::string value); std::string getSecret() const { return this->darkest_secret; } void setSecret(std::string value); private: std::string first_name, last_name, nickname, login, postal_address, email_address, phone_number, birthday_date, favorite_meal, underwear_color, darkest_secret; }; inline void Contact::setFirstName(std::string value) { this->first_name = value; } inline void Contact::setLastName(std::string value) { this->last_name = value; } inline void Contact::setNickname(std::string value) { this->nickname = value; } inline void Contact::setLogin(std::string value) { this->login = value; } inline void Contact::setPostAddr(std::string value) { this->postal_address = value; } inline void Contact::setEmail(std::string value) { this->email_address = value; } inline void Contact::setPhone(std::string value) { this->phone_number = value; } inline void Contact::setBirthday(std::string value) { this->birthday_date = value; } inline void Contact::setMeal(std::string value) { this->favorite_meal = value; } inline void Contact::setColor(std::string value) { this->underwear_color = value; } inline void Contact::setSecret(std::string value) { this->darkest_secret = value; } #endif
e9cd339ca3adc60b064d910c820e9f413333827e
f3e7a082d261d68467d15346118740c5a3db9fd8
/nwn_tools/CERF/CERF.h
cb3a1bc1de60aaad5f6c4330df1758bace5bb7dc
[]
no_license
DanielmGoulart/Sinfar-NWNX
1dea766e8a1f5bf2c5667725f56ef26b6cc5d841
ae76cf748c0e3be14d18050c62064de18fad4849
refs/heads/master
2021-08-22T10:14:22.792483
2017-11-30T00:21:05
2017-11-30T00:21:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
h
CERF.h
#pragma once #include <stdint.h> #include <string> #include <cstring> #include <vector> #include <map> #include <memory> #include <fstream> #include "../../nwnx/common/include/structs/CResRef.h" #include "../CKey/CKey.h" namespace aurora { class CERF : public CResourcesContainer { friend class CERFResource; public: CERF(const std::string& filepath); #pragma pack(push, 1) struct ERF_HEADER { char FileType[4]; char Version[4]; uint32_t LanguageCount; uint32_t LocalizedStringSize; uint32_t EntryCount; uint32_t OffsetToLocalizedString; uint32_t OffsetToKeyList; uint32_t OffsetToResourceList; uint32_t BuildYear; uint32_t BuildDay; uint32_t DescriptionStrRef; uint8_t Reserved[116]; }; struct ERF_KEY { char ResRef[16]; uint32_t ResID; uint16_t ResType; uint16_t Unused; }; struct ERF_RESOURCE { uint32_t OffsetToResource; uint32_t ResourceSize; }; #pragma pack(pop) ERF_HEADER header; std::string filepath; }; class CERFResource : public CResourceData { public: CERFResource(CERF& erf, CERF::ERF_RESOURCE res_info) : erf(erf), res_info(res_info) {}; void ReadData(char* buffer); uint32_t GetDataSize() { return res_info.ResourceSize; } CERF& erf; CERF::ERF_RESOURCE res_info; }; }
6aa4f659979f277b2a3eb77160a05a66263de761
c47c254ca476c1f9969f8f3e89acb4d0618c14b6
/datasets/github_cpp_10/9/6.cpp
599bd7fdf2479b4a5b1adffc56d6a1be736d30a5
[ "BSD-2-Clause" ]
permissive
yijunyu/demo
5cf4e83f585254a28b31c4a050630b8f661a90c8
11c0c84081a3181494b9c469bda42a313c457ad2
refs/heads/master
2023-02-22T09:00:12.023083
2021-01-25T16:51:40
2021-01-25T16:51:40
175,939,000
3
6
BSD-2-Clause
2021-01-09T23:00:12
2019-03-16T07:13:00
C
UTF-8
C++
false
false
843
cpp
6.cpp
#ifndef PROJECT_STRINGREVERSE_H #define PROJECT_STRINGREVERSE_H class stringReverse { }; void LeftShiftOne(char* s,int n){ char t = s[0]; for(int i=1;i<n;i++){ s[i-1] = s[i]; } s[n-1] = t; } void LeftRotateString_1(char* s,int n,int m){ while(m--){ LeftShiftOne(s,n); } } void ReverseString(char* s, int from, int to){ while(from < to){ char t = s[from]; s[from++] = s[to]; s[to--] = t; } } void LeftRotateString_2(char* s,int n,int m){ m %= n ; ReverseString(s,0,m-1); ReverseString(s,m,n-1); ReverseString(s,0,n-1); } void ReverseWords(char* s,int n){ ReverseString(s,0,n-1); int i=0,j=0; for(i=0,j=0;j<n;j++){ if(j==n||s[j+1]==' '){ ReverseString(s,i,j); i=j+2; } } } #endif
63135857dc7d3b6f971c32df9ef06c6abeb4bd71
935bf285a814882fc4ca8bdbd41c6847101752dc
/CustomerList.cpp
65830afe0c6d90b7feeac8dee293925e570c4e85
[]
no_license
Ranner198/CS221_Project_3
33f0d09c101694af1d62817d2075b545e17b554f
e7578bcbad7cf6fc1487738dca94e48e3dbcb99f
refs/heads/master
2020-03-23T21:04:01.354396
2018-07-25T19:37:16
2018-07-25T19:37:16
142,079,374
0
0
null
null
null
null
UTF-8
C++
false
false
2,731
cpp
CustomerList.cpp
/******************************************************************* * EmployeeRecord.cpp * Ran Crump * Prog 1 - Employee Record * * This program is entirely my own work *******************************************************************/ #include <stdlib.h> #include <iostream> #include <iomanip> #include "EmployeeRecord.h" #include "Store.h" using namespace std; CustomerList::CustomerList() { m_pHead = NULL; }; CustomerList::~CustomerList() { Store *temp; while(m_pHead != NULL) { temp = m_pHead; m_pHead = m_pHead->m_pNext; delete temp; } }; //Modified Code from Code Vault 221 -Ordered List- bool CustomerList::addStore(Store *s) { Store *temp, *back, *newNode; newNode = new Store(*s); newNode->m_pNext = NULL; if (m_pHead == NULL) { m_pHead = newNode; } else { temp = m_pHead; back = NULL; while ((temp != NULL) && (temp->getStoreID() < s->getStoreID())) { back = temp; temp = temp->m_pNext; } if (back == NULL) { newNode->m_pNext = m_pHead; m_pHead = newNode; } else { back->m_pNext = newNode; newNode->m_pNext = temp; } } return true; }; bool CustomerList::updateStore(int ID, char *name, char *addr, char *city, char *st, char *zip) { Store *temp; if (m_pHead == NULL) { return false; } temp = m_pHead; while ((temp != NULL) && (ID != temp->getStoreID())) { temp = temp->m_pNext; } if (temp != NULL) { temp->setStoreName(name); temp->setStoreAddress(addr); temp->setStoreCity(city); temp->setStoreState(st); temp->setStoreZip(zip); } else { return false; } return true; }; Store *CustomerList::removeStore(int ID) { Store *temp, *back; temp = m_pHead; back = NULL; while((temp != NULL) && (ID != temp->getStoreID())) { back = temp; temp = temp->m_pNext; } if (temp != NULL) { if (back == NULL) { m_pHead = m_pHead->m_pNext; return temp; } else { back->m_pNext = temp->m_pNext; return temp; } } else { return NULL; } }; Store *CustomerList::getStore(int ID) { Store *temp; temp = m_pHead; while ((temp != NULL) && (ID != temp->getStoreID())) { temp = temp->m_pNext; } if (temp != NULL) { Store *copy = new Store; *copy = *temp; copy->m_pNext = NULL; copy->printStoreInfo(); return copy; } else { return NULL; } }; void CustomerList::printStoresInfo() { Store *temp; if (m_pHead == NULL) { cout<<"The list is currently empty, try adding some stores and try again..." << endl; } else { temp = m_pHead; while(temp != NULL) { temp->printStoreInfo(); temp=temp->m_pNext; } } };
e3ca60ff39abd5aa6000d34587a4d95e43070504
b18b7d5941a27c860619515a8d72a1420a92bdcb
/arduino/sketchbook/habitus.ino
9d00d1e33029547663d11935b47de8e9524a5482
[]
no_license
LaboratoireInsertio/Habitus
28e51daf48a60a66cb28179426383eeb3f46cbc7
aeef57547f059c91b1d233fc3cf96c762c3ef47e
refs/heads/master
2018-10-08T13:37:33.541166
2018-06-22T18:16:00
2018-06-22T18:16:00
76,824,787
0
0
null
null
null
null
UTF-8
C++
false
false
8,001
ino
habitus.ino
/*********************************************************************************** * * Demo Arduino code for 4CH AC DIMMER MODULE * * AC LINE FREQUENCY - 60HZ ! * * Variables for dimming - buf_CH1, buf_CH2, buf_CH3, buf_CH4 ! * * Variables have range 0-255. 0 - Fully ON, 255 - Fully OFF. * * KRIDA Electronics, 4 SEP 2016 ***********************************************************************************/ #include <string.h> #include <TimerThree.h> #define SERIAL_BUFFER_SIZE 256 // ANALOG SENSORS // #define SENS_SOUND_GLOB A0 #define SENS_PHOTO_DOWN A1 #define SENS_PHOTO_UP A2 int sensSoundGlob = 0; int sensPhotoDown = 0; int sensPhotoUp = 0; // DIGITAL SENSORS // #define SENS_SOUND_INTE 4 #define SENS_PIR 5 byte sensSoundInte = 0; byte sensPir = 0; // sensor timer unsigned long lastSensorReading = 0; // REALYS (SmartTint) // #define RELAY_CH1 34 #define RELAY_CH2 35 #define RELAY_CH3 36 #define RELAY_CH4 37 #define RELAY_CH5 38 #define RELAY_CH6 39 #define RELAY_CH7 40 #define RELAY_CH8 41 #define channel_1 24 #define channel_2 25 #define channel_3 26 #define channel_4 27 #define channel_5 28 #define channel_6 29 #define channel_7 30 #define channel_8 31 #define SPEED 1 #define GATE_IMPULSE 9 #define FREQ 84 #define freqDelay 8.33 unsigned long interval=10; // the time we need to wait unsigned long previousMillis=0; byte arrayBulbs[8][2]; byte arrayTints[8][2] = { {34,LOW},{35,LOW},{36,LOW},{37,LOW},{38,LOW},{39,LOW},{40,LOW},{41,LOW} }; unsigned int CH1, CH2, CH3, CH4, CH5, CH6, CH7, CH8; unsigned int buf_CH1, buf_CH2, buf_CH3, buf_CH4,buf_CH5, buf_CH6, buf_CH7, buf_CH8; unsigned char clock_cn; unsigned int clock_tick; unsigned char i; int stepBulb = 5; // Serial declaration ---------------------// const byte numChars = 50; char receivedChars[numChars]; char *p; boolean newData = false; void timerIsr() { clock_tick++; if (CH1==clock_tick) { digitalWrite(channel_1, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_1, LOW); // triac Off } if (CH2==clock_tick) { digitalWrite(channel_2, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_2, LOW); // triac Off } if (CH3==clock_tick) { digitalWrite(channel_3, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_3, LOW); // triac Off } if (CH4==clock_tick) { digitalWrite(channel_4, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_4, LOW); // triac Off } if (CH5==clock_tick) { digitalWrite(channel_5, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_5, LOW); // triac Off } if (CH6==clock_tick) { digitalWrite(channel_6, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_6, LOW); // triac Off } if (CH7==clock_tick) { digitalWrite(channel_7, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_7, LOW); // triac Off } if (CH8==clock_tick) { digitalWrite(channel_8, HIGH); // triac firing delayMicroseconds(freqDelay); // triac On propogation delay (for 60Hz use 8.33) digitalWrite(channel_8, LOW); // triac Off } } void zero_crosss_int() { CH1=buf_CH1; CH2=buf_CH2; CH3=buf_CH3; CH4=buf_CH4; CH5=buf_CH5; CH6=buf_CH6; CH7=buf_CH7; CH8=buf_CH8; clock_tick=0; } unsigned int DIMM_VALUE (unsigned char level) { unsigned int buf_level; if (level < 26) {level=26;} if (level > 247) {level=247;} return ((level*(FREQ))/256)*freqDelay; } void setup() { Serial.begin (1000000); // // initializes relay pins as outputs // for (int i = RELAY_CH1; i <= RELAY_CH8; i++) // pinMode(i, OUTPUT); // initializes dimer pins as outputs for (int i = channel_1; i <= channel_8; i++) pinMode(i, OUTPUT); attachInterrupt(0, zero_crosss_int, RISING); Timer3.initialize(8.33); Timer3.attachInterrupt( timerIsr ); //Setup array for bulbs values for(i=0;i<8;i++){ arrayBulbs[i][0] = 255; arrayBulbs[i][1] = 255; // initializes relay pins as outputs pinMode(arrayTints[i][0], OUTPUT); } } void sendValue(String sensor, int value){ // Serial.print("<"); Serial.print(sensor); Serial.print(":"); Serial.println(value, DEC); // Serial.println(">"); } void recvWithStartEndMarkers() { static boolean recvInProgress = false; static byte ndx = 0; char startMarker = '<'; char endMarker = '>'; char rc; // if (Serial.available() > 0) { while (Serial.available() > 0 && newData == false) { rc = Serial.read(); if (recvInProgress == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string recvInProgress = false; ndx = 0; newData = true; } } else if (rc == startMarker) { recvInProgress = true; } } } void showNewData() { String type; int id; int value; if (newData == true) { // Serial.println(receivedChars); type = strtok(receivedChars,":"); if(type == "b"){ for(int b=0;b<8;b++){ arrayBulbs[b][1] = atol(strtok(NULL,":")); arrayBulbs[b][1] = map(arrayBulbs[b][1], 0,255,255,0); } } if(type == "t"){ for(int b=0;b<8;b++){ arrayTints[b][1] = atol(strtok(NULL,":")); digitalWrite(arrayTints[b][0], arrayTints[b][1]); } } newData = false; } } void loop() { if ((unsigned long)(millis() - previousMillis) >= 5) { previousMillis = millis(); recvWithStartEndMarkers(); showNewData(); //Read data sensors and send sensSoundGlob = analogRead(SENS_SOUND_GLOB); if(sensSoundGlob > 5){ sendValue("sensSoundGlobal", sensSoundGlob); } if(sensSoundInte != digitalRead(SENS_SOUND_INTE)){ sensSoundInte = digitalRead(SENS_SOUND_INTE); if(sensSoundInte == 1) sendValue("sensSoundInte", sensSoundInte); } if(sensPir != digitalRead(SENS_PIR)){ sensPir = digitalRead(SENS_PIR); if(sensPir == 1) sendValue("sensPir",sensPir); } for(i=0;i<8;i++){ if(arrayBulbs[i][0] != arrayBulbs[i][1]){ if(arrayBulbs[i][0] < arrayBulbs[i][1]){ arrayBulbs[i][0] = arrayBulbs[i][0] + stepBulb; if(arrayBulbs[i][0] > 255) arrayBulbs[i][0] = 255; }else{ arrayBulbs[i][0] = arrayBulbs[i][0] - stepBulb; if(arrayBulbs[i][0] < 0) arrayBulbs[i][0] = 0; } //@TODO: Need Simplify this code if(i==0){ buf_CH1=DIMM_VALUE(arrayBulbs[i][0]); } if(i==1){ buf_CH2=DIMM_VALUE(arrayBulbs[i][0]); } if(i==2){ buf_CH3=DIMM_VALUE(arrayBulbs[i][0]); } if(i==3){ buf_CH4=DIMM_VALUE(arrayBulbs[i][0]); } if(i==4){ buf_CH5=DIMM_VALUE(arrayBulbs[i][0]); } if(i==5){ buf_CH6=DIMM_VALUE(arrayBulbs[i][0]); } if(i==6){ buf_CH7=DIMM_VALUE(arrayBulbs[i][0]); } if(i==7){ buf_CH8=DIMM_VALUE(arrayBulbs[i][0]); } // Serial.print("Bulb : "); Serial.print(i);Serial.print(" value : ");Serial.println(arrayBulbs[i][0]); if(arrayBulbs[i][0] == arrayBulbs[i][1]){ // Serial.print("Bulb updated to : "); // Serial.println(arrayBulbs[i][0]); } } } } }
c01aeea8599913bc66b05cd891f67dc0ee6f4df1
b53db618066350fd2ed7090c8b173b5c8a0dc45a
/ffs-desktop/launcher/launcherwindow.cpp
e6d813639f03ae643fc0ab13a7c967bbf1c8e934
[]
no_license
daffodil/ffs-desktop
ec23506eb55fb31bfe8966cc30810f71f24bcd7e
fa753575cc5c74a92c5243030abe2fa225f946e8
refs/heads/master
2021-01-22T14:38:52.106543
2011-03-29T16:29:26
2011-03-29T16:29:26
926,927
0
0
null
null
null
null
UTF-8
C++
false
false
4,981
cpp
launcherwindow.cpp
#include <QtGui/QVBoxLayout> #include <QtGui/QHeaderView> #include "launcher/launcherwindow.h" LauncherWindow::LauncherWindow(MainObject *mainOb, QWidget *parent) : QMainWindow(parent) { mainObject = mainOb; setProperty("settings_namespace", QVariant("launcher_window")); mainObject->settings->restoreWindow(this); setWindowTitle("fgX Launcher"); setWindowIcon(QIcon(":/icons/launcher")); //setWindowFlags( Qt::WindowStaysOnTopHint); //* MainWidget and MainLayout QWidget *mainWidget = new QWidget(this); setCentralWidget(mainWidget); QVBoxLayout *mainVBox = new QVBoxLayout(); mainVBox->setContentsMargins(0,0,0,0); mainVBox->setSpacing(0); mainWidget->setLayout(mainVBox); //** Header Banner across the top ========================= QString header_style("padding: 10px; font-size: 11pt; font-weight: bold; background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 white, stop: 1 #F0DD17);"); headerLabel = new QLabel(this); headerLabel->setText("fgX Launcher"); headerLabel->setStyleSheet(header_style); mainVBox->addWidget(headerLabel, 0); splitter = new QSplitter(); mainVBox->addWidget(splitter, 20); //** Main Tab ========================= tabWidget = new QTabWidget(this); splitter->addWidget(tabWidget); connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(on_tab_changed(int))); //================================================== // Widgets //* Aircraft Widget aircraftWidget = new AircraftWidget(mainObject); tabWidget->addTab(aircraftWidget, tr("Aircraft")); connect(aircraftWidget, SIGNAL(set_arg(QString,QString,QString)), this, SLOT(set_arg(QString,QString,QString))); //* Options mainOptionsWidget = new MainOptionsWidget(mainObject); tabWidget->addTab(mainOptionsWidget, tr("Main Options")); connect(mainOptionsWidget, SIGNAL(set_arg(QString,QString,QString)), this, SLOT(set_arg(QString,QString,QString))); //* MpServers mpServersWidget = new MpServersWidget(mainObject); tabWidget->addTab(mpServersWidget, tr("Network")); connect(mpServersWidget, SIGNAL(set_arg(QString,QString,QString)), this, SLOT(set_arg(QString,QString,QString))); //* Airports Widget airportsWidget = new AirportsWidget(mainObject); tabWidget->addTab(airportsWidget, tr("Airports")); connect(airportsWidget, SIGNAL(set_arg(QString,QString,QString)), this, SLOT(set_arg(QString,QString,QString))); //============================================================= // ## Tree tree = new QTreeWidget(); tree->setRootIsDecorated(false); tree->setMinimumWidth(400); tree->headerItem()->setText(0, "Option"); tree->headerItem()->setText(1, "Value"); tree->header()->setStretchLastSection(true); tree->setColumnWidth(C_ARG, 200); splitter->addWidget(tree); setup_tree(); splitter->setStretchFactor(0,3); splitter->setStretchFactor(1,1); //********************************************************* //** Control Bar //********************************************************* controlBarWidget = new ControlBarWidget(mainObject); mainVBox->addWidget(controlBarWidget, 1); //controlBarWidget->hide(); set_paths(); } LauncherWindow::~LauncherWindow() { } //void LauncherWindow::closeEvent( event ){ // // self.main.settings.save_window( "account_dialog", self ) // qDebug() << "close"; //} void LauncherWindow::closeEvent(QCloseEvent *event){ Q_UNUSED(event); mainObject->settings->saveWindow(this); } void LauncherWindow::on_tab_changed(int tab_index){ Q_UNUSED(tab_index); //TODO maybe we dont need this.. // pusedo code // if isistance(widget, FooClass) : load() } void LauncherWindow::setup_tree(){ return; QStringList args; args << "fgfs" << "--fg-root" << "--aircraft" << "--airport" << "--runway" << "--callsign"; for (int i = 0; i < args.size(); ++i){ QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText(0, args.at(i)); tree->addTopLevelItem(item); } } void LauncherWindow::set_arg(QString action, QString arg, QString val){ qDebug() << "set_arg" << action << " " << arg << " " << val; QList<QTreeWidgetItem *> items = tree->findItems(arg, Qt::MatchExactly, 0); if(action == "remove"){ if(items.count() == 0){ //* item not there return; } QTreeWidgetItem *removeItem = items.first(); tree->invisibleRootItem()->removeChild(removeItem); return; } if(action == "set"){ if(items.count() == 0){ QTreeWidgetItem *newItem = new QTreeWidgetItem(); //* add Item if not exist newItem->setText(C_ARG, arg); newItem->setTextAlignment(C_ARG, Qt::AlignRight); newItem->setText(C_VAL, val); tree->addTopLevelItem(newItem); return; }else{ QTreeWidgetItem *item = items.first(); //* update existing item->setText(C_VAL, val); return; } } qDebug() << "UNHANDLED"; } void LauncherWindow::set_paths(){ set_arg("set", "fgfs", mainObject->settings->fgfs_path()); set_arg("set", "--fg-root=", mainObject->settings->fg_root()); }
d8cd74dfbf4e4de848a8e2c3808ee40204b8165c
c67ed12eae84af574406e453106b7d898ff47dc7
/chap17/Exer17_33.cpp
3299deb1706f8cb933db7f742ba0e00958ec3954
[ "Apache-2.0" ]
permissive
chihyang/CPP_Primer
8374396b58ea0e1b0f4c4adaf093a7c0116a6901
9e268d46e9582d60d1e9c3d8d2a41c1e7b83293b
refs/heads/master
2022-09-16T08:54:59.465691
2022-09-03T17:25:59
2022-09-03T17:25:59
43,039,810
58
23
Apache-2.0
2023-01-14T07:06:19
2015-09-24T02:25:47
C++
UTF-8
C++
false
false
2,383
cpp
Exer17_33.cpp
// Note: this file uses data file ./data/map and ./data/input #include <cstddef> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <random> #include <ctime> #include <stdexcept> using std::size_t; using std::cout; using std::endl; using std::ifstream; using std::istringstream; using std::string; using std::vector; using std::map; using std::default_random_engine; using std::uniform_real_distribution; using std::runtime_error; map<string, vector<string>> buildMap(ifstream &map_file) { map<string, vector<string>> trans_map; string key, value; while(map_file >> key && getline(map_file, value)) { if(value.size() > 1) { string word; istringstream is(value); while(is >> word) trans_map[key].push_back(word); // using white space as separator } else throw runtime_error("no rule for " + key + " at " + __func__); } return trans_map; } const string& transform(const string &s, const map<string, vector<string>> &m) { // static object to generate random numbers static default_random_engine e(time(0)); static uniform_real_distribution<double> u(0, 1); auto map_it = m.find(s); if(map_it != m.cend()) { size_t select = map_it->second.size() * u(e); // truncated, won't be out of range return map_it->second[select]; } else return s; } void word_transform(ifstream &map_file, ifstream &input) { auto trans_map = buildMap(map_file); string text; while(getline(input, text)) { istringstream stream(text); string word; bool firstword = true; while(stream >> word) { // process leading space if(firstword) firstword = false; else cout << " "; // process word cout << transform(word, trans_map); } cout << endl; } } int main(int argc, char *argv[]) { if(argc != 3) return -1; for (size_t i = 0; i < 10; ++i) { ifstream map_file(argv[1]), input_file(argv[2]); try { word_transform(map_file, input_file); } catch(runtime_error err) { cout << "Error: " << err.what() << endl; } } return 0; }
cf603b66386fe15fcda2ae5f3ecde75f37159009
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/windows/advcore/ctf/aimm1.2/dimm/imewnd.h
ec9d164951ab74df67c128c741d194cb1b725432
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
7,353
h
imewnd.h
/*++ Copyright (c) 1985 - 1999, Microsoft Corporation Module Name: imewnd.h Abstract: This file defines the Default IME Window Class. Author: Revision History: Notes: --*/ #ifndef _IMEWND_H_ #define _IMEWND_H_ #include "cstring.h" extern "C" { // windows subclass LRESULT ImeWndProcA(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT ImeWndProcW(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); } class CDefaultIMEWindow { public: CDefaultIMEWindow() { m_hDefaultIMEWnd = NULL; m_hDummyDefaultIMEWnd = NULL; m_nCntInAIMEProc = 0; m_bMyRegisterClass = FALSE; m_bMyCreateWindow = FALSE; // m_bNeedRecoverIMEWndProc = FALSE; m_SubclassWindowProc = 0; } virtual ~CDefaultIMEWindow() { if (IsWindow(m_hDefaultIMEWnd) && m_SubclassWindowProc) { // // Set the wndproc pointer back to original WndProc. // // some other subclass window may keep my WndProc pointer. // but msctf.dll may be unloaded from memory so we don't want to // call him to set the wndproc pointer back to our Wndproc pointer. // The pointer will be bogus. // WNDPROC pfnOrgImeWndProc; pfnOrgImeWndProc = (WNDPROC)GetClassLongPtr(m_hDefaultIMEWnd, GCLP_WNDPROC); SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, (LONG_PTR)pfnOrgImeWndProc); m_SubclassWindowProc = NULL; } } HRESULT GetDefaultIMEWnd(IN HWND hWnd, OUT HWND *phDefWnd); LRESULT CallWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT SendIMEMessage(UINT Msg, WPARAM wParam, LPARAM lParam, BOOL fUnicode = TRUE, BOOL fCheckImm32 = TRUE) { if (fCheckImm32 && IsOnImm()) { return 0L; } LRESULT lRet; InterlockedIncrement(&m_nCntInAIMEProc); // Mark to avoid recursion. if (fUnicode) lRet = SendMessageW(m_hDefaultIMEWnd, Msg, wParam, lParam); else lRet = SendMessageA(m_hDefaultIMEWnd, Msg, wParam, lParam); InterlockedDecrement(&m_nCntInAIMEProc); return lRet; } BOOL IsAIMEHandler() { return (m_nCntInAIMEProc > 0); } public: BOOL _CreateDefaultIMEWindow(HIMC hDefIMC); BOOL _DestroyDefaultIMEWindow(); protected: HWND _CreateIMEWindow(HIMC hDefIMC); public: BOOL IsNeedRecovIMEWndProc() { #if 0 return (m_bNeedRecoverIMEWndProc == TRUE); #endif return FALSE; } private: #if 0 BOOL InitDefIMEWndSubclass() { if (m_SubclassWindowProc == NULL) { m_SubclassWindowProc = SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, (LONG_PTR)ImeWndProcA); if (IsOnImm()) { LONG_PTR _OriginalWindowProc = GetWindowLongPtr(m_hDummyDefaultIMEWnd, GWLP_WNDPROC); // // We assume the m_SubclassWindowProc and _OriginalWindowProc are // the same address of USER32!ImeWndProcA/W. // if (m_SubclassWindowProc != _OriginalWindowProc) { // // Anybody rewrote the default IME window procedure address. // We know the MSIME9x/2K rewrote an address to MSIMEPrivateWindowProc. // We should catch a recovery procedure address by the IME // that using window call hook the _DefImeWnd_CallWndProc. // m_bNeedRecoverIMEWndProc = TRUE; } } } return (m_SubclassWindowProc != 0); } #endif BOOL Start() { Assert(IsWindow(m_hDefaultIMEWnd)); if (m_SubclassWindowProc == NULL) { m_SubclassWindowProc = SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, (LONG_PTR)ImeWndProcA); } return (m_SubclassWindowProc != 0); } #if 0 VOID UninitDefIMEWndSubclass() { if (m_SubclassWindowProc) { SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, m_SubclassWindowProc); m_SubclassWindowProc = NULL; } } #endif WNDPROC Stop() { Assert(IsWindow(m_hDefaultIMEWnd)); WNDPROC pfnBack = (WNDPROC)m_SubclassWindowProc; if (m_SubclassWindowProc != NULL) { // // unfortunately, we can not restore the wndproc pointer always. // someone else subclassed it after we did. // WNDPROC pfnCur = (WNDPROC)GetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC); if (pfnCur == ImeWndProcA) { SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, (LONG_PTR) m_SubclassWindowProc); m_SubclassWindowProc = NULL; } } return pfnBack; } public: VOID ImeDefWndHook(HWND hWnd) { #if 0 LONG_PTR _WindowProc = GetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC); ASSERT(m_hDummyDefaultIMEWnd != NULL); LONG_PTR _OriginalWindowProc = GetWindowLongPtr(m_hDummyDefaultIMEWnd, GWLP_WNDPROC); if (_WindowProc == _OriginalWindowProc) { // // Recovered procedure address. // m_SubclassWindowProc = SetWindowLongPtr(m_hDefaultIMEWnd, GWLP_WNDPROC, (LONG_PTR)ImeWndProcA); } #endif } private: HWND m_hDefaultIMEWnd; // Handle of default IME window. HWND m_hDummyDefaultIMEWnd; // Handle of Dummy default IME window. LONG m_nCntInAIMEProc; // Non-zero if hwnd has called into CCiceroIME::ActivateLayout/DeactivateLayout. BOOL m_bMyRegisterClass; // TRUE: RegisterClass("IME") myself. BOOL m_bMyCreateWindow; // TRUE: CreateWindow("IME") myself. // BOOL m_bNeedRecoverIMEWndProc; // TRUE: Need a recovery IME wnd proc addr. LONG_PTR m_SubclassWindowProc; // Address of subclass window procedure. }; LRESULT ImeWndDestroyHandler(HWND hwnd); LRESULT ImeSelectHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL fUnicode); LRESULT ImeControlHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL fUnicode); LRESULT ImeSetContextHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL fUnicode); LRESULT ImeNotifyHandler(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL fUnicode); #endif // _IMEWND_H_
661da04ee4c2b81efe27451526ae2427f2bb438d
3c9f240e1735e8a90736506bf59055c19a9c7b88
/leet_code/reverseWords.h
1cc1b320b08926513fe838ac311d028f654cef96
[]
no_license
jaykop/cpp_note
110b2660580a84796e5347bbb1bcf12af26e46b7
38503b8634e327fa64126344a209ad855ef030ce
refs/heads/master
2022-02-22T19:46:57.856936
2022-02-09T11:18:48
2022-02-09T11:18:48
189,674,148
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
reverseWords.h
#pragma once class Solution { public: string reverseWords(string s) { vector<string> chunks; string mid, res; for (int i = s.length() - 1; i >= 0; i--) { if (s[i] == ' ') { chunks.emplace_back(mid); mid = ""; } else mid += s[i]; } chunks.emplace_back(mid); while (!chunks.empty()) { auto str = chunks.back(); chunks.pop_back(); res += str; if (!chunks.empty()) res += " "; } return res; } }; //class Solution { //public: // string reverseWords(string s) { // for (int i = 0; i < s.length(); i++) { // if (s[i] != ' ') { // when i is a non-space // int j = i; // for (; j < s.length() && s[j] != ' '; j++) {} // move j to the next space // reverse(s.begin() + i, s.begin() + j); // i = j - 1; // } // } // // return s; // } //};
2b396794f1279f5790a43a08d28b61140562f560
73795a41095db06ef79a5d3a6374e6554ea0ec26
/tests/test_zip_tuple.cc
b4ca9416f534b3a5e57accd8ce4500e06ae68cb6
[ "BSL-1.0" ]
permissive
EVaillant/toolsbox
9d63d530d7aa52bac27dc3fdd606620a94970180
bc84fed59c7d440f322c49a82d299b2336d7b6c8
refs/heads/master
2021-01-10T17:08:06.941420
2016-05-03T20:32:53
2016-05-03T20:32:53
46,289,342
3
1
null
null
null
null
UTF-8
C++
false
false
1,380
cc
test_zip_tuple.cc
#define BOOST_TEST_DYN_LINK #define BOOST_AUTO_TEST_MAIN #include <boost/test/auto_unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/unit_test.hpp> #include <toolsbox/zip_tuple.hpp> #include <toolsbox/mpl/print_type.hpp> BOOST_AUTO_TEST_CASE( zip_tuple_01 ) { auto tuple = toolsbox::make_zip_tuple(std::make_tuple(2, 4), std::make_tuple(0.5, 9.6)); BOOST_CHECK_EQUAL(toolsbox::mpl::print_type<decltype(tuple)>::name(), "tuple(tuple(int, double), tuple(int, double))"); BOOST_CHECK_EQUAL(std::get<0>(std::get<0>(tuple)), 2); BOOST_CHECK_EQUAL(std::get<1>(std::get<0>(tuple)), 0.5); BOOST_CHECK_EQUAL(std::get<0>(std::get<1>(tuple)), 4); BOOST_CHECK_EQUAL(std::get<1>(std::get<1>(tuple)), 9.6); } BOOST_AUTO_TEST_CASE( zip_tuple_02 ) { auto tuple = toolsbox::make_zip_tuple(std::tuple<int, double>(), std::tuple<std::string, char>(), std::tuple<bool, char>()); BOOST_CHECK_EQUAL(toolsbox::mpl::print_type<decltype(tuple)>::name(), "tuple(tuple(int, string, bool), tuple(double, char, char))"); } BOOST_AUTO_TEST_CASE( zip_tuple_03 ) { std::tuple<int, double> t1; std::tuple<std::string, char> t2; std::tuple<bool, char> t3; auto tuple = toolsbox::make_zip_tuple(t1, t2, t3); BOOST_CHECK_EQUAL(toolsbox::mpl::print_type<decltype(tuple)>::name(), "tuple(tuple(int, string, bool), tuple(double, char, char))"); }
5218801cefdc7fa1f5787d6143c5e865dd7d1703
b4a294fa7e878e96bcee0e3269df61b75ce87695
/src/Tile.h
384f2dce5a78832a7e4372cf70c820f46a47f02c
[]
no_license
trungnt2000/PlatformerGame
8fad25b1271c683e281da94185aebac66a2cede9
fc89239df851bb7560dbe22425a4fb8a53606790
refs/heads/master
2022-07-17T22:48:42.273903
2020-05-20T07:33:03
2020-05-20T07:33:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
Tile.h
#ifndef TMX_TILED_MAP_TILE_H #define TMX_TILED_MAP_TILE_H #include "TileLayerTile.h" #include "box2d/box2d.h" #include "tmxlite/Tileset.hpp" #include <vector> class Tile : public TileLayerTile { public: Tile(const std::vector<TextureRegion>& staticTiles, const tmx::Tileset::Tile& tmxTile); ~Tile() override; const TextureRegion& GetTextureRegion() override { return m_tile->GetTextureRegion(); } int GetNumShapes() const { return m_numShapes; } b2Shape** GetShapes() const { return m_shapes; } private: TileLayerTile* m_tile; b2Shape** m_shapes; int m_numShapes; }; #endif // TMX_TILED_MAP_TILE_H
2bcb0be05a138b0ca00d0580cf2567f7d2c29ca6
323b3f8e9d830ba983ef0d1b0742abdec9ba896f
/week-03/day-3/blogpost/Blogpost.cpp
77c34a391d65ecbf1061c93c6406be5160223f30
[]
no_license
green-fox-academy/dezur
531aa6cab9243b6739ce74add0fef22fdb85557c
9108978eeb4d7a8f44e6dcbdb726fa38b5f58751
refs/heads/master
2020-05-04T09:43:41.800182
2019-06-21T14:08:56
2019-06-21T14:08:56
179,074,444
1
1
null
null
null
null
UTF-8
C++
false
false
896
cpp
Blogpost.cpp
// // Created by Zoli on 2019. 04. 17.. // #include "Blogpost.h" #include <iostream> Blogpost::Blogpost(std::string author_name, std::string title, std::string text, std::string publication_date) { SetAuthorName(author_name); SetTitle(title); SetText(text); SetPublicationDate(publication_date); } std::string Blogpost::GetAuthorName() { return _authorName; } std::string Blogpost::GetTitle() { return _title; } std::string Blogpost::GetText() { return _text; } std::string Blogpost::GetPublicationDate() { return _publicationDate; } void Blogpost::SetAuthorName(std::string author_name) { _authorName = author_name; } void Blogpost::SetTitle(std::string title) { _title = title; } void Blogpost::SetText(std::string text) { _text = text; } void Blogpost::SetPublicationDate(std::string publication_date) { _publicationDate = publication_date; }
f468debec02f0ff3009889ba4bf86dd79906d752
7aa577b301ec8aae962713ced4496c104919b7cb
/Classes/MainSceneWithTouch.h
b4127f91e18ab35b977ab40b1a5fed645eae3082
[]
no_license
yeyuexia/SimpleGame
64e50938b16553bbadf1ab306cf59b3e5a6f9848
1fa61e092a6211790e0c6ad35cb6caba9e17c527
refs/heads/master
2016-09-05T08:44:51.084157
2014-02-28T09:14:09
2014-02-28T09:14:09
17,280,761
1
0
null
null
null
null
UTF-8
C++
false
false
595
h
MainSceneWithTouch.h
// // HelloWorldWithTouch.h // Test // // Created by yeyuexia on 2/16/14. // // #ifndef __Test__HelloWorldWithTouch__ #define __Test__HelloWorldWithTouch__ #include <iostream> #include "cocos2d.h" #include "MainScene.h" class MainSceneWithTouch: public MainScene { public: virtual bool init(); static cocos2d::Scene* scene(); void onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *pEvent); // implement the "static node()" method manually CREATE_FUNC(MainSceneWithTouch); }; #endif /* defined(__Test__HelloWorldWithTouch__) */
9c8215671f2e9a5ba49935e57fbedbe48deeb7bc
c4bdccfa1004c8c5d7f61b41c5ec65a1722311c4
/TNonBlockQueue.h
2a8b48fcafe98208bf0152dc0cfc94fe1f9a9e13
[]
no_license
MikhailMalkov/Top
e58868943d2162db35f14a490716a18495ea52d1
4b15329123604313fd2a5613cbc76c9e83895304
refs/heads/master
2022-12-03T06:30:03.453049
2020-08-19T05:25:24
2020-08-19T05:25:24
288,477,977
0
0
null
null
null
null
UTF-8
C++
false
false
3,607
h
TNonBlockQueue.h
#pragma once #ifndef NONBLOCKQUEUE_H #define NONBLOCKQUEUE_H #include <atomic> template<typename T, size_t SIZE> class TNonBlockQueue { public: TNonBlockQueue() : m_buffer(new Item[SIZE]) , m_bufferSize(SIZE) { for (size_t i = 0; i < m_bufferSize; ++i) m_buffer[i].marker.store(i, std::memory_order_relaxed); m_enqPos.store(0, std::memory_order_relaxed); m_deqPos.store(0, std::memory_order_relaxed); } ~TNonBlockQueue() { delete[] m_buffer; } bool Enqueue(T const& data) { Item* pItem = nullptr; size_t index{}; while (true) { index = m_enqPos.load(std::memory_order_relaxed); if (index >= m_bufferSize) // try moving enqueue cursor to the start position { if (m_enqPos.compare_exchange_weak(index, 0, std::memory_order_relaxed)) index = 0; else continue; } pItem = &m_buffer[index]; if (!pItem) return false; size_t marker = pItem->marker.load(std::memory_order_acquire); int dif = static_cast<int>(marker) - static_cast<int>(index); if (dif == 0) // try moving enqueue cursor to the new position { if (m_enqPos.compare_exchange_weak(index, index + 1, std::memory_order_relaxed)) break; else continue; } else if (dif < 0) // queue is full return false; } if (pItem) // place new data to the queue { pItem->data = data; pItem->marker.store(index + 1, std::memory_order_release); return true; } else return false; } bool Dequeue(T& data) { Item* pItem = nullptr; size_t index{}; while (true) { index = m_deqPos.load(std::memory_order_relaxed); if (index >= m_bufferSize) { if (m_deqPos.compare_exchange_weak(index, 0, std::memory_order_relaxed)) { index = 0; break; } else continue; } pItem = &m_buffer[index]; if (!pItem) return false; size_t marker = pItem->marker.load(std::memory_order_acquire); int dif = static_cast<int>(marker) - static_cast<int>(index + 1); if (dif == 0) { if (m_deqPos.compare_exchange_weak(index, index + 1, std::memory_order_relaxed)) break; } else if (dif < 0) return false; } if (pItem) { data = pItem->data; pItem->marker.store(index, std::memory_order_release); return true; } return false; } bool isEmpty() { return m_enqPos == m_deqPos; } TNonBlockQueue(TNonBlockQueue const&) = delete; void operator = (TNonBlockQueue const&) = delete; private: struct Item { std::atomic<size_t> marker; T data; }; Item* const m_buffer; size_t const m_bufferSize; std::atomic<size_t> m_enqPos; std::atomic<size_t> m_deqPos; }; #endif
3a0dd5342b6ec5d5da71d73955278d6ca1475d6e
9a9aae69b61ed42b238a2d8273e08811abed9b58
/src/libkdb/schema.cpp
f17082ddcab3e10e851ad6ac8f56c3c46397af97
[]
no_license
qkmics/kdb
911ab3f09bd1b6cf8476242dd30c7a46d45581cc
b7d2ca3a9f43dd99ab62cc80ba068bd178404ac7
refs/heads/master
2020-12-04T17:07:18.121691
2020-01-07T21:18:03
2020-01-07T21:18:03
231,848,006
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
cpp
schema.cpp
#include "schema.h" #include "record.h" #include "../../include/ksql/sql-parser.h" // Load schema from the input btree void Schema::Load(const BTree& btree) { LoadFromSubtree(btree, 1); // Page 1 is the root page of schema table } void Schema::LoadFromSubtree(const BTree& btree ,int root_page){ BTreeNode node(root_page); const std::vector<std::shared_ptr<BTreeCell>> cells = node.GetCells(); if (node.getType() == PageType::kTableInternal) { for (std::shared_ptr<BTreeCell> cell : cells) { TableInternalCell& table_internal_cell = **(std::static_pointer_cast<std::shared_ptr<TableInternalCell>>(cell)); PageNumber child_page = table_internal_cell.getChildPage(); LoadFromSubtree(btree, child_page); } if (node.ExistRightPage) { LoadFromSubtree(btree, node.getRightPage()); } } else if (node.getType() == PageType::kTableLeaf) { for (std::shared_ptr<BTreeCell> cell : cells) { LoadOneCell(*cell); } } else { // error; } } // Given a table name, determine whether such a table exists. bool Schema::IsTableExist(const std::string& table_name) const { return schema_table_.find(table_name) != schema_table_.end(); } // Given a table name, obtain its root page. int Schema::GetRootPage(const std::string& table_name) const { //return schema_table_[table_name]; return schema_table_.find(table_name)->second.root_page_; } // Given a table name and a column name, determine whether such a column exists in the table. bool Schema::IsColumnExist(const std::string& table_name, const std::string& column_name) const { } // Given a table name and a column name, obtain the type of the column. bool Schema::GetColumnType(const std::string& table_name, const std::string& column_name) const { } // Load schema from one cell void Schema::LoadOneCell(const BTreeCell& cell) { const TableLeafCell& schema_item_cell = static_cast<const TableLeafCell&>(cell); KdbRecord record(*schema_item_cell.ConvertToRawData()); SchemaItem item; item.type_ = record.getString(0); std::string item_name = record.getString(1); item.indexed_table_name_ = record.getString(2); item.root_page_ = record.getInteger(3); item.sql_statement_ = record.getString(4); std::shared_ptr<CreateStmt> creat_stmt=(std::static_pointer_cast<CreateStmt>(SqlParser::Parse(item.sql_statement_))); item.parsed_statement_ = *creat_stmt; schema_table_[item_name] = item; }
2efac914b372762e108d923d645bc2a3cb754275
dfa593b9efc1aac4d8dc96690acda7791925ed81
/math3d/include/math3d/intersections.hpp
c74a333bec798b7f9205a4ad7eb2f4ba2c861ed2
[]
no_license
perjoh/stuff
ce5e3a0c25bd9949506162b7dc52c68c16e2a2e0
897263c9fdfe5aed175c6cdc990ad3d2301819fb
refs/heads/master
2021-01-01T06:45:48.413378
2014-12-15T19:55:03
2014-12-15T19:55:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,195
hpp
intersections.hpp
#ifndef math3d_intersections_hpp #define math3d_intersections_hpp #include "helpers.hpp" #include <limits> namespace math3d { namespace intersect { //! template <typename T> struct Intersection { typedef vector<T, 3> vector_type; Intersection() : point_( 0 ) , normal_( 0 ) { } Intersection( const vector_type& point, const vector_type& normal ) : point_( point ) , normal_( normal ) { } public : const vector_type& point() const { return point_; } const vector_type& normal() const { return normal_; } private : vector_type point_; vector_type normal_; }; //! Calculate ray plane intersection point. template < typename RAY, typename PLANE, typename T> bool intersect_ray_plane_nearest( const RAY& r, const PLANE& p, T& t ) { // TODO Remove 'nearest' suffix. t = ( p.distance() - dot( r.origin(), p.normal() ) ) / dot( r.direction(), p.normal() ); return !( t < 0 ); } //! Ray plane intersection test. template <typename RAY, typename PLANE> bool intersect_ray_plane_test( const RAY& r, const PLANE& p ) { typename RAY::value_type t; return intersect_ray_plane_nearest( r, p, t ); } //! Calculate line plane intersection point. template <typename LINE, typename PLANE, typename T> bool intersect_line_plane_nearest( const LINE& l, const PLANE& p, T& t ) { if ( intersect_ray_plane_nearest( l.to_ray(), p, t) ) { return t <= l.length(); } return false; } //! Line plane intersection. template <typename LINE, typename PLANE> bool intersect_line_plane_test( const LINE& l, const PLANE& p ) { typename LINE::value_type t; return intersect_line_plane_nearest( l, p, t); } //! Calculate the ray sphere intersection point. template <typename RAY, typename SPHERE, typename T> bool intersect_ray_sphere_nearest( const RAY& r, const SPHERE& s, T& t ) { typedef typename RAY::vector_type vec; typedef typename vec::value_type val; const vec m = r.origin() - s.center(); const val b = dot( m, r.direction() ); const val c = dot( m, m ) - s.radius() * s.radius(); // check if ray origin is outside sphere and it points away from the sphere center if ( c > 0 && b > 0 ) { return false; } const val discr = b * b - c; // check if any roots exists, if none there is no intersection if ( discr < 0 ) { return false; } t = -b; // - sqrt( discr ); // if ray origin is outside sphere, pick the negative root, if inside pick positive if ( c > 0 ) { t -= sqrt( discr ); } else { t += sqrt( discr ); } return true; } //! Ray sphere intersection test. template <typename RAY, typename SPHERE> bool intersect_ray_sphere_test( const RAY& r, const SPHERE& s ) { typedef typename RAY::vector_type vec; typedef typename vec::value_type val; const vec m = r.origin() - s.center(); const val c = dot( m, m ) - s.radius() * s.radius(); // check if ray origin is inside sphere, if so there is an intersection if ( c < 0 ) { return true; } const val b = dot( m, r.direction() ); // check if ray origin is outside sphere and it points away from the sphere center if ( c > 0 && b > 0 ) { return false; } const val discr = b * b - c; // check if any roots exists, if none there is no intersection if ( discr < 0 ) { return false; } return true; } //! Calculate the line sphere intersection point. template <typename LINE, typename SPHERE, typename T> bool intersect_line_sphere_nearest( const LINE& l, const SPHERE& p, T& t ) { if ( intersect_ray_sphere_nearest( l.to_ray(), p, t ) ) { return t < l.length(); } return false; } //! Line sphere intersection test. template <typename LINE, typename SPHERE> bool intersect_line_sphere_test( const LINE& l, const SPHERE& s ) { typename LINE::value_type t; return intersect_line_sphere_nearest( l, s, t ); } //! Sphere aabb intersection test. template <typename SPHERE, typename AABB> bool testSphereAabb( const SPHERE& s, const AABB& aabb ) { const typename SPHERE::vector_type cp( aabb.closest_point( s.center() ) ); return dot_square( cp - s.center() ) < square( s.radius() ); } //! Ray / axis aligned bounding box intersection test. //! @param ray Ray to intersect. //! @param aabb Box to intersect. //! @param t0 Point closest to ray origin that intersects the box, or if the ray origin is inside the box this value is zero. //! @param t1 Point furthest away from ray origin that intersects the box. //! @return True if intersection occurs, false if not. template <typename RAY, typename AABB, typename T> bool intersect_ray_aabb( const RAY& ray, const AABB& aabb, T& t0, T& t1 ) { // Based on code from the book 'Realtime collision detection'. using namespace std; T tmin( 0 ); T tmax( numeric_limits<T>::max() ); for ( int i = 0; i < 3; ++i ) { // Check if ray is parallel to planes. if ( abs( ray.direction()[ i ] ) < numeric_limits<T>::epsilon() ) { // Check if ray origin is outside box, if so no intersection occurs. if ( ray.origin()[i] < aabb.min()[i] || aabb.max()[i] < ray.origin()[i] ) { return false; } } else { t0 = ( aabb.min()[i] - ray.origin()[i] ) / ray.direction()[i]; t1 = ( aabb.max()[i] - ray.origin()[i] ) / ray.direction()[i]; if ( t1 < t0 ) { swap( t0, t1 ); } if ( tmin < t0 ) { tmin = t0; } if ( t1 < tmax ) { tmax = t1; } // If tmax 'passes' tmin, no intersection exists. if ( tmax < tmin ) { return false; } } } if ( t0 < 0 ) { t0 = 0; } return true; } //! template <typename LINE, typename AABB, typename T> bool intersect_line_aabb( const LINE& line, const AABB& aabb, T& t0, T& t1 ) { if ( intersect_ray_aabb( line.to_ray(), aabb, t0, t1 ) ) { if ( line.length() >= t0 ) { if ( line.length() < t1 ) { t1 = line.length(); } return true; } } return false; } template <typename Ray, typename Triangle, typename T> bool intersect_ray_triangle(const Ray& ray, const Triangle& triangle, typename Ray::vector_type& uvw, T& t) { // Shamelessly stolen from the book 'Real-time collision detection'. typedef typename Ray::vector_type vec; const vec ab = triangle.pointB() - triangle.pointA(); const vec ac = triangle.pointC() - triangle.pointA(); const vec qp = -ray.direction(); // Optimization: Using static geometry, this can be pre-calculated for each triangle. const vec n = cross(ab, ac); const T d = dot(qp, n); const vec ap = ray.origin() - triangle.pointA(); t = dot(ap, n); if (t < 0) return false; // Add this check for lines. //if (t > d) //return false; enum { u, v, w }; const vec e = cross(qp, ap); uvw[v] = dot(ac, e); if (uvw[v] < 0 || uvw[v] > d) return false; uvw[w] = -dot(ab, e); if (uvw[w] < 0 || uvw[v] + uvw[w] > d) return false; // Optimization: This can be removed for tests. const T ood = 1/d; t *= ood; uvw[v] *= ood; uvw[w] *= ood; uvw[u] = 1 - uvw[v] - uvw[w]; return true; } // Triangle intersection tests // TODO Need to fix names of these functions so they follow the same pattern. //! template <typename Ray, typename Triangle, typename Vector, typename T> inline bool rayTriangle( const Ray& ray, const Triangle& triangle, Vector& uvw, T& t ) { return intersect_ray_triangle(ray, triangle, uvw, t); } //! template <typename Ray, typename Triangle> inline bool testRayTriangle( const Ray& ray, const Triangle& triangle ) { typename Ray::vector_type uvw; typedef typename Ray::vector_type::value_type T; T t; return intersect_ray_triangle(ray, triangle, uvw, t); } //! template <typename Line, typename Triangle, typename Vector, typename T> inline bool lineTriangle( const Line& line, const Triangle& triangle, Vector& uvw, T& t ) { if ( rayTriangle( line.to_ray(), triangle, uvw, t ) ) { return t <= line.length(); } return false; } //! template <typename LINE, typename TRI> inline bool testLineTriangle( const LINE& line, const TRI& triangle ) { typename TRI::vector_type uvw; typename TRI::value_type t; return lineTriangle( line, triangle, uvw, t ); } template <typename VEC, typename PLANE, typename T> inline const std::pair<bool, T> sweepIntersectSpherePlane( const VEC& c0, const VEC& c1, T radius, const PLANE& plane ) { T a = plane.distanceTo(c0); T b = plane.distanceTo(c1); T d = b - a; if ( d != T() ) { T t = (radius - a)/d; if ( t > T() && t <= T(1) ) { return std::pair<bool, T>( true, t ); } return std::pair<bool, T>( false, t ); } return std::pair<bool, T>( false, T() ); } template <typename AABB> inline bool testAabbAabb( const AABB& lhs, const AABB& rhs ) { return lhs.min()[0] < rhs.max()[0] && lhs.max()[0] > rhs.min()[0] && lhs.min()[1] < rhs.max()[1] && lhs.max()[1] > rhs.min()[1] && lhs.min()[2] < rhs.max()[2] && lhs.max()[2] > rhs.min()[2]; } template <typename Aabb, typename Plane> inline bool testAabbPlane(const Aabb& aabb, const Plane& plane) { typedef typename Aabb::vector_type Vector; const Vector center = aabb.center(); const Vector extents = aabb.max() - center; return testCenteredAabbPlane(center, extents, plane.normal(), plane.distance()); } template <typename Vector, typename Float> inline bool testCenteredAabbPlane(const Vector& center, const Vector& extents, const Vector& pn, const Float& pd) { const Float r = extents[0]*abs(pn[0]) + extents[1]*abs(pn[1]) + extents[2]*abs(pn[2]); const Float s = dot(pn, center) - pd; return abs(s) <= r; } template <typename T> T max(const T& a, const T& b) { if (a < b) return b; return a; } template <typename T> T min(const T& a, const T& b) { if (a < b) return a; return b; } template <typename T> T max(const T& a, const T& b, const T& c) { return max(max(a, b), c); } template <typename T> T min(const T&a, const T& b, const T& c) { return min(min(a, b), c); } template <typename Aabb, typename Triangle> struct TestAabbTriangle { enum { x, y, z }; typedef typename Triangle::vector_type vec; typedef typename vec::value_type Float; static bool test(const Aabb& aabb, const Triangle& triangle) { // Shamelessly stolen from the book 'Real-time collision detection'. const vec c = aabb.center(); const vec e = aabb.dim() * Float(.5); const vec v0 = triangle.pointA() - c; const vec v1 = triangle.pointB() - c; const vec v2 = triangle.pointC() - c; const vec f0 = v1 - v0; const vec f1 = v2 - v1; const vec f2 = v0 - v2; if (separatingAxisTest3(v0, v1, v2, f0, f1, f2, e)) { if (separatingAxisTest1(v0, v1, v2, e)) { return separatingAxisTest2(c, e, v0, f0, f1); } } return false; } // Test 1: Three face normals from the AABB. static bool separatingAxisTest1(const vec& v0, const vec& v1, const vec& v2, const vec& e) { return (!(max(v0[x], v1[x], v2[x]) < -e[x] || min(v0[x], v1[x], v2[x]) > e[x])) && (!(max(v0[y], v1[y], v2[y]) < -e[y] || min(v0[y], v1[y], v2[y]) > e[y])) && (!(max(v0[z], v1[z], v2[z]) < -e[z] || min(v0[z], v1[z], v2[z]) > e[z])); } // Test 2: One face normal from the triangle. static bool separatingAxisTest2(const vec& center, const vec& extents, const vec& v0, const vec& f0, const vec& f1) { const vec normal = cross(f0, f1); typedef typename vec::value_type Float; const Float d = dot(normal, v0); return testCenteredAabbPlane(center, extents, normal, d); } // Test 3: Nine axes given by the cross products of any combination of axes from both the triangle and the AABB. static bool separatingAxisTest3(const vec& v0, const vec& v1, const vec& v2, const vec& f0, const vec& f1, const vec& f2, const vec& e) { return testAxis00(v0, v1, v2, f0, e) && testAxis01(v0, v1, v2, f1, e) && testAxis02(v0, v1, v2, f2, e) && testAxis10(v0, v1, v2, f0, e) && testAxis11(v0, v1, v2, f1, e) && testAxis12(v0, v1, v2, f2, e) && testAxis20(v0, v1, v2, f0, e) && testAxis21(v0, v1, v2, f1, e) && testAxis22(v0, v1, v2, f2, e); } template <typename T> static inline T calcp0_00(const vec& v0, const vec& v1) { return v0[z]*v1[y] - v0[y]*v1[z]; } template <typename T> static inline T calcp2_00(const vec& v0, const vec& v1, const vec& v2) { return -v2[y]*(v1[z] - v0[z]) + v2[z]*(v1[y] - v0[y]); } template <typename T> static inline T calcr_00(const vec& e, const vec& f0) { return e[1]*abs(f0[z]) + e[2]*abs(f0[y]); } static inline bool testAxis00(const vec& v0, const vec& v1, const vec& v2, const vec& f0, const vec& e) { // 0, -f0z, f0y const Float p0 = calcp0_00<Float>(v0, v1); const vec a = vec::make(0, -f0[z], f0[y]); const Float p2 = calcp2_00<Float>(v0, v1, v2); const Float r = calcr_00<Float>(e, f0); return !(max(-max(p0, p2), min(p0, p2)) > r); } static inline bool testAxis01(const vec& v0, const vec& v1, const vec& v2, const vec& f1, const vec& e) { // 0, -f1z, f1y (0, -(v2.z - v1.z), v2.y - v1.y) const Float p0 = v0[y]*-(v2[z] - v1[z]) + v0[z]*(v2[y] - v1[y]); const Float p1 = v1[z]*v2[y] - v1[y]*v2[z]; const Float r = e[y]*abs(f1[z]) + e[z]*abs(f1[y]); const vec a = vec::make(0, -f1[z], f1[y]); return !(max(-max(p0, p1), min(p0, p1)) > r); } static inline bool testAxis02(const vec& v0, const vec& v1, const vec& v2, const vec& f2, const vec& e) { // 0, -f2z, f2y (0, -(v0.z - v2.z), v0.y - v2.y const Float p0 = v0[y]*v2[z] - v0[z]*v2[y]; const Float p1 = v1[y]*-(v0[z] - v2[z]) + v1[z]*(v0[y] - v2[y]); const Float r = e[y]*abs(f2[z]) + e[z]*abs(f2[y]); const vec a = vec::make(0, -f2[z], f2[y]); return !(max(-max(p0, p1), min(p0, p1)) > r); } static inline bool testAxis10(const vec& v0, const vec& v1, const vec& v2, const vec& f0, const vec& e) { // f0z, 0, -f0x ((v1.z - v0.z), 0, -(v1.x - v0.x) const Float p0 = v0[x]*v1[z] - v0[z]*v1[x]; const Float p2 = v2[x]*(v1[z] - v0[z]) + v2[z]*-(v1[x] - v0[x]); const Float r = e[x]*abs(f0[z]) + e[z]*abs(f0[x]); const vec a = vec::make(f0[z], 0, -f0[x]); return !(max(-max(p0, p2), min(p0, p2)) > r); } static inline bool testAxis11(const vec& v0, const vec& v1, const vec& v2, const vec& f1, const vec& e) { // f1z, 0, -f1x -> (v2.z - v1.z), 0, -(v2.x - v1.x) const Float p0 = v0[x]*(v2[z] - v1[z]) + v0[z]*-(v2[x] - v1[x]); const Float p1 = v1[x]*v2[z] - v1[z]*v2[x]; const Float r = e[x]*abs(f1[z]) + e[z]*abs(f1[x]); const vec a = vec::make(f1[z], 0, -f1[x]); return !(max(-max(p0, p1), min(p0, p1)) > r); } static inline bool testAxis12(const vec& v0, const vec& v1, const vec& v2, const vec& f2, const vec& e) { // f2z, 0, -f2x -> (v0.z - v2.z), 0, -(v0.x - v2.x) const Float p0 = v0[z]*v2[x] - v0[x]*v2[z]; const Float p1 = v1[x]*(v0[z] - v2[z]) + v1[z]*-(v0[x] - v2[x]); const Float r = e[x]*abs(f2[z]) + e[z]*abs(f2[x]); const vec a = vec::make(f2[z], 0, -f2[x]); return !(max(-max(p0, p1), min(p0, p1)) > r); } static inline bool testAxis20(const vec& v0, const vec& v1, const vec& v2, const vec& f0, const vec& e) { // -f0y, f0x, 0 -> -(v1.y - v0.y), (v1.x - v0.x), 0 const Float p0 = v0[y]*v1[x] - v0[x]*v1[y]; const Float p2 = v2[x]*-(v1[y] - v0[y]) + v2[y]*(v1[x] - v0[x]); const Float r = e[x]*abs(f0[y]) + e[y]*abs(f0[x]); const vec a = vec::make(-f0[y], f0[x], 0); return !(max(-max(p0, p2), min(p0, p2)) > r); } static inline bool testAxis21(const vec& v0, const vec& v1, const vec& v2, const vec& f1, const vec& e) { // -f1y, f1x, 0 -> -(v2.y - v1.y), (v2.x - v1.x), 0 const Float p0 = v0[x]*-(v2[y] - v1[y]) + v0[y]*(v2[x] - v1[x]); const Float p1 = -v1[x]*v2[y] + v1[y]*v2[x]; const Float r = e[x]*abs(f1[y]) + e[y]*abs(f1[x]); const vec a = vec::make(-f1[y], f1[x], 0); return !(max(-max(p0, p1), min(p0, p1)) > r); } static inline bool testAxis22(const vec& v0, const vec& v1, const vec& v2, const vec& f2, const vec& e) { // -f2y, f2x, 0 -> -(v0.y - v2.y), (v0.x - v2.x), 0 const Float p0 = v0[x]*v2[y] - v0[y]*v2[x]; const Float p1 = v1[x]*-(v0[y] - v2[y]) + v1[y]*(v0[x] - v2[x]); const Float r = e[x]*abs(f2[y]) + e[y]*abs(f2[x]); const vec a = vec::make(-f2[y], f2[x], 0); return !(max(-max(p0, p1), min(p0, p1)) > r); } }; template <typename TRIANGLE, typename AAPLANE> bool testTriangleAxisAlignedPlane(const TRIANGLE& triangle, const AAPLANE& plane) { return triangle.min()[plane.axis()] < plane.distance() && triangle.max()[plane.axis()] > plane.distance(); } } } #endif // math3d_intersections_hpp
4324bde7aba10f70f935d3c842f97c237b0c7d66
1791461e6740f81c2dd6704ae6a899a6707ee6b1
/Codeforces/1257B.cpp
5105d2d56c3fec9023a59ef8d0f42be98284b373
[ "MIT" ]
permissive
HeRaNO/OI-ICPC-Codes
b12569caa94828c4bedda99d88303eb6344f5d6e
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
refs/heads/master
2023-08-06T10:46:32.714133
2023-07-26T08:10:44
2023-07-26T08:10:44
163,658,110
22
6
null
null
null
null
UTF-8
C++
false
false
238
cpp
1257B.cpp
#include <bits/stdc++.h> using namespace std; int main() { int T,a,b; scanf("%d",&T); while (T--) { scanf("%d %d",&a,&b); if (a==1) puts(b<=1?"Yes":"No"); else if (a<=3) puts(b<=3?"Yes":"No"); else puts("Yes"); } return 0; }
a2df2b205f1f0ef7fd394e8a159181c9adb15988
3a25498190f3d30b67220df5ae52988802d70070
/engine/graphics/material/program/RMShaderProgram.hpp
dbae01ad5f97ca3f0a5d2a89abea6145ceb1fcba
[ "MIT" ]
permissive
vitali-kurlovich/RMPropeller
c80108ddeab9e8df74da87a33fbafc65490b266c
6b914957000dc5bd35319828b7e2608ceb2c92ca
refs/heads/master
2020-04-03T22:43:01.203168
2017-03-13T22:20:52
2017-03-13T22:20:52
56,176,234
0
0
null
null
null
null
UTF-8
C++
false
false
3,244
hpp
RMShaderProgram.hpp
// // Created by Vitali Kurlovich on 8/23/16. // #ifndef RMPROPELLER_RMPROGRAM_HPP #define RMPROPELLER_RMPROGRAM_HPP #include <vector> #include "graphics/material/material_common.hpp" #include "RMShader.hpp" namespace rmengine { namespace graphics { class RMShaderProgram : public RMObject { protected: std::vector<RMShader*> _shaders; void clearShaders() { for (RMShader* shader : _shaders) { rmRelease(shader); } _shaders.clear(); } public: RMShaderProgram(std::initializer_list<RMShader*> shaders) : _shaders(shaders) { for (RMShader* shader : _shaders) { rmRetain(shader); } } virtual ~RMShaderProgram() { for (RMShader* shader : _shaders) { rmRelease(shader); } } virtual bool compile() noexcept = 0; constexpr uint32 shaderCount() const noexcept { return _shaders.size(); } constexpr RMShader* shaderAtIndex(uint32 index) const { return _shaders[index]; } virtual void use() const noexcept = 0; virtual void setUniform( const char *name, float x, float y, float z, float w) noexcept = 0; virtual void setUniform( const char *name, float x, float y, float z) noexcept = 0; virtual void setUniform( const char *name, float x, float y) noexcept = 0; virtual void setUniform( const char *name, float val) noexcept = 0; virtual void setUniform( const char *name, const vec2 &vec) noexcept = 0; virtual void setUniform( const char *name, const vec3 &vec) noexcept = 0; virtual void setUniform( const char *name, const vec4 &vec) noexcept = 0; virtual void setUniform( const char *name, const mat2x2 &mat) noexcept = 0; virtual void setUniform( const char *name, const mat3x3 &mat) noexcept = 0; virtual void setUniform( const char *name, const mat4x4 &mat) noexcept = 0; virtual void setUniform( const char *name, int32 val ) noexcept = 0; virtual void setUniform( const char *name, uint32 val ) noexcept = 0; virtual void setUniform( const char *name, bool val ) noexcept = 0; virtual void setUniform( const char *name, const amat3x3 &mat) noexcept { mat3x3 m( mat.m00, mat.m01, 0, mat.m10, mat.m11, 0, mat.m20, mat.m21, 1 ); setUniform(name, m); } virtual void setUniform( const char *name, const amat4x4 &mat) noexcept { mat4x4 m( mat.m00, mat.m01, mat.m02, 0, mat.m10, mat.m11, mat.m12, 0, mat.m20, mat.m21, mat.m22, 0, mat.m30, mat.m31, mat.m32, 1 ); setUniform(name, m); } }; } } #endif //RMPROPELLER_RMPROGRAM_HPP
3915e5af9cd5cc64d3fc32f8b92e62c43b060ab4
042dd1b5ce81df82f3d3dd552dd873698612e8b2
/app.ino
1857519dfdcb1e5179e62d5ff39b0f5318363266
[]
no_license
ThorMutoAsmund/ARD_NodeMCU_WiFiTest
280a5157a052d2e12fbbf411a985ae3700529abc
d235a15e911c35eeaf2aac7dda558f9c9afac266
refs/heads/master
2020-04-15T02:54:32.244450
2019-01-06T19:28:18
2019-01-06T19:28:18
164,328,476
0
0
null
null
null
null
UTF-8
C++
false
false
4,592
ino
app.ino
#include <Arduino.h> #include <ESP8266WiFi.h> #include "DHT.h" // See // https://www.instructables.com/id/Quick-Start-to-Nodemcu-ESP8266-on-Arduino-IDE/ // Note about pin mappings // static const uint8_t D0 = 16; // static const uint8_t D1 = 5; // static const uint8_t D2 = 4; // static const uint8_t D3 = 0; // static const uint8_t D4 = 2; // static const uint8_t D5 = 14; // static const uint8_t D6 = 12; // static const uint8_t D7 = 13; // static const uint8_t D8 = 15; // static const uint8_t D9 = 3; // static const uint8_t D10 = 1; const char* ssid = "HomeBox-5100_2.4G"; const char* password = "71c91afee"; #define LED_PIN 13 // D7 #define DHT_PIN 2 // D4 #define DHT_TYPE DHT11 WiFiServer server(80); DHT dht(DHT_PIN, DHT_TYPE); int ledValue = LOW; int dht_status; float dht_h; float dht_t; float dht_hic; // float dht_f; // float dht_hif; void setup() { Serial.begin(115200); delay(10); pinMode(LED_PIN, OUTPUT); ToggleLED(LOW); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL to connect: "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); dht_status = 0; } void loop() { // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); while(!client.available()){ delay(1); } // Read the first line of the request String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); if (request.indexOf("/LED=ON") != -1) { ToggleLED(HIGH); } else if (request.indexOf("/LED=OFF") != -1) { ToggleLED(LOW); } else if (request.indexOf("/MEASURE") != -1) { ReadDHT(); } // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.print("Led pin is now: "); if (ledValue == HIGH) { client.print("On"); } else { client.print("Off"); } client.println("<br><br>"); client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>"); client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a><br />"); client.println("<br><br>"); if (dht_status == 0) { client.println("No measurement yet"); } else if (dht_status == 1) { client.println("Failed to read from DHT sensor!"); } else { client.print("Humidity: "); client.print(dht_h); client.print(" %"); client.println("<br>"); client.print("Temperature: "); client.print(dht_t); client.print(" *C "); client.println("<br>"); client.print("Heat index: "); client.print(dht_hic); client.print(" *C "); } client.println("<br><br>"); client.println("<a href=\"/MEASURE\"\"><button>New measurement</button></a>"); client.println("</html>"); delay(1); Serial.println("Client disonnected"); Serial.println(""); } void ToggleLED(int value) { digitalWrite(LED_PIN, value); ledValue = value; } void ReadDHT() { // Wait a few seconds between measurements. delay(500); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) dht_h = dht.readHumidity(); // Read temperature as Celsius (the default) dht_t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) // dht_f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(dht_h) || isnan(dht_t)) { dht_status = 1; return; } // Compute heat index in Fahrenheit (the default) // dht_hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) dht_hic = dht.computeHeatIndex(dht_t, dht_h, false); dht_status = 2; }
e00560e4a31875ea0d889a93b9ea7cfdce6d731e
dc2a40a1c1f470f10d8e02a970be9f56f097d835
/chrominobicolore.cpp
3eea43532399086abe111fc6d1bd766c63c6adfa
[]
no_license
Abasy/chromino-project
626cf8d2af16cf00781609fa4a15dd7161d49e8a
10ecd1f12916900053427132af1a8ba7da44d069
refs/heads/master
2021-09-20T05:20:44.749857
2018-08-03T19:06:17
2018-08-03T19:06:17
112,177,822
0
0
null
null
null
null
UTF-8
C++
false
false
3,711
cpp
chrominobicolore.cpp
#include "chrominobicolore.h" #include <QDebug> using namespace std; int ChrominoBicolore::nombre_chrominos_bicolore(0); ChrominoBicolore::ChrominoBicolore(QVector<Case *> &cases, QGraphicsItem *parent) :Chromino(cases[0],cases[1],cases[2],parent) { nombre_chrominos_bicolore++; idChrominoBicolore = nombre_chrominos_bicolore; chromino.push_back(cases[0]); chromino.push_back(cases[1]); chromino.push_back(cases[2]); qDebug()<<"Création du chrominoBicolore"; createChromino(chromino); setHandlesChildEvents(false); qDebug()<<"Nombre de chrominoBicolore : "<<nombre_chrominos_bicolore; } ChrominoBicolore::ChrominoBicolore(Case *case1, Case *case2, Case *case3, QGraphicsItem *parent) :Chromino(case1,case2,case3,parent) { nombre_chrominos_bicolore++; idChrominoBicolore = nombre_chrominos_bicolore; chromino.push_back(case1); chromino.push_back(case2); chromino.push_back(case3); qDebug()<<"Création du chrominoBicolore"; createChromino(chromino); setHandlesChildEvents(false); qDebug()<<"Nombre de chrominoBicolore : "<<nombre_chrominos_bicolore; } ChrominoBicolore::~ChrominoBicolore() { nombre_chrominos_bicolore--; } int ChrominoBicolore::getNombre_chrominos_bicolore(){return nombre_chrominos_bicolore;} int ChrominoBicolore::getIdChrominoBicolore() const{return idChrominoBicolore;} void ChrominoBicolore::createChromino(QVector<Case *> &chromino) { for(int i=0 ; i < chromino.size() ; i++) { this->addToGroup(chromino.at(i)); } } void ChrominoBicolore::rotateChromino() { switch(_angle){ case 0: _angle+=90;break; case 90 : _angle+=90;break; case 180 :_angle+=90;break; //case 270 :_angle+=90;break; default : _angle=0; } QPointF offset = this->sceneBoundingRect().center(); qDebug()<<offset; QTransform transform; transform.translate(offset.x(),offset.y()); transform.rotate(_angle); transform.translate(-offset.x(),-offset.y()); this->setTransform(transform); qDebug()<<"angle ="<<_angle; //Enregistrer les nouvelles coordonnées du chromino qDebug()<<"coordonnées ("<<scenePos().x()<<","<<scenePos().y()<<")"; //Enregistrer les nouvelles coordonnées des cases //qDebug()<<"coordonnées ("<<getPosX()<<","<<getPosY()<<")"; } void ChrominoBicolore::afficherChromino() const { QString str=""; for(int i(0);i<chromino.size();i++){ str += QString::number(chromino[i]->getIdCouleur()) + "-"; } qDebug()<<str; } /* bool operator==(Chromino * const &a, Chromino * const &b) { return a->estEgal(b); } */ bool ChrominoBicolore::estEgal(Chromino * const &b) const { bool condition_1(false); bool condition_2(false); QVector<Case *> vectorChr = b->getChromino(); //On vérifie le cas où les chrominos sont rangés de la même manière if(chromino[0]->getIdCouleur()==vectorChr[0]->getIdCouleur() && chromino[1]->getIdCouleur()==vectorChr[1]->getIdCouleur() && chromino[2]->getIdCouleur()==vectorChr[2]->getIdCouleur()){ condition_1=true; qDebug()<< "à l'endroit : les chrominos sont identiques"; } //On vérifie le cas où l'un des chrominos est inversé if(chromino[0]->getIdCouleur()==vectorChr[2]->getIdCouleur() && chromino[1]->getIdCouleur()==vectorChr[1]->getIdCouleur() && chromino[2]->getIdCouleur()==vectorChr[0]->getIdCouleur()){ condition_2 = true; qDebug()<< "à l'envers : les chrominos sont identiques"; } return (condition_1 || condition_2); }
fd5e39f0f8970938ce2635393cba66a0891f43c9
9bdbc99174b877a07fa1d79176bd64f7222bfb99
/src/color_map.cc
fd8791e561b6e2fad6a6c8054fbf1d21a1d6a361
[ "MIT" ]
permissive
nagyistge/kortex
b93dedb0c3eec5f5bcf022ca4ae2d6bafc1f5e60
a8658c9ca4190b38178225522ca55ec4e73be6d2
refs/heads/master
2020-06-16T17:10:39.080381
2016-09-20T10:04:39
2016-09-20T10:04:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,725
cc
color_map.cc
// --------------------------------------------------------------------------- // // This file is part of the <kortex> library suite // // Copyright (C) 2015 Engin Tola // // See LICENSE file for license information. // // author: Engin Tola // e-mail: engintola@gmail.com // web : http://www.engintola.com // web : http://www.aurvis.com // // --------------------------------------------------------------------------- #include <kortex/color_map.h> #include <kortex/string.h> #include <kortex/check.h> namespace kortex { ColorMap::ColorMap() { m_type = "jet"; m_types.push_back( string("jet") ); m_types.push_back( string("hot") ); m_types.push_back( string("winter") ); m_types.push_back( string("hsv") ); m_types.push_back( string("cool") ); set_type( 0 ); m_step_size = 1.0f / float(m_arr_sz-1); } int ColorMap::n_types() const { return m_types.size(); } void ColorMap::set_type( int tid ) { assert_boundary( tid, 0, n_types() ); m_type = m_types[tid]; switch(tid) { case 0: m_arr = g_colormap_jet; break; case 1: m_arr = g_colormap_hot; break; case 2: m_arr = g_colormap_winter; break; case 3: m_arr = g_colormap_hsv; break; case 4: m_arr = g_colormap_cool; break; } } void ColorMap::set_type( const string& t ) { for( int i=0; i<n_types(); i++ ) { if( !compare_string_nc( t, m_types[i] ) ) { set_type( i ); return; } } logman_warning_g( "type [%s] not found", t.c_str() ); } void ColorMap::print_types() const { for( int i=0; i<n_types(); i++ ) { printf( "%d : %s\n", i, m_types[i].c_str() ); } } void ColorMap::get_color( const float& gray, float& red, float& green, float& blue ) const { if( gray < 0.0f || gray > 1.0f ) { logman_warning_g( "supporting only gray values [0,1] [g %f]", gray ); red = 1.0f; green = 1.0f; blue = 1.0f; } else { int ib = int(gray / m_step_size); int ia = ib+1; if( ia >= m_arr_sz ) ia--; float beta = gray/m_step_size - ib; float alpha = 1.0f - beta; assert_statement( beta >= 0.0f && beta <= 1.0f, "invalid beta" ); float r0 = m_arr[ 3*ib ]; float g0 = m_arr[ 3*ib+1 ]; float b0 = m_arr[ 3*ib+2 ]; float r1 = m_arr[ 3*ia ]; float g1 = m_arr[ 3*ia+1 ]; float b1 = m_arr[ 3*ia+2 ]; red = alpha * r0 + beta * r1; green = alpha * g0 + beta * g1; blue = alpha * b0 + beta * b1; } } float g_colormap_hot[] = { 0.0417, 0, 0, 0.0833, 0, 0, 0.1250, 0, 0, 0.1667, 0, 0, 0.2083, 0, 0, 0.2500, 0, 0, 0.2917, 0, 0, 0.3333, 0, 0, 0.3750, 0, 0, 0.4167, 0, 0, 0.4583, 0, 0, 0.5000, 0, 0, 0.5417, 0, 0, 0.5833, 0, 0, 0.6250, 0, 0, 0.6667, 0, 0, 0.7083, 0, 0, 0.7500, 0, 0, 0.7917, 0, 0, 0.8333, 0, 0, 0.8750, 0, 0, 0.9167, 0, 0, 0.9583, 0, 0, 1.0000, 0, 0, 1.0000, 0.0417, 0, 1.0000, 0.0833, 0, 1.0000, 0.1250, 0, 1.0000, 0.1667, 0, 1.0000, 0.2083, 0, 1.0000, 0.2500, 0, 1.0000, 0.2917, 0, 1.0000, 0.3333, 0, 1.0000, 0.3750, 0, 1.0000, 0.4167, 0, 1.0000, 0.4583, 0, 1.0000, 0.5000, 0, 1.0000, 0.5417, 0, 1.0000, 0.5833, 0, 1.0000, 0.6250, 0, 1.0000, 0.6667, 0, 1.0000, 0.7083, 0, 1.0000, 0.7500, 0, 1.0000, 0.7917, 0, 1.0000, 0.8333, 0, 1.0000, 0.8750, 0, 1.0000, 0.9167, 0, 1.0000, 0.9583, 0, 1.0000, 1.0000, 0, 1.0000, 1.0000, 0.0625, 1.0000, 1.0000, 0.1250, 1.0000, 1.0000, 0.1875, 1.0000, 1.0000, 0.2500, 1.0000, 1.0000, 0.3125, 1.0000, 1.0000, 0.3750, 1.0000, 1.0000, 0.4375, 1.0000, 1.0000, 0.5000, 1.0000, 1.0000, 0.5625, 1.0000, 1.0000, 0.6250, 1.0000, 1.0000, 0.6875, 1.0000, 1.0000, 0.7500, 1.0000, 1.0000, 0.8125, 1.0000, 1.0000, 0.8750, 1.0000, 1.0000, 0.9375, 1.0000, 1.0000, 1.0000 }; float g_colormap_jet[] = { 0, 0, 0.5625, 0, 0, 0.6250, 0, 0, 0.6875, 0, 0, 0.7500, 0, 0, 0.8125, 0, 0, 0.8750, 0, 0, 0.9375, 0, 0, 1.0000, 0, 0.0625, 1.0000, 0, 0.1250, 1.0000, 0, 0.1875, 1.0000, 0, 0.2500, 1.0000, 0, 0.3125, 1.0000, 0, 0.3750, 1.0000, 0, 0.4375, 1.0000, 0, 0.5000, 1.0000, 0, 0.5625, 1.0000, 0, 0.6250, 1.0000, 0, 0.6875, 1.0000, 0, 0.7500, 1.0000, 0, 0.8125, 1.0000, 0, 0.8750, 1.0000, 0, 0.9375, 1.0000, 0, 1.0000, 1.0000, 0.0625, 1.0000, 0.9375, 0.1250, 1.0000, 0.8750, 0.1875, 1.0000, 0.8125, 0.2500, 1.0000, 0.7500, 0.3125, 1.0000, 0.6875, 0.3750, 1.0000, 0.6250, 0.4375, 1.0000, 0.5625, 0.5000, 1.0000, 0.5000, 0.5625, 1.0000, 0.4375, 0.6250, 1.0000, 0.3750, 0.6875, 1.0000, 0.3125, 0.7500, 1.0000, 0.2500, 0.8125, 1.0000, 0.1875, 0.8750, 1.0000, 0.1250, 0.9375, 1.0000, 0.0625, 1.0000, 1.0000, 0, 1.0000, 0.9375, 0, 1.0000, 0.8750, 0, 1.0000, 0.8125, 0, 1.0000, 0.7500, 0, 1.0000, 0.6875, 0, 1.0000, 0.6250, 0, 1.0000, 0.5625, 0, 1.0000, 0.5000, 0, 1.0000, 0.4375, 0, 1.0000, 0.3750, 0, 1.0000, 0.3125, 0, 1.0000, 0.2500, 0, 1.0000, 0.1875, 0, 1.0000, 0.1250, 0, 1.0000, 0.0625, 0, 1.0000, 0, 0, 0.9375, 0, 0, 0.8750, 0, 0, 0.8125, 0, 0, 0.7500, 0, 0, 0.6875, 0, 0, 0.6250, 0, 0, 0.5625, 0, 0, 0.5000, 0, 0 }; float g_colormap_winter[] = { 0, 0, 1.0000, 0, 0.0159, 0.9921, 0, 0.0317, 0.9841, 0, 0.0476, 0.9762, 0, 0.0635, 0.9683, 0, 0.0794, 0.9603, 0, 0.0952, 0.9524, 0, 0.1111, 0.9444, 0, 0.1270, 0.9365, 0, 0.1429, 0.9286, 0, 0.1587, 0.9206, 0, 0.1746, 0.9127, 0, 0.1905, 0.9048, 0, 0.2063, 0.8968, 0, 0.2222, 0.8889, 0, 0.2381, 0.8810, 0, 0.2540, 0.8730, 0, 0.2698, 0.8651, 0, 0.2857, 0.8571, 0, 0.3016, 0.8492, 0, 0.3175, 0.8413, 0, 0.3333, 0.8333, 0, 0.3492, 0.8254, 0, 0.3651, 0.8175, 0, 0.3810, 0.8095, 0, 0.3968, 0.8016, 0, 0.4127, 0.7937, 0, 0.4286, 0.7857, 0, 0.4444, 0.7778, 0, 0.4603, 0.7698, 0, 0.4762, 0.7619, 0, 0.4921, 0.7540, 0, 0.5079, 0.7460, 0, 0.5238, 0.7381, 0, 0.5397, 0.7302, 0, 0.5556, 0.7222, 0, 0.5714, 0.7143, 0, 0.5873, 0.7063, 0, 0.6032, 0.6984, 0, 0.6190, 0.6905, 0, 0.6349, 0.6825, 0, 0.6508, 0.6746, 0, 0.6667, 0.6667, 0, 0.6825, 0.6587, 0, 0.6984, 0.6508, 0, 0.7143, 0.6429, 0, 0.7302, 0.6349, 0, 0.7460, 0.6270, 0, 0.7619, 0.6190, 0, 0.7778, 0.6111, 0, 0.7937, 0.6032, 0, 0.8095, 0.5952, 0, 0.8254, 0.5873, 0, 0.8413, 0.5794, 0, 0.8571, 0.5714, 0, 0.8730, 0.5635, 0, 0.8889, 0.5556, 0, 0.9048, 0.5476, 0, 0.9206, 0.5397, 0, 0.9365, 0.5317, 0, 0.9524, 0.5238, 0, 0.9683, 0.5159, 0, 0.9841, 0.5079, 0, 1.0000, 0.5000 }; float g_colormap_hsv[] = { 1.0000, 0, 0, 1.0000, 0.0938, 0, 1.0000, 0.1875, 0, 1.0000, 0.2812, 0, 1.0000, 0.3750, 0, 1.0000, 0.4688, 0, 1.0000, 0.5625, 0, 1.0000, 0.6562, 0, 1.0000, 0.7500, 0, 1.0000, 0.8438, 0, 1.0000, 0.9375, 0, 0.9688, 1.0000, 0, 0.8750, 1.0000, 0, 0.7812, 1.0000, 0, 0.6875, 1.0000, 0, 0.5938, 1.0000, 0, 0.5000, 1.0000, 0, 0.4062, 1.0000, 0, 0.3125, 1.0000, 0, 0.2188, 1.0000, 0, 0.1250, 1.0000, 0, 0.0312, 1.0000, 0, 0, 1.0000, 0.0625, 0, 1.0000, 0.1562, 0, 1.0000, 0.2500, 0, 1.0000, 0.3438, 0, 1.0000, 0.4375, 0, 1.0000, 0.5312, 0, 1.0000, 0.6250, 0, 1.0000, 0.7188, 0, 1.0000, 0.8125, 0, 1.0000, 0.9062, 0, 1.0000, 1.0000, 0, 0.9062, 1.0000, 0, 0.8125, 1.0000, 0, 0.7188, 1.0000, 0, 0.6250, 1.0000, 0, 0.5312, 1.0000, 0, 0.4375, 1.0000, 0, 0.3438, 1.0000, 0, 0.2500, 1.0000, 0, 0.1562, 1.0000, 0, 0.0625, 1.0000, 0.0312, 0, 1.0000, 0.1250, 0, 1.0000, 0.2188, 0, 1.0000, 0.3125, 0, 1.0000, 0.4062, 0, 1.0000, 0.5000, 0, 1.0000, 0.5938, 0, 1.0000, 0.6875, 0, 1.0000, 0.7812, 0, 1.0000, 0.8750, 0, 1.0000, 0.9688, 0, 1.0000, 1.0000, 0, 0.9375, 1.0000, 0, 0.8438, 1.0000, 0, 0.7500, 1.0000, 0, 0.6562, 1.0000, 0, 0.5625, 1.0000, 0, 0.4688, 1.0000, 0, 0.3750, 1.0000, 0, 0.2812, 1.0000, 0, 0.1875, 1.0000, 0, 0.0938 }; float g_colormap_cool[] = { 0, 1.0000, 1.0000, 0.0159, 0.9841, 1.0000, 0.0317, 0.9683, 1.0000, 0.0476, 0.9524, 1.0000, 0.0635, 0.9365, 1.0000, 0.0794, 0.9206, 1.0000, 0.0952, 0.9048, 1.0000, 0.1111, 0.8889, 1.0000, 0.1270, 0.8730, 1.0000, 0.1429, 0.8571, 1.0000, 0.1587, 0.8413, 1.0000, 0.1746, 0.8254, 1.0000, 0.1905, 0.8095, 1.0000, 0.2063, 0.7937, 1.0000, 0.2222, 0.7778, 1.0000, 0.2381, 0.7619, 1.0000, 0.2540, 0.7460, 1.0000, 0.2698, 0.7302, 1.0000, 0.2857, 0.7143, 1.0000, 0.3016, 0.6984, 1.0000, 0.3175, 0.6825, 1.0000, 0.3333, 0.6667, 1.0000, 0.3492, 0.6508, 1.0000, 0.3651, 0.6349, 1.0000, 0.3810, 0.6190, 1.0000, 0.3968, 0.6032, 1.0000, 0.4127, 0.5873, 1.0000, 0.4286, 0.5714, 1.0000, 0.4444, 0.5556, 1.0000, 0.4603, 0.5397, 1.0000, 0.4762, 0.5238, 1.0000, 0.4921, 0.5079, 1.0000, 0.5079, 0.4921, 1.0000, 0.5238, 0.4762, 1.0000, 0.5397, 0.4603, 1.0000, 0.5556, 0.4444, 1.0000, 0.5714, 0.4286, 1.0000, 0.5873, 0.4127, 1.0000, 0.6032, 0.3968, 1.0000, 0.6190, 0.3810, 1.0000, 0.6349, 0.3651, 1.0000, 0.6508, 0.3492, 1.0000, 0.6667, 0.3333, 1.0000, 0.6825, 0.3175, 1.0000, 0.6984, 0.3016, 1.0000, 0.7143, 0.2857, 1.0000, 0.7302, 0.2698, 1.0000, 0.7460, 0.2540, 1.0000, 0.7619, 0.2381, 1.0000, 0.7778, 0.2222, 1.0000, 0.7937, 0.2063, 1.0000, 0.8095, 0.1905, 1.0000, 0.8254, 0.1746, 1.0000, 0.8413, 0.1587, 1.0000, 0.8571, 0.1429, 1.0000, 0.8730, 0.1270, 1.0000, 0.8889, 0.1111, 1.0000, 0.9048, 0.0952, 1.0000, 0.9206, 0.0794, 1.0000, 0.9365, 0.0635, 1.0000, 0.9524, 0.0476, 1.0000, 0.9683, 0.0317, 1.0000, 0.9841, 0.0159, 1.0000, 1.0000, 0, 1.0000 }; }
053b9c64880b845ee205138b861c39fd8db1c502
f1960e86ffed49ead6cbb02c07559ac304bd22e2
/st6/main.cpp
eb70785812645c4b7f878e0db6f373dc7b4a99ab
[]
no_license
skiry/Highschool
6aa09f28f0952c06953f9b8b417c32ef9970f6d4
319b05c33db733a4108b6fbd73328cca159caff3
refs/heads/master
2021-05-14T12:25:57.251753
2018-01-06T00:24:36
2018-01-06T00:24:36
116,405,336
1
0
null
null
null
null
UTF-8
C++
false
false
2,952
cpp
main.cpp
#include <fstream> #include <vector> #include <deque> #include <algorithm> #include <queue> using namespace std; ifstream f("6st.in"); ofstream g("6st.out"); int n,m,i,j,k,crs[301],minim[301],actual,prezent,el,minact,gint[301],gext[301],viz[301],initial,nr,total[301],vizcalc[301],suma; vector <int> a[301]; deque <int> q; vector <int> ordine; vector <int> rez; queue <int> calc; vector <int>::iterator it; inline bool cmp(const int &bb,const int &cc) { if(minim[bb]==minim[cc]) return crs[bb]<crs[cc]; return minim[bb]>minim[cc]; } void calculeaza(int valoare) { if(!viz[valoare]) nr++; viz[valoare]++; for(int j=0;j<a[valoare].size();j++) if(crs[a[valoare][j]]-total[a[valoare][j]]>0&&viz[a[valoare][j]]<m) { prezent=a[valoare][j]; if(!total[prezent]) { if(total[valoare]>=crs[prezent]) total[prezent]=crs[prezent]; else total[prezent]=total[valoare]; if(a[valoare].size()>1) total[valoare]-=total[prezent]; else total[valoare]=0; } else { if(total[valoare]>=crs[prezent]-total[prezent]) total[prezent]=crs[prezent]; else total[prezent]+=total[valoare]; total[valoare]=0; } calculeaza(prezent); } } int main() { f>>n; for(i=1;i<=n;i++) f>>crs[i]; f>>m; for(i=1;i<=n;i++) minim[i]=999; for(i=1;i<=m;i++) { f>>k; for(j=1;j<=k;j++) f>>el,q.push_back(el); actual=q.back(); calc.push(actual); q.pop_back(); minact=crs[actual]; minim[actual]=min(minim[actual],minact); while(q.size()) { prezent=q.back(); q.pop_back(); gint[actual]++; gext[prezent]++; minact=min(minact,crs[prezent]); minim[prezent]=min(minim[prezent],minact); a[prezent].push_back(actual); actual=prezent; } } for(i=1;i<=n;i++) { if(a[i].size()>1) sort(a[i].begin(),a[i].end(),cmp); it=unique(a[i].begin(),a[i].end()); a[i].resize(distance(a[i].begin(),it)); if(gext[i]&&!gint[i]) ordine.push_back(i); else if(gext[i]&gint[i]) rez.push_back(i); } sort(ordine.begin(),ordine.end(),cmp); for(i=0;i<ordine.size();i++) { actual=ordine[i]; if(!viz[actual]) total[actual]=crs[actual],calculeaza(actual); } if(nr!=n) { sort(rez.begin(),rez.end(),cmp); for(i=0;i<rez.size();i++) { actual=rez[i]; if(!viz[actual]) total[actual]=crs[actual],calculeaza(actual); } } while(calc.size()) { actual=calc.front(); calc.pop(); if(!vizcalc[actual]) suma+=total[actual],vizcalc[actual]++; } g<<suma; return 0; }
b33633bfa87f78f0102e94dfcec4789fc1246072
a14cf2c85ac756c75cf142fbb657f8ec05cd19ae
/unittest/common.h
55e8dcf1b46330fe77c9a051bff0a2ab7f67a189
[]
no_license
343829084/futures_cell_proxy
e9083f6fdd11b63b49ac5ea8121815470315cdc8
552d8850227dfe84635fade0f3daee94d96b06d7
refs/heads/master
2020-05-16T09:32:46.947521
2018-09-16T12:28:54
2018-09-16T12:28:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
796
h
common.h
// Copyright (c) 2017, Formax Inc. All rights reserved. #ifndef FUTURES_CELL_PROXY_UNITTEST_COMMON_H #define FUTURES_CELL_PROXY_UNITTEST_COMMON_H #include <string> #include "futures_cell_proxy/proto/futures_service.pb.h" /////////////////////////////// 宏定义开始 //////////////////////////////// // #ifndef FUNC_NAME #define FUNC_NAME \ "[" << __func__ << "] " \ #endif // FUNC_NAME namespace futures { namespace pb { namespace protocols { namespace common { bool HttpGet(const std::string& server_ip, int32_t server_port, int32_t timeout_s, const std::string& func_name, const std::string& http_req_body, const std::string* http_resp_body); } // namespace common } // namespace protocols } // namespace pb } // namespace futures #endif // FUTURES_CELL_PROXY_UNITTEST_COMMON_H
23d33c7d07cc5f57d3b65cc5b81f41812fa88704
3084462cc596f0d513edd65a9d7dd514a7284cc0
/Graph/013MotherVertex.cpp
487a7f457f8154f9da83979c622efc304ddb45f9
[]
no_license
atlas25git/DSA_Mastery
8d330f120a040105ff3932701009f289963ec2b3
97236ff9ada502af2ee2526c8568d3163e4daa2e
refs/heads/master
2023-07-07T14:22:43.127799
2021-08-04T14:44:49
2021-08-04T14:44:49
303,709,740
5
0
null
null
null
null
UTF-8
C++
false
false
1,706
cpp
013MotherVertex.cpp
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: void dfs(int u, vector<int>adj[], vector<bool>&vis) { //marking current vertex as visited. vis[u] = true; //iterating over the adjacent vertices. for(auto v: adj[u]) { //if any vertex is not visited, we call dfs function recursively. if(!vis[v]) dfs(v, adj, vis); } } //Function to find a Mother Vertex in the Graph. int findMotherVertex(int V, vector<int>adj[]) { //boolean list to mark the visited nodes and initially all are //initialized as not visited. vector<bool>vis(V, false); //variable to store last finished vertex (or mother vertex). int v; //iterating over all the vertices for(int i = 0; i < V; i++) { //if current vertex is not visited, we call the dfs //function and then update the variable v. if(!vis[i]){ dfs(i, adj, vis); v = i; } } //we reset all the vertices as not visited. vis.assign(V, false); //calling the dfs function to do DFS beginning from v to check //if all vertices are reachable from it or not. dfs(v, adj, vis); //iterating on boolean list and returning -1 if //any vertex is not visited. for(auto i: vis) if(!i) return -1; //returning mother vertex. return v; } }; // { Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int V, E; cin >> V >> E; vector<int>adj[V]; for(int i = 0; i < E; i++){ int u, v; cin >> u >> v; adj[u].push_back(v); } Solution obj; int ans = obj.findMotherVertex(V, adj); cout << ans <<"\n"; } return 0; } // } Driver Code Ends
313778fb852f229c6f58183317269cead59fd21d
376c88f77e904986c2d81eb9ea8de851a8135b9a
/projects/desktoplife/desktoplife.cpp
723a5a73e35e42e6b5d2f27e590e37f2f651a33a
[ "MIT" ]
permissive
Wiladams/ndt
e01da0e7844c48c591031157cd0611fed08b6f0b
d93f6fd0e6de46e86dbe8e7dbb394f867fa799d4
refs/heads/master
2023-03-01T00:34:48.897819
2023-02-18T19:16:16
2023-02-18T19:16:16
252,350,143
14
0
null
null
null
null
UTF-8
C++
false
false
3,888
cpp
desktoplife.cpp
#include "p5.hpp" using namespace p5; /* Game of life running on the entire desktop as a layered window */ int ** Array2D(int rows, int columns) { int **arr = new int *[rows]; for (int i=0; i<rows; i++) { arr[i] = new int[columns]; } return arr; } static const int w = 2; // size of a cell class Life { int fW; int fColumns; int fRows; int **board; int **next; int **neighborHood; public: Life(int aWidth, int aHeight) { fW = w; // Calculate columns and rows fColumns = (int)floor(aWidth/fW); fRows = (int)floor(aHeight/fW); //printf("rows: %d cols: %d\n", fRows, fColumns); board = Array2D(fRows, fColumns); next = Array2D(fRows, fColumns); neighborHood = Array2D(fRows-2, fColumns-2); init(); } // Fill board randomly void init() { for (int row = 0; row<fRows; row++) { for (int column = 0; column < fColumns; column++) { // Lining the edges with 0s if ((column == 0) || (row == 0) || (column == fColumns-1) || (row == fRows-1)) { board[row][column] = 0; } else { int val = (int)random(0,1); board[row][column] = val; } next[row][column] = 0; } } } // The process of creating the new generation void generate() { // Loop through every spot in our 2D array and check spots neighbors for (int y = 1; y < fRows - 1; y++) { for (int x = 1; x<fColumns - 1; x++) { // Add up all the states in a 3x3 surrounding grid int neighbors = 0; for (int i = -1; i<= 1; i++) { for (int j = -1; j<= 1; j++) { neighbors = neighbors + board[y+j][x+i]; } } // A little trick to subtract the current cell's state since // we added it in the above loop neighbors = neighbors - board[y][x]; //neighborHood[x-1][y-1] = neighbors // Rules of Life if ((board[y][x] == 1) && (neighbors < 2)) { next[y][x] = 0; // Loneliness } else if ((board[y][x] == 1) && (neighbors > 3)) { next[y][x] = 0; // Overpopulation } else if ((board[y][x] == 0) && (neighbors == 3)) { next[y][x] = 1; // Reproduction } else { next[y][x] = board[y][x]; // Stasis } } } // Swap! int **temp = board; board = next; next = temp; } void draw() { generate(); noStroke(); for (int i = 0; i <= fColumns-1; i++) { for (int j = 0; j<=fRows-1;j++) { if (board[j][i] == 1) { fill(0x7f); //fill((uint8_t)randomLowHigh(50,230), (uint8_t)randomLowHigh(127,255)); } else { fill(0,0); } rect(i*fW, j*fW, fW, fW); } } } }; Life* l1 = nullptr; void keyTyped(const KeyboardEvent &event) { // if [Space] reset life if (keyCode == ' ') { l1->init(); } } void keyReleased(const KeyboardEvent &event) { if (keyCode == VK_ESCAPE) { halt(); } } double lasttime; void draw() { double lasttime = millis(); clear(); l1->draw(); double duration = millis() - lasttime; //printf("after draw: %3.3f\n", duration); } void setup() { l1 = new Life(displayWidth, displayHeight); fullscreen(); //frameRate(30); }
922e47af36d077abd4bc31f3f905c9ffdc3f458c
81295026fe4861a79d9172a7496ac34299cbd361
/main/compass.ino
286bdff5613893c6ddbe9a27eaccd67df03b7f7b
[ "Apache-2.0" ]
permissive
trelorny/homealonerobot
8a00120af973f44a9b30dcffa38d59e39f0a4b19
85e6eabeb94b904fbb634d78077df6ea69810183
refs/heads/master
2021-01-17T09:45:58.317155
2017-03-06T17:38:05
2017-03-06T17:38:05
83,992,431
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
ino
compass.ino
#include <Wire.h> #define Addr 0x1E int BEARING_HYSTERESIS = 3; int COURSE_CORRECTION_INTERVAL = 500; void initCompass() { // Setup compass module Wire.begin(); // Set operating mode to continuous Wire.beginTransmission(Addr); Wire.write(byte(0x02)); Wire.write(byte(0x00)); Wire.endTransmission(); } int getHeading() { int x, y, z; // Initiate communications with compass Wire.beginTransmission(Addr); Wire.write(byte(0x03)); // Send request to X MSB register Wire.endTransmission(); Wire.requestFrom(Addr, 6); // Request 6 bytes; 2 bytes per axis if (Wire.available() <= 6) { // If 6 bytes available x = Wire.read() << 8 | Wire.read(); z = Wire.read() << 8 | Wire.read(); y = Wire.read() << 8 | Wire.read(); } // If compass module lies flat on the ground with no tilt, // just x and y are needed for calculation float heading = atan2(-x, y) / 0.0174532925; if (heading < 0) heading += 360; // N=0/360, E=90, S=180, W=270 return (int)heading; }
c9fd9683fdc8a01b2db33e3aee41f53f1d2f4ba3
60cfee38be68565e4263713fa293a3a4fe65fddd
/Blinker/arduino blink light/Blink/Blink.ino
bd17a12d06bc082ddd6e1a44755be3586af79f63
[]
no_license
rupert96/python
0295164cbdd5c27b3412fcb2127e2ce021fda941
b8b1b492ee44f7d54449d19d4cb6f65925792d2e
refs/heads/master
2021-01-11T03:50:28.914787
2016-10-30T18:52:20
2016-10-30T18:52:20
71,257,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
ino
Blink.ino
// Code inside "setup" gets run once, when the program first starts up void setup() { pinMode(13, OUTPUT); // Set pin 13 to be in output mode Serial.begin(9600); } // Code inside "loop" gets run over and over again, once "setup" has finished void loop() { if(Serial.available() > 0) { char message = Serial.read(); if (message == '1'){ digitalWrite(13, HIGH); } if (message == '2') { digitalWrite(13, LOW); } } } //String on = Serial.readStringUntil('\n'); //String off = Serial.readStringUntil('\n'); //Import required libraries //& from serial import * // Open port by name (different for each device) at a speed of 9600 //& port = Serial("/dev/cu.usbmodem1411",9600,timeout=2) // Clear any previous old data waiting in the buffer //& port.readall() // Write out a string to the serial port //& message = "Hello there Arduino\n" //& port.write(message.encode()) //& print("You just said: Hello there Arduino") //Read back in and print the response from the serial port, then close it //& input = port.readline() //& print("Arduino replied: " + input) //& port.close()
34071ac91f1507441079a79f03b9f9c656e9b3df
e17c7cf738ee8c59789e9bef6aca875715545912
/kcwdebug.cpp
9884ca8e0676163488f6a33aae6211020412fc6e
[]
no_license
KDE/libkcw
e279b1336b2228716853e3bc9465a1424adacd75
810b71cc946d7fa0625d481d4245cfb6d3f2a04c
refs/heads/master
2016-09-08T01:32:43.445800
2014-01-17T21:07:48
2014-01-17T21:08:45
42,731,774
2
0
null
null
null
null
UTF-8
C++
false
false
2,991
cpp
kcwdebug.cpp
/* Copyright 2013-2014 Patrick Spendrin <ps_ml@gmx.de> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <string> #include <windows.h> #include "kcwdebug.h" bool KcwDebug::s_enabled = true; std::locale KcwDebug::s_loc(""); KcwDebug::KcwDebug() : m_maybeSpace( false ), m_stringptr( NULL ) {} KcwDebug::KcwDebug(std::string* ptr) : m_maybeSpace( false ), m_stringptr( ptr ) {} KcwDebug::~KcwDebug() { if(s_enabled) { // std::cout << m_ss.str(); OutputDebugStringA(m_ss.str().c_str()); } if(m_stringptr) *m_stringptr = m_ss.str(); } KcwDebug& KcwDebug::maybeSpaceReference() { m_maybeSpace = true; return *this; } void KcwDebug::spaceIt() { if(m_maybeSpace) m_ss << " "; m_maybeSpace = false; } KcwDebug& KcwDebug::operator<<(ManipFunc manipFunc) { return manipFunc(*this); } void KcwDebug::setEnabled(bool enable) { s_enabled = enable; } bool KcwDebug::enabled() { return s_enabled; } // manipulation function /** * writes an end of line character (std::endl) either to the debug console or the string * used by the KcwDebug object. */ KcwDebug& endl(KcwDebug& os) { // before endl, we don't need a space os.m_maybeSpace = false; os.m_ss << std::endl; return os; } template<> KcwDebug& KcwDebug::operator<<(std::wstring i) { spaceIt(); const wchar_t *wstr = i.c_str(); char *str = new char[i.length() + 1]; ZeroMemory(str, (i.length() + 1) * sizeof(char)); std::use_facet<std::ctype<wchar_t> >(s_loc).narrow(wstr, wstr+wcslen(wstr), '?', str); str[wcslen(wstr)] = 0; m_ss << str; return maybeSpaceReference(); } template<> KcwDebug& KcwDebug::operator<<(const wchar_t* i) { return KcwDebug::operator<<(std::wstring(i)); }
bcb9856e9582c49c4abc8790d6d56806d40df84e
8f714265032c8444e3b33dded325ac79e3ece8c4
/HW2/RestaurantReservations.cpp
6693cb165a6010de414310070ecd8f9a8897c8f4
[]
no_license
VictorNguyen031900/Computer-Science-II
dd14a0f20d27432a08ad5851c9396a9ed5a285ea
a440c189e05b6c3aa6d6bca08facc907c4ae981b
refs/heads/master
2022-11-27T03:38:01.076681
2020-07-27T05:48:07
2020-07-27T05:48:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,483
cpp
RestaurantReservations.cpp
#include "RestaurantReservations.h" #include "Restaurant.h" #include "Reservation.h" #include <iostream> #include <iomanip> #include <string> #include <vector> #include <fstream> using namespace std; RestaurantReservations::RestaurantReservations() //Default constructor { } void RestaurantReservations::ProcessTransactionFile(string fileName) //ProcessTransactionFile member function ("Main") { string command; //used to read command from input file string rName; //used to read restaurant name from input file string rAddress; //used to read restaurant address from input file string rCity; //used to read restaurant city from input fille string rType; //used to read restaurant type from input file string cName; //used to read customer name from input file to set reservations string cPhone; //used to read customer phone from input file to set reservations int rGroup; //used to read customer group size from input file to set reservations int rTime; //used to read customer time from input file to set reservations int rCapacity; //used to read restuarant capacity size to create a new restaurant int rNum; //used to read reservation number to cancel reservation ifstream infile; //in file stream named infile, used to read text from infile.open(fileName.c_str()); //open file fileName string that was passed from main to member function if(!infile) //used to check if file could be opened, if can't be open display error message { cout << "File \"" << fileName << "\" couldn't open properly! Try again!" << endl; //error message if can't be opened } else //if file can be open then proceed with else portion of code { while(infile >> command) //while infile can read the first word of each line then proceed with while portion of code { if(command == "CreateNewRestaurant") //if command string is the same as string "CreateNewRestaurant" then proceed with if portion else go to else if { infile >> rName >> rAddress >> rCity >> rType >> rCapacity; //read the rest of the same line as command string cout << "CreateNewRestaurant " << rName << " " << rAddress << " " << rCity << " " << rType << " " << rCapacity << endl; //print command format CreateNewRestaurant(rName, rAddress, rCity, rType, rCapacity); //pass rName, rAddress, rCity, rType, rCapacity to member function CreatenewRestaurant } else if(command == "FindTable") //else if command string is the same as string "FindTable" then proceed with else if portion else go to next else if statement { infile >> rCity >> rType >> rGroup >> rTime; //read the rest of the same line as command string cout << "FindTable " << rCity << " " << rType << " " << rGroup << " " << rTime << endl; //print command format FindTable(rCity, rType, rGroup, rTime); } else if(command == "FindTableAtRestaurant") //else if command string is the same as string "FindTableAtRestaurant" then proceed with else if portion else go to next else if statement { infile >> rName >> rGroup; //read the rest of the same line as command string cout << "FindTableAtRestaurant " << rName << " " << rGroup << endl; //print command format FindTableAtRestaurant(rName, rGroup); //pass rName and rGroup to FindTableAtRestaurant member function } else if(command == "MakeReservation") //else if command string is the same as string "MakeReservation" then proceed with else if portion else go to next else if statement { infile >> rName >> cName >> cPhone >> rGroup >> rTime; //read the rest of the same line as command string cout << "MakeReservation " << rName << " " << cName << " " << cPhone << " " << rGroup << " " << rTime << endl; //print command format MakeReservation(rName, cName, cPhone, rGroup, rTime); //pass rName, cName, cPhone, rGroup, and rTime to MakeReservation member function } else if(command == "CancelReservation") //else if command string is the same as string "CancelReservation" then proceed with else if portion else go to next else if statement { infile >> rName >> rNum; //read the read of the same line as command string cout << "CancelReservation " << rName << " " << rNum << "(Canceled Function)" << endl; //print command format however member function was canceled by professor in an email CancelReservation(rName, rNum); //pass rName and rNum to CancelRservation member function } else if(command == "PrintAllRestaurants") //else if command string is the same as string "PrintAllRestaurants" then proceed with else if portion else go to next else if statement { cout << "PrintAllRestaurants" << endl; //print command format cout << "Restaurant Address, City Type Capacity" << endl; //print table header cout << "-------------------------------------------------------------------------------" << endl; //print table header PrintAllRestaurants(); //call PrintAllRestaurant member function } else if(command == "PrintRestaurantReservations") //else if command string is the same as string "PrintRestaurantReservations" then proceed with else if portion else go to final else statement { infile >> rName; //read the rest of the same line as command string cout << "PrintRestaurantReservations " << rName << endl; //print command format PrintRestaurantReservations(rName); //pass variable rName to member function PrintRestaurantReservations } else //if command string doesn't match with any command then command string was invalid { cout << "Incorrect command!" << endl; //print error message for incorrect command } } } infile.close(); //close file "TransactionFile.txt" } void RestaurantReservations::CreateNewRestaurant(string rName, string rAddress, string rCity, string rType, int rCapacity) //member function used to create a new restaurant and add it to database(vector) { Restaurant temp(rName, rAddress, rCity, rType, rCapacity); //create a new Restaurant class named temp and pass variables rName, rAddess, rCity, rType, and rCapacity restaurants.push_back(temp); //push back(add) temp to vector restaurants } void RestaurantReservations::PrintAllRestaurants() //member function used to print all restaurants in restaurants vector { int vectorSize = restaurants.size(); //variable vectorSize set to the size of vector restaurants to use it for for-loop for(int i = 0; i < vectorSize; i++) //for-loop used to print a restaurant line by line { cout << left << setw(21) << restaurants[i].getName() << left << setw(34) << restaurants[i].getAddress() + ", " + restaurants[i].getCity() << left << setw(16) << restaurants[i].getType() << left << setw(8) << restaurants[i].getSeats(0) << endl; //print restaurant name, address, city, type, and capacity line by line } } void RestaurantReservations::FindTable(string rCity, string rType, int rGroup, int rTime) //member function used to find a table with available for all restaurants based on city, restaurant type, reservation group size, and reservation time { int vectorSize = restaurants.size(); //variable vectorSize set to the size of vector restaurants string nameHold; //string nameHold used to hold name of vector restaurants index i's name vector<string> names; //vector used to hold all restaurant names with available criteria passed in int count = 0; //variable count used to help if there's an entry in vector names for(int i = 0; i < vectorSize; i++) //for-loop used to check through vector restaurants { if(rCity == restaurants[i].getCity()) //if passed in variable rCity matches with vector restaurants index i's city then proceed with if portion { if(rType == restaurants[i].getType()) //if passed in variable rType matches with vector restaurants index i's type then proceed with if portion { if(rTime == 5) //if passed in variable rTime matches with 5 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(0)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 0 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) namedHold to vector names count++; //increment count variable by 1 } } else if(rTime == 6) //else if passed in variable rTime matches with 6 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(1)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 1 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else if(rTime == 7) //else if passed in variable rTime matches with 7 then proceed with if portion else go to next else if statement { if(rGroup <= restaurants[i].getSeats(2)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 2 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else if(rTime == 8) //else if passed in variable rTime matches with 7 then proceed with if portion else go to next else statement { if(rGroup <= restaurants[i].getSeats(3)) //if passed in variable rGroup is greater than or equal to vector restaurants index i's array availableSeats index 3 { nameHold = restaurants[i].getName(); //set variable nameHold to vector restaurants index i's name names.push_back(nameHold); //push back(add) nameHold to vector names count++; //increment count variable by 1 } } else //if rTime doesn't match with 5, 6, 7 or 8 then rTime that was passed in was invalid for the program { cout << "Incorrect time for reservation" << endl; //print error message } } } } int printVector = names.size(); //create a variable named printVector and set it to the size of vector names to be used in the for-loop under if(count > 0) //if count variable is greater than 0 then that means there's a string in the vector names { cout << "You may reserve a table for " << rGroup << " at " << rTime << " pm at:" << endl; //print formatted response for(int i = 0; i < printVector; i++) //for-loop used to print every entry in the vector { cout << names[i] << endl; //print index i in vector names } } else //if count variable equal to or less than 0 then that means there's not entries in the vector print meaning there's no restaurants that fit the criteria { cout << "No restaurant can accommodate such a group at this time, check another time." << endl; //print message indicating there's not restaurant that doesn't fit the criteria } } void RestaurantReservations::FindTableAtRestaurant(string rName, int rGroup) //member function used to find a table at a certain restaurant based on the size of the reservation group, then output times with available seating { int vectorSize = restaurants.size(); //variable vectorsize set to the size of vector restaurants to be used in the for loop int count = 0; //variable used to helped out the available times for seating vector<int> times; //vector times used for to have available times with correct seating for customer for(int i = 0; i < vectorSize; i++) //for-loop used to add available times with correct seating to vector to be used later { if(rName == restaurants[i].getName()) //check if passed in rName is the same as vector restaurants index i's name { for(int j = 0; j < 4; j++) //goes through availableseats array to check capacity { if(rGroup <= restaurants[i].getSeats(j)) //if group size is less than or equal to the capacity in index j of availableseats array { int h = j + 5; //variable h used for times 5:00, 6:00, 7:00, or 8:00 times.push_back(h); //push back(add) variable h to vector times count++; //increase variable count to tell if statement if that there is an available time } } } } int vecPrint = times.size(); //variable vecPrint set to the size of vector times if(count > 0) //if variable count is greater than 0, then that means there's an avaiable times { cout << "You can reserve a table for " << rGroup << " at " << rName << " at "; //print there's an avaiable time for rGroup amount of people at times for(int i = 0; i < vecPrint; i++) //for-loop used to print available times from vector times { cout << times[i] << ":00 pm"; //print time as the format "0:00" if(i < (vecPrint - 1)) //if statement used to print commas inbetween times if multiple times available { cout << ", "; //print comma } } cout << endl; //skip line } else //if there's no available time then print message regarding time avilability { cout << rName << " does not have such availability." << endl; //print message } } void RestaurantReservations::MakeReservation(string rName, string cName, string cPhone, int rGroup, int rTime) //member function used to make a reservation with passed in variables rName, cname, cPhone, rGroup, rTime { int vectorSize = restaurants.size(); //variable vectorsize set to the size of vector restaurants to be used in for-loop for(int i = 0; i < vectorSize; i++) //for-loop used to add reservation to vector { if(rName == restaurants[i].getName()) //if rName variable that was passed in is equal to vector restaurants index i's name then proceed with if portion { restaurants[i].makeReservation(cName, cPhone, rGroup, rTime); //pass in cName, cPhone, rGroup, and rTime in to makeReservation member function from restaurant class } } } void RestaurantReservations::CancelReservation(string rName, long rNum) //member function use was to be used to cancel reservation, but now it s now been removed from the assignment { cout << "Canceled function stated by professor!" << endl; //print message } void RestaurantReservations::PrintRestaurantReservations(string rName) //member function is used to print all the reservations in a certain restaurant indicated by string rname { int vectorSize = restaurants.size(); //variable vectorSize set to size of vector restaurants cout << "Reservation Contact Phone Group Time" << endl; //print table header cout << "--------------------------------------------------" << endl; //print table header for(int i = 0; i < vectorSize; i++) //for-loop used to print all reservations for a certain restaurant { if(rName == restaurants[i].getName()) //if rName matches with vector restaurants index i's name then proceed with if portion { restaurants[i].printReservation(); //call printReservation member function in restaurants class } } }
c6e509bc54b9acfca4a1af6799765c89c4e709a4
1a3d9fda52c764cdb2988f79d13861ae7151ca25
/source/Utils/test/src/Math/FixedPointTests.cpp
e4c304fbdf1df23f16efeb9a5b9325c8ad78c8dc
[ "BSD-3-Clause" ]
permissive
mamaheux/apb
3859ddd57b3fad2569c3cc08e2dc994b3587ec0b
44e3a80c3c67c3516a7a1ac046c666fd7baafb4a
refs/heads/main
2021-06-23T15:11:14.619016
2019-01-03T22:10:42
2019-01-03T22:10:42
142,214,833
0
0
null
null
null
null
UTF-8
C++
false
false
20,356
cpp
FixedPointTests.cpp
#include <Utils/Math/FixedPoint.h> #include <gtest/gtest.h> #include <sstream> using namespace apb; using namespace std; TEST(FixedPointTests, Q3_4_defaultConstructor_shouldSetTheValueTo0) { stringstream ss; FixedPointQ3_4 testee; ss << testee; EXPECT_EQ(ss.str(), "0"); } TEST(FixedPointTests, Q3_4_fixedPointConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(static_cast<int8_t>((1 << 4) + (1 << 3))); ss << testee; EXPECT_EQ(ss.str(), "1.5"); } TEST(FixedPointTests, Q3_4_fixedPointConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(static_cast<int8_t>(-((2 << 4) + (1 << 3)))); ss << testee; EXPECT_EQ(ss.str(), "-2.5"); } TEST(FixedPointTests, Q3_4_floatConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(2.125f); ss << testee; EXPECT_EQ(ss.str(), "2.125"); } TEST(FixedPointTests, Q3_4_floatConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(-3.375f); ss << testee; EXPECT_EQ(ss.str(), "-3.375"); } TEST(FixedPointTests, Q3_4_doubleConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(2.125); ss << testee; EXPECT_EQ(ss.str(), "2.125"); } TEST(FixedPointTests, Q3_4_doubleConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(-1.5); ss << testee; EXPECT_EQ(ss.str(), "-1.5"); } TEST(FixedPointTests, Q3_4_copyConstructor_shouldSetTheRightValue) { stringstream ss; FixedPointQ3_4 testee(FixedPointQ3_4(-2.25)); ss << testee; EXPECT_EQ(ss.str(), "-2.25"); } TEST(FixedPointTests, Q3_4_multiplyAccumulate) { FixedPointQ3_4 testee1(1.0); testee1.multiplyAccumulate(0.5, 2.0); EXPECT_EQ(testee1, 2.0); FixedPointQ3_4 testee2(-1.0); testee2.multiplyAccumulate(0.5, 2.0); EXPECT_EQ(testee2, 0.0); FixedPointQ3_4 testee3(1.0); testee3.multiplyAccumulate(-0.5, 2.0); EXPECT_EQ(testee3, 0.0); FixedPointQ3_4 testee4(1.0); testee4.multiplyAccumulate(0.5, -1.0); EXPECT_EQ(testee4, 0.5); } TEST(FixedPointTests, Q3_4_multiplySubtract) { FixedPointQ3_4 testee1(1.0); testee1.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee1, 0.0); FixedPointQ3_4 testee2(-1.0); testee2.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee2, -2.0); FixedPointQ3_4 testee3(1.0); testee3.multiplySubtract(-0.5, 2.0); EXPECT_EQ(testee3, 2.0); FixedPointQ3_4 testee4(1.0); testee4.multiplySubtract(0.5, -1.0); EXPECT_EQ(testee4, 1.5); } TEST(FixedPointTests, Q3_4_operatorAddAssignation) { FixedPointQ3_4 testee1(1.0); testee1 += 1.25; EXPECT_EQ(testee1, 2.25); FixedPointQ3_4 testee2(-1.0); testee2 += 1.75; EXPECT_EQ(testee2, 0.75); FixedPointQ3_4 testee3(1.0); testee3 += -1.5; EXPECT_EQ(testee3, -0.5); FixedPointQ3_4 testee4(-1.0); testee4 += -1.25; EXPECT_EQ(testee4, -2.25); } TEST(FixedPointTests, Q3_4_operatorSubtractAssignation) { FixedPointQ3_4 testee1(1.0); testee1 -= 1.25; EXPECT_EQ(testee1, -0.25); FixedPointQ3_4 testee2(-1.0); testee2 -= 1.75; EXPECT_EQ(testee2, -2.75); FixedPointQ3_4 testee3(1.0); testee3 -= -1.5; EXPECT_EQ(testee3, 2.5); FixedPointQ3_4 testee4(-1.0); testee4 -= -1.5; EXPECT_EQ(testee4, 0.5); } TEST(FixedPointTests, Q3_4_operatorMultiplyAssignation) { FixedPointQ3_4 testee1(1.0); testee1 *= 1.25; EXPECT_EQ(testee1, 1.25); FixedPointQ3_4 testee2(-1.0); testee2 *= 1.75; EXPECT_EQ(testee2, -1.75); FixedPointQ3_4 testee3(1.0); testee3 *= -1.5; EXPECT_EQ(testee3, -1.5); FixedPointQ3_4 testee4(-1.0); testee4 *= -1.625; EXPECT_EQ(testee4, 1.625); } TEST(FixedPointTests, Q3_4_operatorDivideAssignation) { FixedPointQ3_4 testee1(1.0); testee1 /= 0.25; EXPECT_EQ(testee1, 4.0); FixedPointQ3_4 testee2(-1.0); testee2 /= 0.25; EXPECT_EQ(testee2, -4.0); FixedPointQ3_4 testee3(1.0); testee3 /= -0.5; EXPECT_EQ(testee3, -2.0); FixedPointQ3_4 testee4(-1.0); testee4 /= -4.0; EXPECT_EQ(testee4, 0.25); } TEST(FixedPointTests, Q3_4_operatorIncrement) { FixedPointQ3_4 testee(1.0); EXPECT_EQ(++testee, 2.0); EXPECT_EQ(testee++, 2.0); EXPECT_EQ(testee, 3.0); } TEST(FixedPointTests, Q3_4_operatorDecrement) { FixedPointQ3_4 testee(2.0); EXPECT_EQ(--testee, 1.0); EXPECT_EQ(testee--, 1.0); EXPECT_EQ(testee, 0.0); } TEST(FixedPointTests, Q3_4_operatorUnaryMinus) { EXPECT_EQ(-FixedPointQ3_4(1.0), -1.0); EXPECT_EQ(-FixedPointQ3_4(0.0), 0.0); EXPECT_EQ(-FixedPointQ3_4(-1.0), 1.0); } TEST(FixedPointTests, Q3_4_operatorAdd) { EXPECT_EQ(FixedPointQ3_4(1.0) + 1.25, 2.25); EXPECT_EQ(FixedPointQ3_4(-1.0) + 1.75, 0.75); EXPECT_EQ(FixedPointQ3_4(1.0) + -1.5, -0.5); EXPECT_EQ(FixedPointQ3_4(-1.0) + -1.5, -2.5); } TEST(FixedPointTests, Q3_4_operatorSubtract) { EXPECT_EQ(FixedPointQ3_4(1.0) - 1.25, -0.25); EXPECT_EQ(FixedPointQ3_4(-1.0) - 1.75, -2.75); EXPECT_EQ(FixedPointQ3_4(1.0) - -1.5, 2.5); EXPECT_EQ(FixedPointQ3_4(-1.0) - -1.5, 0.5); } TEST(FixedPointTests, Q3_4_operatorMultiply) { EXPECT_EQ(FixedPointQ3_4(1.0) * 1.25, 1.25); EXPECT_EQ(FixedPointQ3_4(-1.0) * 1.75, -1.75); EXPECT_EQ(FixedPointQ3_4(1.0) * -1.5, -1.5); EXPECT_EQ(FixedPointQ3_4(-1.0) * -1.25, 1.25); } TEST(FixedPointTests, Q3_4_operatorDivide) { EXPECT_EQ(FixedPointQ3_4(1.0) / 0.25, 4.0); EXPECT_EQ(FixedPointQ3_4(-1.0) / 0.5, -2.0); EXPECT_EQ(FixedPointQ3_4(1.0) / -0.5, -2.0); EXPECT_EQ(FixedPointQ3_4(-1.0) / -0.25, 4.0); } TEST(FixedPointTests, Q3_4_operatorEqualTo) { EXPECT_TRUE(FixedPointQ3_4(10.0) == 10.0); EXPECT_FALSE(FixedPointQ3_4(10.0) == 10.1); } TEST(FixedPointTests, Q3_4_operatorNotEqualTo) { EXPECT_FALSE(FixedPointQ3_4(10.0) != 10.0); EXPECT_TRUE(FixedPointQ3_4(10.0) != 10.1); } TEST(FixedPointTests, Q3_4_operatorLessThan) { EXPECT_TRUE(FixedPointQ3_4(10.0) < 11.0); EXPECT_FALSE(FixedPointQ3_4(10.0) < 9.0); } TEST(FixedPointTests, Q3_4_operatorLessThanOrEqualTo) { EXPECT_TRUE(FixedPointQ3_4(10.0) <= 11.0); EXPECT_TRUE(FixedPointQ3_4(10.0) <= 10.0); EXPECT_FALSE(FixedPointQ3_4(10.0) < 9.0); } TEST(FixedPointTests, Q3_4_operatorGreaterThan) { EXPECT_TRUE(FixedPointQ3_4(11.0) > 10.0); EXPECT_FALSE(FixedPointQ3_4(9.0) > 10.0); } TEST(FixedPointTests, Q3_4_operatorGreaterThanOrEqualTo) { EXPECT_TRUE(FixedPointQ3_4(11.0) >= 10.0); EXPECT_TRUE(FixedPointQ3_4(10.0) >= 10.0); EXPECT_FALSE(FixedPointQ3_4(9.0) >= 10.0); } TEST(FixedPointTests, Q7_8_defaultConstructor_shouldSetTheValueTo0) { stringstream ss; FixedPointQ7_8 testee; ss << testee; EXPECT_EQ(ss.str(), "0"); } TEST(FixedPointTests, Q7_8_fixedPointConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(static_cast<int16_t>((1 << 8) + (1 << 7))); ss << testee; EXPECT_EQ(ss.str(), "1.5"); } TEST(FixedPointTests, Q7_8_fixedPointConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(static_cast<int16_t>(-((2 << 8) + (1 << 7)))); ss << testee; EXPECT_EQ(ss.str(), "-2.5"); } TEST(FixedPointTests, Q7_8_floatConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(28.125f); ss << testee; EXPECT_EQ(ss.str(), "28.125"); } TEST(FixedPointTests, Q7_8_floatConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(-56.375f); ss << testee; EXPECT_EQ(ss.str(), "-56.375"); } TEST(FixedPointTests, Q7_8_doubleConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(25.125); ss << testee; EXPECT_EQ(ss.str(), "25.125"); } TEST(FixedPointTests, Q7_8_doubleConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(-36.5); ss << testee; EXPECT_EQ(ss.str(), "-36.5"); } TEST(FixedPointTests, Q7_8_copyConstructor_shouldSetTheRightValue) { stringstream ss; FixedPointQ7_8 testee(FixedPointQ7_8(-45.25)); ss << testee; EXPECT_EQ(ss.str(), "-45.25"); } TEST(FixedPointTests, Q7_8_multiplyAccumulate) { FixedPointQ7_8 testee1(10.0); testee1.multiplyAccumulate(0.5, 20.0); EXPECT_EQ(testee1, 20.0); FixedPointQ7_8 testee2(-10.0); testee2.multiplyAccumulate(0.5, 20.0); EXPECT_EQ(testee2, 0.0); FixedPointQ7_8 testee3(10.0); testee3.multiplyAccumulate(-0.5, 20.0); EXPECT_EQ(testee3, 0.0); FixedPointQ7_8 testee4(10.0); testee4.multiplyAccumulate(0.5, -10.0); EXPECT_EQ(testee4, 5.0); } TEST(FixedPointTests, Q7_8_multiplySubtract) { FixedPointQ7_8 testee1(1.0); testee1.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee1, 0.0); FixedPointQ7_8 testee2(-1.0); testee2.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee2, -2.0); FixedPointQ7_8 testee3(1.0); testee3.multiplySubtract(-0.5, 2.0); EXPECT_EQ(testee3, 2.0); FixedPointQ7_8 testee4(1.0); testee4.multiplySubtract(0.5, -1.0); EXPECT_EQ(testee4, 1.5); } TEST(FixedPointTests, Q7_8_operatorAddAssignation) { FixedPointQ7_8 testee1(10.0); testee1 += 1.25; EXPECT_EQ(testee1, 11.25); FixedPointQ7_8 testee2(-10.0); testee2 += 1.75; EXPECT_EQ(testee2, -8.25); FixedPointQ7_8 testee3(10.0); testee3 += -1.5; EXPECT_EQ(testee3, 8.5); FixedPointQ7_8 testee4(-10.0); testee4 += -1.625; EXPECT_EQ(testee4, -11.625); } TEST(FixedPointTests, Q7_8_operatorSubtractAssignation) { FixedPointQ7_8 testee1(10.0); testee1 -= 1.25; EXPECT_EQ(testee1, 8.75); FixedPointQ7_8 testee2(-10.0); testee2 -= 1.75; EXPECT_EQ(testee2, -11.75); FixedPointQ7_8 testee3(10.0); testee3 -= -1.5; EXPECT_EQ(testee3, 11.5); FixedPointQ7_8 testee4(-10.0); testee4 -= -1.625; EXPECT_EQ(testee4, -8.375); } TEST(FixedPointTests, Q7_8_operatorMultiplyAssignation) { FixedPointQ7_8 testee1(10.0); testee1 *= 1.25; EXPECT_EQ(testee1, 12.5); FixedPointQ7_8 testee2(-10.0); testee2 *= 1.75; EXPECT_EQ(testee2, -17.5); FixedPointQ7_8 testee3(10.0); testee3 *= -1.5; EXPECT_EQ(testee3, -15.0); FixedPointQ7_8 testee4(-10.0); testee4 *= -1.625; EXPECT_EQ(testee4, 16.25); } TEST(FixedPointTests, Q7_8_operatorDivideAssignation) { FixedPointQ7_8 testee1(10.0); testee1 /= 1.25; EXPECT_EQ(testee1, 8.0); FixedPointQ7_8 testee2(-10.0); testee2 /= 2.5; EXPECT_EQ(testee2, -4.0); FixedPointQ7_8 testee3(10.0); testee3 /= -5.0; EXPECT_EQ(testee3, -2.0); FixedPointQ7_8 testee4(-10.0); testee4 /= -8.0; EXPECT_EQ(testee4, 1.25); } TEST(FixedPointTests, Q7_8_operatorIncrement) { FixedPointQ7_8 testee(10.0); EXPECT_EQ(++testee, 11.0); EXPECT_EQ(testee++, 11.0); EXPECT_EQ(testee, 12.0); } TEST(FixedPointTests, Q7_8_operatorDecrement) { FixedPointQ7_8 testee(10.0); EXPECT_EQ(--testee, 9.0); EXPECT_EQ(testee--, 9.0); EXPECT_EQ(testee, 8.0); } TEST(FixedPointTests, Q7_8_operatorUnaryMinus) { EXPECT_EQ(-FixedPointQ7_8(10.0), -10.0); EXPECT_EQ(-FixedPointQ7_8(0.0), 0.0); EXPECT_EQ(-FixedPointQ7_8(-10.0), 10.0); } TEST(FixedPointTests, Q7_8_operatorAdd) { EXPECT_EQ(FixedPointQ7_8(10.0) + 1.25, 11.25); EXPECT_EQ(FixedPointQ7_8(-10.0) + 1.75, -8.25); EXPECT_EQ(FixedPointQ7_8(10.0) + -1.5, 8.5); EXPECT_EQ(FixedPointQ7_8(-10.0) + -1.625, -11.625); } TEST(FixedPointTests, Q7_8_operatorSubtract) { EXPECT_EQ(FixedPointQ7_8(10.0) - 1.25, 8.75); EXPECT_EQ(FixedPointQ7_8(-10.0) - 1.75, -11.75); EXPECT_EQ(FixedPointQ7_8(10.0) - -1.5, 11.5); EXPECT_EQ(FixedPointQ7_8(-10.0) - -1.625, -8.375); } TEST(FixedPointTests, Q7_8_operatorMultiply) { EXPECT_EQ(FixedPointQ7_8(10.0) * 1.25, 12.5); EXPECT_EQ(FixedPointQ7_8(-10.0) * 1.75, -17.5); EXPECT_EQ(FixedPointQ7_8(10.0) * -1.5, -15.0); EXPECT_EQ(FixedPointQ7_8(-10.0) * -1.625, 16.25); } TEST(FixedPointTests, Q7_8_operatorDivide) { EXPECT_EQ(FixedPointQ7_8(10.0) / 1.25, 8.0); EXPECT_EQ(FixedPointQ7_8(-10.0) / 2.5, -4.0); EXPECT_EQ(FixedPointQ7_8(10.0) / -5.0, -2.0); EXPECT_EQ(FixedPointQ7_8(-10.0) / -8.0, 1.25); } TEST(FixedPointTests, Q7_8_operatorEqualTo) { EXPECT_TRUE(FixedPointQ7_8(10.0) == 10.0); EXPECT_FALSE(FixedPointQ7_8(10.0) == 10.1); } TEST(FixedPointTests, Q7_8_operatorNotEqualTo) { EXPECT_FALSE(FixedPointQ7_8(10.0) != 10.0); EXPECT_TRUE(FixedPointQ7_8(10.0) != 10.1); } TEST(FixedPointTests, Q7_8_operatorLessThan) { EXPECT_TRUE(FixedPointQ7_8(10.0) < 11.0); EXPECT_FALSE(FixedPointQ7_8(10.0) < 9.0); } TEST(FixedPointTests, Q7_8_operatorLessThanOrEqualTo) { EXPECT_TRUE(FixedPointQ7_8(10.0) <= 11.0); EXPECT_TRUE(FixedPointQ7_8(10.0) <= 10.0); EXPECT_FALSE(FixedPointQ7_8(10.0) < 9.0); } TEST(FixedPointTests, Q7_8_operatorGreaterThan) { EXPECT_TRUE(FixedPointQ7_8(11.0) > 10.0); EXPECT_FALSE(FixedPointQ7_8(9.0) > 10.0); } TEST(FixedPointTests, Q7_8_operatorGreaterThanOrEqualTo) { EXPECT_TRUE(FixedPointQ7_8(11.0) >= 10.0); EXPECT_TRUE(FixedPointQ7_8(10.0) >= 10.0); EXPECT_FALSE(FixedPointQ7_8(9.0) >= 10.0); } TEST(FixedPointTests, Q15_16_defaultConstructor_shouldSetTheValueTo0) { stringstream ss; FixedPointQ15_16 testee; ss << testee; EXPECT_EQ(ss.str(), "0"); } TEST(FixedPointTests, Q15_16_fixedPointConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee((1 << 16) + (1 << 15)); ss << testee; EXPECT_EQ(ss.str(), "1.5"); } TEST(FixedPointTests, Q15_16_fixedPointConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(-((2 << 16) + (1 << 15))); ss << testee; EXPECT_EQ(ss.str(), "-2.5"); } TEST(FixedPointTests, Q15_16_floatConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(28.125f); ss << testee; EXPECT_EQ(ss.str(), "28.125"); } TEST(FixedPointTests, Q15_16_floatConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(-56.375f); ss << testee; EXPECT_EQ(ss.str(), "-56.375"); } TEST(FixedPointTests, Q15_16_doubleConstructor_positive_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(546.126); ss << testee; EXPECT_EQ(ss.str(), "546.126"); } TEST(FixedPointTests, Q15_16_doubleConstructor_negative_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(-479.568); ss << testee; EXPECT_EQ(ss.str(), "-479.568"); } TEST(FixedPointTests, Q15_16_copyConstructor_shouldSetTheRightValue) { stringstream ss; FixedPointQ15_16 testee(FixedPointQ15_16(-479.568)); ss << testee; EXPECT_EQ(ss.str(), "-479.568"); } TEST(FixedPointTests, Q15_16_multiplyAccumulate) { FixedPointQ15_16 testee1(10.0); testee1.multiplyAccumulate(0.5, 20.0); EXPECT_EQ(testee1, 20.0); FixedPointQ15_16 testee2(-10.0); testee2.multiplyAccumulate(0.5, 20.0); EXPECT_EQ(testee2, 0.0); FixedPointQ15_16 testee3(10.0); testee3.multiplyAccumulate(-0.5, 20.0); EXPECT_EQ(testee3, 0.0); FixedPointQ15_16 testee4(10.0); testee4.multiplyAccumulate(0.5, -10.0); EXPECT_EQ(testee4, 5.0); } TEST(FixedPointTests, Q15_16_multiplySubtract) { FixedPointQ15_16 testee1(1.0); testee1.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee1, 0.0); FixedPointQ15_16 testee2(-1.0); testee2.multiplySubtract(0.5, 2.0); EXPECT_EQ(testee2, -2.0); FixedPointQ15_16 testee3(1.0); testee3.multiplySubtract(-0.5, 2.0); EXPECT_EQ(testee3, 2.0); FixedPointQ15_16 testee4(1.0); testee4.multiplySubtract(0.5, -1.0); EXPECT_EQ(testee4, 1.5); } TEST(FixedPointTests, Q15_16_operatorAddAssignation) { FixedPointQ15_16 testee1(10.0); testee1 += 1.25; EXPECT_EQ(testee1, 11.25); FixedPointQ15_16 testee2(-10.0); testee2 += 1.75; EXPECT_EQ(testee2, -8.25); FixedPointQ15_16 testee3(10.0); testee3 += -1.5; EXPECT_EQ(testee3, 8.5); FixedPointQ15_16 testee4(-10.0); testee4 += -1.625; EXPECT_EQ(testee4, -11.625); } TEST(FixedPointTests, Q15_16_operatorSubtractAssignation) { FixedPointQ15_16 testee1(10.0); testee1 -= 1.25; EXPECT_EQ(testee1, 8.75); FixedPointQ15_16 testee2(-10.0); testee2 -= 1.75; EXPECT_EQ(testee2, -11.75); FixedPointQ15_16 testee3(10.0); testee3 -= -1.5; EXPECT_EQ(testee3, 11.5); FixedPointQ15_16 testee4(-10.0); testee4 -= -1.625; EXPECT_EQ(testee4, -8.375); } TEST(FixedPointTests, Q15_16_operatorMultiplyAssignation) { FixedPointQ15_16 testee1(10.0); testee1 *= 1.25; EXPECT_EQ(testee1, 12.5); FixedPointQ15_16 testee2(-10.0); testee2 *= 1.75; EXPECT_EQ(testee2, -17.5); FixedPointQ15_16 testee3(10.0); testee3 *= -1.5; EXPECT_EQ(testee3, -15.0); FixedPointQ15_16 testee4(-10.0); testee4 *= -1.625; EXPECT_EQ(testee4, 16.25); } TEST(FixedPointTests, Q15_16_operatorDivideAssignation) { FixedPointQ15_16 testee1(10.0); testee1 /= 1.25; EXPECT_EQ(testee1, 8.0); FixedPointQ15_16 testee2(-10.0); testee2 /= 2.5; EXPECT_EQ(testee2, -4.0); FixedPointQ15_16 testee3(10.0); testee3 /= -5.0; EXPECT_EQ(testee3, -2.0); FixedPointQ15_16 testee4(-10.0); testee4 /= -8.0; EXPECT_EQ(testee4, 1.25); } TEST(FixedPointTests, Q15_16_operatorIncrement) { FixedPointQ15_16 testee(10.0); EXPECT_EQ(++testee, 11.0); EXPECT_EQ(testee++, 11.0); EXPECT_EQ(testee, 12.0); } TEST(FixedPointTests, Q15_16_operatorDecrement) { FixedPointQ15_16 testee(10.0); EXPECT_EQ(--testee, 9.0); EXPECT_EQ(testee--, 9.0); EXPECT_EQ(testee, 8.0); } TEST(FixedPointTests, Q15_16_operatorUnaryMinus) { EXPECT_EQ(-FixedPointQ15_16(10.0), -10.0); EXPECT_EQ(-FixedPointQ15_16(0.0), 0.0); EXPECT_EQ(-FixedPointQ15_16(-10.0), 10.0); } TEST(FixedPointTests, Q15_16_operatorAdd) { EXPECT_EQ(FixedPointQ15_16(10.0) + 1.25, 11.25); EXPECT_EQ(FixedPointQ15_16(-10.0) + 1.75, -8.25); EXPECT_EQ(FixedPointQ15_16(10.0) + -1.5, 8.5); EXPECT_EQ(FixedPointQ15_16(-10.0) + -1.625, -11.625); } TEST(FixedPointTests, Q15_16_operatorSubtract) { EXPECT_EQ(FixedPointQ15_16(10.0) - 1.25, 8.75); EXPECT_EQ(FixedPointQ15_16(-10.0) - 1.75, -11.75); EXPECT_EQ(FixedPointQ15_16(10.0) - -1.5, 11.5); EXPECT_EQ(FixedPointQ15_16(-10.0) - -1.625, -8.375); } TEST(FixedPointTests, Q15_16_operatorMultiply) { EXPECT_EQ(FixedPointQ15_16(10.0) * 1.25, 12.5); EXPECT_EQ(FixedPointQ15_16(-10.0) * 1.75, -17.5); EXPECT_EQ(FixedPointQ15_16(10.0) * -1.5, -15.0); EXPECT_EQ(FixedPointQ15_16(-10.0) * -1.625, 16.25); } TEST(FixedPointTests, Q15_16_operatorDivide) { EXPECT_EQ(FixedPointQ15_16(10.0) / 1.25, 8.0); EXPECT_EQ(FixedPointQ15_16(-10.0) / 2.5, -4.0); EXPECT_EQ(FixedPointQ15_16(10.0) / -5.0, -2.0); EXPECT_EQ(FixedPointQ15_16(-10.0) / -8.0, 1.25); } TEST(FixedPointTests, Q15_16_operatorEqualTo) { EXPECT_TRUE(FixedPointQ15_16(10.0) == 10.0); EXPECT_FALSE(FixedPointQ15_16(10.0) == 10.1); } TEST(FixedPointTests, Q15_16_operatorNotEqualTo) { EXPECT_FALSE(FixedPointQ15_16(10.0) != 10.0); EXPECT_TRUE(FixedPointQ15_16(10.0) != 10.1); } TEST(FixedPointTests, Q15_16_operatorLessThan) { EXPECT_TRUE(FixedPointQ15_16(10.0) < 11.0); EXPECT_FALSE(FixedPointQ15_16(10.0) < 9.0); } TEST(FixedPointTests, Q15_16_operatorLessThanOrEqualTo) { EXPECT_TRUE(FixedPointQ15_16(10.0) <= 11.0); EXPECT_TRUE(FixedPointQ15_16(10.0) <= 10.0); EXPECT_FALSE(FixedPointQ15_16(10.0) < 9.0); } TEST(FixedPointTests, Q15_16_operatorGreaterThan) { EXPECT_TRUE(FixedPointQ15_16(11.0) > 10.0); EXPECT_FALSE(FixedPointQ15_16(9.0) > 10.0); } TEST(FixedPointTests, Q15_16_operatorGreaterThanOrEqualTo) { EXPECT_TRUE(FixedPointQ15_16(11.0) >= 10.0); EXPECT_TRUE(FixedPointQ15_16(10.0) >= 10.0); EXPECT_FALSE(FixedPointQ15_16(9.0) >= 10.0); }
79d771e1465002db76856a5a8ed8118487e3cbcb
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-appintegrations/include/aws/appintegrations/model/EventFilter.h
a42243211715aaa8cdd4d0dd12578be499565e32
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
2,339
h
EventFilter.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/appintegrations/AppIntegrationsService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace AppIntegrationsService { namespace Model { /** * <p>The event filter.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/appintegrations-2020-07-29/EventFilter">AWS * API Reference</a></p> */ class EventFilter { public: AWS_APPINTEGRATIONSSERVICE_API EventFilter(); AWS_APPINTEGRATIONSSERVICE_API EventFilter(Aws::Utils::Json::JsonView jsonValue); AWS_APPINTEGRATIONSSERVICE_API EventFilter& operator=(Aws::Utils::Json::JsonView jsonValue); AWS_APPINTEGRATIONSSERVICE_API Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The source of the events.</p> */ inline const Aws::String& GetSource() const{ return m_source; } /** * <p>The source of the events.</p> */ inline bool SourceHasBeenSet() const { return m_sourceHasBeenSet; } /** * <p>The source of the events.</p> */ inline void SetSource(const Aws::String& value) { m_sourceHasBeenSet = true; m_source = value; } /** * <p>The source of the events.</p> */ inline void SetSource(Aws::String&& value) { m_sourceHasBeenSet = true; m_source = std::move(value); } /** * <p>The source of the events.</p> */ inline void SetSource(const char* value) { m_sourceHasBeenSet = true; m_source.assign(value); } /** * <p>The source of the events.</p> */ inline EventFilter& WithSource(const Aws::String& value) { SetSource(value); return *this;} /** * <p>The source of the events.</p> */ inline EventFilter& WithSource(Aws::String&& value) { SetSource(std::move(value)); return *this;} /** * <p>The source of the events.</p> */ inline EventFilter& WithSource(const char* value) { SetSource(value); return *this;} private: Aws::String m_source; bool m_sourceHasBeenSet = false; }; } // namespace Model } // namespace AppIntegrationsService } // namespace Aws
66c88eb5a973a07724d4a51b8fd0bce29bd74031
05ad9f92a8c687f883d4400ab7c489c1884fccfa
/jni/descriptor.cpp
a7b79568174cdb8b94b586a70aa5647351adb909
[]
no_license
amankr/AndroidDrawing
76a630b72e1c0c7135b8aa1dac04609a23ccdda4
330b5fbd2396656988a8c9017caf327b7d4282d8
refs/heads/master
2021-01-19T16:32:57.395966
2015-03-16T14:41:32
2015-03-16T14:41:32
32,331,334
0
1
null
null
null
null
UTF-8
C++
false
false
7,780
cpp
descriptor.cpp
#include "ugp.h" inline float dist(float x1,float y1,float x2, float y2){ return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } void GetOrientations(Mat & src,Mat & dst){ int kernel_size = 3; int scale = 1; int delta = 0; int ddepth = CV_32F; Mat grad_x, grad_y; Sobel( src, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); Sobel( src, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); float *px,*py,*pd; dst.create(src.size(),ddepth); for(int i=0;i<src.rows;++i){ px = grad_x.ptr<float>(i); py = grad_y.ptr<float>(i); pd = dst.ptr<float>(i); for(int j=0;j<src.cols;++j){ if(px[j]==0) pd[j] = M_PI/2; else pd[j] = atan(py[j]/px[j]); } } } void edgeMake(Mat & E,Mat & A,Mat & src,Mat & dst,bool did){ dst.create(src.size(),CV_32F); int scale = 1; int delta = 0; int ddepth = CV_32F; Mat grad_x, grad_y; Sobel( src, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT ); Sobel( src, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT ); float X,Y; for(int i=0;i<src.rows;++i){ for(int j=0;j<src.cols;++j){ if(did){ X = /*cos(A.at<float>(i,j))*cos(A.at<float>(i,j))*/ grad_x.at<float>(i,j);//* E.at<float>(i,j); Y = /*sin(A.at<float>(i,j))*sin(A.at<float>(i,j))*/ grad_y.at<float>(i,j);//* E.at<float>(i,j); } else{ X = cos(A.at<float>(i,j))*cos(A.at<float>(i,j))* grad_x.at<float>(i,j)* E.at<float>(i,j); Y = sin(A.at<float>(i,j))*sin(A.at<float>(i,j))* grad_y.at<float>(i,j)* E.at<float>(i,j); } dst.at<float>(i,j) = dist(X,Y,0,0); } } convertScaleAbs(dst,dst); } void Rotate(Mat &src,Mat &angle,Mat &Rx,Mat &Ry){ int cx,cy; cx = src.rows/2; cy = src.cols/2; int depth = CV_32F; Rx.create(src.size(),depth); Ry.create(src.size(),depth); int X,Y; float *ang,*rx,*ry,theta; for(int i=0;i<src.rows;++i){ ang = angle.ptr<float>(i); rx = Rx.ptr<float>(i); ry = Ry.ptr<float>(i); for(int j=0;j<src.cols;++j){ X = i-cx; Y = j-cy; theta = ang[j]; rx[j] = cos(theta)*X - sin(theta)*Y; ry[j] = sin(theta)*X + cos(theta)*Y; } } } void minMAx(Mat &X, float &Xstart, float &Xlen,int unit){ double minVal,maxVal; Point minLoc,maxLoc; minMaxLoc( X, &minVal, &maxVal, &minLoc, &maxLoc ); Xstart = minVal; Xlen = (maxVal - minVal)/(float)unit; } void createHist(Mat &src,Mat &angle,Mat &X,Mat &Y, Mat &hist){ int nx,ny,n_o; nx = 18; // x bins ny = 8; // y bins n_o = 4; // theta bins //hist.create(nx,ny,CV_32FC(n_o)); float *data = (float *)(hist.data); for(int i=0;i<nx;++i) for(int j=0;j<ny;++j) for(int ch=0;ch<n_o;++ch) hist.ptr<float>(i)[n_o*j+ch] = 0.0; // data[hist.step * i + j + ch] = 0.0; float Xlen,Ylen,Tlen; // unit lengths float Xstart,Ystart,Tstart; minMAx(X,Xstart,Xlen,nx); minMAx(Y,Ystart,Ylen,ny); minMAx(angle,Tstart,Tlen,n_o); int store = src.type(); src.convertTo(src,CV_32F); float *dsrc,*xdata,*ydata,*tdata; int hx,hy,ht; data = (float *)(hist.data); for(int i=0;i<src.rows;++i){ dsrc = src.ptr<float>(i); xdata = X.ptr<float>(i); ydata = Y.ptr<float>(i); tdata = angle.ptr<float>(i); for(int j=0;j<src.cols;++j){ if(Xlen<1e-9) hx = 0; else hx = (xdata[j] - Xstart) / Xlen; if(Ylen<1e-9) hy = 0; else hy = (ydata[j] - Ystart) / Ylen; if(Tlen<1e-9) ht = 0; else ht = (tdata[j] - Tstart) / Tlen; hist.ptr<float>(hx)[n_o*hy + ht] += dsrc[j]; } } } inline bool check(int x,int y,int z,int a, int b,int c){ return (x>=0 && y>=0 && z>=0 && x<a && y<b && z<c); } void histBlur(Mat &src){ Mat temp1,temp2; double c1[] = {0.0545, 0.2442, 0.4026, 0.2442, 0.0545}; double c2[] = {0.0545, 0.2442, 0.4026, 0.2442, 0.0545}; temp1 = src.clone(); temp2 = src.clone(); register double sum; int x1,y1,z1,a,b,c; a = src.rows; b = src.cols; c = src.channels(); //cout<<temp.size()<<' '<<temp.channels(); for(int k = 0; k<c; ++k){ for(int i = 0; i < a; ++i){ for(int j = 0; j < b; ++j){ sum = 0.0; for(int m = -2; m <= 2; ++m){ y1 = j + m; if(check(i,y1,k,a,b,c)) sum = sum + c2[m + 2] * src.ptr<float>(i)[c*y1 + k]; } temp1.ptr<float>(i)[c*j + k] = sum; } } } for(int k = 0; k<c; ++k){ for(int j = 0; j < b; ++j){ for(int i = 0; i < a; ++i){ sum = 0.0; for(int m = -2; m <= 2; ++m){ x1 = i + m; if(check(x1,j,k,a,b,c)) sum = sum + c1[m + 2] * temp1.ptr<float>(x1)[c*j + k]; } temp2.ptr<float>(i)[c*j + k] = sum; } } } for(int i = 0; i < a; ++i){ for(int j = 0; j < b; ++j){ for(int k = 0; k<c; ++k){ sum = 0.0; for(int m = -2; m <= 2; ++m){ z1 = k + m; if(check(i,j,z1,a,b,c)) sum = sum + c1[m + 2] * temp2.ptr<float>(i)[c*j + z1]; } src.ptr<float>(i)[c*j + k] = sum; } } } } int compare (const void * a, const void * b) { return ( *(float*)a - *(float*)b ); } void binarize(Mat &src, Mat &bin){ int t=20; int tot,rest,st=0; tot = src.rows*src.cols*src.channels(); rest = tot*t/100; float arr[tot]; for(int k=0;k<src.channels();++k) for(int i=0;i<src.rows;++i) for(int j=0;j<src.cols;++j) arr[st++] = src.ptr<float>(i)[src.channels()*j+k]; //qsort (arr,st+1, sizeof(float), compare); sort(arr,arr+st); //cout<<arr[0]<<' '<<arr[st-1]<<endl; float val = arr[st-rest]; bin.create(src.size(),CV_32SC(src.channels())); for(int k=0;k<src.channels();++k) for(int i=0;i<src.rows;++i) for(int j=0;j<src.cols;++j) if (src.ptr<float>(i)[src.channels()*j+k] < val) bin.ptr<int>(i)[bin.channels()*j+k] = 0; else bin.ptr<int>(i)[bin.channels()*j+k] = 1; } void printH(std::vector<bool> m){ cout<<m.size()<<endl; for(int i=0;i<m.size();++i) cout<<m[i]; cout<<endl; //cout<<minVal<<' '<<maxVal<<endl; } void linear(Mat &m,std::vector<bool> &v){ for(int k=0;k<m.channels();++k){ for(int i=0;i<m.rows;++i){ for(int j=0;j<m.cols;++j){ v.push_back(m.ptr<int>(i)[m.channels()*j+k]); //cout<<m.ptr<int>(i)[m.channels()*j+k]<<' '; //maxVal = max(maxVal,m.ptr<float>(i)[m.channels()*j+k]); //minVal = min(minVal,m.ptr<float>(i)[m.channels()*j+k]); } //cout<<endl; } //cout<<endl; } } void getDescriptor(Mat &src, vector<bool> &descriptor, Mat &Hist) { Mat norm_grad,dst_norm,lenE; Mat theta; /// edge making -- we will get this as input //src = imread("img.jpg"); __android_log_print(ANDROID_LOG_DEBUG, "LOG_Ndk", "checkpoint 3.1"); if(src.channels()!=1) cvtColor( src, src, CV_RGB2GRAY ); __android_log_print(ANDROID_LOG_DEBUG, "LOG_Ndk", "checkpoint 3.2"); GaussianBlur( src, src, Size(3,3), 0, 0, BORDER_DEFAULT ); edgeMake(src,theta,src,norm_grad,1); convertScaleAbs( norm_grad, norm_grad ); GetOrientations(norm_grad,theta); // normalizing GaussianBlur( norm_grad, dst_norm, Size(3,3), 3, 3, BORDER_DEFAULT ); norm_grad.convertTo(norm_grad,CV_32F); dst_norm.convertTo(dst_norm,CV_32F); for(int i=0;i<norm_grad.rows;++i) for(int j=0;j<norm_grad.cols;++j) norm_grad.ptr<float>(i)[j] = (double)norm_grad.ptr<float>(i)[j] / max((float)4.0 , dst_norm.ptr<float>(i)[j]); ///////////// //Mat theta,norm_grad; Mat Rx,Ry; Mat bin; Rotate(norm_grad,theta,Rx,Ry); createHist(norm_grad,theta,Rx,Ry,Hist); histBlur(Hist); binarize(Hist,bin); linear(bin,descriptor); bin.release(); return; }
e4f99939791d76c879eb2c2e605377820b01717e
bf5be9e5b6033c9634d46955df088771145f6da7
/Source/GameFrame/Private/GameFrame.cpp
b6bac260d6615e307d85f0a4d5840513e4011414
[]
no_license
devilmhzx/SmallWorld
eaff8c1abb460397d7844a083eac24ce77954b92
eff5eddb408fc337e70be716a250ed98f17dd097
refs/heads/master
2020-07-19T00:04:27.629460
2019-09-03T13:34:58
2019-09-03T13:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
188
cpp
GameFrame.cpp
#include "GameFrame.h" #include "ModuleManager.h" void GameFrameModule::StartupModule() { } void GameFrameModule::ShutdownModule() { } IMPLEMENT_MODULE(GameFrameModule, GameFrame);
ce0de5494cbc9f8e56e70059781dd46a4c065484
c27df8ce4903389256023f71fc8004c6caf41d21
/src/oxc_smallrl_q.cpp
b6005b5874c9132b11cee2d393c61892e20d4c23
[]
no_license
atu-guda/stm32oxc
be8f584e6978fa40482bbd5df4a23bd6b41329eb
591b43246b8928329642b06bad8b9de6802e62ed
refs/heads/master
2023-09-03T08:42:36.058233
2023-09-02T19:15:15
2023-09-02T19:15:15
34,165,176
5
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
oxc_smallrl_q.cpp
#include <cstring> #include <oxc_smallrl_q.h> // #include <oxc_debug1.h> #include <task.h> using namespace std; using namespace SMLRL; void task_smallrl_cmd( void * /*prm*/ ) { struct SmallRlCmd cmd; BaseType_t ts; while(1) { ts = xQueueReceive( smallrl_cmd_queue, &cmd, 2000 ); if( ts != pdTRUE ) { continue; } // pr( NL "task_smallrl_cmd:" NL ); // dump8( cmd.cmdline, cmd.l+1 ); exec_direct( cmd.cmdline, cmd.l ); delay_ms( 10 ); if( global_smallrl ) { global_smallrl->redraw(); } } vTaskDelete(0); } int SMLRL::exec_queue( const char *s, int l ) { static SmallRlCmd cmd; if( l >= (int)sizeof( cmd.cmdline ) ) { l = sizeof( cmd.cmdline ) - 1; } cmd.l = l; cmd.cmdline[l+1] = '\0'; memmove( cmd.cmdline, s, l+1 ); // pr( NL "exec_queue: sizeof(SmallRlCmd)= " ); pr_d( sizeof(SmallRlCmd) ); pr( NL ); // dump8( cmd.cmdline, cmd.l+1 ); BaseType_t taskWoken; return xQueueSendFromISR( smallrl_cmd_queue, &cmd, &taskWoken ); }
0ff0431a3f50b1787428cf350855184ebc75aba5
0b01c0e41e5709bce4070005a53378e71c160601
/WormsGame.cpp
965a238db1470e71171a89e28769a46b1e4b6939
[]
no_license
malustewart/TP4_WORMS
e4774369b5a617765f092699997b68504b09c251
41f3fe78b01a829acb4f4b021bf1538d4484fdf5
refs/heads/master
2021-01-18T19:03:53.436253
2017-04-05T09:23:30
2017-04-05T09:23:30
86,884,801
0
1
null
null
null
null
MacCentralEurope
C++
false
false
5,191
cpp
WormsGame.cpp
//CalcNewState(); ver si ponerlo, en caso de que si, donde? //inicializacion y destruccion de allegro poner en otro archivo. #include <stdio.h> #include <allegro5/allegro.h> #define FPS 50.0 #define LOOKLEFT -1 #define LOOKRIGHT 1 #define EXIT ALLEGRO_KEY_SPACE //VER SI DEJAR ESO COMO EXIT, Q O QUE typedef enum { STILL, WALKING_PENDING, WALKING, FINISHING_WALKING, JUMPING, FINISHING_JUMPING, TOGGLE } wormState; //AGREGUE TOGGLE (ver) typedef enum { RIGHTKEY, UPKEY, LEFTKEY } keyCode; int main(int argc, char **argv) //poner que no reciba nada (AL MENOS QUE queramos que se reciba la cantidad de worms o sus posiciones iniciales, por ej) { ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; //inicializaciones if (!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } timer = al_create_timer(1.0 / FPS); if (!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } //JUEGO (logica) al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_keyboard_event_source()); Worm w1, w2; //llamar aca a los constructores de los DOS worms al_start_timer(timer); ALLEGRO_EVENT ev; do { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if (ev.type == ALLEGRO_EVENT_TIMER) //REVISAR BIEN ESTO. { int w1State = w1.getWormState(); // ver en que clase va getWormState w1.ContinueAction(w1State); //ContinueAction tiene que estar adentro de la clase Worms o physics int w2State = w2.getWormState(); // ver en que clase va getWormState w2.ContinueAction(w2State); } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) // Se presionů una tecla { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_LEFT: // Flecha izquierda { switch (w2.currentState) { case STILL: case FINISHING_WALKING: w2.currentState = WALKING_PENDING; break; default: break; } } break; case ALLEGRO_KEY_UP: //Flecha hacia arriba { switch (w2.currentState) { case STILL: w2.currentState = JUMPING; break; default: break; } } break; case ALLEGRO_KEY_RIGHT: //Flecha derecha { switch (w2.currentState) { case STILL: case FINISHING_WALKING: w2.currentState = WALKING_PENDING; break; default: break; } } break; case ALLEGRO_KEY_A: //Tecla A { switch (w1.currentState) { case STILL: case FINISHING_WALKING: w1.currentState = WALKING_PENDING; break; default: break; } } break; case ALLEGRO_KEY_W: //Tecla W { switch (w1.currentState) { case STILL: w1.currentState = JUMPING; break; default: break; } } break; case ALLEGRO_KEY_D: //Tecla D { switch (w1.currentState) { case STILL: case FINISHING_WALKING: w1.currentState = WALKING_PENDING; break; default: break; } } break; default: break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) //Se soltů una tecla { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_LEFT: { if (w2.currentState == WALKING_PENDING && w2.direction == LOOKLEFT) { w2.currentState = STILL; } else if (w2.currentState == WALKING_PENDING && w2.direction == LOOKRIGHT) { w2.CurrentState = TOGGLE; //ver si eliminar TOGGLE y que con LOOKLEFT solo se encargue de invertirse!!!!!!!!!!!!! w2.direction = LOOKLEFT; } } break; case ALLEGRO_KEY_RIGHT: { if (w2.currentState == WALKING_PENDING && w2.direction == LOOKRIGHT) { w2.currentState = STILL; } else if (w2.currentState == WALKING_PENDING && w2.direction == LOOKLEFT) { w2.CurrentState = TOGGLE; //ver si eliminar TOGGLE y que con LOOKLEFT solo se encargue de invertirse!!!!!!!!!!!!! w2.direction = LOOKRIGHT; } } break; case ALLEGRO_KEY_A: { if (w1.currentState == WALKING_PENDING && w1.direction == LOOKLEFT) { w1.currentState = STILL; } else if (w1.currentState == WALKING_PENDING && w1.direction == LOOKRIGHT) { w1.CurrentState = TOGGLE; //ver si eliminar TOGGLE y que con LOOKLEFT solo se encargue de invertirse!!!!!!!!!!!!! w1.direction = LOOKLEFT; } } break; case ALLEGRO_KEY_D: { if (w1.currentState == WALKING_PENDING && w1.direction == LOOKRIGHT) { w1.currentState = STILL; } else if (w1.currentState == WALKING_PENDING && w1.direction == LOOKLEFT) { w1.CurrentState = TOGGLE; //ver si eliminar TOGGLE y que con LOOKLEFT solo se encargue de invertirse!!!!!!!!!!!!! w1.direction = LOOKRIGHT; } } break; default: break; } } } while (ev != EXIT); // DESTROYS DE ALLEGRO al_destroy_timer(timer); al_destroy_event_queue(event_queue); return 0; }
949e2b77eb60d963bc5aa50541eaee1b3e279d76
501656109d2e92441deb4cfc5ed0dccb50208935
/挑战程序设计竞赛/2.1/poj3050.cpp
ef0101b9c344c465c50c814e3f606ae55b342d0f
[]
no_license
ailyanlu1/Acm-icpc-6
32cb3c7c5760dd6fd2f1d641e4dd2b130e317fed
b4c86f65aeb8ce4f4949046a4d3ce9c390034f22
refs/heads/master
2020-03-23T13:55:38.122388
2014-10-01T03:11:58
2014-10-01T03:11:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
cpp
poj3050.cpp
#include <iostream> #include <sstream> #include <ios> #include <iomanip> #include <functional> #include <algorithm> #include <vector> #include <string> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <climits> #include <cctype> using namespace std; #define XINF INT_MAX #define INF 0x3FFFFFFF #define MP(X,Y) make_pair(X,Y) #define PB(X) push_back(X) #define REP(X,N) for(int X=0;X<N;X++) #define REP2(X,L,R) for(int X=L;X<=R;X++) #define DEP(X,R,L) for(int X=R;X>=L;X--) #define CLR(A,X) memset(A,X,sizeof(A)) #define IT iterator typedef long long ll; typedef pair<int,int> PII; typedef vector<PII> VII; typedef vector<int> VI; int G[10][10]; set<int> s; int dx[] = {1,-1,0,0}; int dy[] = {0,0,1,-1}; bool inmap(int x,int y) { return x>=0 && x<5 && y>=0 &&y<5; } void dfs(int x,int y,int num,int k) { if(k==6 ) { s.insert(num); return; } for(int i=0;i<4;i++) { int nx =x+dx[i] , ny = y+dy[i]; if( inmap(nx,ny)) { dfs(nx,ny,num*10+G[nx][ny],k+1); } } } int main() { ios::sync_with_stdio(false); #ifdef LOCAL freopen("in","r",stdin); #endif REP(i,5) { REP(j,5) { cin>>G[i][j]; } } REP(i,5) { REP(j,5) { dfs(i,j,G[i][j],1); } } cout<<s.size()<<endl; return 0; }
61f35922c81c86e2ab9e330771f0f79bd74446b2
2998f0570cf4c345283ab5b3b61ac5c03fd40b6b
/src/pebble_rpc.h
57880d865d8c94f88cc5c7a0c85e0724ec1591f9
[]
no_license
zhaoyaogit/pebble_rpc
5026433244984e9a03745caa88e5dbb9c9e118b6
c2ce83aba0d21ea692ee0e231563080d850a2e02
refs/heads/master
2021-09-14T04:19:00.271462
2018-05-08T12:16:59
2018-05-08T12:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,754
h
pebble_rpc.h
/* * Tencent is pleased to support the open source community by making Pebble available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 _PEBBLE_PEBBLE_RPC_H_ #define _PEBBLE_PEBBLE_RPC_H_ #include "rpc.h" namespace pebble { /* @brief Pebble RPC错误码定义 */ typedef enum { kPEBBLE_RPC_ERROR_BASE = kRPC_PEBBLE_RPC_ERROR_BASE, kPEBBLE_RPC_UNKNOWN_CODEC_TYPE = kPEBBLE_RPC_ERROR_BASE - 1, /* 编码类型错误 */ kPEBBLE_RPC_MISS_RESULT = kPEBBLE_RPC_ERROR_BASE - 2, /* 响应包无结果 */ kPEBBLE_RPC_ENCODE_HEAD_FAILED = kPEBBLE_RPC_ERROR_BASE - 3, /* 编码RPC头失败 */ kPEBBLE_RPC_DECODE_HEAD_FAILED = kPEBBLE_RPC_ERROR_BASE - 4, /* 解码RPC头失败 */ kPEBBLE_RPC_ENCODE_BODY_FAILED = kPEBBLE_RPC_ERROR_BASE - 5, /* 编码RPC消息体失败 */ kPEBBLE_RPC_DECODE_BODY_FAILED = kPEBBLE_RPC_ERROR_BASE - 6, /* 解码RPC消息体失败 */ kPEBBLE_RPC_MSG_TYPE_ERROR = kPEBBLE_RPC_ERROR_BASE - 7, /* 消息类型错误 */ kPEBBLE_RPC_MSG_LENGTH_ERROR = kPEBBLE_RPC_ERROR_BASE - 8, /* 消息长度错误 */ kPEBBLE_RPC_SERVICE_ALREADY_EXISTED = kPEBBLE_RPC_ERROR_BASE - 9, /* 服务已经注册 */ kPEBBLE_RPC_SERVICE_ADD_FAILED = kPEBBLE_RPC_ERROR_BASE - 10, /* 服务注册失败 */ kPEBBLE_RPC_INSUFFICIENT_MEMORY = kPEBBLE_RPC_ERROR_BASE - 11, /* 内存不足 */ } PebbleRpcErrorCode; class PebbleRpcErrorStringRegister { public: static void RegisterErrorString() { SetErrorString(kPEBBLE_RPC_UNKNOWN_CODEC_TYPE, "unknown codec type"); SetErrorString(kPEBBLE_RPC_MISS_RESULT, "miss result"); SetErrorString(kPEBBLE_RPC_ENCODE_HEAD_FAILED, "encode head failed"); SetErrorString(kPEBBLE_RPC_DECODE_HEAD_FAILED, "decode head failed"); SetErrorString(kPEBBLE_RPC_ENCODE_BODY_FAILED, "encode body failed"); SetErrorString(kPEBBLE_RPC_DECODE_BODY_FAILED, "decode body failed"); SetErrorString(kPEBBLE_RPC_MSG_TYPE_ERROR, "msg type error"); SetErrorString(kPEBBLE_RPC_MSG_LENGTH_ERROR, "msg length error"); SetErrorString(kPEBBLE_RPC_SERVICE_ALREADY_EXISTED, "service already exist"); SetErrorString(kPEBBLE_RPC_SERVICE_ADD_FAILED, "add service failed"); SetErrorString(kPEBBLE_RPC_INSUFFICIENT_MEMORY, "infufficient memory"); } }; /* @brief Pebble RPC消息编码类型定义 */ typedef enum { kCODE_BINARY = 0, // thrift binary protocol kCODE_JSON, // thrift json protocol kCODE_PB, // protobuff protocol kCODE_BUTT } CodeType; class IPebbleRpcService; class RpcPlugin; class RpcUtil; namespace dr { namespace protocol { class TProtocol; } } /* @brief PebbleRpc封装同步、并行处理,服务注册等基本能力,和IDL无关 框架内部通用能力如异常处理等编解码使用dr完成 */ class PebbleRpc : public IRpc { public: PebbleRpc(CodeType code_type); virtual ~PebbleRpc(); /* @brief 添加服务,将用户实现的服务注册到PebbleRpc中 @param service 实现了IDL生成服务接口的对象指针,对象内存由用户管理 @return 0 成功 @return 非0 失败 @see PebbleRpcErrorCode */ template<typename Class> int32_t AddService(Class* service); public: /* @brief 编解码内存策略 @note 内部使用,用户无需关注 */ enum MemoryPolicy { kBORROW = 0, kMALLOC = 1, kPOLICY_BUTT }; /* @brief 获取编解码器 @note 内部使用,用户无需关注 */ dr::protocol::TProtocol* GetCodec(MemoryPolicy mem_policy); /* @brief 获取内存buffer @note 内部使用,用户无需关注 */ uint8_t* GetBuffer(int32_t size); private: virtual int32_t HeadEncode(const RpcHead& rpc_head, uint8_t* buff, uint32_t buff_len); virtual int32_t HeadDecode(const uint8_t* buff, uint32_t buff_len, RpcHead* rpc_head); virtual int32_t ExceptionEncode(const RpcException& rpc_exception, uint8_t* buff, uint32_t buff_len); virtual int32_t ExceptionDecode(const uint8_t* buff, uint32_t buff_len, RpcException* rpc_exception); int32_t AddService(cxx::shared_ptr<IPebbleRpcService> service); protected: CodeType m_code_type; RpcPlugin* m_rpc_plugin; dr::protocol::TProtocol* m_codec_array[kPOLICY_BUTT]; uint8_t* m_buff; int32_t m_buff_size; cxx::unordered_map<std::string, cxx::shared_ptr<IPebbleRpcService> > m_services; }; template<typename Class> class GenServiceHandler; template<typename Class> int32_t PebbleRpc::AddService(Class* service) { if (NULL == service) { return kRPC_INVALID_PARAM; } return AddService(GenServiceHandler<typename Class::__InterfaceType>()(this, service)); } /* @brief PebbleRpc IDL生成代码服务端骨架代码接口 @note 内部使用,用户无需关注 */ class IPebbleRpcService { public: virtual ~IPebbleRpcService() {} virtual int32_t RegisterServiceFunction() = 0; virtual std::string Name() = 0; }; } // namespace pebble #endif // _PEBBLE_PEBBLE_RPC_H_
b9e5cc030f1007b16a539eca4d6742ed42b87d02
93bb53787cb3e9fb32371bb0fdc4e9227edce60e
/codeforces/271/B. Worms/main.cpp
d59f17b37015b760ebe6337d33aafe3392623a2f
[]
no_license
lupvasile/contest-problems
b969f6e591d1b3feaebf5675b999642b1f2ade32
a484632c23d8b62b98d550446f697675b50e9dc6
refs/heads/master
2021-07-03T22:19:41.142998
2017-09-27T21:00:02
2017-09-27T21:00:02
105,061,972
1
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
main.cpp
#include <iostream> //#include <fstream> using namespace std; #define nbuf 131072 //#define cin f #define nmax 1000010 //ifstream f("date.in"); char buf[nbuf]; int pos(nbuf); int gI() { int n=0; while (buf[pos]<'0' || buf[pos]>'9') { if(++pos>=nbuf) cin.read(buf,nbuf),pos=0; } while (buf[pos]>='0' && buf[pos]<='9') { n=n*10+buf[pos]-'0'; if(++pos>=nbuf) cin.read(buf,nbuf),pos=0; } return n; } int v[nmax]; int i,x(1),a,n; int main() { cin>>n; for(i=1;i<=n;++i) { cin>>a; for(;a>0;--a,++x) v[x]=i; } cin>>n; for(i=1;i<=n;++i) { cin>>a; cout<<v[a]<<'\n'; } return 0; }
6283c4263dada593726b82b84a98591673197b99
51e9f0b333fb3620063f26fe091abb2bf0032dee
/cpTerrainPro/main.cpp
70fb54bb2c988c9ff9ab356d1d4f171682ab0e6e
[]
no_license
cpillion/AdvancedComputerGraphics
ced22bfd0fa2a2a2ab323271a49720bdc003ac9b
7c9940cacd1151bf04da06f6c23f935a751ad5fb
refs/heads/master
2021-01-18T18:40:05.142447
2017-05-18T22:54:53
2017-05-18T22:54:53
86,870,768
2
0
null
null
null
null
UTF-8
C++
false
false
1,080
cpp
main.cpp
// // cpTerrainPro.cpp // Final Project: Terrain Generation Using OpenGL 4 and Qt 5 // CSCI 5239 Spring 2017 // // Description: Create a program using OpenGL and GLSL demonstrating knowledge of advanced computer graphics // // Created by Chris Pillion on 5/3/17. // Copyright © 2017 University of Colorado - CPillion. All rights reserved. // #include <QApplication> #include <QDesktopWidget> #include <QSurfaceFormat> #include "appWindow.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QDesktopWidget dw; // Use QSurfaceFormat to define the OpenGL Core Profile and Version QSurfaceFormat fmt; // Max Version for the Intel HD 4000 Graphics Card fmt.setVersion(4, 1); fmt.setProfile(QSurfaceFormat::CoreProfile); QSurfaceFormat::setDefaultFormat(fmt); // Create a new instance of the application using the appWindow class appWindow view; // Size the window to 65% and 55% of screen size for initial viewing area view.resize(dw.width()*0.65, dw.height()*0.55); view.show(); return app.exec(); }
77de510386135a4c4e6b868432ac4256c5196695
e6559df51c2a14256962c3757073a491ea66de7c
/Codeforces/698 A - Vacations.cpp
9bd0a5f0bff6ea6c4f5e8d2b6750323ea1fb470f
[]
no_license
Maycon708/Maratona
c30eaedc3ee39d69582b0ed1a60f31ad8d666d43
b6d07582544c230e67c23a20e1a1be99d4b47576
refs/heads/master
2020-04-25T23:37:53.992330
2019-02-28T17:10:25
2019-02-28T17:10:25
143,191,679
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
698 A - Vacations.cpp
#include <bits/stdc++.h> #define INF 1LL << 62 #define rep(i, a, b) for(int i = int(a); i < int(b); i++) #define pb push_back #define debug(x) cout << #x << " = " << x << endl; #define debug2(x,y) cout << #x << " = " << x << " --- " << #y << " = " << y << "\n"; #define debugM( x, l, c ) { rep( i, 0, l ){ rep( j, 0, c ) cout << x[i][j] << " "; printf("\n");}} #define all(S) (S).begin(), (S).end() #define F first #define S second #define mk make_pair #define N 450 using namespace std; typedef long long int ll; typedef pair <ll, ll> ii; int main(){ int n, v[1000], dp[1000][4]; while( scanf("%d", &n ) != EOF ){ rep( i, 0, n ) scanf("%d", &v[i] ), dp[i][0] = dp[i][1] = dp[i][2] = 0; dp[n][0] = dp[n][1] = dp[n][2] = 0; for( int i = n-1; i >= 0; i-- ){ dp[i][0] = max( dp[i+1][0], max( dp[i+1][1], dp[i+1][2] ) ); if( v[i]&1 ) dp[i][1] = 1 + max( dp[i+1][0], dp[i+1][2] ) ; if( v[i] >= 2 ) dp[i][2] = 1 + max( dp[i+1][0], dp[i+1][1] ); } printf("%d\n", n - max( dp[0][0], max( dp[0][1], dp[0][2] ) ) ); } }
5f47fc6ffe635f4d26c98f8cecf05d659523a464
3f7028cc89a79582266a19acbde0d6b066a568de
/test/common/network/listen_socket_impl_test.cc
c6b8c5fd5e1a6504489c282220e4e6224a11929d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
envoyproxy/envoy
882d3c7f316bf755889fb628bee514bb2f6f66f0
72f129d273fa32f49581db3abbaf4b62e3e3703c
refs/heads/main
2023-08-31T09:20:01.278000
2023-08-31T08:58:36
2023-08-31T08:58:36
65,214,191
21,404
4,756
Apache-2.0
2023-09-14T21:56:37
2016-08-08T15:07:24
C++
UTF-8
C++
false
false
11,592
cc
listen_socket_impl_test.cc
#include <memory> #include "envoy/common/platform.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/network/exception.h" #include "envoy/network/socket.h" #include "source/common/api/os_sys_calls_impl.h" #include "source/common/network/io_socket_handle_impl.h" #include "source/common/network/listen_socket_impl.h" #include "source/common/network/utility.h" #include "test/mocks/network/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" using testing::_; using testing::Return; namespace Envoy { namespace Network { namespace { class ConnectionSocketImplTest : public testing::TestWithParam<Address::IpVersion> {}; INSTANTIATE_TEST_SUITE_P(IpVersions, ConnectionSocketImplTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest())); TEST_P(ConnectionSocketImplTest, LowerCaseRequestedServerName) { absl::string_view serverName("www.EXAMPLE.com"); absl::string_view expectedServerName("www.example.com"); auto loopback_addr = Network::Test::getCanonicalLoopbackAddress(Address::IpVersion::v4); auto conn_socket_ = ConnectionSocketImpl(Socket::Type::Stream, loopback_addr, loopback_addr, {}); conn_socket_.setRequestedServerName(serverName); EXPECT_EQ(expectedServerName, conn_socket_.requestedServerName()); } TEST_P(ConnectionSocketImplTest, IpVersion) { ClientSocketImpl socket(Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr); EXPECT_EQ(socket.ipVersion(), GetParam()); } template <Network::Socket::Type Type> class ListenSocketImplTest : public testing::TestWithParam<Address::IpVersion> { using ListenSocketType = NetworkListenSocket<NetworkSocketTrait<Type>>; protected: ListenSocketImplTest() : version_(GetParam()) {} const Address::IpVersion version_; template <typename... Args> std::unique_ptr<ListenSocketType> createListenSocketPtr(Args&&... args) { return std::make_unique<ListenSocketType>(std::forward<Args>(args)...); } void testBindSpecificPort() { // This test has a small but real risk of flaky behavior if another thread or process should // bind to our assigned port during the interval between closing the fd and re-binding. In an // attempt to avoid this, we allow for retrying by placing the core of the test in a loop with // a catch of the SocketBindException, indicating we couldn't bind, at which point we retry. const int kLoopLimit = 20; int loop_number = 0; while (true) { ++loop_number; auto addr_fd = Network::Test::bindFreeLoopbackPort(version_, Socket::Type::Stream); auto addr = addr_fd.first; SocketPtr& sock = addr_fd.second; EXPECT_TRUE(sock->ioHandle().isOpen()); // Confirm that we got a reasonable address and port. ASSERT_EQ(Address::Type::Ip, addr->type()); ASSERT_EQ(version_, addr->ip()->version()); ASSERT_LT(0U, addr->ip()->port()); // Release the socket and re-bind it. EXPECT_TRUE(sock->isOpen()); sock->close(); auto option = std::make_unique<MockSocketOption>(); auto options = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>(); EXPECT_CALL(*option, setOption(_, envoy::config::core::v3::SocketOption::STATE_PREBIND)) .WillOnce(Return(true)); options->emplace_back(std::move(option)); std::unique_ptr<ListenSocketType> socket1; try { socket1 = createListenSocketPtr(addr, options, true); } catch (SocketBindException& e) { if (e.errorNumber() != EADDRINUSE) { ADD_FAILURE() << "Unexpected failure (" << e.errorNumber() << ") to bind a free port: " << e.what(); throw; } else if (loop_number >= kLoopLimit) { ADD_FAILURE() << "Too many failures (" << loop_number << ") to bind a specific port: " << e.what(); return; } continue; } // TODO (conqerAtapple): This is unfortunate. We should be able to templatize this // instead of if block. auto os_sys_calls = Api::OsSysCallsSingleton::get(); if (NetworkSocketTrait<Type>::type == Socket::Type::Stream) { EXPECT_EQ(0, socket1->listen(0).return_value_); } EXPECT_EQ(addr->ip()->port(), socket1->connectionInfoProvider().localAddress()->ip()->port()); EXPECT_EQ(addr->ip()->addressAsString(), socket1->connectionInfoProvider().localAddress()->ip()->addressAsString()); EXPECT_EQ(Type, socket1->socketType()); auto option2 = std::make_unique<MockSocketOption>(); auto options2 = std::make_shared<std::vector<Network::Socket::OptionConstSharedPtr>>(); EXPECT_CALL(*option2, setOption(_, envoy::config::core::v3::SocketOption::STATE_PREBIND)) .WillOnce(Return(true)); options2->emplace_back(std::move(option2)); // The address and port are bound already, should throw exception. EXPECT_THROW(createListenSocketPtr(addr, options2, true), SocketBindException); // Release socket and re-bind it. socket1->close(); // Test createListenSocketPtr from IoHandlePtr's os_fd_t constructor int domain = version_ == Address::IpVersion::v4 ? AF_INET : AF_INET6; auto socket_result = os_sys_calls.socket(domain, SOCK_STREAM, 0); EXPECT_TRUE(SOCKET_VALID(socket_result.return_value_)); Network::IoHandlePtr io_handle = std::make_unique<Network::Test::IoSocketHandlePlatformImpl>(socket_result.return_value_); auto socket3 = createListenSocketPtr(std::move(io_handle), addr, nullptr); EXPECT_EQ(socket3->connectionInfoProvider().localAddress()->asString(), addr->asString()); // Test successful. return; } } void testBindPortZero() { auto loopback = Network::Test::getCanonicalLoopbackAddress(version_); auto socket = createListenSocketPtr(loopback, nullptr, true); EXPECT_EQ(Address::Type::Ip, socket->connectionInfoProvider().localAddress()->type()); EXPECT_EQ(version_, socket->connectionInfoProvider().localAddress()->ip()->version()); EXPECT_EQ(loopback->ip()->addressAsString(), socket->connectionInfoProvider().localAddress()->ip()->addressAsString()); EXPECT_GT(socket->connectionInfoProvider().localAddress()->ip()->port(), 0U); EXPECT_EQ(Type, socket->socketType()); } // Verify that a listen sockets that do not bind to port can be duplicated and closed. void testNotBindToPort() { auto local_address = version_ == Address::IpVersion::v4 ? Utility::getIpv6AnyAddress() : Utility::getIpv4AnyAddress(); auto socket = NetworkListenSocket<NetworkSocketTrait<Type>>(local_address, nullptr, /*bind_to_port=*/false); auto dup_socket = socket.duplicate(); EXPECT_FALSE(socket.isOpen()); EXPECT_FALSE(dup_socket->isOpen()); socket.close(); dup_socket->close(); } }; using ListenSocketImplTestTcp = ListenSocketImplTest<Network::Socket::Type::Stream>; using ListenSocketImplTestUdp = ListenSocketImplTest<Network::Socket::Type::Datagram>; INSTANTIATE_TEST_SUITE_P(IpVersions, ListenSocketImplTestTcp, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); INSTANTIATE_TEST_SUITE_P(IpVersions, ListenSocketImplTestUdp, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(ListenSocketImplTestTcp, BindSpecificPort) { testBindSpecificPort(); } /* * A simple implementation to test some of ListenSocketImpl's accessors without requiring * stack interaction. */ class TestListenSocket : public ListenSocketImpl { public: TestListenSocket(Address::InstanceConstSharedPtr address) : ListenSocketImpl(std::make_unique<Network::Test::IoSocketHandlePlatformImpl>(), address) {} TestListenSocket(Address::IpVersion ip_version) : ListenSocketImpl(/*io_handle=*/nullptr, ip_version == Address::IpVersion::v4 ? Utility::getIpv4AnyAddress() : Utility::getIpv6AnyAddress()) {} Socket::Type socketType() const override { return Socket::Type::Stream; } bool isOpen() const override { return ListenSocketImpl::isOpen(); } void close() override { ListenSocketImpl::close(); } }; TEST_P(ListenSocketImplTestTcp, NonIoHandleListenSocket) { TestListenSocket sock(version_); EXPECT_FALSE(sock.isOpen()); sock.close(); } TEST_P(ListenSocketImplTestTcp, SetLocalAddress) { std::string address_str = "10.1.2.3"; if (version_ == Address::IpVersion::v6) { address_str = "1::2"; } Address::InstanceConstSharedPtr address = Network::Utility::parseInternetAddress(address_str); TestListenSocket socket(Utility::getIpv4AnyAddress()); socket.connectionInfoProvider().setLocalAddress(address); EXPECT_EQ(socket.connectionInfoProvider().localAddress(), address); } TEST_P(ListenSocketImplTestTcp, CheckIpVersionWithNullLocalAddress) { TestListenSocket socket(Utility::getIpv4AnyAddress()); EXPECT_EQ(Address::IpVersion::v4, socket.ipVersion()); } TEST_P(ListenSocketImplTestTcp, SupportedIpFamilyVirtualSocketIsCreatedWithNoBsdSocketCreated) { auto mock_interface = std::make_unique<MockSocketInterface>(std::vector<Network::Address::IpVersion>{version_}); auto* mock_interface_ptr = mock_interface.get(); auto any_address = version_ == Address::IpVersion::v4 ? Utility::getIpv4AnyAddress() : Utility::getIpv6AnyAddress(); StackedScopedInjectableLoader<SocketInterface> new_interface(std::move(mock_interface)); { EXPECT_CALL(*mock_interface_ptr, socket(_, _, _)).Times(0); EXPECT_CALL(*mock_interface_ptr, socket(_, _, _, _, _)).Times(0); TcpListenSocket virtual_listener_socket(any_address, nullptr, /*bind_to_port*/ false); } } TEST_P(ListenSocketImplTestTcp, DeathAtUnSupportedIpFamilyListenSocket) { auto mock_interface = std::make_unique<MockSocketInterface>(std::vector<Network::Address::IpVersion>{version_}); auto* mock_interface_ptr = mock_interface.get(); auto the_other_address = version_ == Address::IpVersion::v4 ? Utility::getIpv6AnyAddress() : Utility::getIpv4AnyAddress(); StackedScopedInjectableLoader<SocketInterface> new_interface(std::move(mock_interface)); { EXPECT_CALL(*mock_interface_ptr, socket(_, _, _)).Times(0); EXPECT_CALL(*mock_interface_ptr, socket(_, _, _, _, _)).Times(0); EXPECT_DEATH( { TcpListenSocket virtual_listener_socket(the_other_address, nullptr, /*bind_to_port*/ false); }, ".*"); } } TEST_P(ListenSocketImplTestUdp, BindSpecificPort) { testBindSpecificPort(); } // Validate that we get port allocation when binding to port zero. TEST_P(ListenSocketImplTestTcp, BindPortZero) { testBindPortZero(); } TEST_P(ListenSocketImplTestUdp, BindPortZero) { testBindPortZero(); } TEST_P(ListenSocketImplTestTcp, NotBindToPortAccess) { testNotBindToPort(); } TEST_P(ListenSocketImplTestUdp, NotBindToPortAccess) { testNotBindToPort(); } } // namespace } // namespace Network } // namespace Envoy
555094ae0f9f6084940af98b4271ab71adff1f32
d16e16221194e3061ab2492d0f25d4406a38365a
/Project/Source/GameEngine/EntitySystem/Components/PlayerProjectileCollisionComponent.cpp
ed5dea66909f178cfe45d4d12e93659e803c926c
[]
no_license
Karthik002/Hack_The_North_2021
a4f246eb0851c48d5ffefb351ab5ecb0ab6dfc9d
435f8201408fd27866c51e4b5da45bb7f0ae09f2
refs/heads/master
2023-02-19T12:57:50.605458
2021-01-17T19:10:57
2021-01-17T19:10:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,761
cpp
PlayerProjectileCollisionComponent.cpp
#include "PlayerProjectileCollisionComponent.h" #include "GameEngine/Util/CollisionManager.h" #include "GameEngine/EntitySystem/Entity.h" #include "GameEngine/GameEngineMain.h" #include <vector> using namespace GameEngine; PlayerProjectileCollisionComponent::PlayerProjectileCollisionComponent() { leftPlayerHitbox = false; currentAngleTravel = 0; collideWithWall = true; } PlayerProjectileCollisionComponent::~PlayerProjectileCollisionComponent() { } void PlayerProjectileCollisionComponent::OnAddToWorld() { CollidableComponent::OnAddToWorld(); } void PlayerProjectileCollisionComponent::OnRemoveFromWorld() { CollidableComponent::OnRemoveFromWorld(); } void PlayerProjectileCollisionComponent::Update() { //For the time being just a simple intersection check that moves the entity out of all potential intersect boxes std::vector<CollidableComponent*>& collidables = CollisionManager::GetInstance()->GetCollidables(); for (int a = 0; a < collidables.size(); ++a) { CollidableComponent* colComponent = collidables[a]; if (colComponent == this) continue; // If colliding with a wall, do the regular physics things. AABBRect intersection; AABBRect myBox = GetWorldAABB(); AABBRect colideBox = colComponent->GetWorldAABB(); std::vector<CollidableComponent*> intersectedComponents; if (myBox.intersects(colideBox, intersection)) { intersectedComponents.push_back(colComponent); if (colComponent->GetEntity()->GetLayer() == CollisionLayer::Wall && collideWithWall) { // need to find which side of the wall it crashes with. sf::Vector2f pos = GetEntity()->GetPos(); float boundedAngle = fmod(currentAngleTravel + 360, 360); if (intersection.width < intersection.height) { // reflect across Y-axis SetCurrentAngleTravel(fmod(180 - boundedAngle + 360, 360)); if (myBox.left < colideBox.left) pos.x -= intersection.width; else pos.x += intersection.width; } else { // reflect across X-axis SetCurrentAngleTravel(fmod(-boundedAngle + 360, 360)); if (myBox.top < colideBox.top) pos.y -= intersection.height; else pos.y += intersection.height; } GetEntity()->SetPos(pos); break; } } } } bool PlayerProjectileCollisionComponent::HasLeftPlayerHitBox() { return leftPlayerHitbox; } void PlayerProjectileCollisionComponent::FlagLeftPlayerHitBox() { leftPlayerHitbox = true; } void PlayerProjectileCollisionComponent::SetCurrentAngleTravel(float angleTravel) { currentAngleTravel = angleTravel; } float PlayerProjectileCollisionComponent::GetCurrentAngleTravel() { return currentAngleTravel; } void PlayerProjectileCollisionComponent::SetCollideWithWall(bool collide) { collideWithWall = collide; }
db2bb64689dd5b3711f5036293a0e4dee035c466
8743445edc75a4116892f070ce3d1546bf5f607b
/clicache/src/impl/ManagedString.hpp
ec702dea89e2e71197381e3ef3a6376ef544de5f
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-unknown" ]
permissive
apache/geode-native
d2ef8d21c62a6ab494bd6be9b20545f699340348
049309470cd01ddcb256cc2c0f60ed0aa3a4caf2
refs/heads/develop
2023-08-19T03:01:18.421251
2022-10-03T12:52:42
2022-10-03T12:52:42
80,904,111
53
77
Apache-2.0
2023-08-19T01:26:43
2017-02-04T08:00:06
C++
UTF-8
C++
false
false
2,344
hpp
ManagedString.hpp
/* * 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. */ #pragma once #include "../geode_defs.hpp" using namespace System; namespace Apache { namespace Geode { namespace Client { private ref class ManagedString sealed { private: IntPtr m_str; public: // Constructors inline ManagedString( String^ str ) { m_str = (str == nullptr) ? IntPtr::Zero : System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi( str ); } // Destructor inline ~ManagedString( ) { if (m_str != IntPtr::Zero) { System::Runtime::InteropServices::Marshal::FreeHGlobal( m_str ); } } // The finalizer should normally never be called; either use non-pointer object // or call delete explicitly. !ManagedString( ) { if (m_str != IntPtr::Zero) { System::Runtime::InteropServices::Marshal::FreeHGlobal( m_str ); } } inline static String^ Get( const char* str ) { return ((str == nullptr) ? nullptr : gcnew String( str )); } inline static String^ Get( const wchar_t* str ) { return ((str == nullptr) ? nullptr : gcnew String( str )); } // Properties property const char* CharPtr { inline const char* get( ) { return ((m_str == IntPtr::Zero) ? nullptr : static_cast<const char*>( m_str.ToPointer( ) )); } } }; } // namespace Client } // namespace Geode } // namespace Apache
273516886e5fee226811d28ae77272b38bb9db07
53ed88d6564725dd4f3992c98c62bb83f628d778
/sliceOperatHandler.hpp
bbb002807c45953ffa289b78b256a13c8ad56f72
[]
no_license
Chreschtf/matriceLangage
34353c6be59b4c2f916fad180813079177aff272
84119e8ab14a83e73dc10d33b4db10b82e40bbaa
refs/heads/master
2021-05-28T20:35:41.240341
2014-12-18T09:11:55
2014-12-18T09:11:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
848
hpp
sliceOperatHandler.hpp
#ifndef _SLICEOPERATHANDLER_H_ #define _SLICEOPERATHANDLER_H_ #include <cstddef> #include <iostream> #include <memory> template<typename T,std::size_t t> class sliceMatrix; template<typename Elem,std::size_t dim,std::size_t callsLeft> class sliceOperatHandler{ private: sliceMatrix<Elem,dim>& slice; std::shared_ptr<std::ptrdiff_t> operatValues_; public: sliceOperatHandler(sliceMatrix<Elem,dim>& ,std::shared_ptr<std::ptrdiff_t>& ); sliceOperatHandler<Elem,dim,callsLeft-1> operator[](std::ptrdiff_t i); }; template<typename Elem,std::size_t dim> class sliceOperatHandler<Elem,dim,1>{ private: sliceMatrix<Elem,dim>& slice; std::shared_ptr<std::ptrdiff_t> operatValues_; public: sliceOperatHandler(sliceMatrix<Elem,dim>& ,std::shared_ptr<std::ptrdiff_t>& ); Elem& operator[](std::ptrdiff_t i); }; #endif
0eddc152d2c0d9057668d403f0be346e86c859fc
854d890848adf26be8eecc57787185fa81294ba0
/SimpleCS/RefLibNet/reflib_circular_buffer.h
1de027cd7033b77981e4a3e7d495be2042db1461
[]
no_license
goopymoon/RefLib
e5c9871ebd249fbdb2a669eda850c3be5b77c4b0
ca8196427dddedbbc66af9560b0e0c9f408c3ce6
refs/heads/master
2021-01-20T17:09:52.328840
2019-02-14T16:21:49
2019-02-14T16:21:49
60,628,227
0
1
null
null
null
null
UTF-8
C++
false
false
818
h
reflib_circular_buffer.h
#pragma once #include "reflib_net_def.h" namespace RefLib { class CircularBuffer { public: CircularBuffer(unsigned int size = DEF_SOCKET_BUFFER_SIZE); virtual ~CircularBuffer(); void Clear() { _headPos = 0; _tailPos = 0; } unsigned int Size() const { return (_headPos <= _tailPos) ? (_tailPos - _headPos) : (_bufSize - (_headPos - _tailPos)); } bool GetData(char *pData, unsigned int len); bool PutData(const char *pData, unsigned int len); private: void PutDataWithoutResize(const char *pData, unsigned int len); void SetCapacity(unsigned int size); unsigned int GetCapacity() const { return _bufSize; } unsigned int _bufSize; char *_buffer; unsigned int _headPos; unsigned int _tailPos; }; } // namespace RefLib
92e695ddf8ededae53aa24f0a86a89abe9600606
93ce607184ed5143ef9e2b8fd99ece6a100c1cf4
/App/Logger.hpp
99d060d3c8dc69a33e88110b99b32d9f01c714b3
[]
no_license
seven-1981/BPMCounter
d3f0bb468614349e4d9c5904954981223c286e8e
9af69f17b0766d75922e15252b4d1f94fcce44fe
refs/heads/master
2020-09-26T06:55:11.664877
2020-08-28T21:03:23
2020-08-28T21:03:23
226,195,629
0
0
null
2020-08-28T20:02:24
2019-12-05T21:54:25
C++
UTF-8
C++
false
false
278
hpp
Logger.hpp
#ifndef _LOGGER_H #define _LOGGER_H class MainWindow; class Logger { public: static Logger& logger() { static Logger logger; return logger; } void init_logger(MainWindow* w); void log(const char* text); private: Logger(); MainWindow* m_mainWindow; }; #endif
3b081c814e517c9f553219449e3c7b7d4a6462a5
b137f5bb9d3b77266f46073bc2da72bf445854d6
/CJ1A.cpp
d08558eaa5d61480503c0ab6653e7548d3ec0ba6
[]
no_license
killzdesu/cpp-archive
307fa05be71618f2a64b3c852078eef88696da86
70f62a7bbc2f3398ac28818849841f18b1145f91
refs/heads/master
2023-04-08T20:16:57.460572
2021-04-20T06:23:31
2021-04-20T06:23:31
359,705,314
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
CJ1A.cpp
#include<stdio.h> #include<stdlib.h> #include<algorithm> #include<iostream> #include<vector> #include<map> using namespace std; vector<int> v1, v2, v; vector<int>::iterator it; map<int, int> m; int main(){ freopen("A-small-attempt0.in", "r", stdin); freopen("A-sm-out.txt", "w", stdout); int a, b, c, d; int s1[100], s2[100]; int X, T; cin >> X; for(T=0;T<X;T++){ cin >> c; m.clear(); v.clear(); for(a=1;a<=4;a++){ for(b=0;b<4;b++){ cin >> d; if(a == c) m[d] = 1; } } cin >> c; for(a=1;a<=4;a++){ for(b=0;b<4;b++){ cin >> d; if(a == c){ if(m[d]== 1){ v.push_back(d); } } } } printf("Case #%d: ", T+1); if(v.size() == 0)printf("Volunteer cheated!"); if(v.size() > 1)printf("Bad magician!"); if(v.size() == 1)printf("%d", v[0]); printf("\n"); // for(it=v.begin();it!=v.end();it++){ // printf("%d ", *it); // } // printf("\n"); } return 0; }
4df9f2c5ff8c55bc15098e472024e2baa715c02b
86d5e3ea484106dfb8f8dfcdb09f77c54f843bdb
/Lab_06/Sorted_2_3_Tree.cpp
d8b0a139ec0b5b6b60b900765613bf716d296869
[]
no_license
Rasakhatskiy/Labs_S2
6daa487f8c37dacb07811f75f22dd0a929ebd7b2
24a96c45414c8979e5c2223b8130122c9adaa3b9
refs/heads/master
2020-12-19T23:43:56.630114
2020-05-30T16:20:16
2020-05-30T16:20:16
235,888,061
1
0
null
null
null
null
UTF-8
C++
false
false
12,859
cpp
Sorted_2_3_Tree.cpp
#include "Sorted_2_3_Tree.hpp" typedef unsigned char byte; Sorted_2_3_Tree::Sorted_2_3_Tree() : Root(nullptr) {} Sorted_2_3_Tree::~Sorted_2_3_Tree() { Dispose(Root); } void Sorted_2_3_Tree::Insert(std::string value) { Root = Insert(Root, value); } void Sorted_2_3_Tree::Remove(std::string value) { Remove(Root, value); } bool Sorted_2_3_Tree::Search(std::string value) { return Search(Root, value); } std::vector<std::string> Sorted_2_3_Tree::ToVectorValues() { std::vector<std::string> vector; ToVectorValues(Root, vector); return vector; } void Sorted_2_3_Tree::Dispose(Node* targetNode) { if (!targetNode) return; Dispose(targetNode->Left); Dispose(targetNode->Middle); Dispose(targetNode->Right); delete targetNode; } Sorted_2_3_Tree::Node::Node(std::string value) : Left(nullptr), Middle(nullptr), Right(nullptr), Value_1(value), Value_2(std::string()), Values(1) {} Sorted_2_3_Tree::Node::Node(std::string value_1, std::string value_2) : Left(nullptr), Middle(nullptr), Right(nullptr), Value_1(value_1), Value_2(value_2), Values(2) {} Sorted_2_3_Tree::Node::Node(std::string value, Node* left, Node* middle, Node* right, Node* parent) : Values(1), Value_1(value), Value_2(std::string()), Left(left), Middle(middle), Right(right), Parent(parent) {} bool Sorted_2_3_Tree::Node::HasValue(std::string value) { return Value_1 == value || Value_2 == value; } void Sorted_2_3_Tree::Node::Sort() { if (Values <= 1) return; if (Value_1.size() > Value_2.size()) std::swap(Value_1, Value_2); } void Sorted_2_3_Tree::Node::Insert(std::string value) { if (Values == 0) Value_1 = value; if (Values == 1) Value_2 = value; Values++; Sort(); } void Sorted_2_3_Tree::Node::Remove(std::string value) { if (Values == 1 && Value_1 == value) { Value_1 = Value_2; Values--; } if (Values == 2 && Value_2 == value) { Value_2 = std::string(); Values--; } } void Sorted_2_3_Tree::Node::Join(std::string value, Node * first, Node * second) { Value_1 = value; Value_2 = std::string(); Left = first; Middle = second; Right = nullptr; Values = 1; } bool Sorted_2_3_Tree::Node::IsLeaf() { return !Left && !Middle && !Right; } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Split(Node* targetNode) { if (targetNode->Values < 2) return targetNode; auto one = new Node( targetNode->Value_1, targetNode->Left, targetNode->Middle, nullptr, targetNode->Parent); auto two = new Node( targetNode->Value_2, targetNode->Right, nullptr, nullptr, targetNode->Parent); if (one->Left) one->Left->Parent = one; if (one->Middle) one->Middle->Parent = one; if (two->Left) two->Left->Parent = two; if (two->Middle) two->Middle->Parent = two; if (targetNode->Parent) { targetNode->Parent->Insert(targetNode->Value_2); if (targetNode->Parent->Left == targetNode) targetNode->Parent->Left = nullptr; else if (targetNode->Parent->Middle == targetNode) targetNode->Parent->Middle = nullptr; else if (targetNode->Parent->Right == targetNode) targetNode->Parent->Right = nullptr; if (!targetNode->Parent->Left) { targetNode->Parent->Right = targetNode->Parent->Middle; targetNode->Parent->Middle = two; targetNode->Parent->Left = one; } else if (targetNode->Parent->Middle == nullptr) { targetNode->Parent->Right = two; targetNode->Parent->Middle = one; } else { targetNode->Parent->Right = one; } Node* temp = targetNode->Parent; delete targetNode; return temp; } else { one->Parent = targetNode; two->Parent = targetNode; targetNode->Join(targetNode->Value_2, one, two); return targetNode; } } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Insert(Node* node, std::string value) { if (!node) return new Node(value); else if (node->IsLeaf()) node->Insert(value); else if (value.size() <= node->Value_1.size()) Insert(node->Left, value); else if ((node->Values == 1) || ((node->Values == 2) && value.size() <= node->Value_2.size())) Insert(node->Middle, value); else Insert(node->Right, value); return Split(node); } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Search(Node* targetNode, std::string value) { if (!targetNode) return nullptr; if (targetNode->HasValue(value)) return targetNode; else if (value < targetNode->Value_1) return Search(targetNode->Left, value); else if ((targetNode->Values == 2) && (value.size() < targetNode->Value_2.size()) || (targetNode->Values == 1)) return Search(targetNode->Middle, value); else if (targetNode->Values == 2) return Search(targetNode->Right, value); } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Min(Node* targetNode) { if (!targetNode) return targetNode; if (!(targetNode->Left)) return targetNode; else return Min(targetNode->Left); } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Remove(Node* targetNode, std::string value) { auto item = Search(targetNode, value); if (!item) return targetNode; Node* min = nullptr; if (item->Value_1.size() == value.size()) min = Min(item->Middle); else min = Min(item->Right); if (min) { std::string &z = ( value == item->Value_1 ? item->Value_1 : item->Value_2); std::swap(z, min->Value_1); item = min; } item->Remove(value); return Fix(item); } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Fix(Node* leaf) { if (!leaf->Values && !leaf->Parent) { delete leaf; return nullptr; } if (leaf->Values) { if (leaf->Parent) return Fix(leaf->Parent); else return leaf; } auto parent = leaf->Parent; if(parent) if (parent->Left && parent->Left->Values == 2 || parent->Middle && parent->Middle->Values == 2 || parent->Values == 2) leaf = Redistribute(leaf); else if (parent->Values == 2 && parent->Right->Values == 2) leaf = Redistribute(leaf); else leaf = Merge(leaf); return Fix(leaf); } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Redistribute(Node* leaf) { auto parent = leaf->Parent; auto first = parent->Left; auto second = parent->Middle; auto third = parent->Right; if ((parent->Values == 2) && (first->Values < 2) && (second->Values < 2) && (third->Values < 2)) { if (first == leaf) { parent->Left = parent->Middle; parent->Middle = parent->Right; parent->Right = nullptr; parent->Left->Insert(parent->Value_1); parent->Left->Right = parent->Left->Middle; parent->Left->Middle = parent->Left->Left; if (leaf->Left != nullptr) parent->Left->Left = leaf->Left; else if (leaf->Middle != nullptr) parent->Left->Left = leaf->Middle; if (parent->Left->Left != nullptr) parent->Left->Left->Parent = parent->Left; parent->Remove(parent->Value_1); delete first; } else if (second == leaf) { first->Insert(parent->Value_1); parent->Remove(parent->Value_1); if (leaf->Left != nullptr) first->Right = leaf->Left; else if (leaf->Middle != nullptr) first->Right = leaf->Middle; if (first->Right != nullptr) first->Right->Parent = first; parent->Middle = parent->Right; parent->Right = nullptr; delete second; } else if (third == leaf) { second->Insert(parent->Value_2); parent->Right = nullptr; parent->Remove(parent->Value_2); if (leaf->Left != nullptr) second->Right = leaf->Left; else if (leaf->Middle != nullptr) second->Right = leaf->Middle; if (second->Right != nullptr) second->Right->Parent = second; delete third; } } else if ((parent->Values == 2) && ((first->Values == 2) || (second->Values == 2) || (third->Values == 2))) { if (third == leaf) { if (leaf->Left != nullptr) { leaf->Middle = leaf->Left; leaf->Left = nullptr; } leaf->Insert(parent->Value_2); if (second->Values == 2) { parent->Value_2 = second->Value_2; second->Remove(second->Value_2); leaf->Left = second->Right; second->Right = nullptr; if (leaf->Left != nullptr) leaf->Left->Parent = leaf; } else if (first->Values == 2) { parent->Value_2 = second->Value_1; leaf->Left = second->Middle; second->Middle = second->Left; if (leaf->Left != nullptr) leaf->Left->Parent = leaf; second->Value_1 = parent->Value_1; parent->Value_1 = first->Value_2; first->Remove(first->Value_2); second->Left = first->Right; if (second->Left != nullptr) second->Left->Parent = second; first->Right = nullptr; } } else if (second == leaf) { if (third->Values == 2) { if (leaf->Left == nullptr) { leaf->Left = leaf->Middle; leaf->Middle = nullptr; } second->Insert(parent->Value_2); parent->Value_2 = third->Value_1; third->Remove(third->Value_1); second->Middle = third->Left; if (second->Middle != nullptr) second->Middle->Parent = second; third->Left = third->Middle; third->Middle = third->Right; third->Right = nullptr; } else if (first->Values == 2) { if (leaf->Middle == nullptr) { leaf->Middle = leaf->Left; leaf->Left = nullptr; } second->Insert(parent->Value_1); parent->Value_1 = first->Value_2; first->Remove(first->Value_2); second->Left = first->Right; if (second->Left != nullptr) second->Left->Parent = second; first->Right = nullptr; } } else if (first == leaf) { if (leaf->Left == nullptr) { leaf->Left = leaf->Middle; leaf->Middle = nullptr; } first->Insert(parent->Value_1); if (second->Values == 2) { parent->Value_1 = second->Value_1; second->Remove(second->Value_1); first->Middle = second->Left; if (first->Middle != nullptr) first->Middle->Parent = first; second->Left = second->Middle; second->Middle = second->Right; second->Right = nullptr; } else if (third->Values == 2) { parent->Value_1 = second->Value_1; second->Value_1 = parent->Value_2; parent->Value_2 = third->Value_1; third->Remove(third->Value_1); first->Middle = second->Left; if (first->Middle != nullptr) first->Middle->Parent = first; second->Left = second->Middle; second->Middle = third->Left; if (second->Middle != nullptr) second->Middle->Parent = second; third->Left = third->Middle; third->Middle = third->Right; third->Right = nullptr; } } } else if (parent->Values == 1) { leaf->Insert(parent->Value_1); if (first == leaf && second->Values == 2) { parent->Value_1 = second->Value_1; second->Remove(second->Value_1); if (leaf->Left == nullptr) leaf->Left = leaf->Middle; leaf->Middle = second->Left; second->Left = second->Middle; second->Middle = second->Right; second->Right = nullptr; if (leaf->Middle != nullptr) leaf->Middle->Parent = leaf; } else if (second == leaf && first->Values == 2) { parent->Value_1 = first->Value_2; first->Remove(first->Value_2); if (leaf->Middle == nullptr) leaf->Middle = leaf->Left; leaf->Left = first->Right; first->Right = nullptr; if (leaf->Left != nullptr) leaf->Left->Parent = leaf; } } return parent; } Sorted_2_3_Tree::Node* Sorted_2_3_Tree::Merge(Node* leaf) { auto parent = leaf->Parent; if (parent->Left == leaf) { if (!parent->Middle) return parent; parent->Middle->Insert(parent->Value_1); parent->Middle->Right = parent->Middle->Middle; parent->Middle->Middle = parent->Middle->Left; if (leaf->Left != nullptr) parent->Middle->Left = leaf->Left; else if (leaf->Middle != nullptr) parent->Middle->Left = leaf->Middle; if (parent->Middle->Left != nullptr) parent->Middle->Left->Parent = parent->Middle; parent->Remove(parent->Value_1); delete parent->Left; parent->Left = nullptr; } else if (parent->Middle == leaf) { if (!parent->Left) return parent; parent->Left->Insert(parent->Value_1); if (leaf->Left != nullptr) parent->Left->Right = leaf->Left; else if (leaf->Middle != nullptr) parent->Left->Right = leaf->Middle; if (parent->Left->Right != nullptr) parent->Left->Right->Parent = parent->Left; parent->Remove(parent->Value_1); delete parent->Middle; parent->Middle = nullptr; } if (parent->Parent == nullptr) { Node* tmp = nullptr; if (parent->Left != nullptr) tmp = parent->Left; else tmp = parent->Middle; tmp->Parent = nullptr; delete parent; return tmp; } return parent; } void Sorted_2_3_Tree::ToVectorValues(Node* node, std::vector<std::string>& vector) { if (!node) return; if (node->Values == 1) { ToVectorValues(node->Right, vector); vector.push_back(node->Value_1); ToVectorValues(node->Middle, vector); } if (node->Values == 2) { ToVectorValues(node->Right, vector); vector.push_back(node->Value_1); ToVectorValues(node->Middle, vector); vector.push_back(node->Value_2); ToVectorValues(node->Left, vector); } }
b1e0ca401952a0196fe7514afd87b701f954688c
fa6114537e74eba28976ac5cbb3fa8b4bc3cf196
/Lab 4/circularlist.cpp
bbaa92f3db7e73f55f33b9e13ae0c08ad5bb3f33
[]
no_license
shakyasimha/dsa-lab-ioe
4b22697c9821825fbc48c09b0e88c4df0a294e6c
c6f7641613ef293acff0289a907e0e038295a62d
refs/heads/main
2023-06-02T09:33:44.572854
2021-06-21T06:24:36
2021-06-21T06:24:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
circularlist.cpp
/* DSA Lab 4: Implementation of Circular Linked List Code written by Sushovan Shakya (THA075BEI046) */ #include <iostream> #define null NULL using namespace std; struct Node { int data; Node *next; }; class List { private: Node* head, *tail; public: List() { head = null; tail = null; } bool isEmpty() { return (head == null); } void insert(int data) { Node *temp = new Node; Node *prev = head; temp->data = data; temp->next = head; if(isEmpty()) { temp->next = temp; } else { do { prev = prev->next; } while(prev->next != null); prev->next = temp; } head = temp; } void display() { if(isEmpty()) { cerr << "Error, the list is empty!" << endl; } else { Node *temp = head; do { cout << temp->data << " "; temp = temp->next; } while (temp->next != head); } } }; int main() { List *list_obj = new List; for(int i = 0; i < 7; ++i) { list_obj->insert(rand() % 7); } list_obj->display(); return 0; }
0a55834eb5265430079f3038794255763d053833
a95f5fca3aecf2c871e3fb5957ca57e3b1d0da76
/bài 9.cpp
59486f078795f6b1525d39d4c78003ccf549d434
[]
no_license
HoangVu52/b-i-ki-m-tra
7b94ab64959b5527da55d5f81e86ff2e9cc31dda
2bee25c9ae0d825e2adec3d42ccd5f9208488b4c
refs/heads/master
2021-05-15T22:30:28.992505
2017-10-12T15:04:02
2017-10-12T15:04:02
106,707,600
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
bài 9.cpp
#include <iostream> #include <math.h> using namespace std; int main(int argc, char* argv[]) { int n, i, dem; dem = 0; i = 1; cout << "n= "; cin >> n; while (i <= n) { if (n%i == 0) dem++; i = i + 1; } if (dem == 2) cout << "SNT" << endl; else cout << "k la SNT" << endl; system("pause"); return 0; }
605518a65e4b630e0f381c278764c65e2d108ed3
2d80a0c6d7ee392bf9c7256aa105d12bb9a14c25
/driver.cpp
6c143343caddb7540a50cc6a5cbd7d0209588d1b
[]
no_license
anagh07/slot_machine_game
1d042d676f528e4f7036410356deaf106f41b816
68d9aca629c798030ec30b1bb3ee5152d83a93c3
refs/heads/master
2022-11-30T23:57:49.212919
2020-08-14T22:54:50
2020-08-14T22:54:50
287,638,226
0
0
null
null
null
null
UTF-8
C++
false
false
1,004
cpp
driver.cpp
#include <iostream> #include <vector> #include <string> #include "Shape.h" #include "Rectangle.h" #include "Rhombus.h" #include "AcuteTriangle.h" #include "RightTriangle.h" #include "SlotMachine.h" using std::cout; using std::cin; using std::endl; using std::string; using std::vector; int main () { Rectangle rect(4, 7, "rectan", "drawing"); cout << rect.toString(); cout << endl; Grid rectangle_image; rectangle_image = rect.draw(); cout << rectangle_image << endl; Rhombus rhom(12, "rhom", "my_rhom"); cout << rhom.toString(); cout << endl; Grid rhombus_image; rhombus_image = rhom.draw(); cout << rhombus_image << endl; AcuteTriangle act(13, "acute", "my_acute"); cout << act.toString(); cout << endl; Grid acute_image; acute_image = act.draw(); cout << acute_image << endl; RightTriangle rat(8, "right", "my_rightangle"); cout << rat.toString(); cout << endl; Grid right_image; right_image = rat.draw(); cout << right_image << endl; SlotMachine slots; slots.run(); }
4483588a2a8416685e0b3be9e241b35a20931bf1
33a52c90e59d8d2ffffd3e174bb0d01426e48b4e
/uva/00500-/00530.cc
8ab257acecf88c61a3b3154b33b8c556c3c0f403
[]
no_license
Hachimori/onlinejudge
eae388bc39bc852c8d9b791b198fc4e1f540da6e
5446bd648d057051d5fdcd1ed9e17e7f217c2a41
refs/heads/master
2021-01-10T17:42:37.213612
2016-05-09T13:00:21
2016-05-09T13:00:21
52,657,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
cc
00530.cc
#include<iostream> #include<list> using namespace std; int nElement, nChose; int gcd(int a, int b){ if(b==0) return a; else return gcd(b,a%b); } bool read(){ cin >> nElement >> nChose; if(nElement==0 && nChose==0) return false; return true; } void work(){ if(nChose==0){ cout << 1 << endl; return; } list<int> divided; list<int> divisor; for(int i=nElement;i>max(nChose,nElement-nChose);i--) divided.push_back(i); for(int i=2;i<=min(nChose,nElement-nChose);i++) divisor.push_back(i); for(list<int>::iterator i=divided.begin();i!=divided.end();i++){ for(list<int>::iterator j=divisor.begin();j!=divisor.end();j++){ int ret = gcd(*i,*j); *i/=ret; *j/=ret; if(*j==1){ j = divisor.erase(j); j--; } } } int result=1; for(list<int>::iterator i=divided.begin();i!=divided.end();i++) result*=*i; cout << result << endl; } int main(){ while(read()) work(); return 0; }
725cff1014435549dd22fe893e72b3ddce3c93d6
73861c79fbe4cb57e6f4a75369519cbe43a0406e
/tf/prog/dll/dac_ploan.cpp
6cc0a38ea6c6add039128f4bbd625541aed5ff09
[]
no_license
hunganhu/dac
5d8cc276601fa8e7e23fa84ae003da51128c48af
a48c7a58578b3503edd564b9ca23eed1926d9642
refs/heads/master
2022-07-28T04:50:00.442444
2007-10-26T02:41:58
2007-10-26T02:41:58
266,997,798
0
0
null
null
null
null
BIG5
C++
false
false
23,657
cpp
dac_ploan.cpp
//--------------------------------------------------------------------------- #pragma hdrstop #include <vcl.h> #include <stdio.h> #include <Math.hpp> #include "dac_ploan.h" #include "loanApp.h" #include "ploanSQL.h" #include "functions.h" #ifndef _WRFLOW //In Project->Options->directories/conditionals, append ";_WRFLOW" to conditinals #define DEBUG 0 #else #define DEBUG 1 #endif //--------------------------------------------------------------------------- //#pragma package(smart_init) #pragma alias "@System@@CheckAutoResult$qqrv"="@System@@CheckAutoResult$qqrl" int prescreen(char *app_sn, char *jcic_data_date, char *app_data_time, char *ole_db, char *error_message) /* int prescreen(char *app_sn, char *jcic_data_date, char *app_data_time, char *ole_db, char *error_message, TADOHandler *dbhandle) */ { TADOHandler *dbhandle; // commemt if past from argument String Message = ""; Loan *ptrLoan; Variant hostVars[20]; int errCode = 0; if (check_expiration(EXPIRATION_DATE) == -1) { strcpy (error_message, EXPIRATION_MSG); return(-1); } try { strcpy (error_message, ""); // return empty string if stop normally. dbhandle = new TADOHandler(); // commemt if past from argument dbhandle->OpenDatabase(ole_db); // commemt if past from argument ptrLoan = new Loan(app_sn, app_data_time, jcic_data_date); ptrLoan->app_info_validate(app_sn, app_data_time, dbhandle); if (ptrLoan->get_code() != 0) { // write data error to approval_cal. hostVars[0] = app_sn; hostVars[1] = jcic_data_date; hostVars[2] = app_data_time; hostVars[3] = ptrLoan->get_product_type(); hostVars[4] = ptrLoan->get_code(); hostVars[5] = ptrLoan->error(); dbhandle->ExecSQLCmd(SQLCommands[Write_Prescreen_Result], hostVars, 5); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (0); } dbhandle->ExecSQLCmd(SQLCommands[Create_Working_Tables]); ptrLoan->prescreen(jcic_data_date, dbhandle); if (Days_between(jcic_data_date, app_data_time) > 30) { errCode = 2; strcpy (error_message, TF_Messages[Warning_201]); } #ifdef _WRFLOW dbhandle->ExecSQLCmd(SQLCommands[Insert_Audit_Table]); #endif dbhandle->ExecSQLCmd(SQLCommands[Drop_Working_Tables]); dbhandle->CloseDatabase(); // commemt if past from argument } catch (Exception &E) { strcpy (error_message, E.Message.c_str()); errCode = -1; /* if (AnsiString(E.ClassName()) == "EOleException") { if (E.Message.SubString(0,18) == "提供不一致或不完全") strcpy (error_message, "無效的物件名稱。"); else strcpy (error_message, E.Message.c_str()); } else strcpy (error_message, E.Message.c_str()); errCode = -1; */ } delete ptrLoan; delete dbhandle; return (errCode); } //--------------------------------------------------------------------------- int optimal_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, char *ole_db, char *error_message) /* int optimal_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, char *ole_db, char *error_message, TADOHandler *dbhandle) */ { TADOHandler *dbhandle; // commemt if past from argument Loan *ptrLoan; Variant hostVars[20]; char sqlCommand[256]; String Message = ""; int errCode = 0; int reason_code = 0; double pb; double a2_npv[][3] = {{150000.0, 0.0, 0.0}, {200000.0, 0.0, 0.0}, {250000.0, 0.0, 0.0}, {300000.0, 0.0, 0.0}, {350000.0, 0.0, 0.0}, {400000.0, 0.0, 0.0}}; // initial values for GX A2 double b2_npv[][3] = {{150000.0, 0.0, 0.0}, {200000.0, 0.0, 0.0}}; // initial values for GX B2 double others_npv[1][3] = {0.0, 0.0, 0.0}; // initial values for GX B1, C // and KHJ A2, B1, B2, C int optimal, max_line; double optimal_line, optimal_pb, optimal_npv; if (check_expiration(EXPIRATION_DATE) == -1) { strcpy (error_message, EXPIRATION_MSG); return(-1); } try { dbhandle = new TADOHandler(); // commemt if past from argument dbhandle->OpenDatabase(ole_db); // commemt if past from argument ptrLoan = new Loan (app_sn, app_data_time, ts_data_date, jcic_data_date, tsn); errCode = ptrLoan->app_info_validate(app_sn, app_data_time, dbhandle); if (errCode == 0) ptrLoan->loan_validate_no_principal(app_sn, tsn, dbhandle); // write common fields hostVars[0] = app_sn; hostVars[1] = tsn; hostVars[2] = ts_data_date; hostVars[3] = jcic_data_date; hostVars[4] = app_data_time; hostVars[5] = ptrLoan->get_product_type(); /* if (ptrLoan->get_code() == 313 ||ptrLoan->get_code() == 305) { // No application, Invalid product // write data error to approval_cal. errCode = -1; strcpy (error_message, ptrLoan->error().c_str()); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (-1); } else */ if (ptrLoan->get_code() != 0) { // write data error to approval_cal. hostVars[6] = ptrLoan->get_principal(); hostVars[7] = ptrLoan->get_code(); hostVars[8] = ptrLoan->error(); dbhandle->ExecSQLCmd(SQLCommands[Write_Optimal_Result_Data_Error], hostVars, 8); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (0); } dbhandle->ExecSQLCmd(SQLCommands[Create_Working_Tables]); ptrLoan->prescreen(jcic_data_date, dbhandle); errCode = ptrLoan->get_code(); if (errCode == 0 || errCode == 201) { // No major derug hit or JCIC expires ptrLoan->calculate_rscore(dbhandle); // check product type and card if (ptrLoan->get_product_type() == 1) { // product GX switch (ptrLoan->get_card()) { case 1:max_line = ptrLoan->calculate_optimal_line(6, a2_npv, dbhandle); optimal_line = a2_npv[max_line][0]; optimal_pb = a2_npv[max_line][1]; optimal_npv = a2_npv[max_line][2]; optimal = 1; break; case 3:max_line = ptrLoan->calculate_optimal_line(2, b2_npv, dbhandle); optimal_line = b2_npv[max_line][0]; optimal_pb = b2_npv[max_line][1]; optimal_npv = b2_npv[max_line][2]; optimal = 1; break; case 2: case 4:others_npv[0][0] = ptrLoan->get_principal(); // set line to loan amount max_line = ptrLoan->calculate_optimal_line(1, others_npv, dbhandle); optimal_line = others_npv[max_line][0]; optimal_pb = others_npv[max_line][1]; optimal_npv = others_npv[max_line][2]; optimal = 0; break; } } else if (ptrLoan->get_product_type() == 2) { // product KHJ others_npv[0][0] = ptrLoan->get_principal(); // set line to loan amount max_line = ptrLoan->calculate_optimal_line(1, others_npv, dbhandle); optimal_line = others_npv[max_line][0]; optimal_pb = others_npv[max_line][1]; optimal_npv = others_npv[max_line][2]; optimal = 0; } // write_optimal result to approval_cal hostVars[9] = optimal_line; hostVars[10] = RoundTo(optimal_pb, -3); hostVars[11] = optimal_npv; if (optimal_npv >= 0){ reason_code = 1; Message = TF_Messages[Normal_1]; } else { reason_code = 0; hostVars[9] = 0; //optimal_line hostVars[11] = 0; //optimal_npv Message = TF_Messages[Normal_0]; } if (Days_between(jcic_data_date, app_data_time) > 30) { errCode = 2; reason_code = 201; Message = TF_Messages[Warning_201]; strcpy (error_message, TF_Messages[Warning_201]); } else { if (optimal == 0) { Message = TF_Messages[Optimal_error_501]; reason_code = 501; } } hostVars[6] = reason_code; hostVars[7] = Message; hostVars[8] = ptrLoan->get_external_monthly_payment(); if (optimal) { dbhandle->ExecSQLCmd(SQLCommands[Write_Optimal_Result], hostVars, 11); } else { dbhandle->ExecSQLCmd(SQLCommands[Write_No_Optimal_Result], hostVars, 8); } } else { // write prescreen result to PRESECREEN errCode = 1; strcpy (error_message, ""); // strcpy (error_message, ptrLoan->error().c_str()); } #ifdef _WRFLOW dbhandle->ExecSQLCmd(SQLCommands[Insert_Audit_Table]); #endif /* Drop all temporary tables before closing a connection to avoid connection creep problem. Without droping temp tables will not release system resource after connection is closed. */ dbhandle->ExecSQLCmd(SQLCommands[Drop_Working_Tables]); dbhandle->CloseDatabase(); // commemt if past from argument } catch (Exception &E) { strcpy (error_message, E.Message.c_str()); errCode = -1; } delete ptrLoan; delete dbhandle; // commemt if past from argument return(errCode); } //--------------------------------------------------------------------------- int specific_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, char *ole_db, char *error_message) /* int specific_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, char *ole_db, char *error_message, TADOHandler *dbhandle) */ { TADOHandler *dbhandle; // commemt if past from argument Loan *ptrLoan; Variant hostVars[20]; char sqlCommand[256]; String Message = ""; int errCode = 0; int reason_code = 0; double pb; if (check_expiration(EXPIRATION_DATE) == -1) { strcpy (error_message, EXPIRATION_MSG); return(-1); } try { dbhandle = new TADOHandler(); // commemt if past from argument dbhandle->OpenDatabase(ole_db); // commemt if past from argument ptrLoan = new Loan (app_sn, app_data_time, ts_data_date, jcic_data_date, tsn); errCode = ptrLoan->app_info_validate(app_sn, app_data_time, dbhandle); if (errCode == 0) ptrLoan->loan_validate(app_sn, tsn, dbhandle); hostVars[0] = app_sn; hostVars[1] = tsn; hostVars[2] = ts_data_date; hostVars[3] = jcic_data_date; hostVars[4] = app_data_time; hostVars[5] = ptrLoan->get_product_type(); /* if (ptrLoan->get_code() == 313 ||ptrLoan->get_code() == 305) { // No application, Invalid product // write data error to approval_cal. errCode = -1; strcpy (error_message, ptrLoan->error().c_str()); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (-1); } else */ if (ptrLoan->get_code() != 0) { // write data error to approval_cal. hostVars[6] = ptrLoan->get_principal(); hostVars[7] = ptrLoan->get_code(); hostVars[8] = ptrLoan->error(); dbhandle->ExecSQLCmd(SQLCommands[Write_Specific_Result_Data_Error], hostVars, 8); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (0); } dbhandle->ExecSQLCmd(SQLCommands[Create_Working_Tables]); ptrLoan->prescreen(jcic_data_date, dbhandle); errCode = ptrLoan->get_code(); if (errCode == 0 || errCode == 201) { // No major derug hit or JCIC expires ptrLoan->calculate_rscore(dbhandle); pb = ptrLoan->calculate_pd(ptrLoan->get_principal(), dbhandle); ptrLoan->calculate_npv(ptrLoan->get_principal(), pb); // write_specific result to approval_cal hostVars[6] = ptrLoan->get_principal(); hostVars[7] = RoundTo(pb, -3); hostVars[8] = ptrLoan->get_npv(); if (ptrLoan->get_npv() >= 0){ reason_code = 1; Message = TF_Messages[Normal_1]; } else { reason_code = 0; Message = TF_Messages[Normal_0]; } if (Days_between(jcic_data_date, app_data_time) > 30) { errCode = 2; reason_code = 201; Message = TF_Messages[Warning_201]; strcpy (error_message, TF_Messages[Warning_201]); } else { switch (ptrLoan->get_card()) { case 1:if (ptrLoan->get_principal() > A2_LIMIT) { reason_code = 202; Message = TF_Messages[Warning_202]; } break; case 2:if (ptrLoan->get_principal() > B1_LIMIT) { reason_code = 203; Message = TF_Messages[Warning_203]; } break; case 3: case 4:if (ptrLoan->get_principal() > B2_C_LIMIT) { reason_code = 204; Message = TF_Messages[Warning_204]; } break; } } hostVars[9] = reason_code; hostVars[10] = Message; hostVars[11] = ptrLoan->get_external_monthly_payment(); dbhandle->ExecSQLCmd(SQLCommands[Write_Specific_Result], hostVars, 11); } else { // write prescreen result to PRESECREEN errCode = 1; strcpy (error_message, ""); } #ifdef _WRFLOW dbhandle->ExecSQLCmd(SQLCommands[Insert_Audit_Table]); #endif /* Drop all temporary tables before closing a connection to avoid connection creep problem. Without droping temp tables will not release system resource after connection is closed. */ dbhandle->ExecSQLCmd(SQLCommands[Drop_Working_Tables]); dbhandle->CloseDatabase(); // commemt if past from argument } catch (Exception &E) { strcpy (error_message, E.Message.c_str()); errCode = -1; } delete ptrLoan; delete dbhandle; // commemt if past from argument return(errCode); } //--------------------------------------------------------------------------- int decision_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, int decision, char *ole_db, char *audit_userno1, char *change_code, char *major_deviation, char *minor_deviation, char *decline_code, char *manual_code, char *error_message) /* int decision_cal(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, int decision, char *ole_db, char *audit_userno1, char *change_code, char *major_deviation, char *minor_deviation, char *decline_code, char *manual_code, char *error_message, TADOHandler *dbhandle) */ { TADOHandler *dbhandle; // commemt if past from argument Loan *ptrLoan; Variant hostVars[20]; char sqlCommand[256]; String Message = ""; int errCode = 0; int reason_code = 0; double pb; if (check_expiration(EXPIRATION_DATE) == -1) { strcpy (error_message, EXPIRATION_MSG); return(-1); } try { dbhandle = new TADOHandler(); // commemt if past from argument dbhandle->OpenDatabase(ole_db); // commemt if past from argument ptrLoan = new Loan (app_sn, app_data_time, ts_data_date, jcic_data_date, tsn); errCode = ptrLoan->app_info_validate(app_sn, app_data_time, dbhandle); if (errCode == 0) ptrLoan->loan_validate(app_sn, tsn, dbhandle); hostVars[0] = app_sn; hostVars[1] = tsn; hostVars[2] = ts_data_date; hostVars[3] = jcic_data_date; hostVars[4] = app_data_time; hostVars[5] = ptrLoan->get_product_type(); hostVars[6] = audit_userno1; hostVars[7] = change_code; hostVars[8] = major_deviation; hostVars[9] = minor_deviation; hostVars[10] = decline_code; hostVars[11] = manual_code; /* if (ptrLoan->get_code() == 313 ||ptrLoan->get_code() == 305) { // No application, Invalid product // write data error to approval_cal. errCode = -1; strcpy (error_message, ptrLoan->error().c_str()); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (-1); } else */ if (ptrLoan->get_code() != 0) { // write data error to approval_cal. hostVars[12] = ptrLoan->get_principal(); hostVars[13] = ptrLoan->get_code(); hostVars[14] = ptrLoan->error(); hostVars[15] = ExecutionTime(); hostVars[16] = decision; dbhandle->ExecSQLCmd(SQLCommands[Write_Decision_Result_Error], hostVars, 16); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (0); } dbhandle->ExecSQLCmd(SQLCommands[Create_Working_Tables]); ptrLoan->prescreen(jcic_data_date, dbhandle); errCode = ptrLoan->get_code(); if (errCode == 0 || errCode == 201) { // No major derug hit or JCIC expires errCode = 0; ptrLoan->calculate_rscore(dbhandle); pb = ptrLoan->calculate_pd(ptrLoan->get_principal(), dbhandle); ptrLoan->calculate_npv(ptrLoan->get_principal(), pb); // write_decision result to decision_cal hostVars[13] = reason_code; hostVars[14] = Message; hostVars[15] = ExecutionTime(); hostVars[16] = decision; hostVars[17] = ptrLoan->get_external_monthly_payment(); if (decision == 1) { // set decision amount to 0 if declined hostVars[12] = ptrLoan->get_principal(); hostVars[18] = RoundTo(pb, -3); hostVars[19] = ptrLoan->get_npv(); } else { hostVars[12] = 0; hostVars[18] = 0; hostVars[19] = 0; } dbhandle->ExecSQLCmd(SQLCommands[Write_Decision_Result], hostVars, 19); } else { // write prescreen result to PRESECREEN errCode = 1; strcpy (error_message, ""); // strcpy (error_message, ptrLoan->error().c_str()); } #ifdef _WRFLOW dbhandle->ExecSQLCmd(SQLCommands[Insert_Audit_Table]); #endif /* Drop all temporary tables before closing a connection to avoid connection creep problem. Without droping temp tables will not release system resource after connection is closed. */ dbhandle->ExecSQLCmd(SQLCommands[Drop_Working_Tables]); dbhandle->CloseDatabase(); // commemt if past from argument } catch (Exception &E) { strcpy (error_message, E.Message.c_str()); errCode = -1; } delete ptrLoan; delete dbhandle; // commemt if past from argument return(errCode); } //--------------------------------------------------------------------------- int specific_cal_test(char *app_sn, char *ts_data_date, char *jcic_data_date, char *app_data_time, char *tsn, char *ole_db, char *error_message, TADOHandler *dbhandle) { // TADOHandler *dbhandle; // commemt if past from argument Loan *ptrLoan; Variant hostVars[20]; char sqlCommand[256]; String Message = ""; int errCode = 0; int reason_code = 0; double pb; if (check_expiration(EXPIRATION_DATE) == -1) { strcpy (error_message, EXPIRATION_MSG); return(-1); } try { // dbhandle = new TADOHandler(); // commemt if past from argument // dbhandle->OpenDatabase(ole_db); // commemt if past from argument ptrLoan = new Loan (app_sn, app_data_time, ts_data_date, jcic_data_date, tsn); errCode = ptrLoan->app_info_validate(app_sn, app_data_time, dbhandle); if (errCode == 0) ptrLoan->loan_validate(app_sn, tsn, dbhandle); hostVars[0] = app_sn; hostVars[1] = tsn; hostVars[2] = ts_data_date; hostVars[3] = jcic_data_date; hostVars[4] = app_data_time; hostVars[5] = ptrLoan->get_product_type(); /* if (ptrLoan->get_code() == 313 ||ptrLoan->get_code() == 305) { // No application, Invalid product // write data error to approval_cal. errCode = -1; strcpy (error_message, ptrLoan->error().c_str()); dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (-1); } else */ if (ptrLoan->get_code() != 0) { // write data error to approval_cal. hostVars[6] = ptrLoan->get_principal(); hostVars[7] = ptrLoan->get_code(); hostVars[8] = ptrLoan->error(); dbhandle->ExecSQLCmd(SQLCommands[Write_Specific_Result_Data_Error], hostVars, 8); // dbhandle->CloseDatabase(); // commemt if past from argument delete ptrLoan; return (0); } // dbhandle->ExecSQLCmd(SQLCommands[Create_Working_Tables]); // ptrLoan->prescreen(jcic_data_date, dbhandle); // errCode = ptrLoan->get_code(); // if (errCode == 0 || errCode == 201) { // No major derug hit or JCIC expires // ptrLoan->calculate_rscore(dbhandle); pb = ptrLoan->calculate_pd_test(ptrLoan->get_principal(), dbhandle); if (ptrLoan->get_card() != 0) { // No major derug hit or JCIC expires ptrLoan->calculate_npv(ptrLoan->get_principal(), pb); // write_specific result to approval_cal hostVars[6] = ptrLoan->get_principal(); hostVars[7] = pb; hostVars[8] = ptrLoan->get_npv(); if (ptrLoan->get_npv() >= 0){ reason_code = 1; Message = TF_Messages[Normal_1]; } else { reason_code = 0; Message = TF_Messages[Normal_0]; } if (Days_between(jcic_data_date, app_data_time) > 30) { errCode = 2; reason_code = 201; Message = TF_Messages[Warning_201]; strcpy (error_message, TF_Messages[Warning_201]); } else { switch (ptrLoan->get_card()) { case 1:if (ptrLoan->get_principal() > A2_LIMIT) { reason_code = 202; Message = TF_Messages[Warning_202]; } break; case 2:if (ptrLoan->get_principal() > B1_LIMIT) { reason_code = 203; Message = TF_Messages[Warning_203]; } break; case 3: case 4:if (ptrLoan->get_principal() > B2_C_LIMIT) { reason_code = 204; Message = TF_Messages[Warning_204]; } break; } } hostVars[9] = reason_code; hostVars[10] = Message; hostVars[11] = ptrLoan->get_external_monthly_payment(); dbhandle->ExecSQLCmd(SQLCommands[Write_Specific_Result], hostVars, 11); } // else { // // write prescreen result to PRESECREEN // errCode = 1; // strcpy (error_message, ""); // } //#ifdef _WRFLOW // dbhandle->ExecSQLCmd(SQLCommands[Insert_Audit_Table]); //#endif /* Drop all temporary tables before closing a connection to avoid connection creep problem. Without droping temp tables will not release system resource after connection is closed. */ // dbhandle->ExecSQLCmd(SQLCommands[Drop_Working_Tables]); // dbhandle->CloseDatabase(); // commemt if past from argument } catch (Exception &E) { strcpy (error_message, E.Message.c_str()); errCode = -1; } delete ptrLoan; // delete dbhandle; // commemt if past from argument return(errCode); }
c099df7bf899ec34bd71832d63f982605893f6a4
24a0e0b288ee1e30f9285d1719a13fabef0e320b
/factors.cpp
8b63cd7accbc3e7157089bd8ee396c0facb9083b
[]
no_license
utkarsh235/CPP-Programming
db3569a8ad5e6605462147583346566245ddaa56
d8faa7089d7fbb4ef6a7bb328c10fa78a7ed1751
refs/heads/main
2023-03-05T21:07:07.952797
2021-02-13T19:28:35
2021-02-13T19:28:35
330,452,704
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
factors.cpp
#include<iostream> using namespace std; class factors { int a,b,c,i,n; public: void get(); void print(); }; void factors :: get() { cout << "enter the number whose prime factors you want to enter\n"; cin >> n; } void factors :: print() { for (i=1; i<=n ; i++) { if (n%i == 0) { cout << i << "is a factor of" << n <<"\n"; } } } int main() { factors f; f.get(); f.print(); return 0; }
e1290e378485904f5a236ef15cdaf8e0d2c4fd67
5e629210c351f369208155a11f395d47be9b837b
/conditionCompleteion/src/include/libraryUtils/object_storage_log_setup.h
9a3f6fb1a1af7bc9ae6c1e347132139ba270d3f5
[]
no_license
confi-surya/pythonicPracto
028f2a50bc595b90bee95b235ec9218da3e45fe5
c366afd9ab54b8cacda767189f1a13efb5f961b2
refs/heads/master
2020-03-23T12:56:55.843408
2018-07-19T11:51:59
2018-07-19T14:37:13
141,572,623
0
0
null
null
null
null
UTF-8
C++
false
false
2,144
h
object_storage_log_setup.h
/* * $Id$ * * objectStorageLogSetup.h, Initialize the logging mechanism in objectStorage. * * * */ #ifndef _object_storage_log_setup_h #define _object_storage_log_setup_h #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <syslog.h> #include <boost/noncopyable.hpp> #include <boost/filesystem/operations.hpp> #include <boost/scoped_ptr.hpp> #include <cool/log.h> #include <cool/stlExtras.h> #include <cool/foreach.h> #include "libraryUtils/object_storage_exception.h" #include "config_file_parser.h" #include <string> std::string const objectStorageLogTag = "[Object Storage Logger] :"; std::string const osd_account_lib_log_tag = "[Account Library] : "; std::string const osd_container_lib_log_tag = "[Container Library] : "; std::string const osd_transaction_lib_log_tag = "[Transaction Library] : "; namespace object_storage_log_setup { // MACROS #define SYSLOG(msg) \ { \ oss os; \ os << msg; \ syslog(LOG_ERR, os.str().c_str()); \ } #define OSDLOG(logLevel, msg)\ {\ LOG(logLevel, msg);\ }\ class LogSetupTool : public boost::noncopyable { public: LogSetupTool(std::string); /** * @brief: * Method will initialize logs for objectStorage. */ void initializeLogSystem(); ~LogSetupTool() throw(); private: /** * @brief: * Check for log directory, if not present then create it. */ void verifyLogDirExistenceAndCreate(); /** * @brief: * Function will change owner of the logFile and logDir to hydragui:hydragui * Function will be executed only when user is root */ void changeOwnerForRMLLogFileAndDir() const; /** * @brief: * Function will check whether current user has write permission on the log file and log directory */ void verifyForWritePermission(); void verifyAndTryToCorrectRMLSettings(); cool::SharedPtr<config_file::LogConfig> get_config(); private: boost::scoped_ptr<cool::InitLog> log_system; bool test_mode; std::string object_storage_root_path; std::string log_dir; std::string log_file; std::string log_config_file; bool enable_logs; }; } // namespace object_storage_log_setup #endif //_OBJECTSTORAGE_OBJECTSTORAGELOGSETUP_H
2aa6f821976bea337b00acc7e255e98479922072
73a6c73fa08a4fc7aabcc6bb705d2e71132685b3
/src/libs/transaction_common/include/keto/transaction_common/SignedTransactionHelper.hpp
a2250b98f7c053f519491c14530f41fe0488776c
[ "MIT" ]
permissive
blockspacer/keto
2f6ff979a9dc9513943bf9cedb4a302a70a2b66a
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
refs/heads/master
2021-02-15T06:48:08.661393
2018-05-22T14:01:34
2018-05-22T14:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
hpp
SignedTransactionHelper.hpp
/* * 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: SignedTransactionHelper.hpp * Author: ubuntu * * Created on April 3, 2018, 9:39 AM */ #ifndef SIGNEDTRANSACTIONHELPER_HPP #define SIGNEDTRANSACTIONHELPER_HPP #include <string> #include <memory> #include "SignedTransaction.h" #include "keto/asn1/HashHelper.hpp" #include "keto/asn1/SignatureHelper.hpp" #include "keto/transaction_common/TransactionHelper.hpp" namespace keto { namespace transaction_common { class SignedTransactionHelper; typedef std::shared_ptr<SignedTransactionHelper> SignedTransactionHelperPtr; class SignedTransactionHelper { public: SignedTransactionHelper(SignedTransaction_t* signedTransaction); SignedTransactionHelper(const SignedTransactionHelper& orig) = delete; virtual ~SignedTransactionHelper(); keto::asn1::HashHelper getHash(); keto::asn1::SignatureHelper getSignature(); TransactionHelperPtr getTransaction(); private: SignedTransaction_t* signedTransaction; }; } } #endif /* SIGNEDTRANSACTIONHELPER_HPP */
c271d758986e7d78f9a496213184937c849170ad
2e9c9c10104d2a1fadbd6a4b8c4538f9056cb93a
/schc.cpp
acc997981eaf1a82b4364a87165da5a2797cd8b0
[ "BSD-3-Clause" ]
permissive
JesusSanchez456/SCHC_Client
ed02e311a64bdec9097e3b0aeae7c97826a375dc
28aaaf58b3e53a2cdbf20d4f3432d2b549916b57
refs/heads/master
2023-03-29T00:10:01.155021
2021-03-31T16:21:28
2021-03-31T16:21:28
353,416,714
0
0
null
null
null
null
UTF-8
C++
false
false
16,311
cpp
schc.cpp
/* * Copyright (c) 2018, Department of Information and Communication Engineering. * University of Murcia. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author(s): * Jorge Gallego Madrid <jorge.gallego1@um.es> * Jesús Sánchez Gómez <jesus.sanchez4@um.es> */ /** * \file * \brief Implementation of the schc.h functions. * * This file implements the SCHC compression/decompression (SCHC C/D) * actions as defined in draft-ietf-lpwan-ipv6-static-context-hc-10. The * most important functions in this file are schc_compress() and * schc_decompress(). * * \note Only a subset of operations of the SCHC C/D are implemented, * not all of them. * * \note The SCHC Fragmentation/Reassembly (SCHC F/R) is not * implemented. * * \note The rule Field Length is not used at all in this * implementation, we hardcoded everything in the struct * field_description. Solving this requires thinking. * * To understand better the structure of a schc_packet: * * \verbatim * +--- ... --+------- ... -------+------------------+~~~~~~~ * | Rule ID |Compression Residue| packet payload | padding * +--- ... --+------- ... -------+------------------+~~~~~~~ * (optional) * <----- compressed header ------> * * Figure 6: from the draft-ietf-lpwan-ipv6-static-context-hc-10 * * \endverbatim * * \related schc_compress */ /**********************************************************************/ /*** Include files ***/ /**********************************************************************/ /**********************************************************************/ /*** Local Include files ***/ /**********************************************************************/ #include "schc.h" #include "context.h" /**********************************************************************/ /*** Macro Definitions ***/ /**********************************************************************/ // #define DEBUG #ifdef DEBUG #warning "DEBUG MODE ACTIVATED!" #define PRINT(...) Serial.print(__VA_ARGS__) #define PRINTLN(...) Serial.println(__VA_ARGS__) #define PRINT_ARRAY(add, len) \ do { \ int i; \ for (i = 0 ; i < (len) ; i++) { \ if (i % 10 == 0) \ Serial.println(); \ if (i % 50 == 0) \ Serial.println(); \ Serial.print((((uint8_t*)(add))[i]), HEX); \ Serial.print(" "); \ } \ Serial.println(); \ } while(0) #else /* DEBUG */ #define PRINT(...) #define PRINTLN(...) #define PRINT_ARRAY(add, len) #endif /* DEBUG */ /**********************************************************************/ /*** Type Definitions ***/ /**********************************************************************/ /**********************************************************************/ /*** Forward Declarations ***/ /**********************************************************************/ /**********************************************************************/ /*** Constants ***/ /**********************************************************************/ /**********************************************************************/ /*** Global Variables ***/ /**********************************************************************/ /**********************************************************************/ /*** Static Variables ***/ /**********************************************************************/ /**********************************************************************/ /*** Static Functions ***/ /**********************************************************************/ static int schc_fragmentate(const uint8_t *schc_packet, size_t schc_packet_len) { /* * If the packet len is equal or less than the max size of a * L2 packet, we send the packet as is, without fragmentation */ if (schc_packet_len <= MAX_SCHC_PKT_LEN) { memcpy(tx_buff, schc_packet, schc_packet_len); tx_buff_len = schc_packet_len; PRINT_ARRAY(tx_buff, tx_buff_len); return 0; } /* * We start the fragmentation procedure. */ int nfrag = schc_packet_len / SCHC_FRG_PAY_LEN + (schc_packet_len % SCHC_FRG_PAY_LEN != 0); schc_fragment fragments[nfrag]; memset(fragments, 0, sizeof(fragments)); size_t bytes_left = schc_packet_len; for (int i = 0 ; i < nfrag ; i++) { fragments[i].rule_id = 0x80; /* TODO hardcoded, make this generic */ fragments[i].fcn = nfrag - i -1; size_t frg_siz = MIN(sizeof(fragments[i].payload), bytes_left); // We send the LoRaWAN packet { if (i + 1 < nfrag) { // This is not the last SCHC_Fragment memcpy(tx_buff, &fragments[i], MIN(sizeof(fragments[i]), sizeof(tx_buff))); tx_buff_len = frg_siz + (sizeof(fragments[i]) - sizeof(fragments[i].payload)); } else { // This is the Last Fragment // uint16_t checksum (uint16_t *addr, int len); uint16_t mic = checksum((uint16_t*)schc_packet, schc_packet_len); mic = htons(mic); memcpy(&tx_buff[2], &mic, sizeof(mic)); memcpy(&tx_buff[4], fragments[i].payload, MIN(sizeof(tx_buff), frg_siz)); tx_buff_len = frg_siz + sizeof(mic) + (sizeof(fragments[i]) - sizeof(fragments[i].payload)); } // PRINT("schc_fragmentate, nfrags: "); // PRINTLN(nfrag, DEC); // PRINTLN("schc_fragmentate, send following Fragment over radio: "); // PRINT_ARRAY(tx_buff, tx_buff_len); // lorawan_send(); // } We send the LoRaWAN packet bytes_left -= frg_siz; } return 0; } /** * \brief Appends the compression residue to the SCHC packet, using the * CA action defined in rule_row. * * \note That this function might not append any bytes to the * compression residue. Such thing is possible depending on the rule. * * @param [in] rule_row The rule row to check the Compression Action * (CA) to do to the ipv6_packet target value. Must not be NULL. * * @param [in] ipv6_packet The original ipv6_packet from wihch we * extract the information in case we need to copy some information to * the compression residue. * * @param [in,out] schc_packet The target SCHC compressed packet result of * aplying the CA. The function appends as many bytes as it needs * depending on the rule_row->CDA. Must be not-null. If the function * returns error, the contents of the schc_packet are undefined. * * function must append bytes to the Compression Residue. Once the * function returns, it will point to the next available byte in the * schc_packet. The idea is to call this function many times in * sequence, every call will append new bytes to the schc_packet, and * after the last call, it points where the application payload should * be. * * @return Zero if success, non-zero if error. * * \note Only implements the following CA: * - COMPUTE_LENGTH * - COMPUTE_CHECKSUM * - NOT_SENT * TODO implement the rest. * * We just need a quick implementation to start testing with a real * scenario, so we don't bother with all the complex compression * actions, like the MSB or Map Matching. We need an ad-hoc solution for * our tests. * */ static int do_compression_action(const struct field_description *rule_row, { if (rule_row == NULL || ipv6_packet == NULL) { return -1; } if (rule_row->CDA == COMPUTE_LENGTH || rule_row->CDA == NOT_SENT || rule_row->CDA == COMPUTE_CHECKSUM) { return 0; } size_t n = 0; uint32_t udp_flow_label; uint16_t ipv6_payload_length; uint16_t udp_dev_port; uint16_t udp_app_port; uint16_t udp_length; uint16_t udp_checksum; if (rule_row->CDA == VALUE_SENT) { switch (rule_row->fieldid) { case IPV6_NEXT_HEADER: n = 1; return 0; case IPV6_HOP_LIMIT: n = 1; return 0; case IPV6_DEV_PREFIX: n = 8; return 0; case IPV6_DEVIID: n = 8; return 0; case IPV6_APP_PREFIX: n = 8; return 0; case IPV6_APPIID: n = 8; return 0; case UDP_DEVPORT: n = 2; udp_dev_port = htons(ipv6_packet->udp_dev_port); return 0; case UDP_APPPORT: n = 2; udp_app_port = htons(ipv6_packet->udp_app_port); return 0; case UDP_LENGTH: n = 2; udp_length = htons(ipv6_packet->udp_length); return 0; case UDP_CHECKSUM: n = 2; udp_checksum = htons(ipv6_packet->udp_checksum); return 0; n = 1; return 0; n = 1; return 0; n = 1; return 0; n = 1; return 0; n = 2; return 0; return 0; n = 1; return 0; n = 1; return 0; return 0; default: break; } } return -1; } static int check_matching(struct field_description rule_row, struct field_values ipv6_packet) { if (rule_row.MO == IGNORE) { return 1; } if (rule_row.MO == EQUALS) { PRINTLN("check_matching entering"); PRINT("fieldid: "); PRINTLN(rule_row.fieldid); uint8_t tv[8] = {0}; switch (rule_row.fieldid) { case IPV6_VERSION: return (atoi(rule_row.tv) == ipv6_packet.ipv6_version); case IPV6_TRAFFIC_CLASS: return (atoi(rule_row.tv) == ipv6_packet.ipv6_traffic_class); case IPV6_FLOW_LABEL: return (atoi(rule_row.tv) == ipv6_packet.ipv6_flow_label); case IPV6_PAYLOAD_LENGTH: return (atoi(rule_row.tv) == ipv6_packet.ipv6_payload_length); case IPV6_NEXT_HEADER: return (atoi(rule_row.tv) == ipv6_packet.ipv6_next_header); case IPV6_HOP_LIMIT: return (atoi(rule_row.tv) == ipv6_packet.ipv6_hop_limit); case IPV6_DEV_PREFIX: string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. if (memcmp((void*)&ipv6_packet.ipv6_dev_prefix, (void*)tv, 8) != 0) { return 0; } return 1; case IPV6_DEVIID: string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. if (memcmp(ipv6_packet.ipv6_dev_iid, tv, 8) != 0) { return 0; } return 1; case IPV6_APP_PREFIX: string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. if (memcmp(ipv6_packet.ipv6_app_prefix, tv, 8) != 0) { return 0; } return 1; case IPV6_APPIID: string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. if (memcmp(ipv6_packet.ipv6_app_iid, tv, 8) != 0) { return 0; } return 1; case UDP_DEVPORT: return (atoi(rule_row.tv) == ipv6_packet.udp_dev_port); case UDP_APPPORT: return (atoi(rule_row.tv) == ipv6_packet.udp_app_port); case UDP_LENGTH: return (atoi(rule_row.tv) == ipv6_packet.udp_length); case UDP_CHECKSUM: return (atoi(rule_row.tv) == ipv6_packet.udp_checksum); string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. return 0; } return 1; { string_to_bin(tv, rule_row.tv); uint8_t tkl = tkl; // If the field is not equal, we must return error. return 0; } return 1; } { string_to_bin(tv, rule_row.tv); // If the field is not equal, we must return error. return 0; } return 1; } default: break; } } PRINTLN("check_matching exit"); return 0; } /**********************************************************************/ /*** Public Functions ***/ /**********************************************************************/ int schc_compress(struct field_values ipv6_packet) { PRINTLN("schc_compress entering"); //uint8_t schc_packet[SIZE_MTU_IPV6] = {0}; uint8_t schc_packet[1280] = {0}; size_t schc_packet_len = 0; /* * Pointer to the current location of the schc_packet. */ /* * We go through all the rules. */ int nrules = sizeof(rules) / sizeof(rules[0]); int field_description_size = sizeof(rules[0])/sizeof(struct field_description); for (int i = 0 ; i < nrules ; i++ ) { //struct field_description current_rule[22] = {0}; struct field_description current_rule[field_description_size]; memset(current_rule, 0, field_description_size * sizeof(struct field_description)); memcpy(&current_rule, rules[i], sizeof(current_rule)); /* * number of field_descriptors in the rule. */ int rule_rows = sizeof(current_rule) / sizeof(current_rule[0]); int rule_matches = 1; /* Guard Condition for the next loop */ if (rule_matches == 0) { PRINTLN("schc_compress - rule don't matched :("); schc_packet_len = 0; continue; } PRINTLN("schc_compress - rule matched!\n"); /* * At this point, all the MO of the rule returned success, we can * start writing the schc_packet. * * First, we append the Rule ID to the schc_packet */ schc_packet[schc_packet_len] = i; schc_packet_l PRINT("schc_packet_len: "); PRINTLN(schc_packet_len); PRINT("schc_packet: "); for (size_t i = 0; i < schc_packet_len; i++){ PRINT(schc_packet[i], HEX); PRINT(" "); } PRINTLN(""); /* * At this point, Compression Ressidue is already in the packet. * We concatenate the app_payload to the packet. */ uint8_t *p = schc_packet + schc_packet_len; schc_packet_len += app_payload_len; PRINTLN("schc_compression() result: "); PRINT_ARRAY(schc_packet, schc_packet_len); /* * We have created the SCHC packet, we now go to the Fragmentation * layer and the packet will be sent to the downlink LPWAN tech by * the schc_fragmentate() function as a whole SCHC packet, or as a * series of fragments. * * If schc_fragmentate succeeds, we return succeed. If it fails, * we return fail. */ return schc_fragmentate(schc_packet, schc_packet_len); } /* * No Rule in the context matched the ipv6_packet. */ return -1; } /**********************************************************************/ /*** main() setup() loop() ***/ /**********************************************************************/ /**********************************************************************/ /*** END OF FILE ***/ /**********************************************************************/ /* * Deprecated or testing functions start here. */
2fe62706ed2b82d39d4e0e76c13eba5ad9a413e2
ca33442a06291fe8b2d89cf2a00595b64bc17168
/include/DecisionTree.hpp
7c67b949575e18af43d4a1deb648f263eb69d915
[]
no_license
tsenmu/kaadugal
09382f5886affc875bc5de8fba2042f0ba932e3a
605224851e3244af40b06b0620134c6a801e81dd
refs/heads/master
2020-04-05T19:02:37.035428
2015-03-26T18:33:24
2015-03-26T18:33:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,034
hpp
DecisionTree.hpp
#ifndef _DECISIONTREE_HPP_ #define _DECISIONTREE_HPP_ #include <vector> #include <stdexcept> #include "DecisionNode.hpp" #include "Abstract/AbstractDataSet.hpp" namespace Kaadugal { // T: AbstractFeatureResponse which is the feature response function or weak learner // S: AbstractStatistics which contains some statistics about node from training // R: AbstractLeafData, arbitrary data stored if this is a leaf node template<class T, class S, class R> class DecisionTree { // TODO: Many methods need to be made const private: std::vector<DecisionNode<T, S, R>> m_Nodes; int m_MaxDecisionLevels; // The root node is level 0 int m_NumNodes; int TraverseRecursive(const std::shared_ptr<AbstractDataPoint>& DataPointPtr, int NodeIndex) { int OutputNodeIndex = NodeIndex; if(m_Nodes[NodeIndex].GetType() == Kaadugal::NodeType::LeafNode || m_Nodes[NodeIndex].GetType() == Kaadugal::NodeType::Invalid) // Termination condition { return OutputNodeIndex; } if(m_Nodes[NodeIndex].GetFeatureResponse().GetResponse(DataPointPtr) > m_Nodes[NodeIndex].GetThreshold()) // Go left. This is same logic as in Tree builder, partition OutputNodeIndex = TraverseRecursive(DataPointPtr, 2*NodeIndex+1); else // Go right OutputNodeIndex = TraverseRecursive(DataPointPtr, 2*NodeIndex+2); return OutputNodeIndex; }; public: DecisionTree(int MaxDecisionLevels = 0) : m_MaxDecisionLevels(MaxDecisionLevels) { if(MaxDecisionLevels < 0) { std::cout << "[ WARN ]: Passed negative value for MaxDecisionLevels. Setting to default of 10." << std::endl; MaxDecisionLevels = 10; m_MaxDecisionLevels = MaxDecisionLevels; } // Following advice from Efficient Implementation of Decision Forests, Shotton et al. 2013 // While allocating for more nodes than needed (in case trees are unbalanced which is bad anyway) // is wasteful memory-wise, it is efficient for access during testing. // NOTE: Will crash if this exceeds available system memory m_Nodes.resize( (1 << (MaxDecisionLevels + 1)) - 1 ); // 2^(l+1) - 1 m_NumNodes = m_Nodes.size(); }; void Serialize(std::ostream& OutputStream) { OutputStream.write((const char *)(&m_MaxDecisionLevels), sizeof(int)); OutputStream.write((const char *)(&m_NumNodes), sizeof(int)); for(int i = 0; i < m_NumNodes; ++i) m_Nodes[i].Serialize(OutputStream); }; void Deserialize(std::istream& InputStream) { InputStream.read((char *)(&m_MaxDecisionLevels), sizeof(int)); InputStream.read((char *)(&m_NumNodes), sizeof(int)); // NOTE: Will crash if this exceeds available system memory m_Nodes.resize(m_NumNodes); for(int i = 0; i < m_NumNodes; ++i) m_Nodes[i].Deserialize(InputStream); }; const std::vector<DecisionNode<T, S, R>>& GetAllNodes(void) { return m_Nodes; }; const DecisionNode<T, S, R>& GetNode(int i) const { return m_Nodes[i]; }; // Read-only DecisionNode<T, S, R>& GetNode(int i) { return m_Nodes[i]; }; const int& GetNumNodes(void) { return m_NumNodes; }; const int& GetMaxDecisionLevels(void) { return m_MaxDecisionLevels; }; const std::shared_ptr<S> Test(std::shared_ptr<AbstractDataPoint> DataPointPtr) { // TODO: Handle arbitrary leaf data if(isValid() == false) std::cout << "[ WARN ]: This tree is invalid. Cannot test data point." << std::endl; S TreeLeafStats; TestRecursive(DataPointPtr, 0, TreeLeafStats); return std::make_shared<S>(TreeLeafStats); }; void TestRecursive(const std::shared_ptr<AbstractDataPoint>& DataPointPtr, int NodeIndex, S& TreeLeafStats) { if(m_Nodes[NodeIndex].GetType() == Kaadugal::NodeType::LeafNode) // Termination condition { TreeLeafStats = m_Nodes[NodeIndex].GetStatistics(); return; } // std::cout << "Response: " << m_Nodes[NodeIndex].GetFeatureResponse().GetResponse(DataPointPtr) << std::endl; // std::cout << "Threshold: " << m_Nodes[NodeIndex].GetThreshold() << std::endl << std::endl; if(m_Nodes[NodeIndex].GetFeatureResponse().GetResponse(DataPointPtr) > m_Nodes[NodeIndex].GetThreshold()) // Go left. This is same logic as in Tree builder, partition TestRecursive(DataPointPtr, 2*NodeIndex+1, TreeLeafStats); else // Go right TestRecursive(DataPointPtr, 2*NodeIndex+2, TreeLeafStats); }; // Return the node index for the leaf or the first invalid node reached by the data point int TraverseToFrontier(std::shared_ptr<AbstractDataPoint> DataPointPtr) { if(GetNumNodes() <= 0) std::cout << "[ WARN ]: No nodes in this tree. Check config." << std::endl; int FrontierIndex = TraverseRecursive(DataPointPtr, 0); return FrontierIndex; }; bool isValid(void) { if(GetNumNodes() <= 0) return false; if(GetNode(0).GetType() == Kaadugal::Invalid) return false; return true; }; // Render methods for visualizing node virtual void Render(void) { // TODO: }; }; } // namespace Kaadugal #endif // _DECISIONTREE_HPP_
9b2925b4ebc00ca00ba63436398db660ac5dd498
08a40030d730be6dd3f0985c3f586cc5b52c2a8f
/4.cpp
3175d8682b982d7e54dc7e6d0172d2de3433075a
[]
no_license
jojiboy334/lafex
5a52319ac15db74e6e3d8a5e4d86f35031a611b9
96d0e3b7d8a5b4921eb10a406aba7556dc60c07e
refs/heads/master
2020-05-18T00:34:02.244625
2019-05-12T16:57:24
2019-05-12T16:57:24
184,066,798
0
0
null
null
null
null
UTF-8
C++
false
false
763
cpp
4.cpp
#include <iostream> using namespace std; int main(void) { cout << "My heart's in the Highlands, my heart is not here\n" << "My heart's in the Highlands, a-chasing the deer\n" << "A - chasing the wild deer, and following the roe\n" << "My heart's in the Highlands wherever I go.\n" << "Farewell to the Highlands, farewell to the North\n" << "The birthpace of valour, the country of worth\n" << "Wherever I wander, wherever I rove\n" << "The hills of the Highlands for ever I love.\n" << "Farewell to the mountains high cover'd with snow\n" << "Farewell to the straths and green valleys below\n" << "Farewell to the forests and wild - hanging woods\n" << "Farewell to the torrents and loud - pouring floods.\n" << '\n'; system("pause"); }
b57d16ebfd38cad8e7f7a37c96a94d228fa22bd2
da75006947c5ca13d76263a672657656057fd45c
/mainwindow.cpp
abbbb190a7b3b84bd53943f05464d43470a19433
[]
no_license
planprm/threadsqt
600658c0d7fe279d6913d76ae47cbca409ed7da2
c1508e03046afa83c5d27894e1b00215bfa938c3
refs/heads/master
2020-03-22T08:09:32.700280
2018-07-04T17:11:38
2018-07-04T17:11:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); thread1 = new mythread(); thread2 = new mythread(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_2_clicked() { thread1->start(); thread2->start(); thread1->generate(); thread2->generate(); QString str; QString str2; for(int i=0;i<k;++i) { str += QString::number(thread1->a[i]) + " "; str2 += QString::number(thread2->a[i]) + " "; } ui->lineEdit->setText(str); } void MainWindow::on_pushButton_clicked() { QString str; QString str2; thread1->start(); for(int i=0;i<k;++i) { str += QString::number(thread1->a[i]) + " "; } thread2->start(); thread2->sort = true; for(int i=0;i<k;++i) { str2 += QString::number(thread2->a[i]) + " "; } ui->lineEdit_2->setText(str); ui->lineEdit_3->setText(str2); } void MainWindow::sortbubble() { ui->lineEdit_2->setText("1"); } void MainWindow::searchmax() { ui->lineEdit_3->setText("2"); }
30a4666d8b2c7b3ff531bbf112a740e187ff93be
e764d2c779a4c99fac505b6ff9eeba713ba4cc4a
/DirectStaticV.hpp
4a297757c9c4787c3bacb933b6bfe469e21d06ba
[]
no_license
mgomezch/Pekomin
77e591ba9ad1fd2c157f1df85e8161e0c223ab3f
fa2897c3f8af85ff5069e89a6c8d127cb44ee149
refs/heads/master
2021-01-10T20:33:01.151243
2012-02-03T22:18:38
2012-02-03T22:18:38
1,720,772
1
0
null
null
null
null
UTF-8
C++
false
false
403
hpp
DirectStaticV.hpp
#ifndef DIRECTSTATICV_HPP #define DIRECTSTATICV_HPP #include <vector> #include "Behavior.hpp" #include "Triple.hpp" #define DirectStaticV_CALL_NAME getPos class DirectStaticV : public virtual Behavior { public: DirectStaticV(std::string name); virtual std::vector<Triple> DirectStaticV_CALL_NAME(unsigned int ticks, unsigned int delta_ticks) = 0; }; #endif
7cf26ec5f248e7dc0d09c30acfa997ac576311bc
76418b18abecbaad8592fa5c8525c0d5d8cb9e71
/main tugas1.cpp
03bf6fd1c1db2028af83dae32de863760acfc423
[]
no_license
IcaNissolekha/tugas-praktikum-1
8fe1ee524c48128567553f0995b9d3e1d5d4d669
3dbe15d09664c9ce2f225ea938bcfdc75cbd73c9
refs/heads/main
2022-12-19T17:53:41.570595
2020-10-11T11:13:02
2020-10-11T11:13:02
303,100,804
0
0
null
null
null
null
UTF-8
C++
false
false
1,567
cpp
main tugas1.cpp
/*billing warnet*/ /*ica nissolekha*/ /*20051397064*/ #include <iostream> /*run this program using the console pauser or add your own getch,system("pause")or input loop*/ using namespace std; int main(int argc, char** argv) { int j1jam,j1menit,j1detik,j2jam,j2menit,j2detik,jumlahdetik,jumlahbayar,selisihjam,selisihmenit,selisihdetik; const int tarif= 5000; string pagar="=================================================================================================="; cout<<pagar<<endl; cout<<"perhitungan billing warnet"<<endl; cout<<pagar<<endl<<endl; cout<<"memulai:"<<endl; cout<<"masukkan jam mulai billing:";cin>>j1jam; cout<<"masukkan menit mulai billing:";cin>>j1menit; cout<<"masukkan detik mulai billing:";cin>>j1detik; cout<<endl; cout<<pagar<<endl; cout<<"mengakhiri:"<<endl; cout<<"masukkan jam mengakhiri billing:";cin>>j2jam; cout<<"masukkan menit mengakhiri biling:";cin>>j2menit; cout<<"masukkan detik mengakhiri billing:";cin>>j2detik; cout<<pagar<<endl; selisihjam=j2jam-j1jam; selisihmenit=j2menit-j1menit; selisihdetik=j2detik-j1detik; jumlahdetik=(selisihjam*3600)+(selisihmenit*60)+selisihdetik; jumlahbayar=(jumlahdetik*tarif/3600); cout<<pagar<<endl; cout<<endl; cout<<"hasilnya:"<<endl; cout<<"lama pemakaian anda adalah"<<selisihjam<<"jam,"<<selisihmenit<<"menit,"<<selisihdetik<<"detik"<<endl; cout<<"jumlah pembayaran billing sebanyak Rp."<<jumlahbayar<<",-"<<endl; cout<<pagar<<endl<<endl; cout<<"terimakasih"<<endl; return 0; }
fde6b4cd5cb695534b5b8e09c1f007626228c316
25b2bfbc91dba186eafbd57260909ce4335ee167
/LibMergeFS/NsError.hpp
bba2f5ae5508d8dfeff32260fde52cecf138de7b
[ "MIT" ]
permissive
SegaraRai/MergeFS
2c8f1ad891feddcec40b452422ea2ecc6a9d857d
d28f8b0934b36fffc1b05149dbfcaa88b75b19a7
refs/heads/main
2023-01-11T08:48:34.095875
2022-12-30T03:40:59
2022-12-30T03:40:59
170,087,632
4
3
null
null
null
null
UTF-8
C++
false
false
426
hpp
NsError.hpp
#pragma once #include <stdexcept> #include <Windows.h> class NsError : public std::runtime_error { const NTSTATUS status; protected: NsError(NTSTATUS status, const char* string); public: NsError(NTSTATUS status); NTSTATUS GetStatus() const; operator NTSTATUS() const; }; class W32Error : public NsError { const DWORD error; public: W32Error(DWORD error = GetLastError()); DWORD GetError() const; };
2f70f318f1c20fd043dde50d9e0a7ff2bbc40050
7a5bae16524ea2f59aab249dbae4d9788ce49e97
/2097_조약돌.cpp
640899114de51872cb4c6d6d685d1354e876236b
[]
no_license
tuktik/backjoon
25ec144661cd90e004b833890c9e7192e8a838aa
1bd2cd2573cdc66240c755708bf58a1a26710f57
refs/heads/master
2021-01-21T13:04:04.872267
2016-04-14T11:45:51
2016-04-14T11:45:51
48,376,274
0
0
null
null
null
null
UTF-8
C++
false
false
1,012
cpp
2097_조약돌.cpp
#include <iostream> using namespace std; int main() { int inputNum; cin >> inputNum; int num = 1; while (inputNum>num*num) { num *= 10; } int prev = num/10; int next = num; int pivot = (prev + next) / 2; bool is_squareNum = false; while (1) { //cout << prev << " " << next << " " << pivot << endl; if (pivot*pivot > inputNum) next = pivot; else if (pivot*pivot < inputNum) prev = pivot; else { is_squareNum = true; break; } pivot = (prev + next) / 2; if (pivot == next || pivot == prev) break; } int resNum = 9999999999; cout << prev << " " << next << endl; if (inputNum <=4) { cout << "4" << endl; return 0; } //cout << prev << " " << next << endl; if (is_squareNum == true) { cout << pivot << endl; resNum = (pivot - 1) * 2 *2; } else { if (inputNum > prev*next) { resNum = (next - 1) * 4; } else { resNum = (next + prev - 2) * 2; } } cout << resNum << endl; //cout << prev << " " << next << endl; return 0; }
80b8409b63b771f1ab9e3aa12646a24cdce8e14d
cb8ffc89cea8fc1cfb54ec043bbaabb5b844dbb2
/DLSim/MathTools.h
11f3ddcaca2c3f849c6175acfda0205c794d27cf
[]
no_license
legharir/DLSim
be6f8ca494c5d452f3ab88eb34843017ff9ff4e1
cbf7d60f1a4d02c3a6e259ac4177dbefe45cd81d
refs/heads/main
2023-09-05T21:38:26.190698
2021-11-18T05:33:42
2021-11-18T05:33:42
429,954,558
0
0
null
null
null
null
UTF-8
C++
false
false
146
h
MathTools.h
#pragma once #include <QPoint> #include <QLine> namespace MathTools { qreal avg(qreal p1, qreal p2); QPointF midpoint(const QLineF& line); };
9a9c3c8e47e8121a649e1ab0477694dc2a2ab7e1
b56e0be82c6c633b5f4a95bf9f31adcb1429fd53
/cpp/sparsematrix.cpp
15119e5435211afea3b0db528b931342bc4d786b
[]
no_license
etsangsplk/sparseheatmap
078c2c7ccca89e6c04bb6f4f3ffe1c097bcd7eaf
258de1f5fa8625efaa1f3ba01c047be05d907ef2
refs/heads/master
2020-05-28T05:37:40.538855
2017-08-14T22:00:57
2017-08-14T22:00:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,085
cpp
sparsematrix.cpp
#include "sparsematrix.h" #include "colorengine.h" #include "lodepng.h" #include <stddef.h> #include <node.h> #include <math.h> #include <iostream> /** * Constructor for a new sparse matrix */ Sparsematrix::Sparsematrix(int w, int h, int bw, int bh, int lt, unsigned int *bdata, int db, int fl, int tpl, int tpt, int tpr, int tpb) { trimPixelsLeft = tpl; trimPixelsTop = tpt; trimPixelsRight = tpr; trimPixelsBottom = tpb; debugMode = db; filter = fl; blobwidth = bw; blobheight = bh; layout = lt; blob = bdata; blobhalfwidth = (int) bw / 2; blobhalfheight = (int) bh / 2; set_size(w, h); } /** * Set the size of the matrix */ void Sparsematrix::set_size(int x, int y) { width = x; height = y; max = 0; data = new unsigned long[width * height]; for (int d = 0; d < width * height; d++) { data[d] = 0; } }; /** * Get the area of the matrix */ unsigned int Sparsematrix::area() { return width * height; } /** * Destructor */ Sparsematrix::~Sparsematrix() { delete[] data; data = NULL; } /** * Get an intensity map */ unsigned char *Sparsematrix::get_intensity_map(int w, Colorengine *ce) { int h = (int) (((float) w / (float) width) * (float) height); lastIntensityHeight = h; int sz = w * h; lastIntensitySize = sz; int osz = width * height; for (int idx = 0; idx < osz; idx++) { max = (max < data[idx]) ? data[idx] : max; } long double fmax = (long double) max; unsigned long total = 0; int dcount = 0; for (int idx = 0; idx < osz; idx++) { long double val = (long double)data[idx]; long double newval = (unsigned long)((val / fmax) * 255); data[idx] = newval; total += (unsigned long)newval; if (newval > 0) { dcount++; } } max = 255; if (filter == 1) { // lowpass double avg = (double)total / (double) dcount; if (debugMode == 1) { std::cout << "SparseHeatmap DEBUG: Average intensity: " << avg << " Max: " << max << "\n"; std::cout << "SparseHeatmap DEBUG: Implementing low-pass filter..\n"; } fmax = 0; long double downsamplerate = 0.5; if (avg < 45) { downsamplerate = 0.46; } if (avg < 35) { downsamplerate = 0.36; } if (avg < 25) { downsamplerate = 0.26; } if (avg < 15) { downsamplerate = 0.16; } if (avg < 5) { downsamplerate = 0.06; } for (int idx = 0; idx < osz; idx++) { long double val = (long double)data[idx]; if (val > (long double)avg) { long double newval = ((val - avg) * downsamplerate) + avg; data[idx] = newval; if (newval > fmax) { fmax = newval; } } } dcount = 0; total = 0; for (int idx = 0; idx < osz; idx++) { long double val = (long double)data[idx]; long double newval = (unsigned long)((val / fmax) * 255); data[idx] = newval; total += (unsigned long)newval; if (newval > 0) { dcount++; } } avg = (double)total / (double) dcount; if (debugMode == 1) { std::cout << "SparseHeatmap DEBUG: Average intensity is now: " << avg << " Max: " << max << "\n"; } } unsigned char *targ = new unsigned char[sz * 4]; double hf = (double) h - (double) 1; double wf = (double) w - (double) 1; double myheight = (double) height - (double) 1; double mywidth = (double) width - (double) 1; int index = 0; for (int y = 0; y < h; y++) { double yp = (double) y / hf; double srcy = yp * myheight; int floory = (int) floor(srcy); int ceily = (int) ceil(srcy); int ybase = floory * width; int yceil = ceily * width; double yprog = srcy - (double) floory; for (int x = 0; x < w; x++) { double xp = (double) x / wf; double srcx = xp * mywidth; int floorx = (int) floor(srcx); int ceilx = (int) ceil(srcx); double xprog = srcx - (double) floorx; double tl = (double) data[ybase + floorx]; double tr = (double) data[ybase + ceilx]; double bl = (double) data[yceil + floorx]; double br = (double) data[yceil + ceilx]; double topavr = (tl * (1.0 - xprog)) + (tr * xprog); double botavr = (bl * (1.0 - xprog)) + (br * xprog); double tots = ((topavr * (1.0 - yprog)) + (botavr * yprog)); Clr intensity_color = ce->get_color((int)tots); targ[index++] = intensity_color.r; targ[index++] = intensity_color.g; targ[index++] = intensity_color.b; targ[index++] = intensity_color.a; } } lastIntensityIndex = index - 1; /* * unsigned encode(std::vector<unsigned char>& out, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); */ std::vector<unsigned char> outVect; lodepng::encode(outVect, targ, (unsigned)w, (unsigned)h); lastIntensityIndex = outVect.size(); /*std::cout << "Outvect size:"; std::cout << x; std::cout << "targ size:"; std::cout << lastIntensityIndex; std::cout << "\n";*/ //std::vector<unsigned char> v(10); unsigned char* myArr = new unsigned char[outVect.size()]; std::copy(outVect.begin(), outVect.end(), myArr); delete [] targ; /* * unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); */ //unsigned char* outPNG; //lodepng::lodepng_encode32(outPNG) return myArr; } /** * Set a blob at a position */ void Sparsematrix::set_blob(int x, int y) { int ydesto = y - blobhalfheight + blobheight; int xdesto = x - blobhalfwidth + blobwidth; int blobidx = 0; if (xdesto < width && x - blobhalfwidth >= 0 && ydesto < height && (int) y - (int) blobhalfheight >= 0) { for (int yp = y - blobhalfheight; yp < ydesto; yp++) { int ydpos = yp * width; for (int xp = x - blobhalfwidth; xp < xdesto; xp++) { data[ydpos + xp] += blob[blobidx++]; } } } else { int nx = x; int ny = y; for (int yp = ny - blobhalfheight; yp < ydesto; yp++) { int ydpos = yp * width; if (yp >= 0 && yp < (int) height) { for (int xp = nx - blobhalfwidth; xp < xdesto; xp++) { if (xp >= 0 && xp < (int) width) { blobidx = ((yp - (ny - blobhalfheight)) * blobwidth) + ((xp - (nx - blobhalfwidth))); data[ydpos + xp] += blob[blobidx]; } } } } } } /** * Integrate a sparse array */ void Sparsematrix::integrate_sparsearray(Sparsearray *sp) { float spw = (float) sp->width; int opw = (int)sp->width; int oph = (int)sp->height; float ow = (float) width; int dlen = sp->datalen; if (layout == 0) { // CENTERFIXEDWIDTH int xofs = (int) ((ow - spw) / 2.0); for (int idx = 0; idx < dlen; idx += 3) { int ox = sp->data[idx + 1]; int ny = (int) sp->data[idx + 2]; if (ox > trimPixelsLeft && ox < (opw - trimPixelsRight) && ny > trimPixelsTop && ny < (oph - trimPixelsBottom)) { int nx = (int) ((float) ox + xofs); if (ny <= height + blobhalfheight) { set_blob(nx, ny); } } } } else if (layout == 1) { // STRETCH for (int idx = 0; idx < dlen; idx += 3) { int ox = sp->data[idx + 1]; int nx = (int) (((float) ox / spw) * ow); int ny = (int) sp->data[idx + 2]; if (ox > trimPixelsLeft && ox < (opw - trimPixelsRight) && ny > trimPixelsTop && ny < (oph - trimPixelsBottom)) { if (ny <= (int) height + (int) blobhalfheight) { set_blob(nx, ny); } } } } else if (layout == 2) { // LEFTFIXEDWIDTH for (int idx = 0; idx < dlen; idx += 3) { int nx = (int) sp->data[idx + 1]; int ny = (int) sp->data[idx + 2]; if (ny <= ((int) height + (int) blobhalfheight) && (nx > trimPixelsLeft && nx < (opw - trimPixelsRight) && ny > trimPixelsTop && ny < (oph - trimPixelsBottom))) { set_blob(nx, ny); } } } }
9c4af3d99eee6572256abfd491cac594a83d1685
012cb90d1fe9db585e90a98907b5634a4dd10ca4
/src/plugins/mi_audioengine/tools/mi_audioengine_scopedsettingschange.h
46d26b5598e219901b7dd3235e6a50743978e607
[]
no_license
andy-fillebrown/audiocarver
6d9fed1a05400efc6b2b2464a10dce8f5d490bba
3a5d79c82d350193f28df86c2cb0fe9b114d79bd
refs/heads/master
2020-05-22T10:21:28.696699
2015-04-26T11:08:43
2015-04-26T11:08:43
186,297,278
0
0
null
null
null
null
UTF-8
C++
false
false
1,550
h
mi_audioengine_scopedsettingschange.h
/************************************************************************** ** ** This file is part of AudioCarver ** ** Copyright (c) 2013 Andrew Fillebrown. ** ** Contact: Andy Fillebrown (andy.fillebrown@gmail.com) ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #ifndef MI_AUDIOENGINE_SCOPEDSETTINGSCHANGE_H #define MI_AUDIOENGINE_SCOPEDSETTINGSCHANGE_H #include <iaggregate.h> #include <iaudioenginesettingswatcher.h> namespace AudioEngine { class ScopedSettingsChange { QList<IAudioEngineSettingsWatcher*> _watchers; public: ScopedSettingsChange(IAudioEngine *engine) { if (!engine) return; const QList<IComponent*> &components = query<IAggregate>(engine)->components(); foreach (IComponent *component, components) if (component->isTypeOfInterface(I::IAudioEngineSettingsWatcher)) _watchers.append(query<IAudioEngineSettingsWatcher>(component)); } ~ScopedSettingsChange() { foreach (IAudioEngineSettingsWatcher *watcher, _watchers) watcher->settingsChanged(); } }; } #endif
f338f03d6b55d44ff322d53aa7781e275c08a27f
d8596f9b43425c490f99677d3efc3fc1f17d1351
/Lista 6/Q11/Q11 - Ary.cpp
b28b1c7c183cfe0399d9973c2dc260949787183e
[ "MIT" ]
permissive
jhonatheberson/data-structure
3b2a4eb56ac684626e9ca4132d70ac9d88ba2e9f
0f0411228df817bb9e9849fa92772f0f94766db2
refs/heads/master
2021-06-22T21:40:00.437822
2021-04-25T16:54:39
2021-04-25T16:54:39
214,277,258
0
0
null
null
null
null
UTF-8
C++
false
false
8,750
cpp
Q11 - Ary.cpp
#include <stdio.h> #include <stdlib.h> #define MAX 10 // máximo do vetor de células (ver na função main) /* Estrutura célula contendo os seguintes campos: - valor - linha e coluna (posição da célula) - ponteiro para o próximo elemento - ponteiro para o elemento anterior */ typedef struct celula { int valor; int lin, col; struct celula *prox; struct celula *ant; } t_celula; // variáveis globais t_celula *primeiro; // primeiro elemento da lista t_celula *ultimo; // último elemento da lista // protótipos de funções t_celula* criar_celula(int lin, int col, int valor); void inserir(t_celula *novo); void deletar(int lin, int col); int vazia(); t_celula* existe_celula(int lin, int col); void imprimir_elementos(); void imprimir_matriz(); /* Função que cria uma nova celula passando a linha e coluna */ t_celula* criar_celula(int lin, int col, int valor) { t_celula * novo; // aloca espaço em memória novo = (t_celula*)malloc(sizeof(t_celula)); // testa se houve falha na alocação if(!novo) { printf("Erro ao alocar memoria!!\n"); exit(1); } // atribuição de variáveis novo->valor = valor; novo->lin = lin; novo->col = col; return novo; } /* Função que insere um novo elemento (célula) na matriz esparsa A lista é ordenada de acordo com o nome da célula */ void inserir(t_celula *novo) { /* obtém uma célula passando a linha e coluna do novo elemento para verificar se a posição já está ocupada */ t_celula* cel = existe_celula(novo->lin, novo->col); if(!cel) // verifica se não existe { if(!ultimo) { /* Se o "ultimo" é NULL, então a lista está vazia, o "novo" será o primeiro elemento a ser inserido */ // o próximo e o anterior apontam para NULL novo->prox = NULL; novo->ant = NULL; // faz o "ultimo" e "primeiro" apontarem para "novo" ultimo = novo; primeiro = novo; } else { // "p" serve para percorrer a lista // "ant" aponta para o anterior de "p" t_celula *p, *ant; p = primeiro; // começa do topo da lista ant = p->ant; // "ant" é o anterior ao "p", ou seja, NULL // poderia fazer também: ant = NULL; // percorre a lista while(p) // enquanto "p" diferente de NULL { /* Se a célula corrente "p" precede a célula "novo", então continua percorrendo */ if((p->lin < novo->lin) || ((p->lin == novo->lin) && (p->lin + p->col) < (novo->lin + novo->col))) { ant = p; // guarda o anterior p = p->prox; // aponta para o próximo } else { /* Se cair aqui é porque encontramos onde inserir a nova célula */ /* Se p->ant é diferente de NULL, então trata-se de um elemento intermediário */ if(p->ant) { /* p->ant é a célula que contém um nome imediatamente anterior à nova célula que será invetserida. Então dizemos que o próximo de p->ant irá apontar para essa nova célula */ p->ant->prox = novo; /* Se p->ant é a célula imediatamente anterior à célula "novo", então "p" é a célula imediatamente posterior à célula "novo", por isso dizendos que o próximo de "novo" aponta para "p'. */ novo->prox = p; // novo->ant tem que apontar para o p->ant novo->ant = p->ant; // faz p->ant apontar para o novo p->ant = novo; // correção de: novo->avetnt = i; return; // sai da função } /* Se chegar aqui é porque p->ant é NULL, então iremos inserir o novo elemento no início, ou seja, o "novo" será o novo primeiro da lista */ novo->prox = p; // o próximo do novo aponta para "p" novo->ant = NULL; // o anterior aponta para NULL (primeiro da lista) p->ant = novo; // faz o anterior de "p" apontar para o novo primeiro = novo; // "primeiro" aponta para "novo" return; // sai da função } } /* Se chegou aqui, então insere no final, agora preciso da variável "ant". */ // faz o próx. do antigo último apontar para "novo" ant->prox = novo; // como o "novo" agora é o último, então o próximo dele // aponta para NULL novo->prox = NULL; // o anterior ao "novo" aponta para o "ant" novo->ant = ant; // atualiza o último elemento da lista ultimo = novo; } } else { // se já existe então sobrescreve o valor cel->valor = novo->valor; } } // Função que deleta um elemento pela posição (linha e coluna) void deletar(int lin, int col) { // verifica se existe a célula (elemento) if(existe_celula(lin, col)) { // remove do começo if(primeiro->lin == lin && primeiro->col == col) { // pego o apontador para o próximo t_celula *prox = primeiro->prox; free(primeiro); // libera memória // verifico se o próximo existe if(prox) prox->ant = NULL; // atualizo o anterior // faz o "primeiro" ser o "prox" primeiro = prox; return; // sai da função } /* Se chegou aqui é porque NÃO irá remover do início e existe mais de 1 elemento */ t_celula *p = primeiro->prox; // percorre a lista while(p) { if(p->lin == lin && p->col == col) { if(p->prox) // testa se NÃO é o último elemento { /* Faço o próximo do anterior de "p" apontar para o próximo de "p" */ p->ant->prox = p->prox; /* Faço o anterior do proximo de "p" apontar para o anterior de "p" */ p->prox->ant = p->ant; } else { // se chegou aqui, é porque é o último elemento // faz o proximo do anterior de "p" apontar para NULL p->ant->prox = NULL; // faz o anterior de "p" ser o "ultimo" ultimo = p->ant; } free(p); // libera o "p" return; // sai da função } p = p->prox; } } } // Função que verifica se a lista está vazia int vazia() { if(!ultimo) // se o último for NULL, então a lista está vazia return 1; return 0; } // Função que verifica se um elemento existe pela posição (linha e coluna) t_celula* existe_celula(int lin, int col) { t_celula* p = primeiro; while(p) // percorre a lista { // verifica a linha e a coluna if(lin == p->lin && col == p->col) return p; // retorna a célula p = p->prox; } return NULL; } // Função que imprime os lementos da lista void imprimir_elementos() { t_celula* p = primeiro; while(p) // percorre a lista { printf("(%d,%d)\n", p->lin, p->col); p = p->prox; } } // Função para imprimir a matriz convencional // "X" indica o elemento repetido da matriz esparsa (pode ser um 0 por exemplo) void imprimir_matriz() { if(!vazia()) // verifica se a lista NÃO está vazia { /* Obtendo a maior linha, basta saber a do último porque está ordenado pela linha */ int total_linhas = ultimo->lin; // obtendo o total de colunas int total_colunas = -1; t_celula* p = primeiro; while(p) // percorre a lista para obter o total de colunas { if(p->col > total_colunas) total_colunas = p->col; p = p->prox; } for(int i = 0; i < total_linhas; i++) { for(int j = 0; j < total_colunas; j++) { // busca por um elemento passando a linha e coluna t_celula* cel = existe_celula(i + 1, j + 1); if(cel) // testa se encontrou o elemento printf("%d\t", cel->valor); else // se não existe o elemento, então imprime 'X' printf("X\t"); } printf("\n"); } } else printf("\nLista vazia!!\n"); } int main(int argc, char * argv[]) { t_celula *vet[MAX]; // vetor de células // passa a linha e coluna da célula vet[0] = criar_celula(2, 1, 10); vet[1] = criar_celula(1, 2, 20); vet[2] = criar_celula(10, 3, 30); vet[3] = criar_celula(1, 1, 40); vet[4] = criar_celula(3, 2, 50); vet[5] = criar_celula(2, 8, 60); vet[6] = criar_celula(3, 1, 70); vet[7] = criar_celula(4, 2, 80); vet[8] = criar_celula(3, 3, 90); vet[9] = criar_celula(1, 6, 100); if(vazia()) // verifica se a lista está vazia printf("\nLista vazia!!\n"); else printf("\nLista NAO vazia!!\n"); // insere os elementos (células) for(int i = 0; i < MAX; i++) inserir(vet[i]); if(vazia()) // verifica se a lista está vazia printf("\nLista vazia!!\n"); else printf("\nLista NAO vazia!!\n"); printf("\nImprimindo os elementos da lista:\n"); imprimir_elementos(); // imprime a matriz printf("\nImprimindo a matriz esparsa (X eh o elemento que se repete):\n"); imprimir_matriz(); // imprime a matriz deletar(10, 3); // deletando a célula da posição (10,3) printf("\nImprimindo a matriz esparsa (X eh o elemento que se repete):\n"); imprimir_matriz(); // imprime a matriz return 0; }
8f29817251ece168905d992210ee5cd056b0819a
2c948211ead22820c13e3ba0f7c3e58ab23f3850
/src/Primitives.cpp
a1bf6c802039175d60690508bcfe3eade2b9e06e
[]
no_license
Aakash1312/CS421_Project
45a2f9f7ea782fe9c2957f3152bc395dbe30c955
bf40792e76438753d43cd8173046a395fad3f2c2
refs/heads/master
2020-03-09T03:14:00.761230
2018-04-08T18:55:39
2018-04-08T18:55:39
128,560,297
0
1
null
2018-04-08T18:55:40
2018-04-07T19:16:50
C++
UTF-8
C++
false
false
14,023
cpp
Primitives.cpp
/* * Primitive.cpp * * Created on: Feb 19, 2009 * Author: njoubert * Modified: sidch */ #include "Primitives.hpp" Primitive::Primitive(RGB const & c, Material const & m, Mat4 const & modelToWorld) { c_ = c; m_ = m; modelToWorld_ = modelToWorld; worldToModel_ = modelToWorld.inverse(); } Primitive::~Primitive() { } Cylinder::Cylinder(double radius, Vec3 top, Vec3 bottom, RGB const & c, Material const & m, Mat4 const & modelToWorld): Primitive(c, m, modelToWorld) { r_ = radius; top_ = top; bottom_ = bottom; } bool Cylinder::intersect(Ray &ray, bool &inside) const { bool inside2 = false; Vec3 top = Vec3(modelToWorld_ * Vec4(top_, 1.0)); Vec3 bottom = Vec3(modelToWorld_ * Vec4(bottom_, 1.0)); inside = false; Vec3 normal = (bottom - top).normalize(); Vec3 nray = ((ray.direction())*normal)*normal; Vec3 xyray = (ray.direction() - nray); double ratio; if ((ray.direction())*normal) { if(((ray.direction())*normal) > 0) { ratio = nray.length() / xyray.length(); } else { ratio = -1 * nray.length() / xyray.length(); } } else { ratio = 0; } Vec3 xyrayn = xyray.normalize(); Vec3 center = top + (((ray.start() - top)*normal)*normal); Vec3 U = center - ray.start(); double m = U*(xyrayn); if (U*U <= r_*r_) { inside2 = true; if ((((ray.start() - top)*normal) > 0) && (((ray.start() - top)*normal) < ((bottom-top).length()))) { inside = true; } } if (m < 0 && (!inside)) { return false; } Vec3 ndisv = ((top - ray.start())*normal)*normal; if (ndisv*normal > 0 && ((ray.direction())*normal) > 0) { double t = ndisv.length()/((ray.direction())*normal); Vec3 pos = ray.start() + t*(ray.direction()); if ((pos - top).length() < r_) { ray.setMinT(1 *t); return true; } } if (((ray.direction())*normal) < 0 && (inside)) { double t = ndisv.length()/((ray.direction())*normal); Vec3 pos = ray.start() - t*(ray.direction()); if ((pos - top).length() < r_) { ray.setMinT(-1*t); return true; } } Vec3 ndish = ((bottom - ray.start())*normal)*normal; if (ndish*normal < 0 && ((ray.direction())*normal) < 0) { double t = ndish.length()/((ray.direction())*normal); Vec3 pos = ray.start() - t*(ray.direction()); if ((pos - bottom).length() < r_) { ray.setMinT(-1*t); return true; } } if (((ray.direction())*normal) > 0 && (inside)) { double t = ndish.length()/((ray.direction())*normal); Vec3 pos = ray.start() + t*(ray.direction()); if ((pos - bottom).length() < r_) { ray.setMinT(1*t); return true; } } if ((U*U - m*m) > r_*r_) { return false; } else { double offset = sqrt(r_*r_ + m*m - U*U); double depth; double gap; if (inside2) { gap = (m + offset); } else { gap = m - offset; } depth = gap*ratio; Vec3 dposition = depth*normal + top-(((top-(ray.start()))*normal)*normal); if (((dposition-bottom).length() < (top-bottom).length()) && ((dposition-bottom)*(top-bottom)) > 0 ) { ray.setMinT(sqrt(depth*depth + gap*gap)); return true; } else { return false; } } } Vec3 Cylinder::calculateNormal(Vec3 const & position) const { Vec3 top = Vec3(modelToWorld_ * Vec4(top_, 1.0)); Vec3 bottom = Vec3(modelToWorld_ * Vec4(bottom_, 1.0)); Vec3 normal = (bottom-top).normalize(); if ((((position - top).length()) < r_)) { return -1 * normal; } if ((((position - bottom).length()) < r_)) { return normal; } // if ((((position - top)* normal) < 0.001) && (((position - top)* normal) > -0.001)) // { // return -1 * normal; // } // if ((((position - bottom)* normal) < 0.001) && (((position - bottom)* normal) > -0.001)) // { // return normal; // } Vec3 temp = position - top; double dist = temp*normal; Vec3 c = top + dist*normal; Vec3 n = (position - c).normalize(); return n; } Sphere::Sphere(double radius, RGB const & c, Material const & m, Mat4 const & modelToWorld): Primitive(c, m, modelToWorld) { r_ = radius; } Lens::Lens(double radius, double width, RGB const & c, Material const & m, Mat4 const & modelToWorld): Primitive(c, m, modelToWorld) { r_ = radius; w_ = width; } bool Lens::intersect(Ray & ray, bool &inside) const { inside = false; Vec3 center = Vec3(modelToWorld_ * Vec4(Vec3(0,0,0), 1.0)); Vec3 c2 = center + Vec3(0,0,-1*(r_-(w_/2))); Vec3 c1 = center + Vec3(0,0,r_-(w_/2)); // std::cout << c1 << " " << c2 << std::endl; // Vec3 c1 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,-1*(r_-(w_/2))), 1.0)); // Vec3 c2 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,r_-(w_/2)), 1.0)); Vec3 d = ray.direction(); Vec3 e = ray.start(); double disc = ((d*(e-c1))*(d*(e -c1))) - (d*d)*(((e-c1)*(e-c1))-(r_*r_)); if (disc < 0) { return false; } else { double disc2 = ((d*(e-c2))*(d*(e -c2))) - (d*d)*(((e-c2)*(e-c2))-(r_*r_)); if (disc2 < 0) { return false; } else { double t1 = (((-1 * d)* (e-c2)) + sqrt(disc2))/(d*d); double t2 = (((-1 * d)* (e-c2)) - sqrt(disc2))/(d*d); double t3 = (((-1 * d)* (e-c1)) + sqrt(disc))/(d*d); double t4 = (((-1 * d)* (e-c1)) - sqrt(disc))/(d*d); double mint; if (t1 > 0 && t2 > 0) { if (t1 < t2) { if (t3 > t4) { if (t3 < t1) { return false; } } else { if (t4 < t1) { return false; } } mint = t1; } else { if (t3 > t4) { if (t3 < t2) { return false; } } else { if (t4 < t2) { return false; } } mint = t2; } ray.setMinT(mint); inside = false; return true; } else { double mint; if (t3 < 0 && t4 < 0) { return false; } else { if (t3 > t4) { mint = t3; } else { mint = t4; } ray.setMinT(mint); inside = true; return true; } } } } } // bool // Lens::intersect(Ray & ray, bool &inside) const // { // inside = false; // Vec3 center = Vec3(modelToWorld_ * Vec4(Vec3(0,0,0), 1.0)); // Vec3 c1 = center + Vec3(0,0,-1*(r_-(w_/2))); // Vec3 c2 = center + Vec3(0,0,r_-(w_/2)); // std::cout << c1 << " " << c2 << std::endl; // // Vec3 c1 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,-1*(r_-(w_/2))), 1.0)); // // Vec3 c2 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,r_-(w_/2)), 1.0)); // Vec3 d = ray.direction(); // Vec3 e = ray.start(); // double disc = ((d*(e-c1))*(d*(e -c1))) - (d*d)*(((e-c1)*(e-c1))-(r_*r_)); // if (disc < 0) // { // return false; // } // else // { // double disc2 = ((d*(e-c2))*(d*(e -c2))) - (d*d)*(((e-c2)*(e-c2))-(r_*r_)); // if (disc2 < 0) // { // return false; // } // else // { // double t1 = (((-1 * d)* (e-c2)) + sqrt(disc2))/(d*d); // double t2 = (((-1 * d)* (e-c2)) - sqrt(disc2))/(d*d); // double mint; // if (t1 > 0 && t2 > 0) // { // return false; // } // else // { // double t3 = (((-1 * d)* (e-c1)) + sqrt(disc))/(d*d); // double t4 = (((-1 * d)* (e-c1)) - sqrt(disc))/(d*d); // double mint; // if (t3 >0 && t4 > 0) // { // inside = false; // return true; // } // else // { if(t1 < 0 || t2 < 0) // { // if (t1 > t2) // { // mint = t1; // } // else // { // mint = t2; // } // ray.setMinT(mint); // inside = true; // return true; // } // } // } // } // } // return false; // } Vec3 Lens::calculateNormal(Vec3 const & position) const { // TODO for 3a Vec3 center = Vec3(modelToWorld_ * Vec4(Vec3(0,0,0), 1.0)); Vec3 c1 = center + Vec3(0,0,-1*(r_-(w_/2))); Vec3 c2 = center + Vec3(0,0,r_-(w_/2)); // Vec3 c2 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,r_-(w_/2)), 1.0)); // Vec3 c1 = Vec3(modelToWorld_ * Vec4(Vec3(0,0,-1*(r_-(w_/2))), 1.0)); Vec3 f; if (((c2 - position).length()) >= ((c1 - position).length())) { f = position - c2; } else { f = position -c1; } // f = Vec3(modelToWorld_.transpose() * Vec4(f, 0.0)); f = f/f.length(); return f; // IMPLEMENT_ME(__FILE__, __LINE__); } bool Sphere::intersect(Ray & ray, bool &inside) const { // TODO for 3a inside = false; Vec3 c = Vec3(modelToWorld_ * Vec4(Vec3(0,0,0), 1.0)); Vec3 d = ray.direction(); Vec3 e = ray.start(); // d = d / d.length(); double disc = ((d*(e-c))*(d*(e -c))) - (d*d)*(((e-c)*(e-c))-(r_*r_)); if (disc < 0) { return false; } else { double t1 = (((-1 * d)* (e-c)) + sqrt(disc))/(d*d); double t2 = (((-1 * d)* (e-c)) - sqrt(disc))/(d*d); double mint; if (t1 < 0 && t2 < 0) { return false; } if (t1 >0 && t2 > 0) { if (t1 < t2) { mint = t1; } else { mint = t2; } } else { inside = true; if (t1 < t2) { mint = t2; } else { mint = t1; } } // ray.transform(modelToWorld_); // if (mint < ray.minT()) // { // return false; // } // else // { ray.setMinT(mint); // } return true; } // IMPLEMENT_ME(__FILE__, __LINE__); } Vec3 Sphere::calculateNormal(Vec3 const & position) const { // TODO for 3a Vec3 c = Vec3(modelToWorld_ * Vec4(Vec3(0,0,0), 1.0)); Vec3 f = position - c; // f = Vec3(modelToWorld_.transpose() * Vec4(f, 0.0)); f = f/f.length(); return f; // IMPLEMENT_ME(__FILE__, __LINE__); } //============================================================================================================================= // Triangle and other primitives are for Assignment 3b, after the midsem. Do not do this for 3a. //============================================================================================================================= Triangle::Triangle(Vec3 const & v0, Vec3 const & v1, Vec3 const & v2, RGB const & c, Material const & m, Mat4 const & modelToWorld) : Primitive(c, m, modelToWorld) { verts[0] = v0; verts[1] = v1; verts[2] = v2; } // bool // Triangle::intersect(Ray & ray, bool& inside) const // { // inside = false; // const double eps = 0.0000001; // Vec3 v0 = Vec3(modelToWorld_ * Vec4(verts[0], 1.0)); // Vec3 v1 = Vec3(modelToWorld_ * Vec4(verts[1], 1.0)); // Vec3 v2 = Vec3(modelToWorld_ * Vec4(verts[2], 1.0)); // Vec3 edge1 = v1 - v0; // Vec3 edge2 = v2 - v0; // Vec3 rayVector = ray.direction(); // rayVector = rayVector.normalize(); // Vec3 h = rayVector^edge2; // Vec3 rayOrigin = ray.start(); // double a = edge1*h; // double f,u,v; // if (a > -1.0*eps && a < eps) // { // // std::cout << "1h" << std::endl; // return false; // } // f = 1.0/a; // Vec3 s = rayOrigin - v0; // u = f * (s*(h)); // // std::cout << u << std::endl; // if (u < 0.0 || u > 1.0) // { // // std::cout << "2h" << std::endl; // return false; // } // Vec3 q = s^(edge1); // v = f * rayVector*(q); // // std::cout << u << " " << u+v << std::endl; // if (v < 0.0 || u + v > 1.0) // { // // std::cout << "3h" << std::endl; // return false; // } // // At this stage we can compute t to find out where the intersection point is on the line. // double t = f * (edge2*(q)); // // std::cout << "t " << t << std::endl; // if (t > eps) // ray intersection // { // // outIntersectionPoint = rayOrigin + rayVector * t; // std::cout << "4h" << std::endl; // return true; // } // else // This means that there is a line intersection but not a ray intersection. // { // std::cout << "5h" << std::endl; // return false; // } // // IMPLEMENT_ME(__FILE__, __LINE__); // } bool Triangle::intersect(Ray & ray, bool& inside) const { inside = false; const double eps = 0.0000001; Vec3 v0 = Vec3(modelToWorld_ * Vec4(verts[0], 1.0)); Vec3 v1 = Vec3(modelToWorld_ * Vec4(verts[1], 1.0)); Vec3 v2 = Vec3(modelToWorld_ * Vec4(verts[2], 1.0)); Vec3 edge1 = v1 - v0; Vec3 edge2 = v2 - v0; Vec3 rayVector = ray.direction(); rayVector = rayVector.normalize(); Vec3 h = rayVector^edge2; Vec3 rayOrigin = ray.start(); double a = edge1*h; double f,u,v; if (a > -1.0*eps && a < eps) { // std::cout << "1h" << std::endl; return false; } f = 1.0/a; Vec3 s = rayOrigin - v0; u = f * (s*(h)); u *= -1; // std::cout << u << std::endl; if (u < 0.0 || u > 1.0) { // std::cout << "2h" << std::endl; return false; } Vec3 q = s^(edge1); v = f * rayVector*(q); // v *= -1; // std::cout << u << " " << u+v << std::endl; if (v < 0.0 || u + v > 1.0) { // std::cout << "3h" << std::endl; return false; } // At this stage we can compute t to find out where the intersection point is on the line. double t = f * (edge2*(q)); // std::cout << "t " << t << std::endl; if (t > eps) // ray intersection { // outIntersectionPoint = rayOrigin + rayVector * t; // std::cout << "4h" << std::endl; ray.setMinT(t); return true; } else // This means that there is a line intersection but not a ray intersection. { // std::cout << "5h" << std::endl; return false; } // IMPLEMENT_ME(__FILE__, __LINE__); } Vec3 Triangle::calculateNormal(Vec3 const & position) const { // TODO for 3b, NOT 3a // std::cout << "normal" << std::endl; Vec3 v0 = Vec3(modelToWorld_ * Vec4(verts[0], 1.0)); Vec3 v1 = Vec3(modelToWorld_ * Vec4(verts[1], 1.0)); Vec3 v2 = Vec3(modelToWorld_ * Vec4(verts[2], 1.0)); return ((v1-v0)^(v2-v0)).normalize(); // IMPLEMENT_ME(__FILE__, __LINE__); }
76550a5e42511c69f44b2e42f144d5fd6357f098
b8c47ade3553b715f03dc2dcef87eacfc4519354
/src/main.cpp
964b8d7eba376b570d763a875cf15df1d67835c1
[]
no_license
dorislee80/gbenchmark_example
93d7d3700ce96e94adb9e421fe72018c4223cd92
2fb0240ac8b1db91a6f35edd2e7cac004aca8c9b
refs/heads/master
2020-04-07T07:06:28.571050
2018-11-20T05:52:32
2018-11-20T05:52:32
158,163,885
1
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
main.cpp
#include <iostream> #include <string> #include "conversion.h" int main(int argc, char** argv) { std::cout << gbenchmarkexample::IntToString(123) << std::endl; return 0; }
902c03b1e6a98bbc5e403e28215b3848611320a9
9b727ccbf91d12bbe10adb050784c04b4753758c
/ZOJ/vol14/ZOJ_2313.cpp
5d637350760e0e5cc64ca3ba837d93a36067e74c
[]
no_license
codeAligned/acm-icpc-1
b57ab179228f2acebaef01082fe6b67b0cae6403
090acaeb3705b6cf48790b977514965b22f6d43f
refs/heads/master
2020-09-19T19:39:30.929711
2015-10-06T15:13:12
2015-10-06T15:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
929
cpp
ZOJ_2313.cpp
#include <cstdio> #include <cstring> const int MAXN=2005; char num[MAXN]; int ans[MAXN]; int n; void dec(int o) { ans[n]-=o; int i=n; while (ans[i]<0) { ans[i-1]-=1; ans[i]+=10; i--; } while (!ans[ans[0]]) ans[0]++; } int main() { int test; scanf("%d", &test); while (test--) { scanf("%s", num); n=strlen(num); if (n==1) { int m=num[0]-'0'; if (m&1) printf("%d\n", m/2); else if (m%4==0) printf("%d\n", m/2-1); else printf("%d\n", m/2-2); } else { int m=(num[n-2]-'0')*10+num[n-1]-'0'; ans[0]=1; for (int i=0; i<n; i++) ans[i+1]=num[i]-'0'; int x=0; for (int i=ans[0]; i<=n; i++) { int tmp=(x*10+ans[i])/2; x=(x*10+ans[i])%2; ans[i]=tmp; } while (!ans[ans[0]]) ans[0]++; if (m&1) ; else if (m%4==0) dec(1); else dec(2); for (int i=ans[0]; i<=n; i++) printf("%d", ans[i]); puts(""); } if (test) puts(""); } return 0; }
6225e4e3c16380e3b1d7d01acb31df5c5cfa1fdf
c85df9a1ad627707fc603f40f7df056af16900c9
/source/settings/SettingsPrompts.cpp
e82536c2f2cd0a55ad42d5155980c1d6c13585c1
[]
no_license
wiidev/usbloadergx
28b582c2c8231ca7f313a321a134d6784358a770
e25c4e96430524c080767679b0c4a0d7595412a8
refs/heads/enhanced
2023-08-11T18:47:12.728031
2023-01-07T23:30:02
2023-01-07T23:30:02
204,522,898
313
124
null
2023-07-21T17:06:18
2019-08-26T17:05:59
C
UTF-8
C++
false
false
9,211
cpp
SettingsPrompts.cpp
#include <gccore.h> #include <unistd.h> #include <string.h> #include "language/gettext.h" #include "language/UpdateLanguage.h" #include "prompts/PromptWindows.h" #include "prompts/ProgressWindow.h" #include "GUI/gui.h" #include "GUI/gui_optionbrowser.h" #include "settings/CSettings.h" #include "settings/GameTitles.h" #include "themes/CTheme.h" #include "network/URL_List.h" #include "FileOperations/fileops.h" #include "FileOperations/DirList.h" #include "main.h" #include "prompts/filebrowser.h" #include "sys.h" #include "menu/menus.h" /*** Extern variables ***/ extern u8 shutdown; extern u8 reset; /**************************************************************************** * MenuOGG ***************************************************************************/ bool MenuBackgroundMusic() { bool ret = false; char entered[1024]; if (!Settings.ogg_path[0]) snprintf(entered, sizeof(entered), "%s/", Settings.BootDevice); else { snprintf(entered, sizeof(entered), "%s", Settings.ogg_path); char *pathptr = strrchr(entered, '/'); if (!pathptr) snprintf(entered, sizeof(entered), "%s/", Settings.BootDevice); else { pathptr++; int choice = WindowPrompt(tr("Playing Music:" ), pathptr, tr("Play Previous"), tr("Play Next"), tr("Change Play Path"), tr("Cancel")); if (choice == 1) return bgMusic->PlayPrevious(); else if (choice == 2) return bgMusic->PlayNext(); else if (choice == 3) pathptr[0] = 0; else return true; } } if (BrowseDevice(entered, sizeof(entered), FB_DEFAULT)) { if (!bgMusic->Load(entered)) WindowPrompt(tr("Unsupported format!"), tr("Loading standard music."), tr("OK")); else ret = true; bgMusic->Play(); bgMusic->SetVolume(Settings.volume); } return ret; } /**************************************************************************** * MenuLanguageSelect ***************************************************************************/ int MenuLanguageSelect() { int cnt = 0; int ret = 0, choice = 0; int returnhere = 0; GuiImageData btnOutline(Resources::GetFile("button_dialogue_box.png"), Resources::GetFileSize("button_dialogue_box.png")); GuiImageData settingsbg(Resources::GetFile("settings_background.png"), Resources::GetFileSize("settings_background.png")); GuiTrigger trigA; trigA.SetSimpleTrigger( -1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A ); GuiTrigger trigB; trigB.SetButtonOnlyTrigger( -1, WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B, PAD_BUTTON_B ); char fullpath[150]; DirList Dir(Settings.languagefiles_path, ".lang"); // Check if a language is specified. if (Settings.language_path[0] == 0) strlcpy(fullpath, tr( "Default" ), sizeof(fullpath)); else strlcpy(fullpath, Settings.languagefiles_path, sizeof(fullpath)); GuiText titleTxt( fullpath, 24, ( GXColor ) {0, 0, 0, 255} ); titleTxt.SetAlignment( ALIGN_CENTER, ALIGN_MIDDLE ); titleTxt.SetPosition( 0, 0 ); GuiButton pathBtn( 300, 50 ); pathBtn.SetAlignment( ALIGN_CENTER, ALIGN_TOP ); pathBtn.SetPosition( 0, 28 ); pathBtn.SetLabel( &titleTxt ); pathBtn.SetSoundOver( btnSoundOver ); pathBtn.SetSoundClick( btnSoundClick2 ); pathBtn.SetTrigger( &trigA ); pathBtn.SetEffectGrow(); GuiImage oggmenubackground( &settingsbg ); oggmenubackground.SetAlignment( ALIGN_LEFT, ALIGN_TOP ); oggmenubackground.SetPosition( 0, 0 ); GuiText backBtnTxt( tr( "Back" ) , 22, thColor("r=0 g=0 b=0 a=255 - prompt windows button text color")); backBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); GuiImage backBtnImg( &btnOutline ); if ( Settings.wsprompt == ON ) { backBtnTxt.SetWidescreen( Settings.widescreen ); backBtnImg.SetWidescreen( Settings.widescreen ); } GuiButton backBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); backBtn.SetAlignment( ALIGN_CENTER, ALIGN_TOP ); backBtn.SetPosition( -190, 400 ); backBtn.SetLabel( &backBtnTxt ); backBtn.SetImage( &backBtnImg ); backBtn.SetSoundOver( btnSoundOver ); backBtn.SetSoundClick( btnSoundClick2 ); backBtn.SetTrigger( &trigA ); backBtn.SetTrigger( &trigB ); backBtn.SetEffectGrow(); GuiText defaultBtnTxt( tr( "Default" ) , 22, thColor("r=0 g=0 b=0 a=255 - prompt windows button text color")); defaultBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); GuiImage defaultBtnImg( &btnOutline ); if ( Settings.wsprompt == ON ) { defaultBtnTxt.SetWidescreen( Settings.widescreen ); defaultBtnImg.SetWidescreen( Settings.widescreen ); } GuiButton defaultBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); defaultBtn.SetAlignment( ALIGN_CENTER, ALIGN_TOP ); defaultBtn.SetPosition( 190, 400 ); defaultBtn.SetLabel( &defaultBtnTxt ); defaultBtn.SetImage( &defaultBtnImg ); defaultBtn.SetSoundOver( btnSoundOver ); defaultBtn.SetSoundClick( btnSoundClick2 ); defaultBtn.SetTrigger( &trigA ); defaultBtn.SetEffectGrow(); GuiText updateBtnTxt( tr( "Update Files" ) , 22, thColor("r=0 g=0 b=0 a=255 - prompt windows button text color")); updateBtnTxt.SetMaxWidth( btnOutline.GetWidth() - 30 ); GuiImage updateBtnImg( &btnOutline ); if ( Settings.wsprompt == ON ) { updateBtnTxt.SetWidescreen( Settings.widescreen ); updateBtnImg.SetWidescreen( Settings.widescreen ); } GuiButton updateBtn( btnOutline.GetWidth(), btnOutline.GetHeight() ); updateBtn.SetAlignment( ALIGN_CENTER, ALIGN_TOP ); updateBtn.SetPosition( 0, 400 ); updateBtn.SetLabel( &updateBtnTxt ); updateBtn.SetImage( &updateBtnImg ); updateBtn.SetSoundOver( btnSoundOver ); updateBtn.SetSoundClick( btnSoundClick2 ); updateBtn.SetTrigger( &trigA ); updateBtn.SetEffectGrow(); OptionList options2; for ( cnt = 0; cnt < Dir.GetFilecount(); cnt++ ) { if(!Dir.GetFilename( cnt )) continue; char filename[64]; strlcpy( filename, Dir.GetFilename( cnt ), sizeof( filename ) ); char *dot = strchr( filename, '.' ); if ( dot ) *dot = '\0'; options2.SetName( cnt, "%s", filename ); options2.SetValue( cnt, NULL ); } GuiOptionBrowser optionBrowser4( 396, 280, &options2, "bg_options_settings.png"); optionBrowser4.SetPosition( 0, 90 ); optionBrowser4.SetAlignment( ALIGN_CENTER, ALIGN_TOP ); HaltGui(); GuiWindow w( screenwidth, screenheight ); w.Append( &oggmenubackground ); w.Append( &pathBtn ); w.Append( &backBtn ); w.Append( &defaultBtn ); w.Append( &updateBtn ); w.Append( &optionBrowser4 ); mainWindow->Append( &w ); w.SetEffect( EFFECT_FADE, 20 ); ResumeGui(); while ( w.GetEffect() > 0 ) usleep( 50 ); while ( !returnhere ) { usleep(100); if ( shutdown == 1 ) Sys_Shutdown(); else if ( reset == 1 ) Sys_Reboot(); else if ( backBtn.GetState() == STATE_CLICKED ) { backBtn.ResetState(); break; } else if ( defaultBtn.GetState() == STATE_CLICKED ) { choice = WindowPrompt( tr( "Loading standard language." ), 0, tr( "OK" ), tr( "Cancel" ) ); if ( choice == 1 ) { Settings.LoadLanguage(NULL, CONSOLE_DEFAULT); Settings.Save(); returnhere = 2; } defaultBtn.ResetState(); //optionBrowser4.SetFocus(1); // commented out to prevent crash } else if ( updateBtn.GetState() == STATE_CLICKED ) { choice = WindowPrompt( tr( "Update all Language Files" ), tr( "Do you wish to update/download all language files?" ), tr( "OK" ), tr( "Cancel" ) ); if ( choice == 1 ) { if (IsNetworkInit() || NetworkInitPrompt()) { if(DownloadAllLanguageFiles() > 0) WindowPrompt(tr("Successfully Updated"), 0, tr("OK")); returnhere = 1; break; } } updateBtn.ResetState(); //optionBrowser4.SetFocus(1); // commented out to prevent crash } else if ( pathBtn.GetState() == STATE_CLICKED ) { w.Remove( &optionBrowser4 ); w.Remove( &backBtn ); w.Remove( &pathBtn ); w.Remove( &defaultBtn ); char entered[43] = ""; strlcpy( entered, Settings.languagefiles_path, sizeof( entered ) ); int result = OnScreenKeyboard( entered, 43, 0 ); w.Append( &optionBrowser4 ); w.Append( &pathBtn ); w.Append( &backBtn ); w.Append( &defaultBtn ); if (result == 1) { if (entered[strlen(entered)-1] != '/') strcat (entered, "/"); snprintf(Settings.languagefiles_path, sizeof(Settings.languagefiles_path), entered); WindowPrompt(tr("Languagepath changed."), 0, tr("OK")); } pathBtn.ResetState(); } ret = optionBrowser4.GetClickedOption(); if (ret >= 0) { choice = WindowPrompt( tr( "Do you want to change language?" ), 0, tr( "Yes" ), tr( "Cancel" ) ); if (choice == 1) { char newLangPath[150]; snprintf(Settings.languagefiles_path, sizeof( Settings.languagefiles_path ), "%s", Dir.GetFilepath(ret)); char * ptr = strrchr(Settings.languagefiles_path, '/'); if(ptr) ptr[1] = 0; snprintf(newLangPath, sizeof(newLangPath), "%s", Dir.GetFilepath(ret)); if (!CheckFile(newLangPath)) { WindowPrompt(tr("File not found."), tr("Loading standard language."), tr("OK")); Settings.LoadLanguage(NULL, CONSOLE_DEFAULT); } else { Settings.LoadLanguage(newLangPath); } Settings.Save(); returnhere = 2; break; } } } w.SetEffect( EFFECT_FADE, -20 ); while ( w.GetEffect() > 0 ) usleep( 50 ); HaltGui(); mainWindow->Remove( &w ); ResumeGui(); return returnhere; }
3583ae9cc3f64798604fe34fb848821be7167c0c
6ff36a97f6d13e2d772658240c4a490d14095040
/StorageObj.cpp
4f4607acb923956b39e5331487ec7722912de0b7
[]
no_license
rivitna/OLE2Viewer
9ed362a71ef894641b8d92d00971cbb61ab41ebd
0fd22f2d9a2377d10b8392da7383c6e4f3fb749b
refs/heads/master
2022-01-21T20:29:09.319330
2021-12-30T13:34:40
2021-12-30T13:34:40
214,134,179
3
1
null
null
null
null
WINDOWS-1251
C++
false
false
37,490
cpp
StorageObj.cpp
//--------------------------------------------------------------------------- #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <windows.h> #include <malloc.h> #include <memory.h> #include "StrUtils.h" #include "FileUtil.h" #include "OLE2Type.h" #include "OLE2CF.h" #include "OLE2Util.h" #include "OLE2MSI.h" #include "OLE2Metadata.h" #include "OLE2VBA.h" #include "OLE2Word.h" #include "OLE2Native.h" #include "StorageObj.h" //--------------------------------------------------------------------------- #ifndef countof #define countof(a) (sizeof(a)/sizeof(a[0])) #endif // countof //--------------------------------------------------------------------------- // Размер буфера по умолчанию для пути к текущему каталогу #define DEFAULT_CURRENTDIRPATH_LEN 256 //--------------------------------------------------------------------------- // Имя файла с текстом из основного потока документа Word const wchar_t WORDDOC_TEXT_FILE_NAME[] = L"{text}"; // Имя текстового файла с информацией const wchar_t INFO_TEXT_FILE_NAME[] = L"{info}.txt"; // Наименования открываемых потоков const wchar_t* const OPENABLE_STREAM_NAMES[] = { L"WordDocument", L"\5SummaryInformation", L"\5DocumentSummaryInformation", L"\1Ole10Native" }; // Наименования типов файлов OLE2 const wchar_t* const OLE2_TYPE_NAMES[] = { L"OLE2 Unknown", L"Microsoft Word", L"Microsoft Excel", L"Microsoft PowerPoint", L"Microsoft Visio", L"Microsoft Excel 5", L"Ichitaro", L"MSI/MSP/MSM" }; // Имя родительского элемента const wchar_t PARENT_ITEM_NAME[] = L".."; //--------------------------------------------------------------------------- /***************************************************************************/ /* OLE2FileTypeToString - Преобразование типа файла OLE2 в строку */ /***************************************************************************/ const wchar_t *OLE2FileTypeToString( int nFileType ) { if (nFileType >= countof(OLE2_TYPE_NAMES)) nFileType = 0; return OLE2_TYPE_NAMES[nFileType]; } //--------------------------------------------------------------------------- /***************************************************************************/ /* */ /* CStorageObject - Класс файла-контейнера */ /* */ /***************************************************************************/ /***************************************************************************/ /* CStorageObject - Конструктор класса */ /***************************************************************************/ CStorageObject::CStorageObject() : UseOpenableStreamAttr(false), m_pwszFilePath(NULL), m_pwszFileName(NULL), m_nFileType(OLE2_UNKNOWN), m_nNumStreams(0), m_nNumStorages(0), m_nNumMacros(0), m_nFindItemIndex(0), m_dwCurParentItemID(0), m_bCurParentItemIsStream(false), m_cchCurrentDirPathBuf(0), m_pwszCurrentDirPath(NULL), m_pItemNameAliases(NULL), m_nNumItemNameAliases(0), m_inStream(), m_ole2File() { } /***************************************************************************/ /* CStorageObject - Деструктор класса */ /***************************************************************************/ CStorageObject::~CStorageObject() { // Закрытие Close(); } /***************************************************************************/ /* Open - Открытие */ /***************************************************************************/ int CStorageObject::Open( const wchar_t *pwszFileName ) { // Закрытие Close(); // Инициализация int res = Init(pwszFileName); if (!GetOpened()) { // Закрытие Close(); } return res; } /***************************************************************************/ /* Init - Инициализация */ /***************************************************************************/ int CStorageObject::Init( const wchar_t *pwszFileName ) { // Открытие файла if (m_inStream.Open(pwszFileName, true)) return O2_ERROR_OPEN; // Проверка сигнатуры файла OLE2 uint32_t dwSign[2]; size_t nSize = sizeof(dwSign); if (m_inStream.Read(&dwSign, &nSize)) return O2_ERROR_READ; if ((nSize != sizeof(dwSign)) || (dwSign[0] != OLE2_SIGNATURE) || (dwSign[1] != OLE2_VERSION)) return O2_ERROR_SIGN; // Открытие файла OLE2 O2Res res = m_ole2File.Open(&m_inStream); if (!m_ole2File.GetOpened()) return res; // Определение типа файла-контейнере DetectFileType(); // Инициализация списка псевдонимов имен элементов InitItemNameAliasList(); // Сохранение пути к файлу-контейнеру m_pwszFilePath = StrDup(pwszFileName); if (m_pwszFilePath) { // Получение имени файла-контейнера m_pwszFileName = ::GetFileName(m_pwszFilePath); } // Выделение буфера памяти для пути к текущему каталогу m_pwszCurrentDirPath = (wchar_t *)malloc(DEFAULT_CURRENTDIRPATH_LEN * sizeof(wchar_t)); if (m_pwszCurrentDirPath) m_cchCurrentDirPathBuf = DEFAULT_CURRENTDIRPATH_LEN; // Обновление пути к текущему каталогу UpdateCurrentDirPath(); // Обновление информации о файле-контейнере UpdateFileInfo(); return res; } /***************************************************************************/ /* Close - Закрытие */ /***************************************************************************/ void CStorageObject::Close() { m_pwszFileName = NULL; m_nFileType = OLE2_UNKNOWN; m_nNumStreams = 0; m_nNumStorages = 0; m_nNumMacros = 0; m_nFindItemIndex = 0; m_dwCurParentItemID = 0; m_bCurParentItemIsStream = false; m_cchCurrentDirPathBuf = 0; m_nNumItemNameAliases = 0; // Закрытие файла OLE2 m_ole2File.Close(); // Закрытие файлового потока m_inStream.Close(); // Уничтожение пути к файлу-контейнеру if (m_pwszFilePath) { free(m_pwszFilePath); m_pwszFilePath = NULL; } // Уничтожение пути к текущему каталогу if (m_pwszCurrentDirPath) { free(m_pwszCurrentDirPath); m_pwszCurrentDirPath = NULL; } // Уничтожение списка псевдонимов имен элементов if (m_pItemNameAliases) { free(m_pItemNameAliases); m_pItemNameAliases = NULL; } } /***************************************************************************/ /* GetFileSize - Получение размера файла */ /***************************************************************************/ unsigned __int64 CStorageObject::GetFileSize() const { if (!m_ole2File.GetOpened()) return 0i64; return (unsigned __int64)m_ole2File.GetSectorSize() * (m_ole2File.GetFATEntryCount() + 1); } /***************************************************************************/ /* GetItemCount - Получение количества элементов в текущем каталоге */ /***************************************************************************/ size_t CStorageObject::GetItemCount( bool bIncludeParentItem ) const { if (!m_ole2File.GetOpened()) return 0; size_t nItemCount = 0; if (bIncludeParentItem) { // Родительский элемент if (m_ole2File.GetDirEntry(m_dwCurParentItemID)) nItemCount++; } if (m_bCurParentItemIsStream) return (nItemCount + 1); for (size_t i = 0; i < m_ole2File.GetDirEntryItemCount(); i++) { if (m_dwCurParentItemID == m_ole2File.GetDirEntryItem(i)->dwParentID) nItemCount++; } return nItemCount; } /***************************************************************************/ /* FindFirstItem - Поиск первого элемента текущего каталога */ /***************************************************************************/ bool CStorageObject::FindFirstItem( bool bIncludeParentItem, PFindItemData pFindItemData ) { if (!m_ole2File.GetOpened()) return false; m_nFindItemIndex = 0; if (bIncludeParentItem) { // Родительский элемент const DIRECTORY_ENTRY *pDirEntry; pDirEntry = m_ole2File.GetDirEntry(m_dwCurParentItemID); if (pDirEntry) { // Атрибуты элемента pFindItemData->dwItemAttributes = FILE_ATTRIBUTE_DIRECTORY; // Дата создания pFindItemData->ftCreationTime.dwLowDateTime = pDirEntry->dwLowCreationTime; pFindItemData->ftCreationTime.dwHighDateTime = pDirEntry->dwHighCreationTime; // Дата изменения pFindItemData->ftModifiedTime.dwLowDateTime = pDirEntry->dwLowModifiedTime; pFindItemData->ftModifiedTime.dwHighDateTime = pDirEntry->dwHighModifiedTime; // Размер элемента pFindItemData->nItemSize = 0i64; // Имя элемента pFindItemData->pwszItemName = PARENT_ITEM_NAME; // Идентификатор элемента pFindItemData->dwItemID = m_dwCurParentItemID; return true; } } // Поиск следующего элемента текущего каталога return FindNextItem(pFindItemData); } /***************************************************************************/ /* FindNextItem - Поиск следующего элемента текущего каталога */ /***************************************************************************/ bool CStorageObject::FindNextItem( PFindItemData pFindItemData ) { if (!m_ole2File.GetOpened()) return false; if (m_bCurParentItemIsStream) { // Поиск следующего фиктивного элемента if (m_nFindItemIndex == 0) { m_nFindItemIndex++; const DIRECTORY_ENTRY *pDirEntry; pDirEntry = m_ole2File.GetDirEntry(m_dwCurParentItemID); if (pDirEntry) { // Дата создания pFindItemData->ftCreationTime.dwLowDateTime = pDirEntry->dwLowCreationTime; pFindItemData->ftCreationTime.dwHighDateTime = pDirEntry->dwHighCreationTime; // Дата изменения pFindItemData->ftModifiedTime.dwLowDateTime = pDirEntry->dwLowModifiedTime; pFindItemData->ftModifiedTime.dwHighDateTime = pDirEntry->dwHighModifiedTime; } else { // Дата создания pFindItemData->ftCreationTime.dwLowDateTime = 0; pFindItemData->ftCreationTime.dwHighDateTime = 0; // Дата изменения pFindItemData->ftModifiedTime.dwLowDateTime = 0; pFindItemData->ftModifiedTime.dwHighDateTime = 0; } // Атрибуты элемента pFindItemData->dwItemAttributes = 0; // Размер элемента pFindItemData->nItemSize = m_dummyItem.nItemSize; // Имя элемента pFindItemData->pwszItemName = m_dummyItem.wszItemName; // Идентификатор элемента pFindItemData->dwItemID = NOSTREAM; return true; } } else { // Поиск следующего элемента записи каталога while (m_nFindItemIndex < m_ole2File.GetDirEntryItemCount()) { const DirEntryItem *pDirEntryItem; pDirEntryItem = m_ole2File.GetDirEntryItem(m_nFindItemIndex); m_nFindItemIndex++; if (m_dwCurParentItemID == pDirEntryItem->dwParentID) { if ((pDirEntryItem->nType == DIR_ENTRY_TYPE_STORAGE) || (pDirEntryItem->nType == DIR_ENTRY_TYPE_LOST)) { // Атрибуты элемента pFindItemData->dwItemAttributes = FILE_ATTRIBUTE_DIRECTORY; // Размер элемента pFindItemData->nItemSize = 0i64; } else { // Атрибуты элемента pFindItemData->dwItemAttributes = 0; if (UseOpenableStreamAttr) { // Определение типа потока StreamType streamType = DetectStream(pDirEntryItem->dwID); if ((streamType == STREAM_VBA) || (streamType == STREAM_WORDDOC) || (streamType == STREAM_SUMINFO) || (streamType == STREAM_DOCSUMINFO) || (streamType == STREAM_NATIVEDATA)) pFindItemData->dwItemAttributes = OPENABLE_STREAM_ATTRIBUTES; } // Размер элемента pFindItemData->nItemSize = (m_ole2File.GetMajorVersion() > 3) ? pDirEntryItem->pDirEntry->qwStreamSize : (unsigned __int64)pDirEntryItem->pDirEntry->dwLowStreamSize; } // Дата создания pFindItemData->ftCreationTime.dwLowDateTime = pDirEntryItem->pDirEntry->dwLowCreationTime; pFindItemData->ftCreationTime.dwHighDateTime = pDirEntryItem->pDirEntry->dwHighCreationTime; // Дата изменения pFindItemData->ftModifiedTime.dwLowDateTime = pDirEntryItem->pDirEntry->dwLowModifiedTime; pFindItemData->ftModifiedTime.dwHighDateTime = pDirEntryItem->pDirEntry->dwHighModifiedTime; // Имя элемента // Поиск псевдонима имени элемента pFindItemData->pwszItemName = FindItemNameAlias(pDirEntryItem->dwID); if (!pFindItemData->pwszItemName) { pFindItemData->pwszItemName = (const wchar_t *)pDirEntryItem->pDirEntry->bName; } // Идентификатор элемента pFindItemData->dwItemID = pDirEntryItem->dwID; return true; } } } return false; } /***************************************************************************/ /* SetCurrentDir - Установка текущего каталога */ /***************************************************************************/ bool CStorageObject::SetCurrentDir( const wchar_t *pwszDirPath ) { if (!pwszDirPath || !pwszDirPath[0] || !m_ole2File.GetOpened()) return false; uint32_t dwDirEntryID; // Получение записи каталога по пути dwDirEntryID = m_ole2File.GetDirEntryByPath(pwszDirPath, m_dwCurParentItemID, true); if (dwDirEntryID == NOSTREAM) return false; // Подкаталог? const DIRECTORY_ENTRY *pDirEntry; pDirEntry = m_ole2File.GetDirEntry(dwDirEntryID); if (!pDirEntry || ((pDirEntry->bObjectType != OBJ_TYPE_STORAGE) && (pDirEntry->bObjectType != OBJ_TYPE_ROOT))) return false; // Установка текущего родительского элемента каталога SetCurParentItemID(dwDirEntryID, false); return true; } /***************************************************************************/ /* OpenStream - Открытие потока */ /***************************************************************************/ bool CStorageObject::OpenStream( unsigned long dwStreamID ) { if (!m_ole2File.GetOpened() || (dwStreamID == NOSTREAM)) return false; O2Res res; // Определение типа потока StreamType streamType = DetectStream(dwStreamID); size_t nItemSize = 0; m_dummyItem.wszItemName[0] = L'\0'; switch (streamType) { case STREAM_VBA: // Определение размера исходного кода макроса VBA res = ExtractVBAMacroSource(&m_ole2File, dwStreamID, NULL, &nItemSize); break; case STREAM_WORDDOC: // Определение размера текста документа Word res = ExtractWordDocumentText(&m_ole2File, dwStreamID, NULL, &nItemSize); break; case STREAM_SUMINFO: case STREAM_DOCSUMINFO: // Определение размера метаданных res = ExtractMetadata(&m_ole2File, dwStreamID, (streamType == STREAM_SUMINFO) ? PSS_SUMMARYINFO : PSS_DOCSUMMARYINFO, NULL, &nItemSize); break; case STREAM_NATIVEDATA: // Получение информации о вложенном объекте res = GetEmbeddedObjectInfo(&m_ole2File, dwStreamID, m_dummyItem.wszItemName, countof(m_dummyItem.wszItemName), &nItemSize); break; } if (nItemSize == 0) return false; // Инициализация фиктивного элемента // Размер элемента m_dummyItem.nItemSize = nItemSize; // Тип и имя элемента const wchar_t *pwszItemName = NULL; switch (streamType) { case STREAM_VBA: m_dummyItem.nItemType = STREAM_DATA_TYPE_VBA_MACRO_SRC; // Получение имени файла исходного кода макроса VBA MakeVBAMacroSourceFileName(&m_ole2File, dwStreamID, m_dummyItem.wszItemName, countof(m_dummyItem.wszItemName)); break; case STREAM_WORDDOC: m_dummyItem.nItemType = STREAM_DATA_TYPE_WORDDOC_TEXT; pwszItemName = WORDDOC_TEXT_FILE_NAME; break; case STREAM_SUMINFO: case STREAM_DOCSUMINFO: m_dummyItem.nItemType = (streamType == STREAM_SUMINFO) ? STREAM_DATA_TYPE_SUMINFO_TEXT : STREAM_DATA_TYPE_DOCSUMINFO_TEXT; pwszItemName = INFO_TEXT_FILE_NAME; break; case STREAM_NATIVEDATA: m_dummyItem.nItemType = STREAM_DATA_TYPE_NATIVE_DATA; break; } if (pwszItemName) { size_t cchItemName = ::lstrlen(pwszItemName); if (cchItemName >= countof(m_dummyItem.wszItemName)) cchItemName = countof(m_dummyItem.wszItemName) - 1; memcpy(m_dummyItem.wszItemName, pwszItemName, cchItemName * sizeof(wchar_t)); m_dummyItem.wszItemName[cchItemName] = L'\0'; } // Установка текущего родительского элемента каталога SetCurParentItemID(dwStreamID, true); return true; } /***************************************************************************/ /* DetectStream - Определение типа потока */ /***************************************************************************/ StreamType CStorageObject::DetectStream( unsigned long dwStreamID ) const { // Проверка, является запись каталога потоком const DIRECTORY_ENTRY *pDirEntry; pDirEntry = m_ole2File.GetDirEntry(dwStreamID); if (!pDirEntry || (pDirEntry->bObjectType != OBJ_TYPE_STREAM)) return STREAM_UNKNOWN; // Детектирование потока VBA if (DetectVBAStream(&m_ole2File, dwStreamID)) return STREAM_VBA; size_t cchStreamType = pDirEntry->wSizeOfName >> 1; if (cchStreamType <= 1) return STREAM_UNKNOWN; cchStreamType--; for (size_t i = 0; i < countof(OPENABLE_STREAM_NAMES); i++) { if (!StrCmpNIW((const wchar_t *)pDirEntry->bName, OPENABLE_STREAM_NAMES[i], cchStreamType) && (OPENABLE_STREAM_NAMES[i][cchStreamType] == L'\0')) return (StreamType)(STREAM_WORDDOC + i); } return STREAM_UNKNOWN; } /***************************************************************************/ /* SetFileItemTime - Установка времени файла по времени записи каталога */ /***************************************************************************/ bool SetFileItemTime( const wchar_t *pwszFileName, const DIRECTORY_ENTRY *pDirEntry ) { const FILETIME *pftCreationTime = NULL; const FILETIME *pftLastWriteTime = NULL; if ((pDirEntry->dwLowCreationTime != 0) || (pDirEntry->dwHighCreationTime != 0)) pftCreationTime = (FILETIME *)pDirEntry->bCreationTime; if ((pDirEntry->dwLowModifiedTime != 0) || (pDirEntry->dwHighModifiedTime != 0)) pftLastWriteTime = (FILETIME *)pDirEntry->bModifiedTime; // Установка времени файла if (!pftCreationTime && !pftLastWriteTime) return true; HANDLE hFile; // Открытие файла hFile = ::CreateFile(pwszFileName, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hFile == INVALID_HANDLE_VALUE) return false; // Установка времени файла bool bSuccess = (0 != ::SetFileTime(hFile, pftCreationTime, NULL, pftLastWriteTime)); ::CloseHandle(hFile); return bSuccess; } /***************************************************************************/ /* ExtractItem - Извлечение элемента */ /***************************************************************************/ bool CStorageObject::ExtractItem( unsigned long dwItemID, const wchar_t *pwszItemName, const wchar_t *pwszDestPath ) const { if (!m_ole2File.GetOpened()) return false; const DIRECTORY_ENTRY *pDirEntry; if (dwItemID != NOSTREAM) { // Запись каталога pDirEntry = m_ole2File.GetDirEntry(dwItemID); } else { // Фиктивный элемент if (!m_bCurParentItemIsStream) return false; pDirEntry = m_ole2File.GetDirEntry(m_dwCurParentItemID); } if (!pDirEntry) return false; // Создание иерархии каталогов if (!ForceDirectories(pwszDestPath)) return false; // Получение имени файла wchar_t *pwszFileName = AllocAndCombinePath(pwszDestPath, pwszItemName); if (!pwszFileName) return false; bool bSuccess = false; if (dwItemID != NOSTREAM) { // Запись каталога if ((pDirEntry->bObjectType == OBJ_TYPE_STORAGE) || (pDirEntry->bObjectType == OBJ_TYPE_ROOT)) { // Создание иерархии каталогов if (ForceDirectories(pwszFileName)) { // Рекурсивное извлечение элементов каталога if (ExtractStorageItems(dwItemID, pwszFileName)) bSuccess = true; } } else { // Извлечение потока if (ExtractStream(dwItemID, pwszFileName)) bSuccess = true; } } else { // Фиктивный элемент // Извлечение данных потока if (ExtractStreamData(m_dwCurParentItemID, m_dummyItem.nItemType, pwszFileName)) bSuccess = true; } if (bSuccess) { // Установка времени файла по времени записи каталога SetFileItemTime(pwszFileName, pDirEntry); } free(pwszFileName); return bSuccess; } /***************************************************************************/ /* ExtractStorageItems - Извлечение элементов каталога */ /***************************************************************************/ bool CStorageObject::ExtractStorageItems( unsigned long dwStorageID, const wchar_t *pwszDestPath ) const { bool bError = false; for (size_t i = 0; i < m_ole2File.GetDirEntryItemCount(); i++) { const DirEntryItem *pDirEntryItem = m_ole2File.GetDirEntryItem(i); if (dwStorageID == pDirEntryItem->dwParentID) { // Поиск псевдонима имени элемента const wchar_t *pwszItemName = FindItemNameAlias(pDirEntryItem->dwID); if (!pwszItemName) pwszItemName = (const wchar_t *)pDirEntryItem->pDirEntry->bName; // Извлечение элемента if (!ExtractItem(pDirEntryItem->dwID, pwszItemName, pwszDestPath)) bError = true; } } return !bError; } /***************************************************************************/ /* ExtractStream - Извлечение потока */ /***************************************************************************/ bool CStorageObject::ExtractStream( unsigned long dwStreamID, const wchar_t *pwszFileName ) const { bool bSuccess = false; // Создание объекта файлового потока для последовательного вывода данных CFileSeqOutStream outStream; // Создание файла if (!outStream.Open(pwszFileName)) { // Извлечение потока if (O2_OK == m_ole2File.ExtractStream(dwStreamID, &outStream)) bSuccess = true; } return bSuccess; } /***************************************************************************/ /* ExtractStreamData - Извлечение данных потока */ /***************************************************************************/ bool CStorageObject::ExtractStreamData( unsigned long dwStreamID, int nStreamDataType, const wchar_t *pwszFileName ) const { O2Res res; size_t nProcessedSize = 0; // Создание объекта файлового потока для последовательного вывода данных CFileSeqOutStream outStream; // Создание файла if (!outStream.Open(pwszFileName)) { switch (nStreamDataType) { case STREAM_DATA_TYPE_VBA_MACRO_SRC: // Извлечение исходного кода макроса VBA res = ExtractVBAMacroSource(&m_ole2File, dwStreamID, &outStream, &nProcessedSize); break; case STREAM_DATA_TYPE_WORDDOC_TEXT: // Извлечение текста документа Word res = ExtractWordDocumentText(&m_ole2File, dwStreamID, &outStream, &nProcessedSize); break; case STREAM_DATA_TYPE_SUMINFO_TEXT: case STREAM_DATA_TYPE_DOCSUMINFO_TEXT: { // Извлечение метаданных PropertySetStreamType streamType; if (m_dummyItem.nItemType == STREAM_DATA_TYPE_SUMINFO_TEXT) streamType = PSS_SUMMARYINFO; else streamType = PSS_DOCSUMMARYINFO; res = ExtractMetadata(&m_ole2File, dwStreamID, streamType, &outStream, &nProcessedSize); } break; case STREAM_DATA_TYPE_NATIVE_DATA: // Извлечение вложенного объекта из потока "\1Ole10Native" ExtractEmbeddedObject(&m_ole2File, dwStreamID, &outStream, &nProcessedSize); break; } } return (nProcessedSize != 0); } /***************************************************************************/ /* SetCurParentItemID - Установка текущего родительского элемента каталога */ /***************************************************************************/ void CStorageObject::SetCurParentItemID( unsigned long dwDirEntryID, bool bIsStream ) { if (dwDirEntryID != m_dwCurParentItemID) { m_dwCurParentItemID = dwDirEntryID; m_bCurParentItemIsStream = bIsStream; m_nFindItemIndex = 0; // Обновление пути к текущему каталогу UpdateCurrentDirPath(); } } /***************************************************************************/ /* UpdateCurrentDirPath - Обновление пути к текущему каталогу */ /***************************************************************************/ void CStorageObject::UpdateCurrentDirPath() { // Получение полного пути записи каталога size_t cch = m_ole2File.GetDirEntryFullPath(m_dwCurParentItemID, m_pwszCurrentDirPath, m_cchCurrentDirPathBuf, true); if (cch == 0) { if (m_pwszCurrentDirPath) m_pwszCurrentDirPath[0] = L'\0'; } else if (cch >= m_cchCurrentDirPathBuf) { if (m_pwszCurrentDirPath) free(m_pwszCurrentDirPath); m_pwszCurrentDirPath = (wchar_t *)malloc(cch * sizeof(wchar_t)); if (!m_pwszCurrentDirPath) { m_cchCurrentDirPathBuf = 0; return; } m_cchCurrentDirPathBuf = cch; // Получение полного пути записи каталога m_ole2File.GetDirEntryFullPath(m_dwCurParentItemID, m_pwszCurrentDirPath, cch, true); } } /***************************************************************************/ /* DetectFileType - Определение типа файла-контейнере */ /***************************************************************************/ void CStorageObject::DetectFileType() { // Наименования основных потоков различных типов файлов OLE2 const wchar_t* const MAIN_STREAM_NAMES[] = { L"WordDocument", L"Workbook", L"PowerPoint Document", L"VisioDocument", L"Book", L"DocumentText" }; // Детектирование файла-контейнера MSI if (DetectMsi(&m_ole2File)) { m_nFileType = OLE2_MSI; return; } // Поиск в корневом каталоге основных потоков различных типов файлов OLE2 m_nFileType = OLE2_UNKNOWN; for (size_t i = 0; i < countof(MAIN_STREAM_NAMES); i++) { if (NOSTREAM != m_ole2File.FindDirEntry(0, OBJ_TYPE_STREAM, MAIN_STREAM_NAMES[i], true)) { m_nFileType = (OLE2FileType)(OLE2_MSWORD + i); break; } } } /***************************************************************************/ /* UpdateFileInfo - Обновление информации о файле-контейнере */ /***************************************************************************/ void CStorageObject::UpdateFileInfo() { // Определение количества потоков, каталогов и макросов m_nNumStreams = 0; m_nNumStorages = 0; m_nNumMacros = 0; for (size_t i = 1; i < m_ole2File.GetDirEntryItemCount(); i++) { const DirEntryItem *pDirEntryItem; pDirEntryItem = m_ole2File.GetDirEntryItem(i); if (pDirEntryItem->nType == DIR_ENTRY_TYPE_STORAGE) { m_nNumStorages++; } else if (pDirEntryItem->nType == DIR_ENTRY_TYPE_STREAM) { m_nNumStreams++; // Детектирование потока VBA if (DetectVBAStream(&m_ole2File, pDirEntryItem->dwID)) { // Определение размера исходного кода макроса VBA size_t cbMacroSrc; ExtractVBAMacroSource(&m_ole2File, pDirEntryItem->dwID, NULL, &cbMacroSrc); if (cbMacroSrc != 0) m_nNumMacros++; } } } } /***************************************************************************/ /* InitItemNameAliasList - Инициализация списка псевдонимов имен элементов */ /***************************************************************************/ void CStorageObject::InitItemNameAliasList() { const DirEntryItem *pDirEntryItem; size_t nNumAliases = 0; // Определение количества псевдонимов в списке for (size_t i = 1; i < m_ole2File.GetDirEntryItemCount(); i++) { pDirEntryItem = m_ole2File.GetDirEntryItem(i); // Проверка необходимости декодирования имени записи каталога MSI или // наличия в имени записи каталога недопустимых символов if (((m_nFileType == OLE2_MSI) && DecodeMsiDirEntryName(pDirEntryItem->pDirEntry->bName, NULL, 0)) || !IsDirEntryNameValid(pDirEntryItem->pDirEntry->bName)) { nNumAliases++; } } if (nNumAliases == 0) return; m_pItemNameAliases = (PDirEntryNameAlias)malloc(nNumAliases * sizeof(DirEntryNameAlias)); if (!m_pItemNameAliases) return; size_t nAliasCount = 0; PDirEntryNameAlias pAlias = m_pItemNameAliases; for (size_t i = 1; (i < m_ole2File.GetDirEntryItemCount()) && (nAliasCount < nNumAliases); i++) { pDirEntryItem = m_ole2File.GetDirEntryItem(i); size_t cchAlias = 0; if (m_nFileType == OLE2_MSI) { // Декодирование имени записи каталога MSI cchAlias = DecodeMsiDirEntryName(pDirEntryItem->pDirEntry->bName, pAlias->wszNameAlias, sizeof(pAlias->wszNameAlias)); } if (cchAlias == 0) { // Проверка, содержит ли имя записи каталога недопустимые символы if (!IsDirEntryNameValid(pDirEntryItem->pDirEntry->bName)) { // Преобразование имени записи каталога в имя файла cchAlias = DirEntryNameToFileName(pDirEntryItem->pDirEntry->bName, pAlias->wszNameAlias, sizeof(pAlias->wszNameAlias)); } } if ((cchAlias == 0) || (cchAlias >= sizeof(pAlias->wszNameAlias))) continue; // Проверка отсутствия записи каталога с именем, соответствующим // псевдониму if (NOSTREAM == m_ole2File.FindDirEntry(pDirEntryItem->dwParentID, 0, pAlias->wszNameAlias, false)) { pAlias->dwDirEntryID = pDirEntryItem->dwID; pAlias++; nAliasCount++; } } m_nNumItemNameAliases = nAliasCount; // Установка списка псевдонимов имен записей каталога m_ole2File.SetDirEntryNameAliases(m_pItemNameAliases, m_nNumItemNameAliases); } /***************************************************************************/ /* FindItemNameAlias - Поиск псевдонима имени элемента */ /***************************************************************************/ const wchar_t *CStorageObject::FindItemNameAlias( unsigned long dwItemID ) const { for (size_t i = 0; i < m_nNumItemNameAliases; i++) { if (dwItemID == m_pItemNameAliases[i].dwDirEntryID) return m_pItemNameAliases[i].wszNameAlias; } return NULL; } //---------------------------------------------------------------------------
497b1d9c56f223f65f605bfb78805a40c0ab1d0f
c3099f0394ff2abc937801e895e209779a07a0fc
/output/wzgSXX.cpp
288d320d8a834b3789335edfd6443201d898844f
[]
no_license
sehe/ideone_slurp
d9307b9591f63c531a454b9809e1c60cdd7d04b0
2936fda7aa5a49921e599f8fccc586047eb760fd
refs/heads/master
2020-05-18T19:07:22.729233
2014-03-17T23:29:48
2014-03-17T23:29:48
17,847,331
1
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
wzgSXX.cpp
// error: OK // langId: 44 // langName: C++11 // langVersion: gcc-4.8.1 // time: 0 // date: 2013-08-07 14:33:36 // status: 0 // result: 0 // memory: 0 // signal: 0 // public: false // ------------------------------------------------ #include <boost/variant.hpp> #include <boost/spirit/include/karma.hpp> namespace karma = boost::spirit::karma; typedef boost::variant<int, std::string> Parameter; typedef std::vector<Parameter> Parameters; void test(boost::variant<Parameters, Parameter> const& v) { typedef boost::spirit::ostream_iterator It; using namespace karma; const static rule<It, std::string()> quoted = '"' << *('\\' << char_('"') | char_) << '"' ; const static rule<It, Parameter()> param = int_ | quoted ; const static rule<It, boost::variant<Parameters, Parameter>()> rule = param | param % ", " ; std::cout << karma::format(rule, v) << '\n'; } int main() { test(1); test("foo"); test("escape: \"foo\""); test(Parameters { 1, 2, 3, "escape: \"foo\"" }); } // ------------------------------------------------ #if 0 // stdin #endif #if 0 // stdout #endif #if 0 // stderr #endif #if 0 // cmpinfo #endif
7b4db0564d29786ad7e3f9641e622fc64537c1a2
6adb44aaf4460a3da37c1454eb3aaa97f6699dc9
/OnlineShopping/OnlineShopping/User.h
3a02109d9c69c041ea70b5eeaafdc9d240c1a451
[]
no_license
EvanFarry/SW-Arch-Assignment3
b6b45ec319b0620781c7ed07dc7360a552fab5ad
640cd7146535b1f7962304a21c3ebd05f188566d
refs/heads/master
2021-04-15T19:01:08.213220
2016-09-13T16:39:30
2016-09-13T16:39:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
984
h
User.h
#pragma once /* Consists of User and Admin functionality. */ class User { public: string name; User(); User(string name); void Login(Database db); }; User::User(void) {} User::User(string name) { this->name = name; } void User::Login(Database db) { char input[100]; cout << "Welcome, " << this->name << "!" << endl; while (1) { cout << "Options:" << endl; cout << "1. browse" << endl; cout << "2. search" << endl; cout << "3. logout" << endl; cout << this->name << ": "; cin.getline(input, sizeof(input)); if (!strcmp(input, "1") || !strcmp(input, "browse")) { db.print_all(); } // Call search functionality if (!strcmp(input, "2") || !strcmp(input, "search")) { cout << "What would you like to search for?" << endl; cout << this->name << ": "; cin.getline(input, sizeof(input)); db.search_item(input); } // Exit the while loop. if (!strcmp(input, "3") || !strcmp(input, "logout")) { break; } cout << endl; } }
2a96ea441032f5e1e4ef575849b3dd1d3995618a
8d11e9aa1c0a4cf39c30837672d5c07cb36034ff
/cash_dispenser.h
cc70f0e74d09a7dc8bde4febd96149a5fe4512d4
[]
no_license
dandelionn/ATM
2eb0fc9c7bfd8375a9a82986f52fe2b577661a95
2c4957a61e4b1215b4f746e4e9225ace990cf067
refs/heads/master
2021-06-26T11:08:32.159121
2020-11-18T18:56:43
2020-11-18T18:56:43
134,469,893
0
0
null
null
null
null
UTF-8
C++
false
false
2,050
h
cash_dispenser.h
#ifndef CASH_DISPENSER_H_INCLUDED #define CASH_DISPENSER_H_INCLUDED #include <fstream> #include "display.h" using namespace std; const int vb[5]={500,200,100,50,10}; ///valorile bancnotelor in ordine descrescatoare const int nrmaxb[5]={10,25,50,20,10}; ///nr maxim de bancnote de un anumit tip pe care are voie sa le scoata bancomatul class CashDispenser{ Display display; int b[5]; ///nr de bancnote de fiecare tip din automat; int sol[5]; ///solutia generata de functia membra CheckForExistence int amountOfCash; ///atribuie valoarea 0 tuturor elementelor vectorului sol; void initsolution(); ///atribuie tabloului solutie valoarea 0 pentru numarul fiecarui tip de bancnota public: CashDispenser(); ///se vor citi valorile din fisier(valori care reprezinta suma ramasa in bancomat) bool CheckForExistence(int); ///Verifica daca exista suficienti bani in atm si genereaza solutia(numarul de bancnote de fiecare tip) int totalCashAmount(); ///returneaza suma totala din bancomat void Withdraw(int); ///retrage suma de bani din bancomat void RefillCashAmount(); ///introduce 200 de bancnote de fiecare tip bool AddCash(int,int); ///introduce un anumit numar de bancnote const int* getBanknotesValues(); ///returneaza adresa unui tablou care contine valorile bancnotelor int* getBanknotesNr(); ///retunrneaza adresa unui tablou care contine numarul bancnotelor de fiecare tip din bancomat void saveValues(); ///salveaza in fisier modificarile legate de numarul bancnotelor int NrBanknotes(int); ///returneaza numarul de bancnote extrase de un anumit tip(tipul 1-10, 2-50...); void RefillCashAmount(int, int); int getBanknotesNrATM(int); }; #endif // CASH_DISPENSER_H_INCLUDED
2ade62b5a1f45df13f523cedf9e8fdec967c5fc9
8a40b7b049e901059cb31a757d49e8f92f4dc1fe
/cxx_pubsub/LibKN/include/LibKN/OfflineQ.h
ea017b45442192786e5827f8b9c7b1b0aad7f22a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
gburd/mod_pubsub
9c65a53cd04f9ab77306c3c49fe2aeb14e0c282a
9abcdb07b02b7979bf4538ac8047783100ecb7bc
refs/heads/master
2021-05-26T18:10:07.142318
2004-09-26T19:43:56
2004-09-26T19:43:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,166
h
OfflineQ.h
/* Copyright 2000-2004 KnowNow, Inc. All rights reserved. @KNOWNOW_LICENSE_START@ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the KnowNow, Inc., nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @KNOWNOW_LICENSE_END@ */ #if !defined(LIBKN_OFFLINEQ_H) #define LIBKN_OFFLINEQ_H #include <LibKN\Defs.h> #include <LibKN\IOfflineQueue.h> class OfflineQueue : public IOfflineQueue { typedef queue<string> Container; friend class Connector; public: OfflineQueue(); ~OfflineQueue(); bool GetQueueing(); void SetQueueing(bool on); bool SaveQueue(const wstring& filename); bool LoadQueue(const wstring& filename); bool Flush(); bool Clear(); bool HasItems(); private: void Add(const string& data); bool FlushImp(Connector* c); private: bool m_On; Container m_Queue; private: OfflineQueue& operator=(const OfflineQueue& rhs); }; #endif
219811fc423287977dee1fd2fa5333ce7d8c29be
c7952699f6f980e1845fa46bb30e0cdac4e6b8ae
/Classes/Player.h
158efd9ba32a50e06e2b529b316e0658859a3b9d
[]
no_license
Ghardian/CastingSpells
a254260f4fa4f653a3e9d45d98e322d5e1ccc6f0
eb28b1dc7f238df92157c568eabbf6813f250711
refs/heads/master
2021-01-10T17:31:19.284017
2016-01-13T17:48:15
2016-01-13T17:48:15
44,616,969
0
0
null
null
null
null
UTF-8
C++
false
false
201
h
Player.h
#ifndef _PLAYER_H_ #define _PLAYER_H_ #include "Wizard.h" #include <string> namespace CastingSpells { class Player: public Wizard { public: void TrySpell(std::string spellname); }; } #endif
e4c9b6e6b5662d5e26c79ec31f975c86d3c0e5eb
911e1d7596af7d8196f609b0e2023f98961260de
/baekjoon/C++/1021.cpp
ef840579ea249762fe341b4008d8e5d6cd015fd9
[]
no_license
not-over-yet/algorithms
001df8939e67a725f95170261e3c47065ab90157
221d2eb07ffd47e44219647d1120d450307c32b5
refs/heads/master
2022-11-10T11:10:47.181615
2020-06-25T08:48:09
2020-06-25T08:48:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,598
cpp
1021.cpp
#include <iostream> #include <vector> #include <deque> using namespace std; int main(void) { ios::sync_with_stdio(0); cin.tie(0); deque<int> dq; vector<int> find; int n, f, s = 0; cin >> n >> f; for (int i = 0; i < n; i++) dq.push_back(0); for (int i = 0, buf; i < f; i++) { cin >> buf; find.push_back(buf - 1); } int p = 0; while (p != find.size()) { int l = find[p++]; int size = dq.size(), d; int test = size % 2 == 0 ? size / 2 - 1 : size / 2; if (l > test) { d = size - l; for (int i = 0; i < d; i++) { dq.push_front(dq.back()); dq.pop_back(); for (int j = p; j < find.size(); j++) if (find[j] + 1 > dq.size() - 1) find[j] = 0; else find[j]++; } dq.pop_front(); for (int j = p; j < find.size(); j++) find[j]--; s += d; } else { d = l; for (int i = 0; i < d; i++) { dq.push_back(dq.front()); dq.pop_front(); for (int j = p; j < find.size(); j++) if (find[j] - 1 < 0) find[j] = dq.size() - 1; else find[j]--; } dq.pop_front(); for (int j = p; j < find.size(); j++) find[j]--; s += d; } } cout << s; return 0; }
b16990df0b5f36356c1108f5cb5efd99380bb17c
e070c2c76bee2d4db180553083b896ce7da83f31
/DwarfPlayerState.h
3fef0575d2275afdfdd3c36bfd125bf633297820
[]
no_license
blockheads/DwarfGame
fe24c525cadd68ee64072676e5deb42570b16516
812e50aa5b37d609d175614bec9da257ba30a105
refs/heads/master
2021-05-12T16:43:06.482079
2018-01-10T23:31:23
2018-01-10T23:31:23
117,023,959
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
h
DwarfPlayerState.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/PlayerState.h" #include "DwarfPlayerState.generated.h" // forward dec class ADworf; /** * State of each player in the game * This is where all of a players dwarves should be kept, and the state for each one. * * So, a giant list of dwarves should be contained here */ UCLASS() class DWARFGAME_API ADwarfPlayerState : public APlayerState { GENERATED_BODY() public: ADwarfPlayerState( const FObjectInitializer& ObjectInitializer ); virtual void Tick( float DeltaSeconds ) override; virtual void BeginPlay( ) override; virtual void GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps ) const override; // Register a Dwarf that the current Client should have control over void RegisterOwnedDwarf( class ADworf* MyDwarf ); // Register a Dwarf as being one that the current Client does not have control over void RegisterOtherDwarf( class ADworf* OtherDwarf ); void RegisterDwarf( class ADworf* Dwarf ); TArray<class ADworf*>& GetDwarves(); private: UPROPERTY( Replicated ) TArray<class ADworf*> Dwarves; };
d25689fce6542471e3b622fb0ec6ad0f0153c162
f3facba9b8fc4e0c34ebb723f70556063488696f
/include/General/mathexpression.h
a1b1626076c1fd2127e06a0850b368becb69c552
[]
no_license
annequeentina/OpendTect
9af07b099d8e738cf0bfefbd4f4c77fb8db9d370
b728451cb04b8a3f3ec0355c5317ef4ebf62cb3f
refs/heads/master
2021-01-02T08:59:20.285242
2017-08-02T11:52:16
2017-08-02T11:52:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,018
h
mathexpression.h
#pragma once /*+ ________________________________________________________________________ (C) dGB Beheer B.V.; (LICENSE) http://opendtect.org/OpendTect_license.txt Author: Kristofer Tingdahl Date: 10-12-1999 ________________________________________________________________________ -*/ #include "generalmod.h" #include "bufstringset.h" #include "uistrings.h" namespace Math { /*! \brief Parsed Math expression. A Expression can be queried about its variables with getNrVariables(), and each variable's name can be queried with getVariableStr( int ). When a calculations should be done, all variables must be set with setVariable( int, double ). Then, the calculation can be done with getValue(). -*/ mExpClass(General) Expression { public: virtual double getValue() const = 0; virtual int nrVariables() const; virtual const char* fullVariableExpression(int) const; virtual void setVariableValue(int,double); // recursive "out" or "this" excluded int nrUniqueVarNames() const { return varnms_.size(); } const char* uniqueVarName( int idx ) const { return varnms_.get(idx).buf(); } int indexOfUnVarName( const char* nm ) const { return varnms_.indexOf( nm ); } int firstOccurVarName(const char*) const; enum VarType { Variable, Constant, Recursive }; VarType getType(int varidx) const; int getConstIdx(int varidx) const; bool isRecursive() const { return isrecursive_; } virtual Expression* clone() const = 0; virtual ~Expression(); const char* type() const; void dump( BufferString& str ) const { doDump(str,0); } protected: Expression(int nrinputs); int nrInputs() const { return inputs_.size(); } bool setInput( int, Expression* ); void copyInput( Expression* target ) const; void addIfOK(const char*); ObjectSet<TypeSet<int> > variableobj_; ObjectSet<TypeSet<int> > variablenr_; ObjectSet<Expression> inputs_; BufferStringSet varnms_; bool isrecursive_; friend class ExpressionParser; void doDump(BufferString&,int nrtabs) const; virtual void dumpSpecifics(BufferString&,int nrtabs) const {} }; /*! \brief Parses a string with a mathematical expression. The expression can consist of constants, variables, operators and standard mathematical functions. A constant can be any number like 3, -5, 3e-5, or pi. Everything that does not start with a digit and is not an operator is treated as a variable. An operator can be either: +, -, *, /, ^, >, <, <=, >=, ==, !=, &&, ||, cond ? true stat : false stat, or |abs| A mathematical function can be either: sin(), cos(), tan(), ln(), log(), exp() or sqrt (). If the parser returns null, it couldn't parse the expression. Then, errmsg_ should contain info. -*/ mExpClass(General) ExpressionParser { mODTextTranslationClass(ExpressionParser) public: ExpressionParser( const char* str=0, bool inputsareseries=true ) : inp_(str), abswarn_(false) , inputsareseries_(inputsareseries) {} void setInput( const char* s ) { inp_ = s; } Expression* parse() const; static BufferString varNameOf(const char* fullvarnm,int* shift=0); static Expression::VarType varTypeOf(const char*); static int constIdxOf(const char*); const uiString errMsg() const { return errmsg_; } bool foundOldAbs() const { return abswarn_; } uiString sParse2ArgStr() const { return tr(" function takes 2 arguments"); } protected: BufferString inp_; const bool inputsareseries_; mutable uiString errmsg_; mutable bool abswarn_; Expression* parse(const char*) const; bool findOuterParens(char*,int,Expression*&) const; bool findOuterAbs(char*,int,Expression*&) const; bool findQMarkOper(char*,int,Expression*&) const; bool findAndOrOr(char*,int,Expression*&) const; bool findInequality(char*,int,Expression*&) const; bool findPlusAndMinus(char*,int,Expression*&) const; bool findOtherOper(BufferString&,int,Expression*&) const; bool findVariable(char*,int,Expression*&) const; bool findMathFunction(BufferString&,int, Expression*&) const; bool findStatsFunction(BufferString&,int, Expression*&) const; }; /*! \brief Expression desc to build UI. */ mExpClass(General) ExpressionOperatorDesc { public: ExpressionOperatorDesc( const char* s, const char* d, bool isop, int n ) : symbol_(s), desc_(d) , isoperator_(isop), nrargs_(n) {} const char* symbol_; // can have spaces, e.g. "? :" const char* desc_; bool isoperator_; //!< if not, function int nrargs_; //!< 2 for normal operators }; /*! \brief Group of similar expression descs. */ mExpClass(General) ExpressionOperatorDescGroup { public: BufferString name_; ManagedObjectSet<ExpressionOperatorDesc> opers_; static const ObjectSet<const ExpressionOperatorDescGroup>& supported(); }; } // namespace Math
c9dc376b54414818f9a9636ecab35cdbcf92fef8
fa659fbb3ae62b3d16c551a6499776c2ec75e017
/Object-oriented programming/c++ labs/lab7/lab7-1/main.cpp
a3074090d465aa7b89cf45a5b56d57eb07f788b2
[]
no_license
stepanplaunov/bmstu-ics9
fe5683371a7806154c735085b075ba94132afd05
d3b1294626512fa0faf347c14856c65d7fa663d6
refs/heads/master
2023-03-16T03:32:06.492608
2020-09-17T08:54:09
2020-09-17T08:54:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
main.cpp
#include <iostream> #include "declaration.h" std::ostream& operator<< (std::ostream& os, Matrix& matr){ for (int i=0; i<matr.m; i++) for (int j=0; j<matr.n; j++){ os << matr[i][j].numerator << "/"; os << matr[i][j].denominator << std::endl; } return os; } int main() { int n, m, a, b; std::cin >> n >> m; Matrix matrix(n, m); for (int i=0; i<m; i++) for (int j=0; j<n; j++){ std::cin >> a; std::cin >> b; matrix[i][j] = *new Fractions(a,b); } std::cout << matrix; //Matrix::get_num_of_lines(matrix); //Matrix::get_num_of_columns(matrix); return 0; }
5f9df55d87c48df59d52fd1c216979e6dfaf1777
ee1a1eb207a53de1e744380e1480e8744542645f
/gui/checkbox.cpp
0a5fb3ed73aeb07e36b9ea84fc744fbc4157ad5a
[]
no_license
lg6s/game
c4f56fe792095290c198c15e5b0c5e6dea3b450f
269d60bcffcced6a89e5a3a7c1b67431cf19696b
refs/heads/master
2022-02-08T03:13:33.879709
2013-12-07T23:34:02
2013-12-07T23:34:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
checkbox.cpp
#include "checkbox.h" #include "resource.h" CheckBox::CheckBox(Resource &res):Button(res) { state = false; imgCheck = res.pixmap("gui/ckBox"); } void CheckBox::setChecked( bool c ) { if( state!=c ){ //state = c; emitClick(); } } bool CheckBox::isClicked() const { return state; } Tempest::Rect CheckBox::viewRect() const { Tempest::Rect r = Button::viewRect(); int dw = std::min( std::min(20,h()), r.w ); r.w -= dw; r.x += dw; return r; } void CheckBox::paintEvent( Tempest::PaintEvent &e ) { Tempest::Painter p(e); p.setBlendMode( Tempest::alphaBlend ); int y = (h()-imgCheck.h())/2; Button::drawBack( p, Tempest::Rect{0,y, imgCheck.w(), imgCheck.h()} ); Button::drawFrame(p, Tempest::Rect{0,y, imgCheck.w(), imgCheck.h()} ); if( state ){ p.setTexture( imgCheck ); if( isPressed() ) p.drawRect( 2, y+2, imgCheck.w()-4, imgCheck.h()-4, 0, 0, imgCheck.w(), imgCheck.h() ); else p.drawRect( 0, y, imgCheck.w(), imgCheck.h() ); } Button::paintEvent(e); } void CheckBox::emitClick() { state = !state; Button::emitClick(); checked(state); } void CheckBox::drawFrame(Tempest::Painter &) {} void CheckBox::drawBack(Tempest::Painter &) {}
909f116870b11f32cdf5f6b3b57751203157e539
f2400ecd988133667f4d2f4ce76e88d078448720
/platform/OSP/BundleAdmin/src/BundleInfoHandler.h
40cca7ac261f8ab0d635f2630f4e23f9931b91e0
[ "Apache-2.0" ]
permissive
jacklicn/macchina.io
29b2daf8fc093ef54cc60fbb5473c3df75024332
d36d987b46efedc6fb5e2138711cdc2d5c33ffe8
refs/heads/develop
2020-05-02T03:10:26.000459
2020-02-29T18:11:23
2020-02-29T18:11:23
50,550,172
1
0
null
2016-03-14T07:02:40
2016-01-28T02:59:52
C++
UTF-8
C++
false
false
1,223
h
BundleInfoHandler.h
// // BundleInfoHandler.h // // Copyright (c) 2007-2014, Applied Informatics Software Engineering GmbH. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // #ifndef BundleAdmin_BundleInfoHandler_INCLUDED #define BundleAdmin_BundleInfoHandler_INCLUDED #include "RequestHandler.h" #include <vector> class BundleInfoHandler: public RequestHandler /// The handler for the bundle information page. { public: BundleInfoHandler(Poco::OSP::BundleContext::Ptr pContext); /// Creates the BundleInfoHandler. ~BundleInfoHandler(); /// Destroys the BundleInfoHandler. void run(); protected: using BundleVec = std::vector<Poco::OSP::Bundle::Ptr>; void dependencies(Poco::OSP::Bundle::Ptr pBundle); void modules(Poco::OSP::Bundle::Ptr pBundle); void provided(Poco::OSP::Bundle::Ptr pBundle); void actions(Poco::OSP::Bundle::Ptr pBundle); bool performAction(Poco::OSP::Bundle::Ptr pBundle, const std::string& action); void confirmUninstall(Poco::OSP::Bundle::Ptr pBundle); void confirmStop(Poco::OSP::Bundle::Ptr pBundle, const BundleVec& dependingBundles); void dependingBundles(Poco::OSP::Bundle::Ptr pBundle, BundleVec& dependingBundles); }; #endif // BundleAdmin_BundleInfoHandler_INCLUDED