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
57bfa6c6ec329c3cd3c8e26cf8b2fae788518c3f
b62dbabb72f3e6a8ad5d7831f7a8e836962c820d
/HelicityLikelihoodDiscriminant/HelicityLikelihoodDiscriminant.cc
33fa63f35735b44616e5b1c15c6ee411ebf26d0f
[]
no_license
amarini/pandolf
53465357b74a300f66a8dd0107e399c53ac06e22
d0820d62c922e00a8e02ea46da3765180b2682c9
refs/heads/master
2016-09-10T09:05:53.910922
2013-07-05T15:29:01
2013-07-05T15:29:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,940
cc
HelicityLikelihoodDiscriminant.cc
#include "HelicityLikelihoodDiscriminant.h" //using namespace RooFit; HelicityLikelihoodDiscriminant::HelicityLikelihoodDiscriminant(): mzz(0.0), costheta1( 0.0 ), costheta2( 0.0 ), costhetastar(0.0 ), phi( 0.0 ), phistar1( 0.0 ) { parfilename_="./ParametersPDF.txt"; // NVARS=6; initBkgdPDFs(); // cout<<" Background -> OK!"<<flush; initSignalPDFs(); // cout<<"\tSignal->OK!"<<endl; }//end constructor HelicityLikelihoodDiscriminant::~HelicityLikelihoodDiscriminant(){ delete background; delete signal; // } void HelicityLikelihoodDiscriminant::initBkgdPDFs(){ //------------------ parameters for Bkg PDF ------------------------- //===================== cos theta 1 ==================== bkgd_h1_acca0_=-1.0; bkgd_h1_acca2_=-1.0; bkgd_h1_acca4_=-1.0; //===================== cos theta 2 =================== bkgd_h2_acca0_=0.0; bkgd_h2_acca2_=0.0; bkgd_h2_acca4_=0.0; bkgd_h2_g_=0.0; bkgd_h2_cutOff_=0.0; //===================== cos theta * ================== bkgd_hs_para2_=0.0; bkgd_hs_para4_=0.0; //===================== phi ========================= bkgd_p_acca0_=-1.0; bkgd_p_acca1_=-1.0; bkgd_p_acca2_=-1.0; //===================== phi1* ======================= bkgd_p1_acca0_=-1.0; bkgd_p1_acca1_=-1.0; bkgd_p1_acca2_=-1.0; setBkgdParameters(); background = new RooBkgd2L2JV2("background","background",costheta1,costheta2, costhetastar,phi,phistar1,mzz, bkgd_h1_acca0_, bkgd_h1_acca2_, bkgd_h1_acca4_, bkgd_h2_acca0_, bkgd_h2_acca2_, bkgd_h2_acca4_, bkgd_h2_g_, bkgd_h2_cutOff_, bkgd_hs_para2_, bkgd_hs_para4_, bkgd_p_acca0_, bkgd_p_acca1_, bkgd_p_acca2_, bkgd_p1_acca0_, bkgd_p1_acca1_, bkgd_p1_acca2_); }//end initBkgdPDFs void HelicityLikelihoodDiscriminant::initSignalPDFs(){ sig_fppVal_= 0.0 ; sig_fmmVal_= 0.0 ; sig_fpmVal_= 0.0 ; sig_fp0Val_= 0.0 ; sig_f0mVal_= 0.0 ; sig_phippVal_= 0.0 ; sig_phimmVal_= 0.0 ; sig_phipmVal_= 0.0 ; sig_phip0Val_= 0.0 ; sig_phi0mVal_= 0.0 ; sig_fz1Val_= 0.0 ; sig_fz2Val_= 0.0 ; sig_R1Val_= 0.0 ; sig_R2Val_= 0.0 ; sig_para2_=0.0; sig_para4_=0.0; sig_acca0_=-999; sig_acca1_=-999 ; sig_acca2_= -999; sig_a2_= -999; sig_a4_= -999; sig_b2_= -999; sig_b4_= -999; sig_N_= -999; sig_g_= 0.0; sig_cutOff_= 0.0; setSignalParameters(); signal=new RooSpinZero5DV2("signal","signal",costheta1,costheta2, costhetastar,phi, phistar1,mzz, sig_fppVal_, sig_fmmVal_, sig_fpmVal_, sig_fp0Val_, sig_f0mVal_, sig_phippVal_, sig_phimmVal_, sig_phipmVal_, sig_phip0Val_, sig_phi0mVal_, sig_fz1Val_, sig_fz2Val_, sig_R1Val_, sig_R2Val_, sig_para2_, sig_para4_, sig_acca0_, sig_acca1_, sig_acca2_, sig_a2_, sig_a4_, sig_cutOff_, sig_g_, sig_b2_, sig_b4_, sig_N_); }//end initSignalPDFs void HelicityLikelihoodDiscriminant::init(){ setSignalParameters(); setBkgdParameters(); }//end init() void HelicityLikelihoodDiscriminant::setParamFile(string myfilename){ parfilename_=myfilename; }//end setParamFile double HelicityLikelihoodDiscriminant::getSignalProbability(){ double sigL=-1.0; sigL=signal->evaluate(); return sigL; } double HelicityLikelihoodDiscriminant::getBkgdProbability(){ double bkgdL=-1.0; bkgdL=background->evaluate(); return bkgdL; } void HelicityLikelihoodDiscriminant::setMeasurables(double newmzz,double newcostheta1,double newcostheta2,double newcosthetastar, double newphi, double newphistar1){ vector<double> newVar; newVar.push_back(newcostheta1); newVar.push_back(newcostheta2); newVar.push_back(newcosthetastar); newVar.push_back(newphi); newVar.push_back(newphistar1); newVar.push_back(newmzz); signal->setVars(newVar); signal->SetAcceptanceParameters(); background->setVars(newVar); background->SetParameters(); } void HelicityLikelihoodDiscriminant::setMeasurables(vector<double> myvars){ // if(int(myvars.size())<NVARS){ cout<<"ERROR in HelicityLikelihoodDiscriminant::setRooVar ! Not enough values to set all RooRealVars: "<<myvars.size()<<endl; return; } costheta1=myvars.at(0); costheta2=myvars.at(1); costhetastar=myvars.at(2); phi=myvars.at(3); phistar1=myvars.at(4); mzz=myvars.at(5); signal->setVars(myvars); signal->SetAcceptanceParameters(); background->setVars(myvars); background->SetParameters(); } void HelicityLikelihoodDiscriminant::setMeasurables(HelicityAngles ha){ costheta1=ha.helCosTheta1; costheta2=ha.helCosTheta2; costhetastar=ha.helCosThetaStar; phi=ha.helPhi; phistar1=ha.helPhi1; mzz=ha.mzz; signal->setVars(costheta1,costheta2,costhetastar,phi,phistar1,mzz); signal->SetAcceptanceParameters(); background->setVars(costheta1,costheta2, costhetastar,phi, phistar1,mzz); background->SetParameters(); } void HelicityLikelihoodDiscriminant::setBkgdParameters(){ bkgd_p_acca0_=-18.1027; bkgd_p_acca1_=1.31479; bkgd_p_acca2_=108.14; bkgd_p1_acca0_=-18.1027; bkgd_p1_acca1_=1.31479; bkgd_p1_acca2_=108.14; bkgd_hs_para2_=-2.40606; bkgd_hs_para4_=1.64613; bkgd_h2_acca0_=.780741; bkgd_h2_acca2_=.288787; bkgd_h2_acca4_=2.54104; bkgd_h2_g_=.0212292; bkgd_h2_cutOff_=.867301; bkgd_h1_acca0_=2.44216; bkgd_h1_acca2_=-1.74955; bkgd_h1_acca4_=1.57681; }//end initBkgdParameters ////////////////STOPPED HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 void HelicityLikelihoodDiscriminant::setSignalParameters(){ sig_fppVal_=.005; sig_fmmVal_=.005; sig_fpmVal_=0; sig_fp0Val_=0; sig_f0mVal_=0; sig_phippVal_=3.14159; sig_phimmVal_=3.14159; sig_phipmVal_=0; sig_phip0Val_=0; sig_phi0mVal_=0; sig_fz1Val_=.4; sig_fz2Val_=.4; sig_R1Val_=.15; sig_R2Val_=0; sig_para2_=-.475; sig_para4_=-.430; sig_acca0_=173.742; sig_acca1_=-1.41212; sig_acca2_=-25.4878; sig_a2_=.0303; sig_a4_=-1.07; sig_b2_=.043; sig_b4_=-1.02; sig_N_=8; sig_g_=.05; sig_cutOff_=.813; }//end initSignalParameters void HelicityLikelihoodDiscriminant::setParametersFromFile(){ ifstream parfile(parfilename_.c_str(),ios::in); if( !parfile ) { cerr << "\nCouldn´t open parameter file" << endl<<endl; return; } bool readval=false; vector<double> h1bkgd_par, h2bkgd_par, cstarbkgd_par,phi1bkgd_par; vector<double> signal_par; while(!parfile.eof()){ string label; string tmplabel; float tmpval; if(!readval){ parfile>>label; readval = true; continue; } else parfile>>tmpval; /* if(tmplabel=="H1BKGDPARS"){ } else if(tmplabel=="H2BKGDPARS"){ } else if(tmplabel=="CSTARBKGDPARS"){ } else if(tmplabel=="PHI1BKGDPARS"){ } else if(tmplabel=="SIGNALPARS"){ } else{ cout<<" HelicityLikelihoodDiscriminant::setParametersFromFile(): Unrecognized string in LD parameter file: "<<label.c_str()<<" . Ignoring it."<<endl; } */ }//end while loop // signal->setParams(signal_par); // h1Background->setParams(h1bkgd_par); // h2Background->setParams(h2bkgd_par); // cStarBackground->setParams(cstarbkgd_par); // tPhiBackground->setParams(tPhibkgd_par); } HelicityLikelihoodDiscriminant::HelicityAngles HelicityLikelihoodDiscriminant::computeHelicityAngles(TLorentzVector leptMinus, TLorentzVector leptPlus, TLorentzVector jet1, TLorentzVector jet2 ) { HelicityLikelihoodDiscriminant::HelicityAngles returnAngles; TLorentzVector Zll = leptPlus + leptMinus; TLorentzVector Zjj = jet1 + jet2; TLorentzVector Higgs = Zjj + Zll; // define lept1 as negatively charged lepton: TLorentzVector lept1 = leptMinus; TLorentzVector lept2 = leptPlus; // no charge for jets (well, not really) // so choose jet with positive scalar product with Zjj // in its restframe: TLorentzVector jet1_Zjjstar_tmp(jet1); jet1_Zjjstar_tmp.Boost(-Zjj.BoostVector()); if( jet1_Zjjstar_tmp.Phi()<0. ) { //swap them TLorentzVector jet1_tmp(jet1); TLorentzVector jet2_tmp(jet2); jet1 = jet2_tmp; jet2 = jet1_tmp; } // BOOSTS: // boosts in Higgs CoM frame: TLorentzVector lept1_Hstar(lept1); lept1_Hstar.Boost(-Higgs.BoostVector()); TLorentzVector lept2_Hstar(lept2); lept2_Hstar.Boost(-Higgs.BoostVector()); TLorentzVector jet1_Hstar(jet1); jet1_Hstar.Boost(-Higgs.BoostVector()); TLorentzVector jet2_Hstar(jet2); jet2_Hstar.Boost(-Higgs.BoostVector()); TLorentzVector Zll_Hstar(Zll); Zll_Hstar.Boost(-Higgs.BoostVector()); TLorentzVector Zjj_Hstar(Zjj); Zjj_Hstar.Boost(-Higgs.BoostVector()); // boosts in Zll CoM frame: TLorentzVector lept1_Zllstar(lept1); lept1_Zllstar.Boost(-Zll.BoostVector()); TLorentzVector H_Zllstar(Higgs); H_Zllstar.Boost(-Zll.BoostVector()); // boosts in Zjj CoM frame: TLorentzVector jet1_Zjjstar(jet1); jet1_Zjjstar.Boost(-Zjj.BoostVector()); TLorentzVector H_Zjjstar(Higgs); H_Zjjstar.Boost(-Zjj.BoostVector()); returnAngles.helCosThetaStar = Zll_Hstar.CosTheta(); TVector3 v_pbeamLAB( 0.0, 0.0, 1.0 ); //cross prod beam x Zll TVector3 v_1 = (v_pbeamLAB.Cross( (Zll_Hstar.Vect()).Unit()) ).Unit();//versor normal to z-z' plane //v_2 = cross prod l1 x l2 = versor normal to Zll decay plane // careful to the order: L1, the z-axis and Z->ll make a right-handed (non-orthogonal) frame (xyz); at the end we want the angle btw x and y TVector3 v_2((Zll_Hstar.Vect().Cross(lept1_Hstar.Vect().Unit())).Unit()); //v_3 = similar to v_2, BUT //now, if we want a right-handed set of Unit-vectors, keeping the same direction of the z-axis //we must swap the direction of one of the other two vectors of the Z bosons. //Keeping the same direction of the z-axis //means measuring phiZll and phiZjj w.r.t. to the same v_1 vector (i.e. w.r.t. the same z'-Zll plane) TVector3 v_3(((-1.0*Zjj_Hstar.Vect()).Cross(jet1_Hstar.Vect().Unit())).Unit()) ; //in other terms: we can define v_3 as above and then do the crss prod with v_1 //or define v_3 in a way consistent with v_2 and then do the cross product with a newly defined //Unit vector v_4 = (v_pbeamLAB.Cross( (ZjjboostedX->momentum()).Unit()) ).Unit();//versor normal to z-Zjj plane // helphiZll: float phiZll = fabs( acos(v_1.Dot(v_2)) ); if(v_pbeamLAB.Dot(v_2)>0.0)phiZll=-1.0*phiZll; else phiZll=+1.0*phiZll; // helphiZjj: float phiZjj = fabs( acos(v_1.Dot(v_3)) ); if(v_pbeamLAB.Dot(v_3)>0.0)phiZjj=+1.0*phiZjj; else phiZjj=-1.0*phiZjj; float phi1 = phiZll; //phi float phi = fabs( acos(v_2.Dot(v_3)) );//two-fold ambiguity when doing the acos + pi ambiguity from sign of v_3 if(lept1_Hstar.Vect().Dot(v_3)>0.0)phi= +1.0 * phi; else phi= -1.0 * phi; returnAngles.helPhi1 = phi1; returnAngles.helPhi = phi; returnAngles.helCosTheta1 = (-1.0*(lept1_Zllstar.X()* H_Zllstar.X()+ lept1_Zllstar.Y()* H_Zllstar.Y()+ lept1_Zllstar.Z()* H_Zllstar.Z())/ (lept1_Zllstar.Vect().Mag()* H_Zllstar.Vect().Mag()) ); returnAngles.helCosTheta2 = fabs( (jet1_Zjjstar.X()* H_Zjjstar.X()+ jet1_Zjjstar.Y()* H_Zjjstar.Y()+ jet1_Zjjstar.Z()* H_Zjjstar.Z())/ (jet1_Zjjstar.Vect().Mag()* H_Zjjstar.Vect().Mag()) ); returnAngles.mzz = Higgs.M(); return returnAngles; }
4f34af6b991df50430e791925acf15a39a36555f
d0c97d1c64bbdf6b9a231ad5b0bdb87d34182815
/include/data/net/session.hpp
8293f4b14c934a0de6c97a3ee87e3ef3ca3f46c6
[]
no_license
DanielKrawisz/data
2c7130d25fbb2b56ee249c8ca3205bae349f305a
718d38bb17695547420f922471b8f1459ae4bcd7
refs/heads/production
2023-08-09T15:25:25.913713
2023-07-28T23:41:49
2023-07-29T00:29:14
164,427,457
10
9
null
2023-07-29T00:29:15
2019-01-07T12:10:39
C++
UTF-8
C++
false
false
1,029
hpp
session.hpp
// Copyright (c) 2021 Daniel Krawisz // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef DATA_NET_SESSION #define DATA_NET_SESSION #include <data/types.hpp> namespace data::net { // A basic session type. Not every session // works exactly the same way, so // you are not required to use this. template <typename message_out> struct session { virtual ~session () {} virtual void send (message_out) = 0; virtual bool closed () = 0; virtual void close () = 0; }; using close_handler = function<void ()>; // interaction describes an interaction with a remote peer. template <typename in, typename out = in> using interaction = function<handler<in> (ptr<session<out>>)>; // a function type that would open a new session. template <typename in, typename out = in> using open = function<void (close_handler, interaction<in, out>)>; } #endif
6af045eb36b28e41ee91f41d4dddf1880bf9deba
445b355e3d407564073a4c335ca0e5f864ef0c2b
/AOList.h
44c1f75dd97509d877a40cd0e9cdbe1add74138c
[]
no_license
RomanHale/cs260-wk4
3730a5e2c11b9efa2d24fed2293c0fe538fa0a2e
ccd9c36f03409229c350e08a2379bb48b19fa2a3
refs/heads/main
2023-02-23T18:41:30.496997
2021-02-01T19:09:45
2021-02-01T19:09:45
335,054,964
0
0
null
null
null
null
UTF-8
C++
false
false
193
h
AOList.h
#include "AOList_node.h" class AOList { private: node *top; public: AOList(); void add(int new_value, int position); int remove(int position); int peek(int position); };
caa52e09bf788dd6e79000a7df821ed7047c7ff2
2e5c33f159adf150b67ef1b19f14607d2d11f1fe
/include/aeongames/Texture.h
edace0573df779895d0b5dbb2073b5050ac50d05
[ "Apache-2.0" ]
permissive
AeonGames/AeonEngine
29fedf6dcba2548e594ec067f99c834d8f975f27
2cdbf540227c1c4bbf4d893145627564dbb2a8a3
refs/heads/master
2023-07-22T01:35:42.972067
2023-07-19T01:47:20
2023-07-19T01:47:20
54,066,866
17
4
null
null
null
null
UTF-8
C++
false
false
2,791
h
Texture.h
/* Copyright (C) 2016-2021 Rodrigo Jose Hernandez Cordoba Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef AEONGAMES_TEXTURE_H #define AEONGAMES_TEXTURE_H #include <cstdint> #include <string> #include <functional> #include <vector> #include "aeongames/Platform.h" #include "aeongames/Resource.h" namespace AeonGames { class Texture : public Resource { public: enum class Format : uint32_t { Unknown = 0, RGB, RGBA, BGRA }; enum class Type : uint32_t { Unknown = 0, UNSIGNED_BYTE, UNSIGNED_SHORT, UNSIGNED_INT_8_8_8_8_REV }; DLL ~Texture(); DLL void Resize ( uint32_t aWidth, uint32_t aHeight, const uint8_t* aPixels = nullptr, Format aFormat = Format::Unknown, Type aType = Type::Unknown ); DLL void WritePixels ( int32_t aXOffset, int32_t aYOffset, uint32_t aWidth, uint32_t aHeight, Format aFormat, Type aType, const uint8_t* aPixels ); DLL void LoadFromMemory ( const void* aBuffer, size_t aBufferSize ) final; DLL void Unload() final; DLL uint32_t GetWidth() const; DLL uint32_t GetHeight() const; DLL Format GetFormat() const; DLL Type GetType() const; DLL const std::vector<uint8_t>& GetPixels() const; private: std::vector<uint8_t> mPixels{}; uint32_t mWidth{}; uint32_t mHeight{}; Format mFormat{}; Type mType{}; }; /**@name Decoder Functions */ /*@{*/ /***/ DLL bool RegisterImageDecoder ( const std::string& aMagick, const std::function < bool ( Texture&, size_t, const void* ) > & aDecoder ); /***/ DLL bool UnregisterImageDecoder ( const std::string& aMagick ); /***/ DLL bool DecodeImage ( Texture& aTexture, const void* aBuffer, size_t aBufferSize ); /***/ DLL bool DecodeImage ( Texture& aTexture, const std::string& aFileName ); /*@}*/ static constexpr size_t GetPixelSize ( Texture::Format aFormat, Texture::Type aType ) { return ( aFormat == Texture::Format::Unknown || aType == Texture::Type::Unknown ) ? 0 : ( ( aFormat == Texture::Format::RGB ) ? 3 : 4 ) * ( ( aType == Texture::Type::UNSIGNED_BYTE ) ? 1 : 2 ); } } #endif
c9bafe6482007b0085c65816621171c613ab60f2
34698d07825471010a55b71059287ca428880d6d
/OSHW/OSHW/소스.cpp
de557346a06bdfb29412195c68cb6eda2bd1bf9c
[]
no_license
jychoi130/Problem_Solve_project
890429fabb5ccfd9704b5718df4dddb5924e7eb0
ed6ebf26926eaeb2e9f32de0db284ce1ea25ff96
refs/heads/main
2023-03-24T22:11:05.189795
2021-03-24T04:28:55
2021-03-24T04:28:55
350,942,574
1
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
소스.cpp
#include<iostream> using namespace std; int main() { int prime,check=1; cin >> prime; cout << "prime: 2"; for (int i = 3; i < prime; i++) { for (int j = 2; j <i; j++) { check = 1; if (i%j == 0) { check = 0; break; } } if (check = 1) cout << " " << i; } cout << endl; }
acf9289da249229f9c73d89c41750e84653f95cc
2b9a69bb87049f15460547c9a140d532a00747ad
/user/sniff_thread.h
4228116d193a9fded71e78dee4eb813410d11fca
[]
no_license
zhang35/VMM-Monitor
ed052c7befe2c9bf734781cbe34a14d3a841df4a
6f6024b8af0394410f170f078566bf37e2a9ad5b
refs/heads/master
2020-04-10T00:04:55.907708
2018-12-06T13:03:11
2018-12-06T13:03:11
160,675,155
5
0
null
null
null
null
UTF-8
C++
false
false
338
h
sniff_thread.h
#ifndef SNIFF_THREAD_H #define SNIFF_THREAD_H #include <QThread> #include "my_packet.h" class sniff_thread : public QThread { Q_OBJECT public: explicit sniff_thread(QObject *parent = 0); void run(); void stop(); volatile bool stoprun; signals: public slots: }; #endif // SNIFF_THREAD_H
e1e0b32b72de08a2d7133f7492778d20ea167790
9e409a0a4333c376059ef795a336ef580c1ded20
/codeforces/contest/1159/a/54093567.cpp
dad5ba551cd20d2645ca935c85febdd0852069b5
[]
no_license
hobby10/problems-solution
569d4f52f7fe5d437c91041f5f6b9247c70915b1
f35fb13a34f32b789e707b854eb0778c2c3c8484
refs/heads/master
2023-06-14T13:21:38.941953
2021-07-07T13:42:04
2021-07-07T13:42:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
54093567.cpp
#include <bits/stdc++.h> #define ll long long using namespace std; const int N = 1e2 + 9; void debug() { ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); cout << fixed << setprecision(0); #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); #endif } char arr[N]; int main() { debug(); int n; cin >> n; for (int i = 1; i <= n; ++i) { cin >> arr[i]; } bool can = 0; for (int i = 0; i <= n; ++i) { int total = i; can = 1; for (int j = 1; j <= n; ++j) { if(arr[j] == '-') --total; else ++total; if(total < 0) { can = 0; break; } } if(can) { cout << total; return 0; } } return 0; }
7ad7355bf5698f6e01ed327029144abdb52e8ff9
2dde1215b3c5b13d2c1e4bca05920cfe9d1d2060
/15/ex5.cpp
b5e06c6b85205e7ab10b917762dfff6966e039ee
[]
no_license
rengdjim/Programming-Principles-and-Practice-Using-C-
a9938a84197d0d54fc0e2072e52791f7b9513f52
d60c494318306aa56e6560125d4ab69f96a27f4f
refs/heads/master
2023-03-16T05:48:35.347966
2019-01-14T02:15:47
2019-01-14T02:15:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
ex5.cpp
/* Chapter 15 Exercise 5 “Animate” (as in §15.5) the series 1–1/3+1/5–1/7+1/9–1/11+ . . . . It is known as Leibniz’s series and converges to pi/4. */ #include "../14/14.h" #include "15.h" using namespace Graph_lib; constexpr int x_size = 800; constexpr int y_size = 600; constexpr double r1 = 0; constexpr double r2 = 100; constexpr Point orig {x_size/2,y_size/2}; constexpr int numbers = 100; constexpr int xscale = 3; constexpr int yscale = 200; constexpr int xoffset = 25; constexpr int yoffset = 25; double leibniz_series(double t) { return (t > 1) ? ((int(t)%2) ? 1.0/(t*2-1) : -1.0/(t*2-1)) + leibniz_series(t-1) : 1;} int main() { Simple_window win {Point {100,100}, x_size, y_size, "Leibniz’s series"}; Axis x_axis (Axis::x, Point{xoffset,y_size/2},x_size-2*xoffset,(x_size-2*xoffset)/xscale, "x axis"); x_axis.set_color(Color::red); win.attach(x_axis); Axis y_axis (Axis::y, Point{x_size/2,y_size-yoffset},y_size-2*yoffset,(y_size-2*yoffset)/yscale, "y axis"); y_axis.set_color(Color::red); win.attach(y_axis); for (int i = 1; i < r2; ++i) { Funct f1 (leibniz_series, r1, i, orig, i, xscale, yscale); win.attach(f1); win.wait_for_button(); } }
15263c0090f3ca66c2dd5efd544dffbfa91eaf44
2b80dd12a0a49cb1647d9cbe79f20e659504e5ed
/FluidSimulation/SphContainer.cpp
207c0fe8e8a8bc25961e8340b1ed61a7c8146159
[]
no_license
Banteu/FluidSimulation
6951c891e6c35283f6795cf6465c7e268185cb07
17e997dc5ab86d6425044afa53329f810891b696
refs/heads/master
2021-01-10T19:14:07.284984
2015-04-15T15:33:54
2015-04-15T15:33:54
32,821,993
4
0
null
null
null
null
UTF-8
C++
false
false
9,158
cpp
SphContainer.cpp
#include "SphContainer.h" #include <time.h> float MPI = acos(-1.0); SphContainer::SphContainer(float x, float y, float z, float w, float l, float h) { containerDrawVertex = new vec3[24]; containerDrawIndex = new uint[24]; float dx = x + w / 2; float dxm = x - w / 2; float dy = y + l / 2; float dym = y - l / 2; float dz = z + h / 2; float dzm = z - h / 2; containerDrawVertex[0] = vec3(dxm, dym, dzm); containerDrawVertex[1] = vec3(dx, dym, dzm); containerDrawVertex[2] = vec3(dx, dy, dzm); containerDrawVertex[3] = vec3(dxm, dy, dzm); containerDrawVertex[4] = vec3(dxm, dym, dz); containerDrawVertex[5] = vec3(dxm, dy, dz); containerDrawVertex[6] = vec3(dx, dy, dz); containerDrawVertex[7] = vec3(dx, dym, dz); containerDrawVertex[8] = vec3(dxm, dy, dzm); containerDrawVertex[9] = vec3(dx, dy, dzm); containerDrawVertex[10] = vec3(dx, dy, dz); containerDrawVertex[11] = vec3(dxm, dy, dz); containerDrawVertex[12] = vec3(dxm, dym, dzm); containerDrawVertex[13] = vec3(dxm, dym, dz); containerDrawVertex[14] = vec3(dx, dym, dz); containerDrawVertex[15] = vec3(dx, dym, dzm); containerDrawVertex[16] = vec3(dx, dym, dzm); containerDrawVertex[17] = vec3(dx, dym, dz); containerDrawVertex[18] = vec3(dx, dy, dz); containerDrawVertex[19] = vec3(dx, dy, dzm); containerDrawVertex[20] = vec3(dxm, dym, dzm); containerDrawVertex[21] = vec3(dxm, dy, dzm); containerDrawVertex[22] = vec3(dxm, dy, dz); containerDrawVertex[23] = vec3(dxm, dym, dz); for (int i = 0; i < 24; ++i) { containerDrawIndex[i] = i; } centerX = x; centerY = y; centerZ = z; width = w; length = l; height = h; } void SphContainer::createParticles(particleInfo pInfo) { particleCount = pInfo.particleCount; rest_density = pInfo.fluidDensity; viscosity = pInfo.fluidViscosity; radius = pInfo.activeRadius; pressure_koeff = pInfo.stiffness; r2 = radius * radius; r3 = radius * radius * radius; mass = 4.0f * r3 * rest_density * MPI / 3.0f / 19; float OFFSET = radius * 0.6; particlePosition = new vec3[particleCount]; particleVelocity = new vec4[particleCount]; particleHvelocity = new vec3[particleCount]; particleDensity = new float[particleCount]; particleColor = new vec3[particleCount]; particleIndex = new int[particleCount]; particleZindex = new int[particleCount]; for (int i = 0; i < particleCount; ++i) { particleVelocity[i] = vec4(0,0,0,0); particleHvelocity[i] = vec3(0,0,0); particleDensity[i] = 0; particleIndex[i] = i; particleZindex[i] = 0; particleColor[i] = vec3(1, 1, (rand() % 100) / 500 + 0.05); } vec3 tempPos = vec3(centerX - width / 2 + OFFSET, centerY - length / 2 + OFFSET, centerZ - height / 2 + OFFSET); vec3 addPos = tempPos; int cnt = 0; while(cnt < particleCount) { for(int i = 0; i * i * i < particleCount && cnt < particleCount; ++i) { for(int j = 0; j * j * j < particleCount && cnt < particleCount; ++j) { particlePosition[cnt] = addPos + vec3((rand() % 100) / 1000.0, (rand() % 100) / 1000.0, (rand() % 100) / 1000.0); addPos.x += OFFSET; ++cnt; } addPos.y += OFFSET; addPos.x = tempPos.x; } addPos.z += OFFSET; addPos.y = tempPos.y; } glGenBuffers(1, &particlePositionVBO1); glBindBuffer(GL_ARRAY_BUFFER, particlePositionVBO1); glBufferData(GL_ARRAY_BUFFER, particleCount * sizeof(vec3), particlePosition, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &particleColorVBO); glBindBuffer(GL_ARRAY_BUFFER, particleColorVBO); glBufferData(GL_ARRAY_BUFFER, particleCount * sizeof(vec3), particleColor, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); gpuErrchk( cudaGraphicsGLRegisterBuffer(&cudaPosVbo, particlePositionVBO1, cudaGraphicsMapFlagsWriteDiscard)); gpuErrchk( cudaGraphicsGLRegisterBuffer(&cudaColorResource, particleColorVBO, cudaGraphicsMapFlagsWriteDiscard)); const uint HASH_TABLE_SIZE = 1453021;//prime number; particleBeg = new int[HASH_TABLE_SIZE]; particleEnd = new int[HASH_TABLE_SIZE]; // gpuErrchk( cudaMalloc(&particlePositionGPU, count * sizeof(float) * 3)); gpuErrchk( cudaMalloc(&pData.vel, particleCount * sizeof(float) * 3)); gpuErrchk( cudaMalloc(&pData.posTextured, particleCount * sizeof(float) * 4)); gpuErrchk( cudaMalloc(&pData.accel, particleCount * sizeof(float) * 3)); gpuErrchk( cudaMalloc(&pData.hVel, particleCount * sizeof(float) * 3)); gpuErrchk( cudaMalloc(&pData.dens, particleCount * sizeof(float))); gpuErrchk(cudaMalloc(&pData.zind, particleCount * sizeof(int))); gpuErrchk(cudaMalloc(&pData.pind, particleCount * sizeof(int))); gpuErrchk(cudaMalloc(&pData.hashTableStart, HASH_TABLE_SIZE * sizeof(int))); gpuErrchk(cudaMalloc(&pData.hashTableEnd, HASH_TABLE_SIZE * sizeof(int))); gpuErrchk( cudaMalloc(&pData.tempVel, particleCount * sizeof(float) * 3)); gpuErrchk( cudaMalloc(&pData.temphVel, particleCount * sizeof(float) * 3)); // gpuErrchk(cudaMemcpy(particlePositionGPU, particlePosition, count * sizeof(float) * 3, cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(pData.vel, particleVelocity, particleCount * sizeof(float) * 3, cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(pData.hVel, particleHvelocity, particleCount * sizeof(float) * 3, cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(pData.tempVel, particleVelocity, particleCount * sizeof(float) * 3, cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(pData.temphVel, particleHvelocity, particleCount * sizeof(float) * 3, cudaMemcpyHostToDevice)); // gpuErrchk(cudaMemcpy(pData.dens, particleDensity, particleCount * sizeof(float), cudaMemcpyHostToDevice)); // gpuErrchk(cudaMemcpy(pData.pind, particleIndex, particleCount * sizeof(int), cudaMemcpyHostToDevice)); // gpuErrchk(cudaMemcpy(pData.zind, particleZindex, particleCount * sizeof(int), cudaMemcpyHostToDevice)); pData.gravity.x = 0; pData.gravity.y = 0; pData.gravity.z = -9.8; pData.count = particleCount; pData.mass = mass; pData.r = radius; pData.r2 = r2; pData.rest_pressure = 0; pData.rest_density = rest_density; pData.viscosity = viscosity; pData.pressure_Koeff = pressure_koeff; pData.center.x = centerX; pData.center.y = centerY; pData.center.z = centerZ; pData.sizeContainer.x = width; pData.sizeContainer.y = length; pData.sizeContainer.z = height; pData.gridDimConst = radius * 1.2; pData.maxAcceleration = 1000; pData.wallDamping = 0.1; pData.diffKern = 315.0f / (64.0 * MPI * r3 * r3 * r3); pData.pressKern = 45.0 / (MPI * r3 * r3); pData.viscKern = 45.0 / (MPI * r3 * r3); pData.HASH_TABLE_SIZE = HASH_TABLE_SIZE; bindToTextures(&pData); } float lstTime = 1; forceData frc; void SphContainer::setPower(float power, float rad, vec3 pos, vec3 vel) { frc.coord = make_float3(pos.x, pos.y, pos.z); frc.velocity = make_float3(vel.x, vel.y, vel.z); frc.radius = rad; frc.r2 = rad * rad; frc.power = power; } void SphContainer::computeFluid(float dt) { gpuErrchk( cudaGraphicsMapResources(1, &cudaPosVbo, NULL)); size_t size; gpuErrchk( cudaGraphicsResourceGetMappedPointer((void** )&pData.pos, &size, cudaPosVbo)); gpuErrchk( cudaGraphicsMapResources(1, &cudaColorResource, NULL)); gpuErrchk( cudaGraphicsResourceGetMappedPointer((void** )&pData.color, &size, cudaColorResource)); updateSimData(pData); prepareFluidGPU(pData, dt); updateSimData(pData); solveFluid(pData, dt,frc); // cudaMemcpy(particleZindex, pData.zind, sizeof(int) * particleCount, cudaMemcpyDeviceToHost); // cudaMemcpy(particleIndex, pData.pind, sizeof(int) * particleCount, cudaMemcpyDeviceToHost); gpuErrchk( cudaGraphicsUnmapResources(1, &cudaPosVbo, NULL)); gpuErrchk( cudaGraphicsUnmapResources(1, &cudaColorResource, NULL)); } void SphContainer::drawParticles() { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, particlePositionVBO1); glVertexPointer(3, GL_FLOAT, 0, NULL); glBindBuffer(GL_ARRAY_BUFFER, particleColorVBO); glColorPointer(3, GL_FLOAT, 0, NULL); glDrawArrays(GL_POINTS, 0, pData.count); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); } void SphContainer::drawContainer() { vec3* p = containerDrawVertex; for (int i = 0; i < 6; ++i) { glBegin(GL_LINE_LOOP); glVertex3fv((float*)p++); glVertex3fv((float*)p++); glVertex3fv((float*)p++); glVertex3fv((float*)p++); glEnd(); } } SphContainer::~SphContainer(void) { delete[] containerDrawIndex; delete[] containerDrawVertex; }
77f2d16820a9a43e293263f5ebccd05474c76245
0b69a011c9ffee099841c140be95ed93c704fb07
/problemsets/SPOJ/SPOJ/GNY07A.cpp
bbbae9f67e3106f06eff860c03d32bb03269dd00
[ "Apache-2.0" ]
permissive
juarezpaulino/coderemite
4bd03f4f2780eb6013f07c396ba16aa7dbbceea8
a4649d3f3a89d234457032d14a6646b3af339ac1
refs/heads/main
2023-01-31T11:35:19.779668
2020-12-18T01:33:46
2020-12-18T01:33:46
320,931,351
0
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
GNY07A.cpp
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <iostream> #include <string> #include <cstdio> using namespace std; int main() { int t; cin >> t; for (int i = 1; i <= t; i++) { string S; int M; cin >> M >> S; S.erase(S.begin() + M - 1); printf("%d %s\n", i, S.c_str()); } return 0; }
a7c7dd6bf86a7fcf84f8bd84385e2e73bde97b7d
2b076d99088d1aae905a1cc8597586deb168881a
/compare triplet/comparetriplet.cpp
e823cf53e8642d6cae09c6a5ad3a55acc97e359a
[]
no_license
harryp0/programming
d75876eeceb47c167b52af783c52d425e151a2e3
07ad40712545b4a6d0acad8bf284ae261b1b1155
refs/heads/master
2020-07-21T17:37:29.648921
2019-09-02T16:14:20
2019-09-02T16:14:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
comparetriplet.cpp
#include <bits/stdc++.h> using namespace std; int main() { int i,alice=0,bob=0,num; int a[3],b[3]; for(i=0;i<3;i++) cin>>a[i]; for(i=0;i<3;i++) cin>>b[i]; for(i=0;i<3;i++) { if(a[i]>b[i]) alice=alice+1; else if(a[i]<b[i]) bob=bob+1; else { alice=alice+0; bob=bob+0; } } cout<<alice<<" "<<bob; return 0; }
e5bfb0d0fdac25c5e3f57e2ef59ee317ab9064f7
a8e5517df264ca12e84c377270574a3cc378f0c1
/BOJ/10305/solution.cpp
539f7751bd13a0e692e52ea45c0601e015fab357
[]
no_license
wowoto9772/Hungry-Algorithm
cb94edc0d8a4a3518dd1996feafada9774767ff0
4be3d0e2f07d01e55653c277870d93b73ec917de
refs/heads/master
2021-05-04T23:28:12.443915
2019-08-11T08:11:39
2019-08-11T08:11:39
64,544,872
1
1
null
null
null
null
UTF-8
C++
false
false
815
cpp
solution.cpp
#include <cstdio> using namespace std; int main(){ int t; scanf("%d", &t); while(t--){ int ans = -1, cmp = 0; int l = 1, r = 1; int x, y; int n; scanf("%d", &n); for(int i=1; i<n; i++){ int e; scanf("%d", &e); cmp += e; if(cmp < 0){ l = i+1, r = i+1; cmp = 0; }else{ r++; if(ans < cmp){ ans = cmp; x = l, y = r; }else if(ans == cmp && y-x < r-l){ x = l, y = r; } } } if(ans < 0)printf("no good path"); else{ printf("%d %d", x, y); } printf("\n"); } }
4d24658967d88eb066547324f94e1cd4e0603586
de80b91a12b10bd962b59a89b2badbb83a0193da
/ClientProject/Mof/RatchetNClankCopy/RatchetApplication/Component/Player/PlayerIdleComponent.h
daf08dabedb7699712d97f828bd0ee9c0e070de6
[ "MIT" ]
permissive
OIC-Shinchaemin/RatchetNclank-PrivateCopy
8845eea799b3346646c8c93435c0149e842dede8
e2e646e89ef3c29d474a503f5ca80405c4c676c9
refs/heads/main
2023-08-15T06:36:05.244293
2021-10-08T00:34:48
2021-10-08T00:34:48
350,923,064
0
0
MIT
2021-10-06T11:05:03
2021-03-24T02:35:36
C++
SHIFT_JIS
C++
false
false
2,297
h
PlayerIdleComponent.h
#ifndef RATCHET_COMPONENT_PLAYER_ACTION_PLAYER_IDLE_COMPONENT_H #define RATCHET_COMPONENT_PLAYER_ACTION_PLAYER_IDLE_COMPONENT_H #include "PlayerActionComponent.h" namespace ratchet::component::player { class PlayerComponent; } namespace ratchet::component::player::action { class PlayerIdleComponent : public ::ratchet::component::player::action::PlayerActionComponent { using super = ::ratchet::component::player::action::PlayerActionComponent; private: //! 型機能 std::weak_ptr<ratchet::component::player::PlayerComponent> _type_com; //! 次の状態 std::string _next_state; public: /// <summary> /// コンストラクタ /// </summary> /// <param name="priority"></param> PlayerIdleComponent(int priority); /// <summary> /// コピーコンストラクタ /// </summary> /// <param name="obj"></param> PlayerIdleComponent(const PlayerIdleComponent& obj); /// <summary> /// デストラクタ /// </summary> virtual ~PlayerIdleComponent(); /// <summary> /// ゲッター /// </summary> /// <param name=""></param> /// <returns></returns> virtual std::string GetType(void) const override; /// <summary> /// ゲッター /// </summary> /// <param name=""></param> /// <returns></returns> virtual std::string_view GetStateType(void) const override; /// <summary> /// 初期化 /// </summary> /// <param name=""></param> /// <returns></returns> virtual bool Initialize(void) override; /// <summary> /// 入力 /// </summary> /// <param name=""></param> /// <returns></returns> virtual bool Input(void) override; /// <summary> /// 更新 /// </summary> /// <param name="delta_time">時間</param> /// <returns></returns> virtual bool Update(float delta_time) override; /// <summary> /// 複製 /// </summary> /// <param name=""></param> /// <returns></returns> virtual std::shared_ptr<ratchet::component::Component> Clone(void) override; /// <summary> /// 開始 /// </summary> /// <param name=""></param> /// <returns>成功</returns> virtual bool Start(void) override; }; } #endif // !RATCHET_COMPONENT_PLAYER_ACTION_PLAYER_IDLE_COMPONENT_H
cfb131919fe184e43bbd914df27bacea54c33e89
969a3f74a957b7fa3685ac5ae5f94ac225af9522
/Common/DataModel/Testing/Cxx/TestInformationDataObjectKey.cxx
712bceaf93016caceac2c259ef1e97edc3f7aeb5
[ "BSD-3-Clause" ]
permissive
gview/VTK
61adbce5b78e0fdf8069e2384c0fc1899a723df5
17c664f1c3bdb84997aa2c9bfdf51ba77171672e
refs/heads/master
2023-06-01T11:56:23.857210
2023-05-30T04:01:23
2023-05-30T04:01:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,510
cxx
TestInformationDataObjectKey.cxx
/*========================================================================= Program: Visualization Toolkit Module: TestInformationDataObjectKey.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkInformation.h" #include "vtkInformationDataObjectKey.h" #include "vtkPolyData.h" //---------------------------------------------------------------- // The vtkInformationDataObjectKey uses reinterpret_cast to cast between // vtkDataObject* and vtkObjectBase*, instead of using static_cast. See // the comments in vtkInformationDataObjectKey.cxx for the reasons. // In this test, we do compile-time and run-time checks to ensure that // reinterpret_cast does not give the wrong answer. //---------------------------------------------------------------- // First, some compile-time checks via static_assert, but use conversion // to void pointer as a surrogate for reinterpret_cast since the latter // cannot be used in a static_assert. namespace { // This will be used to test static casts with multiple inheritance struct OtherBase { double x{ 0.0 }; }; // create our own data object type for testing class TestClass : public vtkDataObject , public OtherBase { public: // public constructor, destructor to allow static allocation TestClass() = default; ~TestClass() override { ReferenceCount = 0; } }; // a static instantiation for static testing TestClass inst; // pointers where C++ knows the object type constexpr vtkDataObject* inst_dp = &inst; constexpr vtkObjectBase* inst_bp = &inst; constexpr OtherBase* inst_op = &inst; // these hold the address without knowing the object type constexpr void* inst_void_dp = inst_dp; constexpr void* inst_void_bp = inst_bp; constexpr void* inst_void_op = inst_op; // well defined, will always succeed static_assert(inst_bp == inst_dp, "Simple typed pointer comparison failed"); // undefined by C++ standard, but expected to be equal static_assert(inst_void_bp == inst_void_dp, "Single-inherited base address mismatch"); // undefined by C++ standard, but expected to be different static_assert(inst_void_bp != inst_void_op, "Multi-inherited base addresses match"); } // anonymous namespace //---------------------------------------------------------------- // The run-time tests int TestStoreDataObject() { int rval = 0; // test storing data object in vtkInformation and then retrieving vtkNew<vtkInformation> information; vtkNew<vtkPolyData> polydata; information->Set(vtkDataObject::DATA_OBJECT(), polydata); vtkDataObject* data = information->Get(vtkDataObject::DATA_OBJECT()); if (data != polydata) { std::cerr << "Error: Failed to store polydata in vtkInformation" << std::endl; rval = 1; } // vtkInformationDataObjectKey requires these two casts to equivalent if (reinterpret_cast<vtkObjectBase*>(data) != static_cast<vtkObjectBase*>(data)) { std::cerr << "Error: Object address changed by static_cast<vtkObjectBase*>(vtkDataObject*)" << std::endl; rval = 1; } return rval; } int TestInformationDataObjectKey(int, char*[]) { return TestStoreDataObject(); }
5262cada5369ddffb1a9562ed9fcd76d79ae7ea1
1a8ea057ae862c3dfd525abda7ef5285ed1b0c0e
/ShortestPath.cpp
8e205dbfd7365d9e6b18ab4c13ccd137eb710878
[]
no_license
pareshbhambhani/Graph-Shortest-Path
b6ece93ae94f13b46aa9728f301905f93db3992c
cf7ade333c4c5b717844a94f44f3bf0fe0fafcc1
refs/heads/master
2021-01-21T21:14:24.087920
2017-05-25T18:42:34
2017-05-25T18:42:34
92,319,118
1
0
null
null
null
null
UTF-8
C++
false
false
3,652
cpp
ShortestPath.cpp
// ----------------------------------------------------------------------- /** File: ShortestPath.cpp Author: Paresh B. Web: pareshbhambhani.github.io Description: Implementation file for ShortestPath Header file **/ #include "ShortestPath.hpp" ShortestPath::ShortestPath(UndirectedGraph &graph, int startNode, int endNode) { // we want the priority queue to always behave such that low values have higher priority pQueue.setComparator(false); updateGraph(graph, startNode, endNode); } void ShortestPath::updateGraph(UndirectedGraph &graph, int startNode, int endNode) { initialize(graph); currStartNode = startNode; currEndNode = endNode; pathExists = run(startNode, endNode); } list<int> ShortestPath::path() { if (!exists()) // there is no path from the starting to the ending node return list<int>(); else if (currStartNode == currEndNode) // the starting and ending nodes are the same return list<int>(2, currStartNode); list<int> path; int currNode = currEndNode; // reconstruct the shortest path from the ending node to the starting node path.push_front(currNode); while (previous[currNode] != -1) { path.push_front(previous[currNode]); currNode = previous[currNode]; // traverse backwards to the starting node } return path; } void ShortestPath::initialize(UndirectedGraph &graph) { currGraph = &graph; pQueue.clear(); visited.clear(); previous.clear(); for (int i = 0; i < currGraph->getNumNodes(); i++) { currGraph->setNodeValue(i, numeric_limits<double>::max()); // re-initialize the node values visited.push_back(false); // mark all nodes as un-visited previous.push_back(-1); // mark all previous nodes as undefined } } bool ShortestPath::run(int startNode, int endNode) { currGraph->setNodeValue(startNode, 0.0); // initialize distance from the starting node to itself pQueue.push(startNode, 0.0); // start with the starting node in the priority queue // temporary variables int currNode; // holds the current node being examined double distFromStart = 0.0; // accumulates the shortest distance from the starting node vector<int> neighbors; // holds the adjacent nodes to the current node while (!pQueue.empty()) { // main algorithm loop currNode = pQueue.pop(); // get the node with the smallest distance visited[currNode] = true; // mark this node as visited if (currNode == endNode) return true; // we are at the target node; terminate // acquire and iterate the neighboring nodes currGraph->getNeighbors(currNode, neighbors); for (vector<int>::iterator it = neighbors.begin(); it != neighbors.end(); ++it) { // compute the shortest distance from the starting node distFromStart = currGraph->getNodeValue(currNode) + currGraph->getEdgeValue(currNode, *it); // keep the shortest distance if it is less than the current value at the neighboring node AND // if the neighboring node has not yet been visited if ((distFromStart < currGraph->getNodeValue(*it)) && !visited[*it]) { currGraph->setNodeValue(*it, distFromStart); // update the new value previous[*it] = currNode; // keep track of the parent node if (pQueue.contains(*it)) // update the node's value if it already exists in the queue pQueue.changePriority(*it, distFromStart); else // otherwise add it to the queue to be processed pQueue.push(*it, distFromStart); } } } return false; // the starting and ending nodes are in disconnected graphs }
07bcffa7937e47d2a78999649ef413f0467ca306
c655e509c3840af49fae65214e3cb00a06b028ba
/detectors/CascadeClassifierDetector.hpp
49e0114b3c2d55477f36430788e9cdf44c5399f6
[]
no_license
pdiasalmeida/objectDetector
043326ae9979d27e2ff087464de246bd723db222
a1b29c07c9e25fb441963274a752193039959de7
refs/heads/master
2021-01-23T20:21:59.630642
2015-03-11T13:14:57
2015-03-11T13:14:57
24,840,853
0
0
null
null
null
null
UTF-8
C++
false
false
990
hpp
CascadeClassifierDetector.hpp
#ifndef CASCADECLASSIFIERDETECTOR_HPP_ #define CASCADECLASSIFIERDETECTOR_HPP_ #include "Detector.hpp" #include "../libs/rapidxml/rapidxml.hpp" #include <opencv2/core/core.hpp> #include <opencv2/objdetect/objdetect.hpp> class CascadeClassifierDetector : Detector { public: CascadeClassifierDetector( std::string name, std::string procDir, std::string outDir, int output, bool aggr, bool ann, std::string path, double scale, int minNeighb, cv::Size minSize, cv::Size maxSize, bool debug, bool saveThumbs ); CascadeClassifierDetector( rapidxml::xml_node<> *node, std::string name, std::string procDir, std::string outDir, int output, bool aggregate, bool annotate, bool debug, bool saveThumbs ); virtual std::vector< cv::Rect > detect( cv::Mat image, std::string name ); ~CascadeClassifierDetector(); private: void init(); protected: std::string _path; double _scale; int _minNeighbours; cv::Size _minSize; cv::Size _maxSize; cv::CascadeClassifier cascade; }; #endif
42c75e25d2d7786272497b82403762d7652a37a6
04101fb4c49840c54d314b44ecdfbacaea99d9ec
/test_222/test_222/main.cpp
8a08c05dc73a6e762a36f02a2f66b5ddff155c28
[]
no_license
lantian-fz/test_cpp
b3e14da51e84876a20244f3693364e66e47b904d
8b0a776be3b00591f08deca9b208130ccdbedb8c
refs/heads/master
2021-07-16T00:25:39.257501
2020-10-17T08:07:14
2020-10-17T08:07:14
216,210,039
0
0
null
null
null
null
GB18030
C++
false
false
1,381
cpp
main.cpp
#define _CRT_SECURE_NO_WARNINGS 1 //力扣-反转字符串中的单词 III //给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 // //输入 : "Let's take LeetCode contest" //输出 : "s'teL ekat edoCteeL tsetnoc" //注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 #include <iostream> #include <string> #include <algorithm> using namespace std; string reverseWords(string s) { if (s.empty() || s.size() == 1) return s; int pos = 0; int index = 0; string ret; while (index != s.npos) { index = s.find(' ', pos); if (index == s.npos) break; string tmp(s.begin() + pos, s.begin() + index); reverse(tmp.begin(), tmp.end()); ret += tmp + ' '; pos = index + 1; } string tmp(s.begin() + pos, s.end()); reverse(tmp.begin(), tmp.end()); ret += tmp; return ret; } //原地翻转 string reverseWords_2(string s) { if (s.empty() || s.size() == 1) return s; int len = s.size(); int left = 0, right = 0; while (right < len) { while (right < len&&s[right] != ' ') right++; int n = right-- + 1;//right退回空格前 while (left < right) swap(s[left++], s[right--]); left = n; right = n; } return s; } void main() { string s = "Let's take LeetCode contest"; cout << reverseWords_2(s) << endl; }
bb44c5750608ad56b33b87c4848fa0316a3ad2d5
8649eeec7e766f693e8a1926d3c6ab48bf94218b
/Calculator.ino
71ecc765039758f2ae8b5b862b48b2d7da09c8c7
[]
no_license
daniel-tsonkov/ArduinoGSM
21f778109e3c690dcf9b383aa072840ca409d683
dd5279313f563d37f9859af4a26115f9f58c558b
refs/heads/master
2021-01-10T12:47:46.928206
2015-11-21T18:16:38
2015-11-21T18:16:38
46,623,540
0
0
null
null
null
null
UTF-8
C++
false
false
8,107
ino
Calculator.ino
void cal(){ calculatorFirstNumber = 0; calculatorSecondNumber = 0; calculatorResult = 0; calculatorOperation = 0; calculatorDigits = 0; myGLCD.clrScr(); menuClock(); colorTextWhite(); myGLCD.drawRect(1, 24, 478, 105); myGLCD.setFont(SevenSegNumFont); colorTextBackBlack(); colorTextWhite(); myGLCD.print("0", 20, 43); myGLCD.setColor(255, 120, 120); myGLCD.fillRect(247, 197, 425, 247); myGLCD.setFont(BigFont); myGLCD.setBackColor(255, 120, 120); colorBlack(); myGLCD.print("C", 330, 215); int xA = 55; int yA = 257; int xB = xA + 85; int yB = yA + 85; int charX = 80; int charY = 275; myGLCD.setBackColor(50, 50, 50); myGLCD.setColor(50, 50, 50); for(int i = 0; i <= 15; i++){ if(xB > 440){ xA = 55; xB = xA + 85; yA = yB + 10; yB = yA + 85; charX = 85; charY += 95; } myGLCD.setColor(50, 50, 50); myGLCD.fillRect(xA, yA, xB, yB); if((i == 3) || (i == 7) || (i == 11) || (i == 13) || (i == 14) || (i == 15)){ myGLCD.setFont(BigFont); }else{ myGLCD.setFont(SevenSegNumFont); } colorTextWhite(); myGLCD.print(calculatorArray[i], charX, charY); xA += 95; xB += 95; charX += 95; } backButton(); } void drawCalculatorNumber(){ calculatorDigits++; if(calculatorDigits == 1){ calculatorResult = calculatorFirstNumber; colorBlack(); myGLCD.fillRect(3, 25, 476, 103); myGLCD.setFont(SevenSegNumFont); colorTextBackBlack(); colorTextWhite(); myGLCD.printNumI(calculatorResult, 20, 43); } if((calculatorDigits > 1) && (calculatorDigits <= 10)){ calculatorResult = (calculatorResult * 10) + calculatorFirstNumber; colorBlack(); myGLCD.fillRect(3, 25, 476, 103); myGLCD.setFont(SevenSegNumFont); colorTextBackBlack(); colorTextWhite(); myGLCD.printNumI(calculatorResult, 20, 43); } zakusnenie(); } void calculatorDigitAfterOperation(String action){ myGLCD.setFont(BigFont); colorTextBackBlack(); colorTextWhite(); myGLCD.print(action, 450, 38); zakusnenie(); } //----------------------------------------------------------------------------------- from calculator to main menu functions(calculator functions) 247, 197, 425, 247 void calulatorFunctions(){ if (myTouch.dataAvailable()){ if(((tp_x > 247) && (tp_x < 425)) && ((tp_y > 197) && (tp_y < 247))){//-------- C calculatorFirstNumber = 0; calculatorSecondNumber = 0; calculatorResult = 0; calculatorOperation = 0; calculatorDigits = 0; colorBlack(); myGLCD.fillRect(3, 25, 476, 103); myGLCD.setFont(SevenSegNumFont); colorTextBackBlack(); colorTextWhite(); myGLCD.printNumI(0, 20, 43); zakusnenie(); } int xA = 55; int yA = 257; int xB = xA + 85; int yB = yA + 85; int charX = 80; int charY = 275; myGLCD.setBackColor(50, 50, 50); myGLCD.setColor(50, 50, 50); for(int i = 0; i <= 15; i++){ if(xB > 440){ xA = 55; xB = xA + 85; yA = yB + 10; yB = yA + 85; charX = 85; charY += 95; } if(((tp_x > xA) && (tp_x < xB)) && ((tp_y > yA) && (tp_y < yB))){ switch (i + 1) { case 1://---------------------------------------------------------------------------------- 1 calculatorFirstNumber = 1; calculatorFirstNumberf = 0.1; drawCalculatorNumber(); break; case 2://---------------------------------------------------------------------------------- 2 calculatorFirstNumber = 2; calculatorFirstNumberf = 0.2; drawCalculatorNumber(); break; case 3://---------------------------------------------------------------------------------- 3 calculatorFirstNumber = 3; calculatorFirstNumberf = 0.3; drawCalculatorNumber(); break; case 4://---------------------------------------------------------------------------------- / calculatorOperation = 2; calculatorSecondNumber = calculatorResult; calculatorDigits = 0; calculatorFirstNumber = 0; calculatorDigitAfterOperation("/"); break; case 5://---------------------------------------------------------------------------------- 4 calculatorFirstNumber = 4; calculatorFirstNumberf = 0.4; drawCalculatorNumber(); break; case 6://---------------------------------------------------------------------------------- 5 calculatorFirstNumber = 5; calculatorFirstNumberf = 0.5; drawCalculatorNumber(); break; case 7://---------------------------------------------------------------------------------- 6 calculatorFirstNumber = 6; calculatorFirstNumberf = 0.6; drawCalculatorNumber(); break; case 8://---------------------------------------------------------------------------------- * calculatorOperation = 1; calculatorSecondNumber = calculatorResult; calculatorDigits = 0; calculatorFirstNumber = 0; calculatorDigitAfterOperation("*"); break; case 9://---------------------------------------------------------------------------------- 7 calculatorFirstNumber = 7; calculatorFirstNumberf = 0.7; drawCalculatorNumber(); break; case 10://--------------------------------------------------------------------------------- 8 calculatorFirstNumber = 8; calculatorFirstNumberf = 0.8; drawCalculatorNumber(); break; case 11://--------------------------------------------------------------------------------- 9 calculatorFirstNumber = 9; calculatorFirstNumberf = 0.9; drawCalculatorNumber(); break; case 12://--------------------------------------------------------------------------------- - calculatorOperation = 4; calculatorSecondNumber = calculatorResult; calculatorDigits = 0; calculatorFirstNumber = 0; calculatorDigitAfterOperation("-"); break; case 13://---------------------------------------------------------------------------------- 0 calculatorFirstNumber = 0; drawCalculatorNumber(); break; case 14://---------------------------------------------------------------------------------- . //calculatorResult = calculatorResult + calculatorFirstNumberf; break; case 15://---------------------------------------------------------------------------------- = switch (calculatorOperation) { case 1: // your hand is on the sensor calculatorSecondNumber *= calculatorResult; break; case 2: // your hand is close to the sensor calculatorSecondNumber /= calculatorResult; break; case 3: // your hand is a few inches from the sensor calculatorSecondNumber += calculatorResult; break; case 4: // your hand is nowhere near the sensor calculatorSecondNumber -= calculatorResult; break; } calculatorResult = calculatorSecondNumber; colorBlack(); myGLCD.fillRect(3, 25, 476, 103); myGLCD.setFont(SevenSegNumFont); colorTextBackBlack(); colorTextWhite(); myGLCD.printNumI(calculatorSecondNumber, 20, 43); zakusnenie(); break; case 16://---------------------------------------------------------------------------------- + calculatorOperation = 3; calculatorSecondNumber = calculatorResult; calculatorDigits = 0; calculatorFirstNumber = 0; calculatorDigitAfterOperation("+"); break; } } xA += 95; xB += 95; charX += 95; } toMainMenu(); } }
b1fb6ebe332f1d51a984f0ce82689773e05116b1
32ffee400604bf821858eaf9cd8cfc65926e2bc1
/libmamba/src/core/repo.cpp
78e8a32bf6a931fe07abf9a34772cff71837b78a
[ "BSD-3-Clause" ]
permissive
mamba-org/mamba
ebabfe45c866f7d812a8dddbcc6814e40c96b9b2
319f0553f5036cc74cb7919f6ecadc784cb6c187
refs/heads/main
2023-08-31T05:00:08.103215
2023-08-29T14:35:10
2023-08-29T14:35:10
173,947,939
4,478
292
BSD-3-Clause
2023-09-14T10:14:10
2019-03-05T13:05:10
C++
UTF-8
C++
false
false
11,758
cpp
repo.cpp
// Copyright (c) 2019, QuantStack and Mamba Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #include <algorithm> #include <array> #include <tuple> #include <nlohmann/json.hpp> #include <solv/repo.h> #include <solv/repo_solv.h> #include <solv/repo_write.h> #include <solv/solvable.h> extern "C" // Incomplete header { #include <solv/conda.h> #include <solv/repo_conda.h> } #include "mamba/core/context.hpp" #include "mamba/core/mamba_fs.hpp" #include "mamba/core/output.hpp" #include "mamba/core/package_info.hpp" #include "mamba/core/pool.hpp" #include "mamba/core/prefix_data.hpp" #include "mamba/core/repo.hpp" #include "mamba/core/util.hpp" #include "solv-cpp/pool.hpp" #include "solv-cpp/repo.hpp" #define MAMBA_TOOL_VERSION "1.3" #define MAMBA_SOLV_VERSION MAMBA_TOOL_VERSION "_" LIBSOLV_VERSION_STRING namespace mamba { namespace { auto attrs(const RepoMetadata& m) { return std::tie(m.url, m.etag, m.mod, m.pip_added); } } auto operator==(const RepoMetadata& lhs, const RepoMetadata& rhs) -> bool { return attrs(lhs) == attrs(rhs); } auto operator!=(const RepoMetadata& lhs, const RepoMetadata& rhs) -> bool { return !(lhs == rhs); } void to_json(nlohmann::json& j, const RepoMetadata& m) { j["url"] = m.url; j["etag"] = m.etag; j["mod"] = m.mod; j["pip_added"] = m.pip_added; } void from_json(const nlohmann::json& j, RepoMetadata& m) { m.url = j.value("url", m.url); m.etag = j.value("etag", m.etag); m.mod = j.value("mod", m.mod); m.pip_added = j.value("pip_added", m.pip_added); } namespace { // Keeping the solv-cpp header private auto srepo(const MRepo& r) -> solv::ObjRepoViewConst { return solv::ObjRepoViewConst{ *const_cast<const ::Repo*>(r.repo()) }; } auto srepo(MRepo& r) -> solv::ObjRepoView { return solv::ObjRepoView{ *r.repo() }; } } MRepo::MRepo(MPool& pool, const std::string& name, const fs::u8path& index, const RepoMetadata& metadata) : m_pool(pool) , m_metadata(metadata) { auto [_, repo] = pool.pool().add_repo(name); m_repo = repo.raw(); repo.set_url(m_metadata.url); load_file(index); set_solvables_url(m_metadata.url); repo.internalize(); } MRepo::MRepo(MPool& pool, const std::string& name, const std::vector<PackageInfo>& package_infos) : m_pool(pool) { auto [_, repo] = pool.pool().add_repo(name); m_repo = repo.raw(); for (auto& info : package_infos) { add_package_info(info); } repo.internalize(); } MRepo::MRepo(MPool& pool, const PrefixData& prefix_data) : m_pool(pool) { auto [repo_id, repo] = pool.pool().add_repo("installed"); m_repo = repo.raw(); for (auto& [name, record] : prefix_data.records()) { add_package_info(record); } if (Context::instance().add_pip_as_python_dependency) { add_pip_as_python_dependency(); } repo.internalize(); pool.pool().set_installed_repo(repo_id); } void MRepo::set_solvables_url(const std::string& repo_url) { // WARNING cannot call ``url()`` at this point because it has not been internalized. // Setting the channel url on where the solvable so that we can retrace // where it came from srepo(*this).for_each_solvable( [&](solv::ObjSolvableView s) { // The solvable url, this is not set in libsolv parsing so we set it manually // while we still rely on libsolv for parsing s.set_url(fmt::format("{}/{}", repo_url, s.file_name())); // The name of the channel where it came from, may be different from repo name // for instance with the installed repo s.set_channel(repo_url); } ); } void MRepo::set_installed() { m_pool.pool().set_installed_repo(srepo(*this).id()); } void MRepo::set_priority(int priority, int subpriority) { m_repo->priority = priority; m_repo->subpriority = subpriority; } void MRepo::add_package_info(const PackageInfo& info) { LOG_INFO << "Adding package record to repo " << info.name; auto [id, solv] = srepo(*this).add_solvable(); solv.set_name(info.name); solv.set_version(info.version); solv.set_build_string(info.build_string); solv.set_noarch(info.noarch); solv.set_build_number(info.build_number); solv.set_channel(info.channel); solv.set_url(info.url); solv.set_subdir(info.subdir); solv.set_file_name(info.fn); solv.set_license(info.license); solv.set_size(info.size); // TODO conda timestamp are not Unix timestamp. // Libsolv normalize them this way, we need to do the same here otherwise the current // package may get arbitrary priority. solv.set_timestamp( (info.timestamp > 253402300799ULL) ? (info.timestamp / 1000) : info.timestamp ); solv.set_md5(info.md5); solv.set_sha256(info.sha256); for (const auto& dep : info.depends) { // TODO pool's matchspec2id solv::DependencyId const dep_id = pool_conda_matchspec(m_pool, dep.c_str()); assert(dep_id); solv.add_dependency(dep_id); } for (const auto& cons : info.constrains) { // TODO pool's matchspec2id solv::DependencyId const dep_id = pool_conda_matchspec(m_pool, cons.c_str()); assert(dep_id); solv.add_constraint(dep_id); } solv.add_track_features(info.track_features); solv.add_self_provide(); } auto MRepo::name() const -> std::string_view { return srepo(*this).name(); } Id MRepo::id() const { return srepo(*this).id(); } Repo* MRepo::repo() const { return m_repo; } void MRepo::add_pip_as_python_dependency() { solv::DependencyId const python_id = pool_conda_matchspec(m_pool, "python"); solv::DependencyId const pip_id = pool_conda_matchspec(m_pool, "pip"); srepo(*this).for_each_solvable( [&](solv::ObjSolvableView s) { if ((s.name() == "python") && !s.version().empty() && (s.version()[0] >= '2')) { s.add_dependency(pip_id); } if (s.name() == "pip") { s.add_dependency(python_id, SOLVABLE_PREREQMARKER); } } ); } void MRepo::read_json(const fs::u8path& filename) { LOG_INFO << "Reading repodata.json file " << filename << " for repo " << name(); // TODO make this as part of options of the repo/pool const int flags = Context::instance().use_only_tar_bz2 ? CONDA_ADD_USE_ONLY_TAR_BZ2 : 0; srepo(*this).legacy_read_conda_repodata(filename, flags); } bool MRepo::read_solv(const fs::u8path& filename) { LOG_INFO << "Attempting to read libsolv solv file " << filename << " for repo " << name(); auto repo = srepo(*this); auto lock = LockFile(filename); repo.read(filename); const auto read_metadata = RepoMetadata{ /* .url= */ std::string(repo.url()), /* .etag= */ std::string(repo.etag()), /* .mod= */ std::string(repo.mod()), /* .pip_added= */ repo.pip_added(), }; const auto tool_version = repo.tool_version(); { auto j = nlohmann::json(m_metadata); j["tool_version"] = tool_version; LOG_INFO << "Expecting solv metadata : " << j.dump(); } { auto j = nlohmann::json(read_metadata); j["tool_version"] = tool_version; LOG_INFO << "Loaded solv metadata : " << j.dump(); } if ((tool_version != std::string_view(MAMBA_SOLV_VERSION)) || (read_metadata == RepoMetadata{}) || (read_metadata != m_metadata)) { LOG_INFO << "Metadata from solv are NOT valid, canceling solv file load"; repo.clear(/* reuse_ids= */ false); return false; } LOG_INFO << "Metadata from solv are valid, loading successful"; return true; } void MRepo::load_file(const fs::u8path& filename) { auto repo = srepo(*this); bool is_solv = filename.extension() == ".solv"; fs::u8path solv_file = filename; fs::u8path json_file = filename; if (is_solv) { json_file.replace_extension("json"); } else { solv_file.replace_extension("solv"); } LOG_INFO << "Reading cache files '" << (filename.parent_path() / filename).string() << ".*' for repo index '" << name() << "'"; if (is_solv) { const auto lock = LockFile(solv_file); const bool read = read_solv(solv_file); if (read) { return; } } auto lock = LockFile(json_file); read_json(json_file); // TODO move this to a more structured approach for repodata patching? if (Context::instance().add_pip_as_python_dependency) { add_pip_as_python_dependency(); } if (name() != "installed") { write_solv(solv_file); } } void MRepo::write_solv(fs::u8path filename) { LOG_INFO << "Writing libsolv solv file " << filename << " for repo " << name(); auto repo = srepo(*this); repo.set_url(m_metadata.url); repo.set_etag(m_metadata.etag); repo.set_mod(m_metadata.mod); repo.set_pip_added(m_metadata.pip_added); repo.set_tool_version(MAMBA_SOLV_VERSION); repo.internalize(); repo.write(filename); } void MRepo::clear(bool reuse_ids) { m_pool.remove_repo(id(), reuse_ids); } } #include <map> namespace mamba { auto MRepo::py_name() const -> std::string_view { return name(); } auto MRepo::py_priority() const -> std::tuple<int, int> { return std::make_tuple(m_repo->priority, m_repo->subpriority); } auto MRepo::py_clear(bool reuse_ids) -> bool { clear(reuse_ids); return true; } auto MRepo::py_size() const -> std::size_t { return srepo(*this).solvable_count(); } void MRepo::py_add_extra_pkg_info(const std::map<std::string, PyExtraPkgInfo>& extra) { auto repo = srepo(*this); repo.for_each_solvable( [&](solv::ObjSolvableView s) { if (auto const it = extra.find(std::string(s.name())); it != extra.cend()) { if (auto const& noarch = it->second.noarch; !noarch.empty()) { s.set_noarch(noarch); } if (auto const& repo_url = it->second.repo_url; !repo_url.empty()) { s.set_channel(repo_url); } } } ); repo.internalize(); } } // namespace mamba
f0765dac0b7ce485f465c695c73b066af14e3d5e
ab12dfc50ccf3476c594955ff431ea54be3e6950
/include/ctag/filtration_factory.h
c675145b3192794080491992b18e60acb0f8d182
[]
no_license
compTAG/reconstruction
dc18763bf70a2bb1b87513dee3d65c6934d3fd31
d9fd6109cc048f0fdb96f157866475e26e00a28e
refs/heads/master
2020-03-25T06:00:05.412755
2019-10-04T19:17:57
2019-10-04T19:17:57
143,478,070
1
0
null
2019-10-04T19:17:58
2018-08-03T22:20:52
C++
UTF-8
C++
false
false
1,219
h
filtration_factory.h
#ifndef _FILTRATION_FACTORY_H_ #define _FILTRATION_FACTORY_H_ namespace ctag { template<typename FilterFunction_, typename Filtration_> class FiltrationFactory { public: typedef FilterFunction_ FilterFunction; typedef typename FilterFunction::Simplex Simplex; typedef Filtration_ Filtration; private: void add_simplex(Filtration& f, const Simplex& s) const { for (auto sb : s.boundary()) { add_simplex(f, sb); } f.push_back(s); } public: Filtration make_filtration(const FilterFunction& f, const std::initializer_list<Simplex>& simplices) const { return make_filtration(f, std::begin(simplices), std::end(simplices)); } template<class Iterator> Filtration make_filtration(const FilterFunction& f, Iterator begin, Iterator end) const { Filtration filtration; for (Iterator it = begin ; it != end ; ++it) { add_simplex(filtration, *it); } filtration.sort([&f](const Simplex& s1, const Simplex& s2) { return f(s1) < f(s2) || (f(s1) == f(s2) && s1.dimension() < s2.dimension()); }); return filtration; } }; }; #endif
64a24ae205dd6553159e48181ee192e86dd4ce83
c485fdae8bb027549c648e49c55926f32c7b9b3f
/core/apps/experience_builder.cpp
6fe91c0fd6b5b2e061988c31971881b3bfea5306
[]
no_license
jbasu2013/L3
74468d450ee55e39f72413cfee9b3990cfec682e
9edd3414019300043db05d88fb53be3b9358ea44
refs/heads/master
2022-06-30T02:39:35.672928
2020-05-14T22:46:02
2020-05-14T23:01:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
879
cpp
experience_builder.cpp
#include <sstream> #include "L3.h" int main( int argc, char** argv ) { if ( argc < 4 ) { std::cerr << "Usage: " << argv[0] << " <char::dataset> <float::start_time> <float::end_time>" << std::endl; exit( EXIT_FAILURE ); } char* dataset_directory = argv[1]; /* * L3 */ L3::Dataset dataset( dataset_directory ); boost::shared_ptr< L3::ExperienceBuilder > experience_builder; switch( argc ) { case 5: experience_builder.reset( new L3::ExperienceBuilder( dataset, atof( argv[2]), atof( argv[3]), atof( argv[4]) ) ); break; case 6: experience_builder.reset( new L3::ExperienceBuilder( dataset, atof( argv[2]), atof( argv[3]), atof( argv[4]), atof( argv[5] ) ) ); break; default: experience_builder.reset( new L3::ExperienceBuilder( dataset, atof( argv[2]), atof( argv[3]) ) ); break; }; }
724967db30f99741887cb9f877883897f9b9c84d
e8ba1d3ee4b0307b446432b25141b0cd13a85b39
/dfs_short.cpp
d2e77a49521502d98396cca147584223d72a257c
[]
no_license
ThongVoHien/algorithm
1642088da700ac7a61e76aa94f58b7cac6914862
6a790a5ad00a36882ec96e9c8116ab0a70004a23
refs/heads/master
2021-06-03T07:22:33.078396
2021-04-22T20:10:22
2021-04-22T20:10:22
150,565,738
0
0
null
null
null
null
UTF-8
C++
false
false
2,347
cpp
dfs_short.cpp
#include <cstdio> #include <cstring> #include <cctype> #include <cmath> #include <iostream> #include <sstream> #include <iomanip> #include <functional> #include <algorithm> #include <climits> #include <string> #include <vector> #include <utility> #include <map> #include <bitset> #include <stack> #include <queue> #include <set> #include <list> #include <time.h> #define fr(a) freopen(a,"r",stdin) #define fw(a) freopen(a,"w",stdout) #define reset(a) memset(a,0,sizeof(a)) #define upf(i,m,n) for (int i=m;i<=n;i++) #define downf(i,n,m) for (int i=n;i>=m;i--) #define all(a) a.begin(),a.end() #define PB push_back #define InS insert #define mP make_pair #define mT make_tuple #define EB emplace_back #define X first #define Y second #define bug(x) cout << #x << "=" << x <<" "; #define line() cout << endl; #define Sbug(x) cout << #x << "=" << x <<"\n"; #define tc() int tc; cin >> tc; for(int _tc=0;_tc<tc;_tc++) #define sl(n) scanf("%lld",&n) #define slf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) #define pl(n) printf("%lld",n) #define ps(n) printf("%s",n) #define PQ priority_queue #define IT iterator #define stop() int _stop;cin>>_stop; #define PrintAll(x) for (auto i:x) cout<<i<<" ";line(); #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #include <limits.h> using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double lf; typedef pair<int,int>pii; typedef pair<ll,ll>pll; typedef vector<int> vi; typedef vector<ll> vll; const int si=1000; int n, m, k, mark[si]; vi node[si]; /* simple and short dfs */ // warning for multiple edges over two points void dfs(int s){ mark[s] = 1; for ( auto pos: node[s]) if ( mark[pos]==0 ) dfs(pos); } /* advance dfs keeps track of in and out value */ //int in[si], out[si], cnt; // in[i]: time discovering i/first meet node i // out[i]: time getting out of node i //void dfs( int s ){ // mark[s] = 1; // in[s] = ++cnt; // for ( auto pos: node[s]) // if ( mark[pos]==0 ) // dfs(pos); // out[s] = ++cnt; //} int main(){ cin >> n >> m; int x, y; upf(i,1,m){ cin >> x >> y; if ( x!=y ){ node[x].PB(y); } } reset(mark); dfs( 1 ); }
97db4259f40bf6b88e01b4e8c20c0ce13798caeb
45874c847c5a2fc4e89e05a7fc8ad9b63d8c4860
/sycl/source/detail/global_handler.cpp
a03d6a03b54e956c406f7f43b85d730f0453fd20
[ "LicenseRef-scancode-unknown-license-reference", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
intel/llvm
2f023cefec793a248d8a237267410f5e288116c5
a3d10cf63ddbdcc23712c45afd1b6b0a2ff5b190
refs/heads/sycl
2023-08-24T18:53:49.800759
2023-08-24T17:38:35
2023-08-24T17:38:35
166,008,577
1,050
735
NOASSERTION
2023-09-14T20:35:07
2019-01-16T09:05:33
null
UTF-8
C++
false
false
12,826
cpp
global_handler.cpp
//==--------- global_handler.cpp --- Global objects handler ----------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifdef ENABLE_STACK_TRACE #include "llvm/ADT/StringRef.h" #include "llvm/Support/Signals.h" #endif #include <detail/config.hpp> #include <detail/global_handler.hpp> #include <detail/platform_impl.hpp> #include <detail/plugin.hpp> #include <detail/program_manager/program_manager.hpp> #include <detail/scheduler/scheduler.hpp> #include <detail/thread_pool.hpp> #include <detail/xpti_registry.hpp> #include <sycl/detail/device_filter.hpp> #include <sycl/detail/pi.hpp> #include <sycl/detail/spinlock.hpp> #ifdef _WIN32 #include <windows.h> #endif #include <vector> namespace sycl { inline namespace _V1 { namespace detail { using LockGuard = std::lock_guard<SpinLock>; SpinLock GlobalHandler::MSyclGlobalHandlerProtector{}; // Utility class to track references on object. // Used for GlobalHandler now and created as thread_local object on the first // Scheduler usage. Origin idea is to track usage of Scheduler from main and // other used threads - they increment MCounter; and to use but not add extra // reference by our thread_pool threads. For this control MIncrementCounter // class member is used. class ObjectUsageCounter { public: ObjectUsageCounter(bool ModifyCounter) : MModifyCounter(ModifyCounter) { if (MModifyCounter) MCounter++; } ~ObjectUsageCounter() { if (!MModifyCounter) return; MCounter--; if (!MCounter) { LockGuard Guard(GlobalHandler::MSyclGlobalHandlerProtector); GlobalHandler *RTGlobalObjHandler = GlobalHandler::getInstancePtr(); if (RTGlobalObjHandler) { RTGlobalObjHandler->prepareSchedulerToRelease(); } } } private: static std::atomic_uint MCounter; bool MModifyCounter; }; std::atomic_uint ObjectUsageCounter::MCounter{0}; GlobalHandler::GlobalHandler() = default; GlobalHandler::~GlobalHandler() = default; void GlobalHandler::InitXPTI() { #ifdef XPTI_ENABLE_INSTRUMENTATION // Let subscribers know a new stream is being initialized getXPTIRegistry().initializeStream(SYCL_STREAM_NAME, GMajVer, GMinVer, GVerStr); xpti::payload_t SYCLPayload("SYCL Runtime Exceptions"); uint64_t SYCLInstanceNo; GSYCLCallEvent = xptiMakeEvent("SYCL Try-catch Exceptions", &SYCLPayload, xpti::trace_algorithm_event, xpti_at::active, &SYCLInstanceNo); #endif } void GlobalHandler::TraceEventXPTI(const char *Message) { if (!Message) return; #ifdef XPTI_ENABLE_INSTRUMENTATION static std::once_flag InitXPTIFlag; if (xptiTraceEnabled()) { std::call_once(InitXPTIFlag, [&]() { InitXPTI(); }); // We have to handle the cases where: (1) we may have just the code location // set and not UID and (2) UID set detail::tls_code_loc_t Tls; auto CodeLocation = Tls.query(); // Creating a tracepoint will convert a CodeLocation to UID, if not set xpti::framework::tracepoint_t TP( CodeLocation.fileName(), CodeLocation.functionName(), CodeLocation.lineNumber(), CodeLocation.columnNumber(), nullptr); // The call to notify will have the signature of: // (1) the stream defined in .stream() // (2) The trace type equal to what is set by .trace_type() // (3) Parent event set to NULL // (4) Current event set to one created from CodeLocation and UID // (5) An instance ID that records the number of times this code location // has been seen (6) The message generated by the exception handler TP.stream(SYCL_STREAM_NAME) .trace_type(xpti::trace_point_type_t::diagnostics) .notify(static_cast<const void *>(Message)); } #endif } GlobalHandler *&GlobalHandler::getInstancePtr() { static GlobalHandler *RTGlobalObjHandler = new GlobalHandler(); return RTGlobalObjHandler; } GlobalHandler &GlobalHandler::instance() { GlobalHandler *RTGlobalObjHandler = GlobalHandler::getInstancePtr(); assert(RTGlobalObjHandler && "Handler must not be deallocated earlier"); return *RTGlobalObjHandler; } template <typename T, typename... Types> T &GlobalHandler::getOrCreate(InstWithLock<T> &IWL, Types... Args) { const LockGuard Lock{IWL.Lock}; if (!IWL.Inst) IWL.Inst = std::make_unique<T>(Args...); return *IWL.Inst; } void GlobalHandler::attachScheduler(Scheduler *Scheduler) { // The method is used in unit tests only. Do not protect with lock since // releaseResources will cause dead lock due to host queue release if (MScheduler.Inst) prepareSchedulerToRelease(); MScheduler.Inst.reset(Scheduler); } static void enableOnCrashStackPrinting() { #ifdef ENABLE_STACK_TRACE static std::once_flag PrintStackFlag; std::call_once(PrintStackFlag, []() { llvm::sys::PrintStackTraceOnErrorSignal(llvm::StringRef()); }); #endif } Scheduler &GlobalHandler::getScheduler() { getOrCreate(MScheduler); registerSchedulerUsage(); // On Windows the registration of the signal handler before main function // (e.g. from DLLMain or from constructors of program scope objects) doesn't // work. So, registering signal handler here because: // 1) getScheduler is likely to be called for any non-trivial application; // 2) first call to getScheduler is likely to be done after main starts. // The same is done in getPlugins. enableOnCrashStackPrinting(); return *MScheduler.Inst; } void GlobalHandler::registerSchedulerUsage(bool ModifyCounter) { thread_local ObjectUsageCounter SchedulerCounter(ModifyCounter); } ProgramManager &GlobalHandler::getProgramManager() { return getOrCreate(MProgramManager); } std::unordered_map<PlatformImplPtr, ContextImplPtr> & GlobalHandler::getPlatformToDefaultContextCache() { return getOrCreate(MPlatformToDefaultContextCache); } std::mutex &GlobalHandler::getPlatformToDefaultContextCacheMutex() { return getOrCreate(MPlatformToDefaultContextCacheMutex); } Sync &GlobalHandler::getSync() { return getOrCreate(MSync); } std::vector<PlatformImplPtr> &GlobalHandler::getPlatformCache() { return getOrCreate(MPlatformCache); } std::mutex &GlobalHandler::getPlatformMapMutex() { return getOrCreate(MPlatformMapMutex); } std::mutex &GlobalHandler::getFilterMutex() { return getOrCreate(MFilterMutex); } std::vector<PluginPtr> &GlobalHandler::getPlugins() { enableOnCrashStackPrinting(); return getOrCreate(MPlugins); } device_filter_list & GlobalHandler::getDeviceFilterList(const std::string &InitValue) { return getOrCreate(MDeviceFilterList, InitValue); } ods_target_list & GlobalHandler::getOneapiDeviceSelectorTargets(const std::string &InitValue) { return getOrCreate(MOneapiDeviceSelectorTargets, InitValue); } XPTIRegistry &GlobalHandler::getXPTIRegistry() { return getOrCreate(MXPTIRegistry); } ThreadPool &GlobalHandler::getHostTaskThreadPool() { int Size = SYCLConfig<SYCL_QUEUE_THREAD_POOL_SIZE>::get(); ThreadPool &TP = getOrCreate(MHostTaskThreadPool, Size); return TP; } void GlobalHandler::releaseDefaultContexts() { // Release shared-pointers to SYCL objects. #ifndef _WIN32 MPlatformToDefaultContextCache.Inst.reset(nullptr); #else // Windows does not maintain dependencies between dynamically loaded libraries // and can unload SYCL runtime dependencies before sycl.dll's DllMain has // finished. To avoid calls to nowhere, intentionally leak platform to device // cache. This will prevent destructors from being called, thus no PI cleanup // routines will be called in the end. // Update: the pi_win_proxy_loader addresses this for SYCL's own dependencies, // but the GPU device dlls seem to manually load yet another DLL which may // have been released when this function is called. So we still release() and // leak until that is addressed. context destructs fine on CPU device. MPlatformToDefaultContextCache.Inst.release(); #endif } struct DefaultContextReleaseHandler { ~DefaultContextReleaseHandler() { GlobalHandler::instance().releaseDefaultContexts(); } }; void GlobalHandler::registerDefaultContextReleaseHandler() { static DefaultContextReleaseHandler handler{}; } // Note: Split from shutdown so it is available to the unittests for ensuring // that the mock plugin is the lone plugin. void GlobalHandler::unloadPlugins() { // Call to GlobalHandler::instance().getPlugins() initializes plugins. If // user application has loaded SYCL runtime, and never called any APIs, // there's no need to load and unload plugins. if (MPlugins.Inst) { for (const PluginPtr &Plugin : getPlugins()) { // PluginParameter is reserved for future use that can control // some parameters in the plugin tear-down process. // Currently, it is not used. void *PluginParameter = nullptr; Plugin->call<PiApiKind::piTearDown>(PluginParameter); Plugin->unload(); } } // Clear after unload to avoid uses after unload. getPlugins().clear(); } void GlobalHandler::prepareSchedulerToRelease() { #ifndef _WIN32 drainThreadPool(); if (MScheduler.Inst) MScheduler.Inst->releaseResources(); #endif } void GlobalHandler::drainThreadPool() { if (MHostTaskThreadPool.Inst) MHostTaskThreadPool.Inst->drain(); } #ifdef _WIN32 // because of something not-yet-understood on Windows // threads may be shutdown once the end of main() is reached // making an orderly shutdown difficult. Fortunately, Windows // itself is very aggressive about reclaiming memory. Thus, // we focus solely on unloading the plugins, so as to not // accidentally retain device handles. etc void shutdown() { GlobalHandler *&Handler = GlobalHandler::getInstancePtr(); Handler->unloadPlugins(); } #else void shutdown() { const LockGuard Lock{GlobalHandler::MSyclGlobalHandlerProtector}; GlobalHandler *&Handler = GlobalHandler::getInstancePtr(); if (!Handler) return; // Ensure neither host task is working so that no default context is accessed // upon its release Handler->prepareSchedulerToRelease(); if (Handler->MHostTaskThreadPool.Inst) Handler->MHostTaskThreadPool.Inst->finishAndWait(); // If default contexts are requested after the first default contexts have // been released there may be a new default context. These must be released // prior to closing the plugins. // Note: Releasing a default context here may cause failures in plugins with // global state as the global state may have been released. Handler->releaseDefaultContexts(); // First, release resources, that may access plugins. Handler->MPlatformCache.Inst.reset(nullptr); Handler->MScheduler.Inst.reset(nullptr); Handler->MProgramManager.Inst.reset(nullptr); // Clear the plugins and reset the instance if it was there. Handler->MXPTIRegistry.Inst.reset(nullptr); Handler->unloadPlugins(); if (Handler->MPlugins.Inst) Handler->MPlugins.Inst.reset(nullptr); // Release the rest of global resources. delete Handler; Handler = nullptr; } #endif #ifdef _WIN32 extern "C" __SYCL_EXPORT BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) { bool PrintPiTrace = false; static const char *PiTrace = std::getenv("SYCL_PI_TRACE"); static const int PiTraceValue = PiTrace ? std::stoi(PiTrace) : 0; if (PiTraceValue == -1 || PiTraceValue == 2) { // Means print all PI traces PrintPiTrace = true; } // Perform actions based on the reason for calling. switch (fdwReason) { case DLL_PROCESS_DETACH: if (PrintPiTrace) std::cout << "---> DLL_PROCESS_DETACH syclx.dll\n" << std::endl; #ifdef XPTI_ENABLE_INSTRUMENTATION if (xptiTraceEnabled()) return TRUE; // When doing xpti tracing, we can't safely call shutdown. // TODO: figure out what XPTI is doing that prevents release. #endif shutdown(); break; case DLL_PROCESS_ATTACH: if (PrintPiTrace) std::cout << "---> DLL_PROCESS_ATTACH syclx.dll\n" << std::endl; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } return TRUE; // Successful DLL_PROCESS_ATTACH. } #else // Setting low priority on destructor ensures it runs after all other global // destructors. Priorities 0-100 are reserved by the compiler. The priority // value 110 allows SYCL users to run their destructors after runtime library // deinitialization. __attribute__((destructor(110))) static void syclUnload() { shutdown(); } #endif } // namespace detail } // namespace _V1 } // namespace sycl
d89be6df46338ae1a2cce4d344d989a679cd5f12
5a8fafefd7712b3730b27c5907ca8f54b567e328
/neb/inc/com/centreon/engine/nebstructs.hh
6aa60e5b95bab530a87adc80d2c5710e5b93c928
[ "Apache-2.0" ]
permissive
joe4568/centreon-broker
672d831389c17f92f09948704437c4bc9026998d
daf454371520989573c810be1f6dfca40979a75d
refs/heads/master
2020-04-13T05:11:03.126655
2018-12-24T14:53:34
2018-12-24T14:53:34
162,984,149
0
0
Apache-2.0
2018-12-24T11:33:05
2018-12-24T11:33:04
null
UTF-8
C++
false
false
16,540
hh
nebstructs.hh
/* ** Copyright 2003-2007 Ethan Galstad ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #ifndef CCE_NEBSTRUCTS_HH # define CCE_NEBSTRUCTS_HH # include "com/centreon/engine/objects/command.hh" # include "com/centreon/engine/objects/customvariablesmember.hh" # include "com/centreon/engine/objects/host.hh" # include "com/centreon/engine/objects/service.hh" /* Acknowledgement structure. */ typedef struct nebstruct_acknowledgement_struct { int type; int flags; int attr; struct timeval timestamp; int acknowledgement_type; char* host_name; char* service_description; int state; char* author_name; char* comment_data; int is_sticky; int persistent_comment; int notify_contacts; void* object_ptr; } nebstruct_acknowledgement_data; /* Adaptive contact data structure. */ typedef struct nebstruct_adaptive_contact_data_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; unsigned long modified_attribute; unsigned long modified_attributes; unsigned long modified_host_attribute; unsigned long modified_host_attributes; unsigned long modified_service_attribute; unsigned long modified_service_attributes; void* object_ptr; } nebstruct_adaptive_contact_data; /* Adaptive dependency data structure. */ typedef struct nebstruct_adaptive_dependency_data_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_adaptive_dependency_data; /* Adaptive escalation data structure. */ typedef struct nebstruct_adaptive_escalation_data_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_adaptive_escalation_data; /* Adaptive host data structure. */ typedef struct nebstruct_adaptive_host_data_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; unsigned long modified_attribute; unsigned long modified_attributes; void* object_ptr; } nebstruct_adaptive_host_data; /* Adaptive program data structure. */ typedef struct nebstruct_adaptive_program_data_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; unsigned long modified_host_attribute; unsigned long modified_host_attributes; unsigned long modified_service_attribute; unsigned long modified_service_attributes; } nebstruct_adaptive_program_data; /* Adaptive service data structure. */ typedef struct nebstruct_adaptive_service_data_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; unsigned long modified_attribute; unsigned long modified_attributes; void* object_ptr; } nebstruct_adaptive_service_data; /* Adaptive timeperiod data structure. */ typedef struct nebstruct_adaptive_timeperiod_data_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; void* object_ptr; } nebstruct_adaptive_timeperiod_data; /* Aggregated status data structure. */ typedef struct nebstruct_aggregated_status_struct { int type; int flags; int attr; struct timeval timestamp; } nebstruct_aggregated_status_data; /* Command data structure. */ typedef struct nebstruct_command_struct { int type; int flags; int attr; struct timeval timestamp; command* cmd; } nebstruct_command_data; /* Comment data structure. */ typedef struct nebstruct_comment_struct { int type; int flags; int attr; struct timeval timestamp; int comment_type; char const* host_name; char const* service_description; time_t entry_time; char const* author_name; char const* comment_data; int persistent; int source; int entry_type; int expires; time_t expire_time; unsigned long comment_id; void* object_ptr; /* not implemented yet */ } nebstruct_comment_data; /* Contact notification data structure. */ typedef struct nebstruct_contact_notification_struct { int type; int flags; int attr; struct timeval timestamp; int notification_type; struct timeval start_time; struct timeval end_time; char* host_name; char* service_description; char* contact_name; int reason_type; int state; char* output; char* ack_author; char* ack_data; int escalated; void* object_ptr; void* contact_ptr; } nebstruct_contact_notification_data; /* Contact notification method data structure. */ typedef struct nebstruct_contact_notification_method_struct { int type; int flags; int attr; struct timeval timestamp; int notification_type; struct timeval start_time; struct timeval end_time; char* host_name; char* service_description; char* contact_name; char* command_name; char* command_args; int reason_type; int state; char* output; char* ack_author; char* ack_data; int escalated; void* object_ptr; void* contact_ptr; } nebstruct_contact_notification_method_data; /* Contact status structure. */ typedef struct nebstruct_contact_status_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_contact_status_data; /* Custom variable structure. */ typedef struct nebstruct_custom_variable_struct { int type; int flags; int attr; struct timeval timestamp; char* var_name; char* var_value; void* object_ptr; } nebstruct_custom_variable_data; /* Downtime data structure. */ typedef struct nebstruct_downtime_struct { int type; int flags; int attr; struct timeval timestamp; int downtime_type; char const* host_name; char const* service_description; time_t entry_time; char const* author_name; char const* comment_data; time_t start_time; time_t end_time; int fixed; unsigned long duration; unsigned long triggered_by; unsigned long downtime_id; void* object_ptr; /* not implemented yet */ } nebstruct_downtime_data; /* Event handler structure. */ typedef struct nebstruct_event_handler_struct { int type; int flags; int attr; struct timeval timestamp; int eventhandler_type; char* host_name; char* service_description; int state_type; int state; int timeout; char* command_name; char* command_args; char* command_line; struct timeval start_time; struct timeval end_time; int early_timeout; double execution_time; int return_code; char* output; void* object_ptr; } nebstruct_event_handler_data; /* External command data structure. */ typedef struct nebstruct_external_command_struct { int type; int flags; int attr; struct timeval timestamp; int command_type; time_t entry_time; char* command_string; char* command_args; } nebstruct_external_command_data; /* Flapping data structure. */ typedef struct nebstruct_flapping_struct { int type; int flags; int attr; struct timeval timestamp; int flapping_type; char* host_name; char* service_description; double percent_change; double high_threshold; double low_threshold; unsigned long comment_id; void* object_ptr; } nebstruct_flapping_data; /* Group structure. */ typedef struct nebstruct_group_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_group_data; /* Group member structure. */ typedef struct nebstruct_group_member_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; void* group_ptr; } nebstruct_group_member_data; /* Host check structure. */ typedef struct nebstruct_host_check_struct { int type; int flags; int attr; struct timeval timestamp; char* host_name; int current_attempt; int check_type; int max_attempts; int state_type; int state; int timeout; char* command_name; char* command_args; char* command_line; struct timeval start_time; struct timeval end_time; int early_timeout; double execution_time; double latency; int return_code; char* output; char* long_output; char* perf_data; void* object_ptr; } nebstruct_host_check_data; /* Host status structure. */ typedef struct nebstruct_host_status_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_host_status_data; /* Log data structure. */ typedef struct nebstruct_log_struct { int type; int flags; int attr; struct timeval timestamp; time_t entry_time; int data_type; char* data; } nebstruct_log_data; /* Module data structure. */ typedef struct nebstruct_module_struct { int type; int flags; int attr; struct timeval timestamp; char* module; char* args; } nebstruct_module_data; /* Notification data structure. */ typedef struct nebstruct_notification_struct { int type; int flags; int attr; struct timeval timestamp; int notification_type; struct timeval start_time; struct timeval end_time; char* host_name; char* service_description; int reason_type; int state; char* output; char* ack_author; char* ack_data; int escalated; int contacts_notified; void* object_ptr; } nebstruct_notification_data; /* Process data structure. */ typedef struct nebstruct_process_struct { int type; int flags; int attr; struct timeval timestamp; } nebstruct_process_data; /* Program status structure. */ typedef struct nebstruct_program_status_struct { int type; int flags; int attr; struct timeval timestamp; time_t program_start; int pid; int daemon_mode; time_t last_command_check; time_t last_log_rotation; int notifications_enabled; int active_service_checks_enabled; int passive_service_checks_enabled; int active_host_checks_enabled; int passive_host_checks_enabled; int event_handlers_enabled; int flap_detection_enabled; int failure_prediction_enabled; int process_performance_data; int obsess_over_hosts; int obsess_over_services; unsigned long modified_host_attributes; unsigned long modified_service_attributes; char const* global_host_event_handler; char const* global_service_event_handler; } nebstruct_program_status_data; /* Relation data structure. */ typedef struct nebstruct_relation_struct { int type; int flags; int attr; struct timeval timestamp; host* hst; service* svc; host* dep_hst; service* dep_svc; } nebstruct_relation_data; /* Retention data structure. */ typedef struct nebstruct_retention_struct { int type; int flags; int attr; struct timeval timestamp; } nebstruct_retention_data; /* Service check structure. */ typedef struct nebstruct_service_check_struct { int type; int flags; int attr; struct timeval timestamp; char* host_name; char* service_description; int check_type; int current_attempt; int max_attempts; int state_type; int state; int timeout; char* command_name; char* command_args; char* command_line; struct timeval start_time; struct timeval end_time; int early_timeout; double execution_time; double latency; int return_code; char* output; char* long_output; char* perf_data; void* object_ptr; } nebstruct_service_check_data; /* Service status structure. */ typedef struct nebstruct_service_status_struct { int type; int flags; int attr; struct timeval timestamp; void* object_ptr; } nebstruct_service_status_data; /* State change structure. */ typedef struct nebstruct_statechange_struct { int type; int flags; int attr; struct timeval timestamp; int statechange_type; char* host_name; char* service_description; int state; int state_type; int current_attempt; int max_attempts; char* output; void* object_ptr; } nebstruct_statechange_data; /* System command structure. */ typedef struct nebstruct_system_command_struct { int type; int flags; int attr; struct timeval timestamp; struct timeval start_time; struct timeval end_time; int timeout; char* command_line; int early_timeout; double execution_time; int return_code; char* output; } nebstruct_system_command_data; /* Timed event data structure. */ typedef struct nebstruct_timed_event_struct { int type; int flags; int attr; struct timeval timestamp; int event_type; int recurring; time_t run_time; void* event_data; void* event_ptr; } nebstruct_timed_event_data; #endif /* !CCE_NEBSTRUCTS_HH */
acfa2de63581701ee45fa3bf96f5c48bac3dcb41
0e40a0486826825c2c8adba9a538e16ad3efafaf
/S3DAPI/HookDirect3D9.h
62c9f36c72860c4685c7437adb2a3cec3ac3fae6
[ "MIT" ]
permissive
iraqigeek/iZ3D
4c45e69a6e476ad434d5477f21f5b5eb48336727
ced8b3a4b0a152d0177f2e94008918efc76935d5
refs/heads/master
2023-05-25T19:04:06.082744
2020-12-28T03:27:55
2020-12-28T03:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,306
h
HookDirect3D9.h
#pragma once #include <d3d9.h> template<typename Signature, Signature> struct function_offset; #ifndef REGISTER_FUNCTION_OFFSET #define REGISTER_FUNCTION_OFFSET(Func, Offset) template<> struct function_offset<decltype(Func), Func> { static const int value = Offset; }; #endif REGISTER_FUNCTION_OFFSET(&IDirect3D9::QueryInterface, 0) REGISTER_FUNCTION_OFFSET(&IDirect3D9::AddRef, 1) REGISTER_FUNCTION_OFFSET(&IDirect3D9::Release, 2) REGISTER_FUNCTION_OFFSET(&IDirect3D9::RegisterSoftwareDevice, 3) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetAdapterCount, 4) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetAdapterIdentifier, 5) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetAdapterModeCount, 6) REGISTER_FUNCTION_OFFSET(&IDirect3D9::EnumAdapterModes, 7) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetAdapterDisplayMode, 8) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CheckDeviceType, 9) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CheckDeviceFormat, 10) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CheckDeviceMultiSampleType, 11) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CheckDepthStencilMatch, 12) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CheckDeviceFormatConversion, 13) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetDeviceCaps, 14) REGISTER_FUNCTION_OFFSET(&IDirect3D9::GetAdapterMonitor, 15) REGISTER_FUNCTION_OFFSET(&IDirect3D9::CreateDevice, 16)
70dac4a7a90be0a76b2e488a0585986a367fd77f
43f6f1bea42500a3f451c7067d757719366766e4
/Cart/Arduino/Driver/Driver.ino
0928d06d61564dc1d1251fbcacec8b454c0efa7f
[]
no_license
nonguyen1/HHack
fa81b4d0b27329b7b037667e0569f4e1022ab4eb
53b70ceabe633e0d2756a09eb933fda42fc8d7cf
refs/heads/master
2020-04-17T13:30:19.796170
2019-01-20T20:23:14
2019-01-20T20:23:14
166,618,610
0
0
null
null
null
null
UTF-8
C++
false
false
3,304
ino
Driver.ino
#define MOTOR_A_CONTROL_1 5 #define MOTOR_A_CONTROL_2 6 #define MOTOR_B_CONTROL_1 7 #define MOTOR_B_CONTROL_2 8 #define MOTOR_A_PWM 10 #define MOTOR_B_PWM 9 // TODO: change it #define MOTOR_SPEED_FAST 255 #define MOTOR_SPEED_MEDIUM 150 #define MOTOR_SPEED_SLOW 50 #define ENCODER_A 2 #define ENCODER_B 3 volatile int aCount = 0; volatile int bCount = 0; volatile bool isAForward = true; volatile bool isBForward = true; void setup() { Serial.begin(115200); // Motor Driver TB6612FNG pinMode(MOTOR_A_CONTROL_1, OUTPUT); pinMode(MOTOR_A_CONTROL_2, OUTPUT); pinMode(MOTOR_B_CONTROL_1, OUTPUT); pinMode(MOTOR_B_CONTROL_2, OUTPUT); pinMode(MOTOR_A_PWM, OUTPUT); pinMode(MOTOR_B_PWM, OUTPUT); // Encoder digitalWrite (ENCODER_A, HIGH); // enable pull-ups digitalWrite (ENCODER_B, HIGH); attachInterrupt (0, encoderACB, RISING); // interrupt 0 is pin 2, interrupt 1 is pin 3 attachInterrupt (1, encoderBCB, RISING); } void loop() { motorSpeed(100, 100); backward(); delay(2000); shortBreak(); // motorSpeed(MOTOR_SPEED_MEDIUM, MOTOR_SPEED_MEDIUM); // testDrive(); // // motorSpeed(MOTOR_SPEED_FAST, MOTOR_SPEED_FAST); // // testDrive(); while (1); } void testDrive() { forward(); delay(500); backward(); delay(500); left(); delay(500); right(); delay(500); shortBreak(); } /** Set motor speed @param left motor speed @param right motor speed */ void motorSpeed(int left, int right) { analogWrite(MOTOR_A_PWM, min(left, 255)); analogWrite(MOTOR_B_PWM, min(right, 255)); } // Set motor driver to go forward void forward() { isAForward = true; isBForward = true; digitalWrite(MOTOR_A_CONTROL_1, HIGH); digitalWrite(MOTOR_A_CONTROL_2, LOW); digitalWrite(MOTOR_B_CONTROL_1, HIGH); digitalWrite(MOTOR_B_CONTROL_2, LOW); } // Set motor driver to go backward void backward() { isAForward = false; isBForward = false; digitalWrite(MOTOR_A_CONTROL_1, LOW); digitalWrite(MOTOR_A_CONTROL_2, HIGH); digitalWrite(MOTOR_B_CONTROL_1, LOW); digitalWrite(MOTOR_B_CONTROL_2, HIGH); } // Set motor driver to go left void left() { isAForward = false; isBForward = true; digitalWrite(MOTOR_A_CONTROL_1, HIGH); digitalWrite(MOTOR_A_CONTROL_2, LOW); digitalWrite(MOTOR_B_CONTROL_1, LOW); digitalWrite(MOTOR_B_CONTROL_2, HIGH); } // Set motor driver to go right void right() { isAForward = true; isBForward = false; digitalWrite(MOTOR_A_CONTROL_1, LOW); digitalWrite(MOTOR_A_CONTROL_2, HIGH); digitalWrite(MOTOR_B_CONTROL_1, HIGH); digitalWrite(MOTOR_B_CONTROL_2, LOW); } // Set motor driver to short break mode void shortBreak() { isAForward = true; isBForward = true; digitalWrite(MOTOR_A_CONTROL_1, HIGH); digitalWrite(MOTOR_A_CONTROL_2, HIGH); digitalWrite(MOTOR_B_CONTROL_1, HIGH); digitalWrite(MOTOR_B_CONTROL_2, HIGH); } // Interrupt Service Routine for a change to encoder pin A void encoderACB () { if (isAForward) { aCount++; } else { aCount--; } Serial.print(aCount); Serial.print("\t"); Serial.println(bCount); } // Interrupt Service Routine for a change to encoder pin B void encoderBCB () { if (isBForward) { bCount++; } else { bCount--; } Serial.print(aCount); Serial.print("\t"); Serial.println(bCount); }
dc77546cd6e304489f888865ab26e8ba0e99c159
6f714dbab92f0507f13aa582fa992277e42c1777
/Plugin/ping/PingMgr.cpp
36bb4e1153cf812e6da405cb4829d0fcd0dc9300
[]
no_license
sinzuo/bluedon-soc
90d72b966ace8d49b470dab791bd65f0d56d520e
809b59888de2f94b345b36ae33afacdbe103a1dd
refs/heads/master
2020-09-20T17:54:20.882559
2019-11-28T02:27:16
2019-11-28T02:27:16
224,552,658
0
1
null
null
null
null
UTF-8
C++
false
false
12,518
cpp
PingMgr.cpp
#include "PingMgr.h" #include "utils/bdstring.h" #include "icmp/bd_ping.h" #include <iostream> #include <cstdio> using namespace Poco; using namespace std; CPingMgr::CPingMgr(const string &strConfigName) { m_strConfigName = strConfigName; memset(&m_pingConfig,0,sizeof(m_pingConfig)); m_pFuncReportData = NULL; m_pFuncFetchData = NULL; m_bIsRunning = false; m_pthreadnum = 0; m_pthreadnum_alive = 0; m_bIsLoaded = false; m_vecPolicy.clear(); m_vecThreadPool.clear(); } CPingMgr::~CPingMgr(void) { m_vecPolicy.clear(); m_vecThreadPool.clear(); } //初始化数据,先于Start被调用 bool CPingMgr::Init(void) { if(access(m_strConfigName.c_str(), F_OK) != 0) { return false; } if(!LoadConfig()) { return false; } if( strlen(m_pingConfig.chLog4File) > 0 ) { if(access(m_pingConfig.chLog4File, F_OK) != 0) { return false; } else { try { log4cxx::PropertyConfigurator::configure(m_pingConfig.chLog4File); //g_logger = Logger::getLogger("LOG4_PROXY"); } catch (Exception &) { return false; } } } else { return false; } PING_INFO_S( CPingMgr::Init() successed...); printConfig(); return true; } bool CPingMgr::IsRunning(void) { FastMutex::ScopedLock lock(m_ModMutex); return m_bIsRunning; } UInt32 CPingMgr::GetModuleId(void) { return m_pingConfig.nModuleId; } UInt16 CPingMgr::GetModuleVersion(void) { return m_pingConfig.wModuleVersion; } string CPingMgr::GetModuleName(void) { return m_pingConfig.chModuleName; } //开始(下发)任务 bool CPingMgr::StartTask(const PModIntfDataType pDataType,const void * pData) { return true; } //停止(取消)任务 bool CPingMgr::StopTask(const PModIntfDataType pDataType,const void * pData) { return true; } bool CPingMgr::LoadConfig(void) { AutoPtr<IniFileConfiguration> pConf = NULL; try { pConf = new IniFileConfiguration(m_strConfigName); } catch (NotFoundException& exc ) { cerr << "PING LoadConfig IniFileConfiguration:" << exc.displayText() << endl; return false; } catch (SyntaxException& exc) { cerr << "LoadConfig IniFileConfiguration:" << exc.displayText() << endl; return false; } catch (Exception& exc) { cerr << "PING LoadConfig:" << exc.displayText() << endl; return false; } try { GET_CONF_ITEM_CHAR(log4configfile,m_pingConfig.chLog4File,100); GET_CONF_ITEM_INT(moduleid,m_pingConfig.nModuleId); GET_CONF_ITEM_CHAR(modulename,m_pingConfig.chModuleName,20); GET_CONF_ITEM_INT(moduleversion,m_pingConfig.wModuleVersion); GET_CONF_ITEM_CHAR(record_separator,m_pingConfig.chRecordSep,2); GET_CONF_ITEM_CHAR(field_separator,m_pingConfig.chFieldSep,2); GET_CONF_ITEM_INT(tasknum_perthread,m_pingConfig.nTaskNumPerThread); GET_CONF_ITEM_INT(nSleepsec,m_pingConfig.nSleepsec); if( m_pingConfig.nTaskNumPerThread <= 0 ) { m_pingConfig.nTaskNumPerThread = 1000; // 默认每个线程处理1000个IP } if( m_pingConfig.nSleepsec <= 0 ) { m_pingConfig.nSleepsec = 60; // 默认睡眠60秒 } } catch (NotFoundException& exc ) { cerr << "PING LoadConfig:" << exc.displayText() << endl; return false; } catch (SyntaxException& exc) { cerr << "PING LoadConfig:" << exc.displayText() << endl; return false; } return true; } void CPingMgr::printConfig() { PING_INFO_S(<=========netservice configure information=========>); PING_INFO_V(" log4configfile=> ["+string(m_pingConfig.chLog4File)+string("]")); char chModuleId[10] = {0}; sprintf(chModuleId,"%d",m_pingConfig.nModuleId); PING_INFO_V(" moduleid=> ["+string(chModuleId)+string("]")); PING_INFO_V(" modulename=> ["+string(m_pingConfig.chModuleName)+string("]")); char chVersion[10] = {0}; sprintf(chVersion,"%d",m_pingConfig.wModuleVersion); PING_INFO_V(" moduleversion=> ["+string(chVersion)+string("]")); PING_INFO_V(" record_separator=> ["+string(m_pingConfig.chRecordSep)+string("]")); PING_INFO_V(" field_separator=> ["+string(m_pingConfig.chFieldSep)+string("]")); char chTemp[5] = {0}; sprintf(chTemp,"%d",m_pingConfig.nTaskNumPerThread); PING_INFO_V(" tasknum_perthread=> ["+string(chTemp)+string("]")); sprintf(chTemp,"%d", m_pingConfig.nSleepsec); PING_INFO_V(" nSleepsec=> ["+string(chTemp)+string("]")); PING_INFO_S(<=========netservice configure information=========>); } bool CPingMgr::Load(void) { return true; } //调用方下发数据 bool CPingMgr::SetData(const PModIntfDataType pDataType,const void * pData,UInt32 dwLength) { string strPolicy = *(string *)pData; m_vecPolicy.clear(); vector<string> vecIP; string strFsep = m_pingConfig.chFieldSep; string_split(strPolicy,strFsep,vecIP); if(vecIP.size() == 0) return false; m_vecPolicy.reserve(vecIP.size()); vector<string>::iterator iter = vecIP.begin(); PING_INFO_S(<=========PING PlOCY=========>); for(;iter!= vecIP.end();iter++) { tag_ping_policy_t temp; temp.strIP = *iter; //temp.nResult = 0; temp.bChange = false; m_vecPolicy.push_back(temp); PING_INFO_V(" PING PlOCY =>" + temp.strIP); } PING_INFO_S(<=========PING PlOCY=========>); m_pthreadnum = 1; //(int)ceil((double)m_vecPolicy.size()/m_pingConfig.nTaskNumPerThread); m_vecThreadPool.reserve(m_pthreadnum); // 提前分配线程池空间 char chThreadNum[10] = {0}; sprintf(chThreadNum, "%d", m_pthreadnum); PING_DEBUG_V("m_pthread number = " + string(chThreadNum)); return true; } //调用方获取数据 void * CPingMgr::GetData(const PModIntfDataType pDataType,UInt32& dwRetLen) { return NULL; } //调用方释放获取到的内存 void CPingMgr::FreeData(void * pData) { return; } //set callback for report function void CPingMgr::SetReportData(pFunc_ReportData pCbReport) { m_pFuncReportData = pCbReport; } //set call back for fetch function void CPingMgr::SetFetchData(pFunc_FetchData pCbFetch) { m_pFuncFetchData = pCbFetch; } //Report Data bool CPingMgr::ReportData(const PModIntfDataType pDataType,const void * pData,UInt32 dwLength) { if (m_pFuncReportData){ return m_pFuncReportData(m_pingConfig.nModuleId,pDataType,pData,dwLength); } return true; } //Fetch Data const char* CPingMgr::FetchData(const PModIntfDataType pDataType,UInt32& dwRetLen) { return NULL; } //启动模块 bool CPingMgr::Start(void) { FastMutex::ScopedLock lock(m_ModMutex); /* for test..... *string test = "172.16.12.153~172.16.33.3~172.16.33.4~172.16.12.210"; *SetData(NULL,&test,0); */ if (! m_bIsRunning ) { pthread_attr_t pa; //线程属性 pthread_attr_init(&pa); //初始化线程属性 pthread_attr_setdetachstate(&pa, PTHREAD_CREATE_DETACHED); //设置线程属性 for (int i=0; i<m_pthreadnum; i++) { tag_ping_threadpool_t temp; memset(&temp, 0, sizeof(temp)); temp.t_num = i; m_vecThreadPool.push_back(temp); if (pthread_create(&(m_vecThreadPool[i].t_id), &pa, OnPingHandle, this) != 0) { PING_ERROR_S(Create OnPingHandle Thread failed!); return false; } usleep(10000); // 10毫秒,启动线程需要一些执行时间 m_pthreadnum_alive++; PING_INFO_S(Create OnPingHandle Thread successed!); } if (pthread_create(&p_thread_report, &pa, OnReportHandle, this) != 0) { PING_ERROR_S(Create OnReportHandle Thread failed!); return false; } usleep(1000); // 1毫秒 PING_INFO_S(Create OnReportHandle Thread successed!); } m_bIsLoaded = true; PING_INFO_S(CPingMgr::Start successed!); return true; } //停止模块 bool CPingMgr::Stop(void) { FastMutex::ScopedLock lock(m_ModMutex); m_bIsLoaded = false; for(int i=0; i< m_pthreadnum; i++) { m_vecThreadPool[i].b_state = false; } //m_vecThreadPool PING_INFO_S(CPingMgr::Stop successed!); return true; } void *CPingMgr::OnFetchHandle(void *arg) { return NULL; } //上报ping结果 void *CPingMgr::OnReportHandle(void *arg) { //if (pthread_detach(pthread_self()) ==0 ) PING_INFO_S(start thread with detach state...); CPingMgr *cThis = reinterpret_cast<CPingMgr*>(arg); while(true) { if ( cThis->m_pthreadnum == cThis->m_pthreadnum_alive ) { cThis->m_bIsRunning = true; //此时线程池中所有线程已经建立完毕 } vector<tag_ping_policy_t>::iterator iter_temp = cThis->m_vecPolicy.begin(); for( ;iter_temp != cThis->m_vecPolicy.end(); iter_temp++) { if( iter_temp->bChange ) { // 结果有变化才上报 char chRes[64] = {0}; sprintf(chRes, "%d~%d", iter_temp->nResult, iter_temp->nTimecost); string strResult = chRes; strResult = iter_temp->strIP + cThis->m_pingConfig.chFieldSep + strResult + "~0~0"; modintf_datatype_t temp; temp.nDataType = MODULE_DATA_PERFORMANCE; temp.nMainCategory = MODULE_DATA_PERFORMANCE_PING; if(! cThis->ReportData(&temp,(void *)&(strResult),strResult.length()) ) { PING_DEBUG_S(Report data failed!); } else { iter_temp->bChange = false; // 重置 PING_DEBUG_V("Report data: " + strResult); } } } if(cThis->m_pthreadnum_alive == 0 ) { break; //ping处理线程池全部退出后则退出该线程 } if(cThis->m_bIsRunning) sleep(1); // 不用一直扫描 } cThis->m_bIsRunning = false; cThis->m_vecThreadPool.clear(); PING_INFO_S(OnReportHandle Thread exit...); return NULL; } void* CPingMgr::OnPingHandle(void *arg) { //if (pthread_detach(pthread_self()) ==0 ) PING_INFO_S(start thread with detach state...); CPingMgr *cThis = reinterpret_cast<CPingMgr*>(arg); int thread_num = cThis->m_vecThreadPool.size() - 1; // 当前线程num号 cThis->m_vecThreadPool[thread_num].b_state = true; // 线程状态修改为启动 int timout = 1000000; // ping的超时时间(单位:microsecond) int nPolocyNum = cThis->m_vecPolicy.size(); while( cThis->m_vecThreadPool[thread_num].b_state ) { /* if(cThis->m_bIsRunning ) { bd_ping bdPing; for(int i=thread_num; i< nPolocyNum; i += cThis->m_pthreadnum) { int timecost = 0; // 微秒(usec) bool bConnect = bdPing.ping(cThis->m_vecPolicy[i].strIP, timout, &timecost); int nRes = bConnect?2:1; //1:不通 2:连通 //修改ping结果变化状态 if (cThis->m_vecPolicy[i].nResult != nRes) { cThis->m_vecPolicy[i].nResult = nRes; cThis->m_vecPolicy[i].nTimecost = timecost; cThis->m_vecPolicy[i].bChange = true; // 需要发送结果给分析引擎 } } sleep(m_pingConfig.nSleepsec); // ping的频率 }*/ if(cThis->m_bIsRunning ) { bd_ping bdPing; for(int i = thread_num; i < nPolocyNum; i += cThis->m_pthreadnum) { int timecost = 0; bool bConnect = false; int nRes = 1; //1:不通 2:连通 string strtmp = cThis->m_vecPolicy[i].strIP; int lenth = strtmp.length(); if(strtmp[lenth - 1] == '0' && strtmp[lenth - 2] == '.') //判断是否为网段(以.0结尾) { nRes = 2; } else { bConnect = bdPing.ping(cThis->m_vecPolicy[i].strIP, timout, &timecost); nRes = bConnect? 2:1; //1:不通 2:连通 } //修改ping结果变化状态 if (cThis->m_vecPolicy[i].nResult != nRes) { cThis->m_vecPolicy[i].nResult = nRes; cThis->m_vecPolicy[i].bChange = true; // 需要发送结果给分析引擎 } usleep(70000); //休眠70 ms } for(int i = 0; i < cThis->m_pingConfig.nSleepsec/5; i++) // ping的频率 { sleep(5); if(!cThis->m_vecThreadPool[thread_num].b_state) break; //收到停止命令, 打断休眠 } } } --cThis->m_pthreadnum_alive; PING_INFO_S(OnPingHandle Thread exit...); return NULL; } //base64解码 string CPingMgr::fromBase64 (const string &source) { istringstream in(source); ostringstream out; Base64Decoder b64in(in); copy(istreambuf_iterator<char>(b64in), istreambuf_iterator<char>(), ostreambuf_iterator<char>(out)); return out.str(); }
efef644b2573c303758e3c468fd724f04164e337
3854a0635e6a7784ddd91a092ca2d7dd83550bbe
/Class/NOIP/StackOverflow.cpp
cb78fdf6c255798f23e3fe1a8171dc55a62d24b1
[]
no_license
CYACN/NOIP
f92c4e16dadf74e0b4bd4863e6331e01b080cf34
b546cc5ac4b56c0c170e3496f55c7ccc47265510
refs/heads/master
2020-03-23T03:02:10.162788
2018-08-08T07:58:51
2018-08-08T07:58:51
141,005,746
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
StackOverflow.cpp
#include <queue> #include <iostream> using namespace std; queue<int> hi; int main(int argc, char const *argv[]) { hi.push(7); hi.push(5); hi.push(3); //int x = hi.front; while(hi.empty!=1) { hi.pop; } return 0; }
f3e21b287a336ae8fd5fe2c32825e68a6bb1e30b
ea8aa77c861afdbf2c9b3268ba1ae3f9bfd152fe
/zoj3953_copy.cpp
2f3a53ec470efdc5d1a71823988a2896ba679a37
[]
no_license
lonelam/SolveSet
987a01e72d92f975703f715e6a7588d097f7f2e5
66a9a984d7270ff03b9c2dfa229d99b922907d57
refs/heads/master
2021-04-03T02:02:03.108669
2018-07-21T14:25:53
2018-07-21T14:25:53
62,948,874
9
3
null
null
null
null
UTF-8
C++
false
false
1,756
cpp
zoj3953_copy.cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<vector> using namespace std; int dd[100005],num[100005],cnt; struct node{ int x,y,lab; bool operator <(const node& a)const{ return y<a.y; } }e[50005]; vector<int>ans; priority_queue<node,vector<node>,less<node> >sp; bool cmp(node a,node b){ return a.x<b.x; } int main(){ int t; scanf("%d",&t); while(t--){ int n,i,j; scanf("%d",&n); memset(dd,0,sizeof(dd)); cnt=0; for(i=1;i<=n;i++){ scanf("%d%d",&e[i].x,&e[i].y); e[i].lab=i; num[++cnt]=e[i].x; num[++cnt]=e[i].y; } sort(e+1,e+1+n,cmp); int mix=0; sort(num+1,num+1+cnt); cnt=unique(num+1,num+1+cnt)-num-1; for(i=1;i<=n;i++){ e[i].x=lower_bound(num+1,num+1+cnt,e[i].x)-num; e[i].y=lower_bound(num+1,num+1+cnt,e[i].y)-num; } e[n+1].x=-111; int now=1; while(!sp.empty())sp.pop(); ans.clear(); for(i=1;i<=cnt;i++){ while(e[now].x==i){ sp.push(e[now]); mix++; dd[e[now].y+1]--; now++; } mix+=dd[i]; while(mix>=3){ node f=sp.top(); sp.pop(); mix--; dd[f.y+1]++; ans.push_back(f.lab); } } sort(ans.begin(),ans.end()); int dt=ans.size(); printf("%d\n",dt); for(i=0;i<dt;i++){ printf("%d",ans[i]); if(i==dt-1)break; else printf(" "); } printf("\n"); } return 0; }
df859b3e3804e4ffcc3b985ec6518251a1b03a63
a5ccbbfff9cc6a477bfea9853cf3b9e8a6e1ff57
/Source/murphys/Minigames/Starfighter/StarfighterPlayerController.h
cf87ce47b86b38c9cebef1d9df18348fd6d10504
[]
no_license
Quarantine-Zone/murphys
373909375993efd61c8a121973528375881196dc
82c9682c060d5d3a2265eff37ec835d2307e6165
refs/heads/master
2022-08-01T21:11:40.980543
2020-06-01T22:16:29
2020-06-01T22:16:29
261,191,987
0
0
null
null
null
null
UTF-8
C++
false
false
599
h
StarfighterPlayerController.h
#pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "StarfighterPlayerController.generated.h" /** * */ enum TeamEnum; UCLASS() class MURPHYS_API AStarfighterPlayerController : public APlayerController { GENERATED_BODY() private: UPROPERTY(EditAnywhere) float CrosshairXLocation = .5; UPROPERTY(EditAnywhere) float CrosshairYLocation = .4; // UPROPERTY(BlueprintReadWrite) // TeamEnum team; public: FVector2D GetSteeringVector(); //UFUNCTION(Server, Reliable) //void Server_TeamSelected(APlayerController* player, TeamEnum team); };
ec85c45f7c571b40ab6d9f049590a502e5385f09
95c4a9c4129d131206f057beeaa3a1872bead809
/Longest Palindromic Substring.cc
52b65b478c972576aee2beda95d695eb19cec1dc
[]
no_license
Dionysus1227/edocteel
85c6daeff6a6b895b829fcace118e16bfeff1e86
3c8fa5ae88538037916adc40e8588b8a9407d67f
refs/heads/master
2016-09-06T04:16:42.171813
2013-10-06T09:37:59
2013-10-06T09:37:59
12,487,458
0
1
null
null
null
null
UTF-8
C++
false
false
918
cc
Longest Palindromic Substring.cc
class Solution { public: string longestPalindrome(string s) { if (s.empty()) return ""; vector<int> expand; for (int i = 0; i < s.size(); i++) { expand.push_back(-1); expand.push_back(s[i]); } expand.push_back(-1); vector<int> best(expand.size(), 0); int center = 1; int ans = 1; for (int i = 1; i < expand.size(); i++) { best[i] = min(best[center * 2 - i], center + best[center] - i); for (; i - best[i] - 1 >= 0 && i + best[i] + 1 < expand.size() && expand[i - best[i] - 1] == expand[i + best[i] + 1]; best[i]++); if (i + best[i] > center + best[center]) center = i; if (best[i] > best[ans]) ans = i; } return s.substr((ans - best[ans]) / 2, best[ans]); } };
cc7200af8938f0fa1d76964e68e6e2c298f604fa
c068fd732028306b2265a31bae92b59f62410a2b
/src/autocorrectcomplete.cpp
b7527ebd7a04e73e7b1fde1699f2b769d33b9631
[]
no_license
EricLiCA/autocorrect
a3351b56efc5709c18222607b47a5f8f7893345b
5bd839cc88024323c3ab0c77d75123d1d1b107d6
refs/heads/master
2022-03-09T05:36:29.503909
2017-10-08T21:10:48
2017-10-08T21:10:48
106,209,790
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
cpp
autocorrectcomplete.cpp
#include "autocorrectcomplete.h" #include "ui_autocorrectcomplete.h" AutoCorrectComplete::AutoCorrectComplete(QWidget *parent) : QWidget(parent), ui(new Ui::AutoCorrectComplete) { ui->setupUi(this); connect(ui->pushButton, SIGNAL(click()), this, SLOT(back())); tree_ = nullptr; } AutoCorrectComplete::~AutoCorrectComplete() { delete ui; } void AutoCorrectComplete::on_pushButton_clicked() { back(); } void AutoCorrectComplete::back() { this->hide(); } void AutoCorrectComplete::on_lineEdit_textChanged(const QString &arg1) { if(arg1.endsWith(" ")){ //autocorrect ui->textEdit->clear(); std::string word = arg1.toStdString(); word.pop_back(); if(word.size() > 1){ std::vector<std::string> lexiconV = tree_->autocorrect(word); for(int i = 0; i < lexiconV.size() && i < 10; i++){ std::string word = lexiconV[i]; QString w = QString::fromStdString(word); ui->textEdit->append(w); } } else{ // autocomplete if only one letter typed by the user ui->textEdit->clear(); std::string word = arg1.toStdString(); word.pop_back(); tree_->autocomplete(word); std::vector<std::string> lexiconV = tree_->getSuggestions(); for(int i = 0; i < lexiconV.size() && i < 10; i++){ std::string word = lexiconV[i]; QString w = QString::fromStdString(word); ui->textEdit->append(w); } } } else if(arg1 != ""){ // autocomplete ui->textEdit->clear(); std::string word = arg1.toStdString(); tree_->autocomplete(word); std::vector<std::string> lexiconV = tree_->getSuggestions(); for(int i = 0; i < lexiconV.size() && i < 10; i++){ std::string word = lexiconV[i]; QString w = QString::fromStdString(word); ui->textEdit->append(w); } } else ui->textEdit->clear(); } void AutoCorrectComplete::setTree(Tree* tree){ tree_ = tree; }
b924d75950763fab072c08c941a128a43190cc98
035962062f7aff530fac5bf7e01f4dfc4def33db
/kded/kwin_bridge/dummydecoratedclient.cpp
83bfc9eae9c831500d174343d0baaeedef80c3af
[]
no_license
KDE/kde-gtk-config
572b8c78ec2c02bada067ac9708c509ce1977952
889eddb89c1827c83968e8d81170261751bac2e6
refs/heads/master
2023-08-08T11:39:12.920981
2023-08-06T11:26:44
2023-08-06T11:29:33
42,731,610
33
3
null
null
null
null
UTF-8
C++
false
false
3,383
cpp
dummydecoratedclient.cpp
/* * SPDX-FileCopyrightText: 2020 Mikhail Zolotukhin <zomial@protonmail.com> * * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "dummydecoratedclient.h" namespace KDecoration2 { DummyDecoratedClient::DummyDecoratedClient(DecoratedClient *client, Decoration *decoration) : DecoratedClientPrivate(client, decoration) , m_pallete(QStringLiteral("kdeglobals")) , m_maximized() , m_active(true) { } bool DummyDecoratedClient::isActive() const { return m_active; } QString DummyDecoratedClient::caption() const { return {}; } bool DummyDecoratedClient::isOnAllDesktops() const { return true; } bool DummyDecoratedClient::isShaded() const { return true; } QIcon DummyDecoratedClient::icon() const { return {}; } bool DummyDecoratedClient::isMaximized() const { return m_maximized; } bool DummyDecoratedClient::isMaximizedHorizontally() const { return m_maximized; } bool DummyDecoratedClient::isMaximizedVertically() const { return m_maximized; } bool DummyDecoratedClient::isKeepAbove() const { return true; } bool DummyDecoratedClient::isKeepBelow() const { return true; } bool DummyDecoratedClient::isCloseable() const { return true; } bool DummyDecoratedClient::isMaximizeable() const { return true; } bool DummyDecoratedClient::isMinimizeable() const { return true; } bool DummyDecoratedClient::providesContextHelp() const { return true; } bool DummyDecoratedClient::isModal() const { return true; } bool DummyDecoratedClient::isShadeable() const { return true; } bool DummyDecoratedClient::isMoveable() const { return true; } bool DummyDecoratedClient::isResizeable() const { return true; } WId DummyDecoratedClient::windowId() const { return {}; } WId DummyDecoratedClient::decorationId() const { return {}; } int DummyDecoratedClient::width() const { return {}; } int DummyDecoratedClient::height() const { return {}; } QSize DummyDecoratedClient::size() const { return {}; } QPalette DummyDecoratedClient::palette() const { return m_pallete.palette(); } QColor DummyDecoratedClient::color(ColorGroup group, ColorRole role) const { return m_pallete.color(group, role); } Qt::Edges DummyDecoratedClient::adjacentScreenEdges() const { return {}; } QString DummyDecoratedClient::windowClass() const { return {}; } void DummyDecoratedClient::requestShowToolTip(const QString &text) { Q_UNUSED(text) } void DummyDecoratedClient::requestHideToolTip() { } void DummyDecoratedClient::requestClose() { } void DummyDecoratedClient::requestToggleMaximization(Qt::MouseButtons buttons) { Q_UNUSED(buttons) m_maximized = !m_maximized; } void DummyDecoratedClient::requestMinimize() { } void DummyDecoratedClient::requestContextHelp() { } void DummyDecoratedClient::requestToggleOnAllDesktops() { } void DummyDecoratedClient::requestToggleShade() { } void DummyDecoratedClient::requestToggleKeepAbove() { } void DummyDecoratedClient::requestToggleKeepBelow() { } void DummyDecoratedClient::requestShowWindowMenu(const QRect &rect) { Q_UNUSED(rect) } void DummyDecoratedClient::setMaximized(bool maximized) { m_maximized = maximized; } void DummyDecoratedClient::setActive(bool active) { m_active = active; } } #include "moc_dummydecoratedclient.cpp"
d9bfb460c7ce76cdb2eb5e594824fdea794290ae
1c17e303249b5036c46d95e5e0075ac932aeeb7f
/cppBaseGrammar/drink.h
392c79dd76133096a34073c7a8af7fd3f381e8d4
[]
no_license
ilib0x00000000/code-x
6275a5526b1a68d1c837f4ed906b7f746bff1230
dc2d47fa94cf3b4707afe6ab314d73d409e44409
refs/heads/master
2020-05-21T16:48:55.423772
2017-09-02T14:32:47
2017-09-02T14:32:47
84,635,302
0
0
null
null
null
null
UTF-8
C++
false
false
84
h
drink.h
namespace kedaierboluo { struct User{ char *name; char sex; int age; }; }
22b14982bd6fe35c8bcb277d0082661c5c32ec38
5b9619fa90d6617a6264e64b3fa6129dfa517f1a
/Qt - Station de Montagne/mainview.h
059ecbbd56ba83c279e3c6792735a964606c3407
[]
no_license
pvnkrockjesvs/StationMontagne
bee31185cc8d1ec38bcf0a4c680c9b9409112bdf
f5b0bd5d4e29f247b4d27ac509bd633b9284d696
refs/heads/master
2020-11-30T20:42:45.006713
2019-12-29T16:01:56
2019-12-29T16:01:56
230,474,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
h
mainview.h
#include <QMainWindow> namespace Ui { class MainView; } class MainView : public QMainWindow { Q_OBJECT public: explicit MainView(QWidget *parent = nullptr); ~MainView(); bool etatPiste1; bool etatPiste2; bool etatPiste3; bool etatPiste4; bool etatPiste5; bool etatPiste6; QString etatTelesiege1; QString etatTelesiege2; QString message[10]; Ui::MainView *ui; private slots: void on_piste1ouvert_clicked(); void on_piste1ferme_clicked(); void on_piste2ouvert_clicked(); void on_piste2ferme_clicked(); void on_piste3ouvert_clicked(); void on_piste3ferme_clicked(); void on_piste4ouvert_clicked(); void on_piste4ferme_clicked(); void on_piste5ouvert_clicked(); void on_piste5ferme_clicked(); void on_piste6ouvert_clicked(); void on_piste6ferme_clicked(); void on_teles1ouvert_clicked(); void on_teles1ferme_clicked(); void on_teles2ouvert_clicked(); void on_teles2ferme_clicked(); void on_message1Edit_textChanged(); void on_message2Edit_textChanged(); void on_message3Edit_textChanged(); void on_message4Edit_textChanged(); void on_message5Edit_textChanged(); void on_message6Edit_textChanged(); void on_message7Edit_textChanged(); void on_message8Edit_textChanged(); void on_message9Edit_textChanged(); void on_message10Edit_textChanged(); void on_ConfirmerP_clicked(); void on_ConfirmerM_clicked(); signals: void sigChangement(); private: // void Modification(); };
346258e4fb2c1659e01e458b4a59d46b0229c71e
7992642cb94d5d5b6113b3efd423f6966639f637
/main.cpp
c464aaeba3dd7f7486d4959bf87ebeabcfa21fa0
[]
no_license
nicotho/circuit_simulator_MNA
4db306ba92775a90fdf5ff3bc532e6d6abcd7b00
dc68a1a0189804b4a95913d6ad806ffafe278215
refs/heads/master
2020-12-24T13:44:50.174187
2014-09-29T15:48:38
2014-09-29T15:48:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
cpp
main.cpp
#include"globals.hpp" /* * TODO : Learn harwell-boeing format for dense matrix * TODO : Try if MNA matrix can be filled while reading circuit * TODO : See if MNA matrix can be filled in parallel */ int main(int argc, char* argv[]) { if(argc != 2) { cout<<"Error: Input circuit not found"<<endl; exit(1); } cout<<endl<<"***************************************START***************************************************"<<endl; GraphOfNetwork G; G.convertNetworkIntoGraph(argv[1]); G.findVoltage(); G.printSolution(); cout<<endl<<"***************************************END*****************************************************"<<endl; return 0; }
983f1ee87e045591bd27fa3d0bb0222182f03c45
54b9ee00bcd582d56853ddb90be5cfeb0c29ba29
/src/utils/quake3_math_vector.cc
a6af2bc07f46a6cfea832b8a3d74eda1887283e1
[ "BSD-3-Clause" ]
permissive
pengdu/bubblefs
8f4deb8668831496bb0cd8b7d9895900b1442ff1
9b27e191a287b3a1d012adfd3bab6a30629a5f33
refs/heads/master
2020-04-04T19:32:11.311925
2018-05-02T11:20:18
2018-05-02T11:20:18
156,210,664
2
0
null
2018-11-05T11:57:22
2018-11-05T11:57:21
null
UTF-8
C++
false
false
4,047
cc
quake3_math_vector.cc
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ // Quake-III-Arena/code/splines/math_vector.cpp //#include "../game/q_shared.h" #include "utils/quake3_math_vector.h" #include <assert.h> #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include <time.h> namespace bubblefs { namespace myquake3 { #define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h #define LERP_DELTA 1e-6 idVec3_t vec_zero( 0.0f, 0.0f, 0.0f ); Bounds boundsZero; float idVec3_t::toYaw( void ) { float yaw; if ( ( y == 0 ) && ( x == 0 ) ) { yaw = 0; } else { yaw = atan2( y, x ) * 180 / M_PI; if ( yaw < 0 ) { yaw += 360; } } return yaw; } float idVec3_t::toPitch( void ) { float forward; float pitch; if ( ( x == 0 ) && ( y == 0 ) ) { if ( z > 0 ) { pitch = 90; } else { pitch = 270; } } else { forward = ( float )idSqrt( x * x + y * y ); pitch = atan2( z, forward ) * 180 / M_PI; if ( pitch < 0 ) { pitch += 360; } } return pitch; } /* angles_t idVec3_t::toAngles( void ) { float forward; float yaw; float pitch; if ( ( x == 0 ) && ( y == 0 ) ) { yaw = 0; if ( z > 0 ) { pitch = 90; } else { pitch = 270; } } else { yaw = atan2( y, x ) * 180 / M_PI; if ( yaw < 0 ) { yaw += 360; } forward = ( float )idSqrt( x * x + y * y ); pitch = atan2( z, forward ) * 180 / M_PI; if ( pitch < 0 ) { pitch += 360; } } return angles_t( -pitch, yaw, 0 ); } */ idVec3_t LerpVector( idVec3_t &w1, idVec3_t &w2, const float t ) { float omega, cosom, sinom, scale0, scale1; cosom = w1 * w2; if ( ( 1.0 - cosom ) > LERP_DELTA ) { omega = acos( cosom ); sinom = sin( omega ); scale0 = sin( ( 1.0 - t ) * omega ) / sinom; scale1 = sin( t * omega ) / sinom; } else { scale0 = 1.0 - t; scale1 = t; } return ( w1 * scale0 + w2 * scale1 ); } /* ============= idVec3_t::string This is just a convenience function for printing vectors ============= */ char *idVec3_t::string( void ) { static int index = 0; static char str[ 8 ][ 36 ]; char *s; // use an array so that multiple toString's won't collide s = str[ index ]; index = (index + 1)&7; sprintf( s, "%.2f %.2f %.2f", x, y, z ); return s; } } // namespace myquake3 } // namespace bubblefs
369e8d7d01596f9111ab95d52a44cecfff06f3c2
9e48aee08decf2bac02150454bfff2fc7d5af161
/PS/2167 2차원 배열의 합.cc
9ea3dabffcae8cf0c1c2a0584fb79ed8fb363a45
[]
no_license
sooooojinlee/TIL
f29649174506cfdf92ffeaaeaaedf343c232df0b
bd3755731a9cddc22117a5f57ccbdaa9c02d0fc4
refs/heads/master
2022-05-07T07:37:59.105932
2022-03-15T13:36:26
2022-03-15T13:36:26
202,124,182
1
1
null
null
null
null
UTF-8
C++
false
false
488
cc
2167 2차원 배열의 합.cc
#include <iostream> using namespace std; int s[301][301]; int a[301][301]; int main() { int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; s[i][j] = s[i][j - 1] + s[i - 1][j] - s[i - 1][j - 1] + a[i][j]; } } int t; cin >> t; while (t--) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; cout << s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1] << '\n'; } return 0; }
283a05c865669972bb42c1537e7e3cb0e306c95c
13b504a6635a312466175d45ae42e45467dbf188
/shifts/main.cpp
55fa24393e6f25e7044e1f1c573a86a9eeaf48f0
[]
no_license
Captain-Vorobey/labs
db24eaa2b90af188ab25e443a63dc856f749ada9
652168cfe2d6bf2d2fb3bd81f7c9541aa8e7a594
refs/heads/master
2020-03-29T23:55:21.225337
2019-03-12T12:00:40
2019-03-12T12:00:40
150,496,307
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
main.cpp
#include <iostream> #include <list> #include "print_line.h" struct Value { int byte[8]; int cf = 0; Value(std::initializer_list<int> list) { int j = 0; for(auto i = list.begin(); i != list.end(); ++i) { byte[j++] = *i; } } void print() { print_bytes_number(); for(int i = 0; i < 8; ++i) { std::cout << byte[i] << " "; } std::cout << " " << cf; std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; } void shr() { cf = byte[0]; for(int i = 0; i < 8; ++i) { byte[i] = byte[i + 1]; } byte[7] = 0; } void sar() { int temp = byte[7]; shr(); byte[7] = temp; } void shl() { cf = byte[7]; for(int i = 8; i > -1; --i) { byte[i] = byte[i - 1]; } byte[0] = 0; } void sal() { shl(); } }; int main() { Value a = {1, 2, 3, 4, 5, 6, 7, 8}; a.shr(); a.print(); Value b = {1, 2, 3, 4, 5, 6, 7, 8}; b.sar(); b.print(); b.sar(); b.print(); b.sal(); b.print(); return 0; }
806d18a9fd02269374fd762b67eb90c29652aef2
52e96fdaa9cd48fd6cad61d3cba8ecdc15f88c3a
/include/time_record.h
60e0bfee734b5fa071143b08dc8a4a95b9d731dd
[]
no_license
RTLAB-UESTC/SET-MRTS-public
7918aa76495383cd433c652cf297384c091437f2
59b9308271c353a254507d066048b763082a7c19
refs/heads/master
2021-06-23T23:10:53.299733
2020-11-02T19:15:22
2020-11-02T19:15:22
136,583,138
0
2
null
null
null
null
UTF-8
C++
false
false
650
h
time_record.h
// Copyright [2018] <Zewei Chen> // ------By Zewei Chen------ // Email:czwking1991@gmail.com #ifndef INCLUDE_TIME_RECORD_H_ #define INCLUDE_TIME_RECORD_H_ #include <types.h> #include <ctime> using std::cout; using std::endl; using std::vector; class Time_Record { private: time_t time_start, time_end; clock_t clock_start, clock_end; uint64_t start, end; public: Time_Record(); void Record_S_A(); void Record_S_B(); void Record_S(); void Record_MS_A(); void Record_MS_B(); double Record_MS(); void Record_NS_A(); void Record_NS_B(); void Record_NS(); }; #endif INCLUDE_TIME_RECORD_H_
56144a38610fb89da86d6ea63a95ef94b4401e2e
cabf3a3aa51c98c774f3efaea2f9e43dae2cdebb
/DecompressionLZW.h
46d37664488dc76b3d7afc352520cdaf183406d2
[]
no_license
26zet/LZW
43b348d26593e8708a6c6f8621e635cd72676dc7
b3c43f759a6feff39877d377a5dc34361043902f
refs/heads/master
2021-01-17T08:26:13.572339
2017-03-04T18:10:21
2017-03-04T18:10:21
83,914,037
0
0
null
null
null
null
UTF-8
C++
false
false
958
h
DecompressionLZW.h
#ifndef dlzw #define dlzw #include <string> #include "LZWStorage.h" #include "InOut.h" class DLZW{ public: InOut *IO; LZWStorage *Storage; void MainLoop(){ unsigned short t1,t2; IO->read(&t1); IO->Write(Storage->dict[t1],Storage->Length[t1]); Storage->LengthOfDict++; while(IO->read(&t2)){ if(Storage->LengthOfDict < 65536){ Storage->dict[Storage->LengthOfDict] = new char[Storage->Length[t1] + 1]; for (int i = 0; i < Storage->Length[t1]; i++) Storage->dict[Storage->LengthOfDict][i] = Storage->dict[t1][i]; Storage->dict[Storage->LengthOfDict][Storage->Length[t1]] = Storage->dict[t2][0]; Storage->Length[Storage->LengthOfDict] = Storage->Length[t1] + 1; Storage->LengthOfDict++; } IO->Write(Storage->dict[t2],Storage->Length[t2]); t1 = t2; } } public: DLZW(string a, string b){ IO = new InOut(a,b); Storage = new LZWStorage(); MainLoop(); } }; #endif
f56804d678b7d23845ecf13788887b8083632471
69c340aed4412535dd6e185ade0d3e2b6147418e
/Greedy/maximize_array_sum_in_K_negations.cpp
4b5a8c5078a9fd14e8fafd14561c2755282cae0a
[]
no_license
Meaha7/DSA-Marathon
656f1c1505adf24d2a3501a1f216e2fcb9aa3e32
9fb5c4d16a0192cb35f3da5c0a09b67ea2906dbd
refs/heads/main
2023-07-11T07:14:01.912316
2021-08-21T21:25:05
2021-08-21T21:25:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
maximize_array_sum_in_K_negations.cpp
#include <iostream> #include <vector> #include <string> #include <queue> #include <stack> using namespace std; long long int maximizeSum(long long int a[], int n, int k) { // Your code goes here priority_queue<long long, vector<long long>, greater<long long>> pq; for (int i = 0; i < n; i++) { pq.push(a[i]); } while (k--) { long long t = pq.top(); pq.pop(); t = t * (-1); pq.push(t); } long long sum = 0; while (!pq.empty()) { sum += (pq.top()); pq.pop(); } return sum; } int main() { }
7eeb76bcdb9626a65f38c7f453386ce19666ebcc
8e068eede9730e6ce3773f1e7232c34dd03ef29d
/Engine/Modules/Crypto/ProtectedKey/NotSecureKey.cpp
e9c631aaf0a7e88fd5b1916af4ff0dab6d1e60e8
[ "MIT" ]
permissive
leec0m3t/Leggiero
2e228fa23f723132883577c8018e7f6a47879f61
8fe13d86454a08ba8a3a8cebe1ce92343090c1be
refs/heads/main
2023-04-09T19:17:06.555139
2021-04-19T06:54:00
2021-04-19T06:54:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,396
cpp
NotSecureKey.cpp
//////////////////////////////////////////////////////////////////////////////// // ProtectedKey/NotSecureKey.cpp (Leggiero/Modules - Crypto) // // Not secure key implementation //////////////////////////////////////////////////////////////////////////////// // My Header #include "NotSecureKey.h" // Standard Library #include <cstdlib> // Leggiero.Utility #include <Utility/Encoding/Base64.h> namespace Leggiero { namespace Crypto { namespace Security { //////////////////////////////////////////////////////////////////////////////// NotSecureKey //------------------------------------------------------------------------------ NotSecureKey::NotSecureKey(const char *keyData, std::size_t keySize) : m_keySize(keySize) { m_keyBuffer = (uint8_t *)malloc(keySize); memcpy(m_keyBuffer, keyData, keySize); } //------------------------------------------------------------------------------ NotSecureKey::NotSecureKey(const std::string &keyData) : m_keySize(keyData.length()) { m_keyBuffer = (uint8_t *)malloc(m_keySize); memcpy(m_keyBuffer, keyData.c_str(), m_keySize); } //------------------------------------------------------------------------------ NotSecureKey::NotSecureKey(const NotSecureKey &other) : m_keySize(other.m_keySize) { m_keyBuffer = (uint8_t *)malloc(m_keySize); memcpy(m_keyBuffer, other.m_keyBuffer, m_keySize); } //------------------------------------------------------------------------------ NotSecureKey::NotSecureKey(NotSecureKey &&other) : m_keySize(other.m_keySize) , m_keyBuffer(other.m_keyBuffer) { other.m_keyBuffer = nullptr; other.m_keySize = 0; } //------------------------------------------------------------------------------ NotSecureKey &NotSecureKey::operator=(const NotSecureKey &other) { if (m_keyBuffer == nullptr) { m_keySize = other.m_keySize; m_keyBuffer = (uint8_t *)malloc(m_keySize); } else { if (m_keySize != other.m_keySize) { m_keySize = other.m_keySize; free(m_keyBuffer); m_keyBuffer = (uint8_t *)malloc(m_keySize); } } memcpy(m_keyBuffer, other.m_keyBuffer, m_keySize); return *this; } //------------------------------------------------------------------------------ NotSecureKey &NotSecureKey::operator=(NotSecureKey &&other) { if (m_keyBuffer != nullptr) { free(m_keyBuffer); } m_keySize = other.m_keySize; m_keyBuffer = other.m_keyBuffer; other.m_keyBuffer = nullptr; other.m_keySize = 0; return *this; } //------------------------------------------------------------------------------ NotSecureKey::~NotSecureKey() { if (m_keyBuffer != nullptr) { free(m_keyBuffer); } m_keyBuffer = nullptr; } //------------------------------------------------------------------------------ NotSecureKey NotSecureKey::FromBase64String(const std::string &base64Key) { return NotSecureKey(Utility::Encoding::Base64::Decode(base64Key)); } //------------------------------------------------------------------------------ std::shared_ptr<NotSecureKey> NotSecureKey::NewFromBase64String(const std::string &base64Key) { return std::make_shared<NotSecureKey>(Utility::Encoding::Base64::Decode(base64Key)); } //------------------------------------------------------------------------------ // Get length of the key size_t NotSecureKey::GetLength() const { return m_keySize; } //------------------------------------------------------------------------------ // Get key byte value at given offset uint8_t NotSecureKey::GetAt(size_t idx) const { if (idx < m_keySize) { return m_keyBuffer[idx]; } if (m_keySize == 0) { return 0; } else if (m_keySize == 1) { return m_keyBuffer[0]; } return m_keyBuffer[idx % m_keySize]; } //------------------------------------------------------------------------------ // Copy key to given buffer void NotSecureKey::FillKey(void *buffer, size_t length, size_t keyOffset) const { if (keyOffset + length <= m_keySize) { memcpy(buffer, m_keyBuffer + keyOffset, length); return; } uint8_t *byteBuffer = (uint8_t *)buffer; if (m_keySize == 0) { for (std::size_t i = 0; i < length; ++i) { byteBuffer[i] = 0; } } else if (m_keySize == 1) { uint8_t maskByte = m_keyBuffer[0]; for (std::size_t i = 0; i < length; ++i) { byteBuffer[i] = maskByte; } } for (std::size_t i = 0; i < length; ++i) { byteBuffer[i] = m_keyBuffer[(keyOffset + i) % m_keySize]; } } //------------------------------------------------------------------------------ // Do XOR on given data using the key void NotSecureKey::XORKey(void *buffer, size_t length, size_t keyOffset) const { uint8_t *byteBuffer = (uint8_t *)buffer; if (m_keySize == 0) { // No key to XOR return; } else if (m_keySize == 1) { uint8_t maskByte = m_keyBuffer[0]; for (std::size_t i = 0; i < length; ++i) { byteBuffer[i] ^= maskByte; } } for (std::size_t i = 0; i < length; ++i) { byteBuffer[i] ^= m_keyBuffer[(keyOffset + i) % m_keySize]; } } } } }
985658a777db0f67977e0d5694e00a6d85926da1
9b1639af63f7fc82f0e488b452dee0cb7ae22a3b
/SolarisNAVScanner/navex15/wdsigutl.cpp
2d7f40a32d7986396c661efe4ba8376c9fc7cc34
[]
no_license
ExpLife/Norton_AntiVirus_SourceCode
af7cd446efb2f3a10bba04db8e7438092c7299c0
b90225233fa7930d2ef7922080ed975b7abfae8c
refs/heads/master
2017-12-19T09:15:25.150463
2016-10-03T02:33:34
2016-10-03T02:33:34
76,859,815
2
4
null
2016-12-19T12:21:02
2016-12-19T12:21:01
null
UTF-8
C++
false
false
6,522
cpp
wdsigutl.cpp
//************************************************************************ // // $Header: S:/NAVEX/VCS/WDSIGUTL.CPv 1.0 17 Jan 1997 11:24:00 DCHI $ // // Description: // Utility functions for getting values from signature streams. // //************************************************************************ // $Log: S:/NAVEX/VCS/WDSIGUTL.CPv $ // // Rev 1.0 17 Jan 1997 11:24:00 DCHI // Initial revision. // //************************************************************************ #include "platform.h" #include "wdsigutl.h" //************************************************************************* // // int WDGetControlStreamNibble() // // Parameters: // lpabyControlStream Ptr to beginning of control stream // lpnIndex Ptr to int of nibble index in control stream // // Description: // Returns the value of the nibble of the control stream at the // given index. The index is incremented before the function returns. // // Returns: // int Value of nibble // //************************************************************************* int WDGetControlStreamNibble ( LPBYTE lpabyControlStream, LPINT lpnIndex ) { int nNibble; if ((*lpnIndex & 0x01) == 0) { // First nibble nNibble = lpabyControlStream[(*lpnIndex) >> 1] & 0x0F; } else { // Second nibble nNibble = (lpabyControlStream[(*lpnIndex) >> 1] >> 4) & 0x0F; } ++*lpnIndex; return(nNibble); } //************************************************************************* // // BYTE WDGetDataStreamBYTE() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the BYTE value at the current position in the data stream. // The current position is incremented by one. // // Returns: // BYTE Value of BYTE at current position // //************************************************************************* BYTE WDGetDataStreamBYTE ( LPLPBYTE lplpabyDataStream ) { BYTE by; by = **lplpabyDataStream; ++*lplpabyDataStream; return(by); } //************************************************************************* // // WORD WDGetDataStreamWORD() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the WORD value at the current position in the data stream. // The current position is incremented by two. // // The WORD value returned is properly endianized. // // Returns: // WORD Value of WORD at current position // //************************************************************************* WORD WDGetDataStreamWORD ( LPLPBYTE lplpabyDataStream ) { WORD w; w = ((WORD)**lplpabyDataStream) | (((WORD)*(*lplpabyDataStream + 1)) << 8); *lplpabyDataStream += 2; return(w); } //************************************************************************* // // DWORD WDGetDataStreamDWORD() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the DWORD value at the current position in the data stream. // The current position is incremented by four. // // The DWORD value returned is properly endianized. // // Returns: // DWORD Value of DWORD at current position // //************************************************************************* DWORD WDGetDataStreamDWORD ( LPLPBYTE lplpabyDataStream ) { DWORD dw; LPBYTE lpabyDataStream; lpabyDataStream = *lplpabyDataStream; dw = ((DWORD)lpabyDataStream[0]) | (((DWORD)lpabyDataStream[1]) << 8) | (((DWORD)lpabyDataStream[2]) << 16) | (((DWORD)lpabyDataStream[3]) << 24); *lplpabyDataStream += 4; return(dw); } //************************************************************************* // // SBYTE WDGetDataStreamSBYTE() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the SBYTE value at the current position in the data stream. // The current position is incremented by one. // // Returns: // SBYTE Value of SBYTE at current position // //************************************************************************* SBYTE WDGetDataStreamSBYTE ( LPLPBYTE lplpabyDataStream ) { SBYTE sby; sby = **lplpabyDataStream; ++*lplpabyDataStream; return(sby); } //************************************************************************* // // SWORD WDGetDataStreamSWORD() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the SWORD value at the current position in the data stream. // The current position is incremented by two. // // The SWORD value returned is properly endianized. // // Returns: // SWORD Value of SWORD at current position // //************************************************************************* SWORD WDGetDataStreamSWORD ( LPLPBYTE lplpabyDataStream ) { SWORD sw; sw = ((WORD)**lplpabyDataStream) | (((WORD)*(*lplpabyDataStream + 1)) << 8); *lplpabyDataStream += 2; return(sw); } //************************************************************************* // // SDWORD WDGetDataStreamSDWORD() // // Parameters: // lplpabyDataStream Ptr to ptr to current position in data stream // // Description: // Returns the SDWORD value at the current position in the data stream. // The current position is incremented by four. // // The SDWORD value returned is properly endianized. // // Returns: // SDWORD Value of SDWORD at current position // //************************************************************************* SDWORD WDGetDataStreamSDWORD ( LPLPBYTE lplpabyDataStream ) { SDWORD sdw; LPBYTE lpabyDataStream; lpabyDataStream = *lplpabyDataStream; sdw = ((DWORD)lpabyDataStream[0]) | (((DWORD)lpabyDataStream[1]) << 8) | (((DWORD)lpabyDataStream[2]) << 16) | (((DWORD)lpabyDataStream[3]) << 24); *lplpabyDataStream += 4; return(sdw); }
9be5ae2a66a725acb076068164bcf31f95130f67
8a87f2400813fd33a4761437383f66d22fa57bb6
/Client/Gendo/HttpDownloadMng.cpp
c97c749ef5e3746b07e287e8435d570a79eaa595
[]
no_license
aboutboy/Gendo
f75270bd27b75170ad8a0bb65daeadc7b2707f36
9df3e28643790c7cde3f7af400dfcbe1b93ac001
refs/heads/master
2021-06-14T14:04:10.570221
2016-12-30T11:02:34
2016-12-30T11:02:34
null
0
0
null
null
null
null
GB18030
C++
false
false
18,655
cpp
HttpDownloadMng.cpp
#include "StdAfx.h" #include "HttpDownloadMng.h" #include "GendoWnd.h" #include "RopUtil.h" BOOL DownloadDuiControlMng::add_ListItem(char *strUrl, char *strFilePath, BOOL bOpenMode, _Nv_Download_Ex *pdlg) { //获取list指针 CListUI *cList_Item = static_cast<CListUI*>(((CGendoWnd*)m_pDsgWnd)->GetDownloadList()); if(NULL == cList_Item) { return FALSE; } pdlg->m_pList = cList_Item; //创建list item节点指针 CListContainerElementUI *new_node = new CListContainerElementUI; new_node->ApplyAttributeList(_T("height=\"60\"")); pdlg->m_pListElement = new_node; //创建一个界面布局器 横向布局 高度 60 CVerticalLayoutUI *new_v_lay = new CVerticalLayoutUI; new_v_lay->ApplyAttributeList(_T("height=\"60\"")); pdlg->m_pVerticalLayout = new_v_lay; ////////////////////////////////////////////////////////////////////////// //创建各种控件 CButtonUI *cBtn_Ico = new CButtonUI; cBtn_Ico->ApplyAttributeList( _T("name=\"ico\" float=\"true\" pos=\"5,10,0,0\" width=\"48\" height=\"38\" tooltip=\"图标..\" bkimage=\"file='exe_file.png'\"") ); pdlg->m_pBtnIco = cBtn_Ico; CTextUI *cText_file = new CTextUI; cText_file->ApplyAttributeList( _T("name=\"file\" float=\"true\" pos=\"55,15,0,0\" width=\"300\" height=\"20\" tooltip=\"文件名..\" font=\"0\" textcolor=\"#ffffffff\"") ); pdlg->m_pTextFile = cText_file; CTextUI *cText_Print = new CTextUI; cText_Print->ApplyAttributeList( _T("name=\"print\" float=\"true\" pos=\"55,35,0,0\" width=\"300\" height=\"20\" text=\"正在准备下载..\" tooltip=\"进度提示..\" font=\"0\" textcolor=\"#ffddd333\"") ); pdlg->m_pTextPrint = cText_Print; CTextUI *cText_jdtbk = new CTextUI; cText_jdtbk->ApplyAttributeList( _T("name=\"jdtbk\" float=\"true\" pos=\"300,15,0,0\" width=\"210\" height=\"7\" bkimage=\"file='progress_back.png'\"") ); pdlg->m_pTextJdtBk = cText_jdtbk; CProgressUI *cProgress = new CProgressUI; cProgress->ApplyAttributeList( _T("name=\"jdt\" float=\"true\" pos=\"300,15,0,0\" width=\"210\" height=\"7\" foreimage=\"file='progress_fore.png'\"") ); pdlg->m_pProgRess = cProgress; cProgress->SetMaxValue(100); cProgress->SetMinValue(0); CButtonUI *cBtn_Stop = new CButtonUI; cBtn_Stop->ApplyAttributeList( _T("name=\"stop\" float=\"true\" pos=\"400,25,0,0\" width=\"30\" height=\"30\" tooltip=\"暂停下载..\" normalimage=\"file='stop.png'\"") ); pdlg->m_pBtnStop = cBtn_Stop; CButtonUI *cBtn_Down = new CButtonUI; cBtn_Down->ApplyAttributeList( _T("name=\"down\" float=\"true\" pos=\"440,25,0,0\" width=\"30\" height=\"30\" tooltip=\"开始下载..\" normalimage=\"file='go.png'\"") ); pdlg->m_pBtnGo = cBtn_Down; CButtonUI *cBtn_Open = new CButtonUI; cBtn_Open->ApplyAttributeList( _T("name=\"open\" float=\"true\" pos=\"480,25,0,0\" width=\"30\" height=\"30\" tooltip=\"打开文件..\" normalimage=\"file='ok.png'\"") ); pdlg->m_pBtnOK = cBtn_Open; CButtonUI *cBtn_Dele = new CButtonUI; cBtn_Dele->ApplyAttributeList( _T("name=\"dele\" float=\"true\" pos=\"520,5,0,0\" width=\"20\" height=\"20\" tooltip=\"删除任务..\" normalimage=\"file='close.png'\"") ); pdlg->m_pBtnClose = cBtn_Dele; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //将创建好的控件添加到界面布局器中 new_v_lay->Add(cBtn_Ico); new_v_lay->Add(cText_file); new_v_lay->Add(cText_Print); new_v_lay->Add(cText_jdtbk); new_v_lay->Add(cProgress); new_v_lay->Add(cBtn_Stop); new_v_lay->Add(cBtn_Down); new_v_lay->Add(cBtn_Open); new_v_lay->Add(cBtn_Dele); //将界面布局器添加到list item节点中 new_node->Add(new_v_lay); //最后把list节点插入到list中 cList_Item->AddAt(new_node,0); return TRUE; } //创建list item BOOL DownloadDuiControlMng::create_ListItem(CHAR *strUrl, CHAR *strFilePath, CHAR *strFileName, BOOL bOpenMode) { tag_Donwload_File_Ini_Data tag_File_Data; _Nv_Download_Ex *Nv_Task_ = new _Nv_Download_Ex; CDuiString cDuiStr; WCHAR wUrl[512] = {0}; WCHAR wFilePath[512] = {0}; WCHAR wFileName[512] = {0}; INT iLen = 512; MultiByteToWideChar(CP_ACP, 0, strUrl, 20, wUrl, iLen); iLen = 512; MultiByteToWideChar(CP_ACP, 0, strFilePath, -1, wFilePath, iLen); iLen = 512; MultiByteToWideChar(CP_ACP, 0, strFileName, -1, wFileName, iLen); string sFilePathName = strFilePath; sFilePathName += strFileName; tag_File_Data.strUrl = strUrl; tag_File_Data.strFileName = strFileName; tag_File_Data.strPath = strFilePath; tag_File_Data.strDataPrint = sFilePathName; tag_File_Data.strCoolie = ""; tag_File_Data.n64ProgRessPos = 5; tag_File_Data.n64FileSize = 100; tag_File_Data.bOpenFile = TRUE; Nv_Task_->m_strUrl = strUrl; Nv_Task_->m_strFileSavePath = sFilePathName; Nv_Task_->m_bOpenFile = bOpenMode; Nv_Task_->m_strCoolie = ""; //获取list指针 CListUI *cList_Item = static_cast<CListUI*>(((CGendoWnd*)m_pDsgWnd)->GetDownloadList()); if(NULL == cList_Item) { return FALSE; } //创建list item节点指针 CListContainerElementUI *new_node = new CListContainerElementUI; new_node->ApplyAttributeList(_T("height=\"45\"")); //创建一个界面布局器 横向布局 高度 60 CVerticalLayoutUI *new_v_lay = new CVerticalLayoutUI; new_v_lay->ApplyAttributeList(_T("height=\"45\"")); ////////////////////////////////////////////////////////////////////////// //创建各种控件 CButtonUI *cBtn_Ico = new CButtonUI; cBtn_Ico->ApplyAttributeList( _T("name=\"ico\" float=\"true\" pos=\"5,5,0,0\" width=\"45\" height=\"38\" tooltip=\"图标..\" bkimage=\"file='exe_file.png'\"") ); CTextUI *cText_file = new CTextUI; cText_file->ApplyAttributeList( _T("name=\"file\" float=\"true\" pos=\"55,8,0,0\" width=\"300\" height=\"20\" tooltip=\"文件名..\" font=\"0\" textcolor=\"#FFAAAAAA\"") ); cText_file->SetText(wUrl); CTextUI *cText_Print = new CTextUI; cText_Print->ApplyAttributeList( _T("name=\"print\" float=\"true\" pos=\"55,25,0,0\" width=\"300\" height=\"20\" text=\"正在准备下载..\" tooltip=\"进度提示..\" font=\"0\" textcolor=\"#0070cc\"") ); cText_Print->SetText(_T("腾讯QQ 把妹神器!")); CTextUI *cText_jdtbk = new CTextUI; cText_jdtbk->ApplyAttributeList( _T("name=\"jdtbk\" float=\"true\" pos=\"300,10,0,0\" width=\"220\" height=\"10\" bkimage=\"file='progress_back.png'\"") ); CProgressUI *cProgress = new CProgressUI; cProgress->ApplyAttributeList( _T("name=\"jdt\" float=\"true\" pos=\"300,10,0,0\" width=\"220\" height=\"10\" foreimage=\"file='progress_fore.png'\"") ); cProgress->SetMaxValue((int)(tag_File_Data.n64FileSize)); cProgress->SetMinValue(0); cProgress->SetValue((int)(tag_File_Data.n64ProgRessPos)); CButtonUI *cBtn_Stop = new CButtonUI; cBtn_Stop->ApplyAttributeList( _T("name=\"stop\" float=\"true\" pos=\"450,25,0,0\" width=\"14\" height=\"14\" tooltip=\"暂停下载..\" normalimage=\"file='toolbar\\pause2.png'\"") ); CButtonUI *cBtn_Down = new CButtonUI; cBtn_Down->ApplyAttributeList( _T("name=\"down\" float=\"true\" pos=\"475,25,0,0\" width=\"14\" height=\"14\" tooltip=\"开始下载..\" normalimage=\"file='toolbar\\start.png'\"") ); CButtonUI *cBtn_Open = new CButtonUI; cBtn_Open->ApplyAttributeList( _T("name=\"open\" float=\"true\" pos=\"500,25,0,0\" width=\"14\" height=\"14\" tooltip=\"打开文件..\" normalimage=\"file='toolbar\\open.png'\"") ); CButtonUI *cBtn_Dele = new CButtonUI; cBtn_Dele->ApplyAttributeList( _T("name=\"dele\" float=\"true\" pos=\"540,15,0,0\" width=\"20\" height=\"20\" tooltip=\"删除任务..\" normalimage=\"file='close.png'\"") ); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //将创建好的控件添加到界面布局器中 new_v_lay->Add(cBtn_Ico); new_v_lay->Add(cText_file); new_v_lay->Add(cText_Print); new_v_lay->Add(cText_jdtbk); new_v_lay->Add(cProgress); new_v_lay->Add(cBtn_Stop); new_v_lay->Add(cBtn_Down); new_v_lay->Add(cBtn_Open); new_v_lay->Add(cBtn_Dele); //将界面布局器添加到list item节点中 new_node->Add(new_v_lay); //最后把list节点插入到list中 cList_Item->Add(new_node); Nv_Task_->m_pList = cList_Item; Nv_Task_->m_pListElement = new_node; Nv_Task_->m_pVerticalLayout = new_v_lay; Nv_Task_->m_pBtnIco = cBtn_Ico; Nv_Task_->m_pTextFile = cText_file; Nv_Task_->m_pTextPrint = cText_Print; Nv_Task_->m_pTextJdtBk = cText_jdtbk; Nv_Task_->m_pProgRess = cProgress; Nv_Task_->m_pBtnStop = cBtn_Stop; Nv_Task_->m_pBtnGo = cBtn_Down; Nv_Task_->m_pBtnOK = cBtn_Open; Nv_Task_->m_pBtnClose = cBtn_Dele; m_vt_Nv_Download.push_back(Nv_Task_); Nv_Task_->SetCtrlMng(this); return TRUE; } int DownloadDuiControlMng::get_DownloadPtrPos(CControlUI* cContrCmp) { if (cContrCmp == NULL) { return -1; } DWORD dwSize = m_vt_Nv_Download.size(); for (int i=0; i<(int)dwSize; ++i) { if (m_vt_Nv_Download[i]->m_pListElement == cContrCmp) { return i; } } return -1; } /* * Get task element by button clicked */ _Nv_Download_Ex *DownloadDuiControlMng::GetCurrentTaskByOptBtn(CControlUI* pBtn) { if (pBtn == NULL) return NULL; CControlUI *pBtnPapa = pBtn->GetParent(); if (pBtnPapa == NULL) return NULL; CControlUI *pListElmt = pBtnPapa->GetParent(); if (pListElmt == NULL) return NULL; DWORD dwSize = m_vt_Nv_Download.size(); for (int i = 0; i < (int)dwSize; i++) { if (m_vt_Nv_Download[i]->m_pListElement == pListElmt) { return m_vt_Nv_Download[i]; } } return NULL; } char *DownloadDuiControlMng::get_ProcessPath(void) { static CHAR szOutCpyFile[512] = {0}; TCHAR cPath[512] = {0}; int iSize = 512; DWORD dw = GetModuleFileName(NULL, (LPWSTR)(cPath), 512); DWORD dwSize = lstrlen(cPath); for (int i=0; i<(int)dwSize; ++i) { if(cPath[dwSize-i-1] == _T('\\')) { cPath[dwSize-i] = _T('\0'); break; } } szOutCpyFile[0] = '\0'; wc2mb(cPath, dwSize, szOutCpyFile, &iSize); return szOutCpyFile; } //添加一个配置文件记录 BOOL DownloadDuiControlMng::AddDownloadRecord( CHAR *strUrl, CHAR *strSaveFilePath, CHAR *strFileName, __in __int64 n64FileSize, CHAR *strCoolie, __in __int64 n64ProgRessPos, CHAR *strPrint, __in bool bOpenFile ) { if (strCoolie == NULL) { strCoolie = "strCoolie"; } //拷贝数据 tag_Donwload_File_Ini_Data tag_File_Data; tag_File_Data.strUrl = strUrl; tag_File_Data.strPath = strSaveFilePath; tag_File_Data.strFileName = strFileName; tag_File_Data.strDataPrint = strPrint; tag_File_Data.strCoolie = strCoolie; tag_File_Data.n64ProgRessPos = n64ProgRessPos; tag_File_Data.bOpenFile = bOpenFile; tag_File_Data.n64FileSize = n64FileSize; vector<tag_Donwload_File_Ini_Data>::iterator it; it = m_vtDownLoadFileData.begin(); m_vtDownLoadFileData.insert(it, tag_File_Data); string strPath = string(get_ProcessPath()) + "downloadfile.ini"; FILE *fp = fopen(strPath.c_str(), "w+"); if (fp != NULL) { //写入 DWORD dwSize = m_vtDownLoadFileData.size(); fprintf(fp, "%d\n", dwSize); for (int i=0; i<(int)dwSize; ++i) { fprintf(fp, "%s\n%s\n%s\n%s\n%s\n%lld\n%lld\n%d\n", m_vtDownLoadFileData[i].strUrl.c_str(), m_vtDownLoadFileData[i].strPath.c_str(), m_vtDownLoadFileData[i].strFileName.c_str(), m_vtDownLoadFileData[i].strCoolie.c_str(), m_vtDownLoadFileData[i].strDataPrint.c_str(), m_vtDownLoadFileData[i].n64FileSize, m_vtDownLoadFileData[i].n64ProgRessPos, m_vtDownLoadFileData[i].bOpenFile ); } fclose(fp); } return TRUE; } BOOL DownloadDuiControlMng::ModRecordFile(tag_Donwload_File_Ini_Data *pData) { int dwSize = m_vtDownLoadFileData.size(); int iCur = -1, i = 0; for (i = 0; i < dwSize; i++) { if (m_vtDownLoadFileData[i].strUrl == pData->strUrl && m_vtDownLoadFileData[i].strFileName == pData->strFileName) { iCur = i; break; } } if (iCur == -1) { return FALSE; } m_vtDownLoadFileData[iCur] = *pData; /* force all download record flushed */ string strPath = string(get_ProcessPath()) + "downloadfile.ini"; FILE *fp = fopen(strPath.c_str(), "w+"); if (fp != NULL) { //写入 dwSize = m_vtDownLoadFileData.size(); fprintf(fp, "%d\n", dwSize); for (int i=0; i<(int)dwSize; ++i) { fprintf(fp, "%s\n%s\n%s\n%s\n%s\n%lld\n%lld\n%d\n", m_vtDownLoadFileData[i].strUrl.c_str(), m_vtDownLoadFileData[i].strPath.c_str(), m_vtDownLoadFileData[i].strFileName.c_str(), m_vtDownLoadFileData[i].strCoolie.c_str(), m_vtDownLoadFileData[i].strDataPrint.c_str(), m_vtDownLoadFileData[i].n64FileSize, m_vtDownLoadFileData[i].n64ProgRessPos, m_vtDownLoadFileData[i].bOpenFile); } fclose(fp); } return true; } //修改一个配置文件记录 BOOL DownloadDuiControlMng::ModDownloadRecord( CHAR *strUrl, CHAR *strSaveFilePath, CHAR *strFileName, CHAR *strCoolie, __in __int64 n64FileSize, __in __int64 n64ProgRessPos, CHAR *strPrint, __in bool bOpenFile) { if (strCoolie == NULL) { strCoolie = "strCoolie"; } //拷贝数据 tag_Donwload_File_Ini_Data tag_File_Data; tag_File_Data.strUrl = strUrl; tag_File_Data.strPath = strSaveFilePath; tag_File_Data.strFileName = strFileName; tag_File_Data.strDataPrint = strPrint; tag_File_Data.strCoolie = strCoolie; tag_File_Data.n64FileSize = n64FileSize; tag_File_Data.n64ProgRessPos = n64ProgRessPos; tag_File_Data.bOpenFile = bOpenFile; ModRecordFile(&tag_File_Data); return TRUE; } //读取配置文件 BOOL DownloadDuiControlMng::ReInitDownloadRecord(VOID) { string strPath = string(get_ProcessPath()) + "downloadfile.ini"; FILE *fp = fopen(strPath.c_str(), "r"); WCHAR wBuf[1024] = {0}; CHAR cBuf[1024] = {0}; int wLen = 1024, cLen = 1024; if (fp != NULL) { //拷贝数据 tag_Donwload_File_Ini_Data tag_File_Data; //写入 DWORD dwSize = 0; fscanf(fp, "%d\n", &dwSize); for (int i=0; i<(int)dwSize; ++i) { fgets(cBuf, 1024, fp); set_StrSign(cBuf); tag_File_Data.strUrl = cBuf; fgets(cBuf, 1024, fp); set_StrSign(cBuf); tag_File_Data.strPath = cBuf; fgets(cBuf, 1024, fp); set_StrSign(cBuf); tag_File_Data.strFileName = cBuf; fgets(cBuf, 1024, fp); set_StrSign(cBuf); tag_File_Data.strCoolie = cBuf; fgets(cBuf, 1024, fp); set_StrSign(cBuf); tag_File_Data.strDataPrint = cBuf; fscanf(fp, "%lld\n%lld\n%d\n", &tag_File_Data.n64FileSize, &tag_File_Data.n64ProgRessPos, &tag_File_Data.bOpenFile); m_vtDownLoadFileData.push_back(tag_File_Data); create_ListItem((char*)tag_File_Data.strUrl.c_str(), (char*)tag_File_Data.strPath.c_str(), (char*)tag_File_Data.strFileName.c_str(), tag_File_Data.bOpenFile); } fclose(fp); } return TRUE; } BOOL DownloadDuiControlMng::FlushDownloadRecord(VOID) { string strPath = string(get_ProcessPath()) + "downloadfile.ini"; FILE *fp = fopen(strPath.c_str(), "w+"); if (fp != NULL) { //写入 DWORD dwSize = m_vtDownLoadFileData.size(); fprintf(fp, "%d\n", dwSize); for (int i=0; i<(int)dwSize; ++i) { fprintf(fp, "%s\n%s\n%s\n%s\n%s\n%lld\n%lld\n%d\n", m_vtDownLoadFileData[i].strUrl.c_str(), m_vtDownLoadFileData[i].strPath.c_str(), m_vtDownLoadFileData[i].strFileName.c_str(), m_vtDownLoadFileData[i].strCoolie.c_str(), m_vtDownLoadFileData[i].strDataPrint.c_str(), m_vtDownLoadFileData[i].n64FileSize, m_vtDownLoadFileData[i].n64ProgRessPos, m_vtDownLoadFileData[i].bOpenFile ); } fclose(fp); return TRUE; } return FALSE; } //剔除字符串\n void DownloadDuiControlMng::set_StrSign(__in char *strData) { int nLen = 0; while (strData[nLen] != '\0') { if (strData[nLen] == '\n') { strData[nLen] = '\0'; } nLen++; } }
a8b2140844c56439812e80befa168cd0f27a599f
ca249ca9733de013d6c5e317551897fa56479d15
/1508.cpp
6f82e27b03b87054d7a590e3534a30be46babfc9
[]
no_license
fjl1005/BSOJ-answers
6d2055a6e3229e06bf81be45996d20a0b587e349
7773b1c588d3f17eef470dfba2daa59be3fce7fa
refs/heads/master
2020-06-28T22:55:52.475735
2019-08-03T11:42:37
2019-08-03T11:42:37
200,363,773
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
1508.cpp
#include<cstdio> int u[105],w[105]; int f[105][30005]; int max(int a,int b) { return a>b?a:b; } int main() { int n,m; scanf("%d%d",&n,&m); int i; for(i=1; i<=m; i++) { scanf("%d%d",&u[i],&w[i]); w[i]=w[i]*u[i]; } int j; for(i=1; i<=m; i++) { for(j=1; j<=n; j++) { f[i][j]=f[i-1][j]; if(u[i]<=j) { f[i][j]=max(f[i][j],f[i-1][j-u[i]]+w[i]); } } } printf("%d",f[m][n]); return 0; }
b5e7f90d6897072c3c0993b8a5f98cf08a887216
5795af16335f6c04b07500343703cd75eba7edfa
/Utils/haddPlus.cc
f7851dc09891b8b56097bb6b8ca1b4676556d74a
[]
no_license
duartej/AnalysisVH
f5bf152b717c3abd6ae949cea065177359fbb3f1
5f05b75448df06f05fd6143a020b9cd884aa8c5b
refs/heads/master
2020-04-05T23:40:38.654548
2013-11-07T18:27:00
2013-11-07T18:27:00
4,871,087
0
0
null
2013-01-15T10:30:16
2012-07-03T10:43:32
C++
UTF-8
C++
false
false
7,776
cc
haddPlus.cc
/* This program will add histograms (see note) and Trees from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... or hadd -f targetfile source1 source2 ... (targetfile is overwritten if it exists) When -the -f option is specified, one can also specify the compression level of the target file. By default the compression level is 1, but if "-f0" is specified, the target file will not be compressed. if "-f6" is specified, the compression level 6 will be used. For example assume 3 files f1, f2, f3 containing histograms hn and Trees Tn f1 with h1 h2 h3 T1 f2 with h1 h4 T1 T2 f3 with h5 the result of hadd -f x.root f1.root f2.root f3.root will be a file x.root with h1 h2 h3 h4 h5 T1 T2 where h1 will be the sum of the 2 histograms in f1 and f2 T1 will be the merge of the Trees in f1 and f2 The files may contain sub-directories. if the source files contains histograms and Trees, one can skip the Trees with hadd -T targetfile source1 source2 ... Wildcarding and indirect files are also supported hadd result.root myfil*.root will merge all files in myfil*.root hadd result.root file1.root @list.txt file2. root myfil*.root will merge file1. root, file2. root, all files in myfil*.root and all files in the indirect text file list.txt ("@" as the first character of the file indicates an indirect file. An indirect file is a text file containing a list of other files, including other indirect files, one line per file). If the sources and and target compression levels are identical (default), the program uses the TChain::Merge function with option "fast", ie the merge will be done without unzipping or unstreaming the baskets (i.e. direct copy of the raw byte on disk). The "fast" mode is typically 5 times faster than the mode unzipping and unstreaming the baskets. NOTE1: By default histograms are added. However hadd does not support the case where histograms have their bit TH1::kIsAverage set. NOTE2: hadd returns a status code: 0 if OK, -1 otherwise Authors: Rene Brun, Dirk Geppert, Sven A. Schmidt, sven.schmidt@cern.ch : rewritten from scratch by Rene Brun (30 November 2005) to support files with nested directories. Toby Burnett implemented the possibility to use indirect files. J. Duarte Campderros: added support for InputParameters and TCounterUI class, also deleting the extra TKeys (cycles) created for the InputParameters */ #include "RConfig.h" #include <string> #include "TFile.h" #include "THashList.h" #include "TKey.h" #include "TObjString.h" #include "Riostream.h" #include "TClass.h" #include "TSystem.h" #include <stdlib.h> #include <sstream> #include "TFileMerger.h" TList *FileList; TFile *Target, *Source; Bool_t noTrees; Bool_t fastMethod; Bool_t reoptimize; int AddFile(TList* sourcelist, std::string entry, int newcomp) ; int MergeRootfile( TDirectory *target, TList *sourcelist); //___________________________________________________________________________ int main( int argc, char **argv ) { if ( argc < 3 || "-h" == string(argv[1]) || "--help" == string(argv[1]) ) { cout << "Usage: " << argv[0] << " [-f[0-9]] [-k] [-T] [-O] targetfile source1 [source2 source3 ...]" << endl; cout << "This program will add histograms from a list of root files and write them" << endl; cout << "to a target root file. The target file is newly created and must not " << endl; cout << "exist, or if -f (\"force\") is given, must not be one of the source files." << endl; cout << "Supply at least two source files for this to make sense... ;-)" << endl; cout << "If the option -k is used, hadd will not exit on corrupt or non-existant input files but skip the offending files instead." << endl; cout << "If the option -T is used, Trees are not merged" <<endl; cout << "If the option -O is used, when merging TTree, the basket size is re-optimized" <<endl; cout << "When -the -f option is specified, one can also specify the compression" <<endl; cout << "level of the target file. By default the compression level is 1, but" <<endl; cout << "if \"-f0\" is specified, the target file will not be compressed." <<endl; cout << "if \"-f6\" is specified, the compression level 6 will be used." <<endl; cout << "if Target and source files have different compression levels"<<endl; cout << " a slower method is used"<<endl; return 1; } FileList = new TList(); Bool_t force = kFALSE; Bool_t skip_errors = kFALSE; reoptimize = kFALSE; noTrees = kFALSE; int ffirst = 2; Int_t newcomp = 1; for( int a = 1; a < argc; ++a ) { if ( strcmp(argv[a],"-T") == 0 ) { noTrees = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-f") == 0 ) { force = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-k") == 0 ) { skip_errors = kTRUE; ++ffirst; } else if ( strcmp(argv[a],"-O") == 0 ) { reoptimize = kTRUE; ++ffirst; } else if ( argv[a][0] == '-' ) { char ft[4]; for( int j=0; j<=9; ++j ) { snprintf(ft,4,"-f%d",j); if (!strcmp(argv[a],ft)) { force = kTRUE; newcomp = j; ++ffirst; break; } } } } gSystem->Load("libTreePlayer"); // Extra objects copy // J. Duarte Campderros gSystem->Load("libInputParameters.so"); gSystem->Load("libTCounterUI.so"); cout << "Target file: " << argv[ffirst-1] << endl; // Storing the name for the post-processing J. Duarte Campderros const char * targetoutputfilename = argv[ffirst-1]; TFileMerger merger(kFALSE,kFALSE); merger.SetPrintLevel(99); if (!merger.OutputFile(argv[ffirst-1],force,newcomp) ) { cerr << "Error opening target file (does " << argv[ffirst-1] << " exist?)." << endl; cerr << "Pass \"-f\" argument to force re-creation of output file." << endl; exit(1); } fastMethod = kTRUE; int nInputFiles = 0; // J. Duarte Campderros for ( int i = ffirst; i < argc; i++ ) { if (argv[i] && argv[i][0]=='@') { std::ifstream indirect_file(argv[i]+1); if( ! indirect_file.is_open() ) { std::cerr<< "Could not open indirect file " << (argv[i]+1) << std::endl; return 1; } while( indirect_file ){ std::string line; std::getline(indirect_file, line); if( !merger.AddFile(line.c_str()) ) { return 1; } } } else if( ! merger.AddFile(argv[i]) ) { if ( skip_errors ) { cerr << "Skipping file with error: " << argv[i] << endl; } else { cerr << "Exiting due to error in " << argv[i] << endl; return 1; } } nInputFiles++; } if (merger.HasCompressionChange() && !reoptimize) { // Don't warn if the user any request re-optimization. cout <<"Sources and Target have different compression levels"<<endl; cout <<"Merging will be slower"<<endl; } Bool_t status = merger.Merge(); //must delete Target to avoid a problem with dictionaries in~ TROOT delete Target; // Post-processing: Keep only the highest cycle number for each key (J. Duarte Campderros) Target = new TFile(targetoutputfilename,"UPDATE"); Target->Purge(); delete Target; if (status) { return 0; } else { return 1; } }
30e60d8efbc83ee31ac0f9404a16d424be2a09b2
fb689146cc19e1113e095e6dfd12f8b73177b22f
/source/lac/petsc_precondition.cc
90f6e70e7d73fc0d5e99388b43894e0cb6d54537
[]
no_license
qsnake/deal.II
0418a4c9371e2630a0fce65b8de3529fa168d675
79c0458c8cc3fa03e5d89357a53a4f9397ead5c3
refs/heads/master
2021-01-01T15:55:27.801304
2012-07-27T13:31:57
2012-07-27T14:16:10
5,205,180
3
1
null
null
null
null
UTF-8
C++
false
false
14,918
cc
petsc_precondition.cc
//--------------------------------------------------------------------------- // $Id: petsc_precondition.cc 24320 2011-09-13 09:41:50Z young $ // Version: $Name$ // // Copyright (C) 2004, 2006, 2008, 2009, 2010 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <deal.II/lac/petsc_precondition.h> #ifdef DEAL_II_USE_PETSC # include <deal.II/base/utilities.h> # include <deal.II/lac/petsc_matrix_base.h> # include <deal.II/lac/petsc_vector_base.h> # include <deal.II/lac/petsc_solver.h> # include <petscconf.h> # include <cmath> DEAL_II_NAMESPACE_OPEN namespace PETScWrappers { PreconditionerBase::PreconditionerBase () : pc(NULL), matrix(NULL) {} PreconditionerBase::~PreconditionerBase () { if (pc!=NULL) { #if DEAL_II_PETSC_VERSION_LT(3,2,0) int ierr = PCDestroy(pc); #else int ierr = PCDestroy(&pc); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); } } void PreconditionerBase::vmult (VectorBase &dst, const VectorBase &src) const { AssertThrow (pc != NULL, StandardExceptions::ExcInvalidState ()); int ierr; ierr = PCApply(pc, src, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void PreconditionerBase::create_pc () { // only allow the creation of the // preconditioner once AssertThrow (pc == NULL, StandardExceptions::ExcInvalidState ()); MPI_Comm comm; int ierr; // this ugly cast is necessay because the // type Mat and PETScObject are // unrelated. ierr = PetscObjectGetComm(reinterpret_cast<PetscObject>(matrix), &comm); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCCreate(comm, &pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetOperators(pc , matrix, matrix, SAME_PRECONDITIONER); AssertThrow (ierr == 0, ExcPETScError(ierr)); } const PC & PreconditionerBase::get_pc () const { return pc; } PreconditionerBase::operator Mat () const { return matrix; } /* ----------------- PreconditionJacobi -------------------- */ PreconditionJacobi::PreconditionJacobi () {} PreconditionJacobi::PreconditionJacobi (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionJacobi::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCJACOBI)); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionBlockJacobi -------------------- */ PreconditionBlockJacobi::PreconditionBlockJacobi () {} PreconditionBlockJacobi:: PreconditionBlockJacobi (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionBlockJacobi::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCBJACOBI)); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionSOR -------------------- */ PreconditionSOR::AdditionalData:: AdditionalData (const double omega) : omega (omega) {} PreconditionSOR::PreconditionSOR () {} PreconditionSOR::PreconditionSOR (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionSOR::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCSOR)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // then set flags as given ierr = PCSORSetOmega (pc, additional_data.omega); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionSSOR -------------------- */ PreconditionSSOR::AdditionalData:: AdditionalData (const double omega) : omega (omega) {} PreconditionSSOR::PreconditionSSOR () {} PreconditionSSOR::PreconditionSSOR (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionSSOR::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCSOR)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // then set flags as given ierr = PCSORSetOmega (pc, additional_data.omega); AssertThrow (ierr == 0, ExcPETScError(ierr)); // convert SOR to SSOR ierr = PCSORSetSymmetric (pc, SOR_SYMMETRIC_SWEEP); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionEisenstat -------------------- */ PreconditionEisenstat::AdditionalData:: AdditionalData (const double omega) : omega (omega) {} PreconditionEisenstat::PreconditionEisenstat () {} PreconditionEisenstat::PreconditionEisenstat (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionEisenstat::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCEISENSTAT)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // then set flags as given ierr = PCEisenstatSetOmega (pc, additional_data.omega); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionICC -------------------- */ PreconditionICC::AdditionalData:: AdditionalData (const unsigned int levels) : levels (levels) {} PreconditionICC::PreconditionICC () {} PreconditionICC::PreconditionICC (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionICC::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCICC)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // then set flags #if DEAL_II_PETSC_VERSION_LT(2,3,1) PCICCSetLevels (pc, additional_data.levels); #else PCFactorSetLevels (pc, additional_data.levels); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionILU -------------------- */ PreconditionILU::AdditionalData:: AdditionalData (const unsigned int levels) : levels (levels) {} PreconditionILU::PreconditionILU () {} PreconditionILU::PreconditionILU (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionILU::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCILU)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // then set flags #if DEAL_II_PETSC_VERSION_LT(2,3,1) PCILUSetLevels (pc, additional_data.levels); #else PCFactorSetLevels (pc, additional_data.levels); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } /* ----------------- PreconditionBoomerAMG -------------------- */ PreconditionBoomerAMG::AdditionalData:: AdditionalData(const bool symmetric_operator, const double strong_threshold, const double max_row_sum, const unsigned int aggressive_coarsening_num_levels, const bool output_details ) : symmetric_operator(symmetric_operator), strong_threshold(strong_threshold), max_row_sum(max_row_sum), aggressive_coarsening_num_levels(aggressive_coarsening_num_levels), output_details(output_details) {} PreconditionBoomerAMG::PreconditionBoomerAMG () {} PreconditionBoomerAMG::PreconditionBoomerAMG (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionBoomerAMG::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; #ifdef PETSC_HAVE_HYPRE create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCHYPRE)); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCHYPRESetType(pc, "boomeramg"); AssertThrow (ierr == 0, ExcPETScError(ierr)); if (additional_data.output_details) PetscOptionsSetValue("-pc_hypre_boomeramg_print_statistics","1"); PetscOptionsSetValue("-pc_hypre_boomeramg_agg_nl", Utilities::int_to_string( additional_data.aggressive_coarsening_num_levels ).c_str()); std::stringstream ssStream; ssStream << additional_data.max_row_sum; PetscOptionsSetValue("-pc_hypre_boomeramg_max_row_sum", ssStream.str().c_str()); ssStream.str(""); // empty the stringstream ssStream << additional_data.strong_threshold; PetscOptionsSetValue("-pc_hypre_boomeramg_strong_threshold", ssStream.str().c_str()); if (additional_data.symmetric_operator) { PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_up", "symmetric-SOR/Jacobi"); PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_down", "symmetric-SOR/Jacobi"); PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_coarse", "Gaussian-elimination"); } else { PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_up", "SOR/Jacobi"); PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_down", "SOR/Jacobi"); PetscOptionsSetValue("-pc_hypre_boomeramg_relax_type_coarse", "Gaussian-elimination"); } ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); #else // PETSC_HAVE_HYPRE (void)pc; Assert (false, ExcMessage ("Your PETSc installation does not include a copy of " "the hypre package necessary for this preconditioner.")); #endif } /* ----------------- PreconditionLU -------------------- */ PreconditionLU::AdditionalData:: AdditionalData (const double pivoting, const double zero_pivot, const double damping) : pivoting (pivoting), zero_pivot (zero_pivot), damping (damping) {} PreconditionLU::PreconditionLU () {} PreconditionLU::PreconditionLU (const MatrixBase &matrix, const AdditionalData &additional_data) { initialize(matrix, additional_data); } void PreconditionLU::initialize (const MatrixBase &matrix_, const AdditionalData &additional_data_) { matrix = static_cast<Mat>(matrix_); additional_data = additional_data_; create_pc(); int ierr; ierr = PCSetType (pc, const_cast<char *>(PCLU)); AssertThrow (ierr == 0, ExcPETScError(ierr)); // set flags as given #if DEAL_II_PETSC_VERSION_LT(2,3,1) ierr = PCLUSetPivoting (pc, additional_data.pivoting); #elif DEAL_II_PETSC_VERSION_LT(3,0,1) ierr = PCFactorSetPivoting (pc, additional_data.pivoting); #else ierr = PCFactorSetColumnPivot (pc, additional_data.pivoting); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); #if DEAL_II_PETSC_VERSION_LT(2,3,0) ierr = PCLUSetZeroPivot (pc, additional_data.zero_pivot); #else ierr = PCFactorSetZeroPivot (pc, additional_data.zero_pivot); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); #if DEAL_II_PETSC_VERSION_LT(2,3,0) ierr = PCLUSetDamping (pc, additional_data.damping); #elif DEAL_II_PETSC_VERSION_LT(3,0,1) ierr = PCFactorSetShiftNonzero (pc, additional_data.damping); #else ierr = PCFactorSetShiftAmount (pc, additional_data.damping); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetFromOptions (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = PCSetUp (pc); AssertThrow (ierr == 0, ExcPETScError(ierr)); } } DEAL_II_NAMESPACE_CLOSE #endif // DEAL_II_USE_PETSC
4314dd0a33fbad6c74cc683bb24963f9e036b873
1695d3005542eeaf519de6d7624ccbde2357688f
/sysmodule/source/main.cpp
fd20496c91616a48522c930d51ba8aacdd0ce301
[]
no_license
WerWolv/Sysmodule_Access
a424ee6359edefa92ae877bffcfcd5147928c381
b2e7db884b22e35f5bf6b66f0348778cfcdd3f13
refs/heads/master
2020-03-29T07:22:04.528597
2018-11-01T06:09:55
2018-11-01T06:09:55
149,662,284
1
0
null
null
null
null
UTF-8
C++
false
false
2,061
cpp
main.cpp
/* * Copyright (c) 2018 Atmosphère-NX * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <cstdint> #include <cstring> #include <malloc.h> #include <switch.h> #include <stratosphere.hpp> #include "edizon_service.hpp" extern "C" { extern u32 __start__; u32 __nx_applet_type = AppletType_None; #define INNER_HEAP_SIZE 0x20000 size_t nx_inner_heap_size = INNER_HEAP_SIZE; char nx_inner_heap[INNER_HEAP_SIZE]; void __libnx_initheap(void); void __appInit(void); void __appExit(void); } void __libnx_initheap(void) { void* addr = nx_inner_heap; size_t size = nx_inner_heap_size; /* Newlib */ extern char* fake_heap_start; extern char* fake_heap_end; fake_heap_start = (char*)addr; fake_heap_end = (char*)addr + size; } void __appInit(void) { Result rc; svcSleepThread(10000000000L); rc = smInitialize(); rc = fsInitialize(); rc = fsdevMountSdmc(); rc = timeInitialize(); rc = hidInitialize(); } void __appExit(void) { fsdevUnmountAll(); fsExit(); smExit(); audoutExit(); timeExit(); } int main(int argc, char **argv) { /* TODO: What's a good timeout value to use here? */ auto server_manager = std::make_unique<WaitableManager>(U64_MAX); /* Add services to manager. */ server_manager->add_waitable(new ServiceServer<EdiZonService>("edz:tst", 1)); /* Loop forever, servicing our services. */ server_manager->process(); return 0; }
ffaf6681c38de19a6856870c77f8d77cb3c0a1a6
085b0b660560d64465b0f25cc9678aed1d5799f9
/src/opengl.cpp
482394d5e4ace9e98751d350e15509ad6082068b
[ "MIT" ]
permissive
ddevault/wayfire
3eafa63d6955cbe31123eb99c9cba02fa45ae88c
007452f6ccc07ceca51879187bba142431832382
refs/heads/master
2020-03-15T13:55:01.974924
2018-03-27T06:07:37
2018-03-27T19:11:18
132,178,245
4
0
null
null
null
null
UTF-8
C++
false
false
13,154
cpp
opengl.cpp
#include "opengl.hpp" #include <compositor.h> #include "debug.hpp" #include "output.hpp" #include "render-manager.hpp" #include <gl-renderer-api.h> namespace { OpenGL::context_t *bound; } const char* gl_error_string(const GLenum err) { switch (err) { case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; } return "UNKNOWN GL ERROR"; } void gl_call(const char *func, uint32_t line, const char *glfunc) { GLenum err; if ((err = glGetError()) == GL_NO_ERROR) return; debug << "gles: function " << func << " at line " << line << ": \n" << glfunc << " == " << gl_error_string(err) << "\n"; } namespace OpenGL { GLuint compile_shader(const char *src, GLuint type) { GLuint shader = GL_CALL(glCreateShader(type)); GL_CALL(glShaderSource(shader, 1, &src, NULL)); int s; char b1[10000]; GL_CALL(glCompileShader(shader)); GL_CALL(glGetShaderiv(shader, GL_COMPILE_STATUS, &s)); GL_CALL(glGetShaderInfoLog(shader, 10000, NULL, b1)); if ( s == GL_FALSE ) { errio << "shader compilation failed!\n" "src: ***************************\n" << src << "********************************\n" << b1 << "********************************\n"; return -1; } return shader; } GLuint load_shader(const char *path, GLuint type) { std::fstream file(path, std::ios::in); if(!file.is_open()) { errio << "Cannot open shader file " << path << "." << std::endl; return -1; } std::string str, line; while(std::getline(file, line)) str += line, str += '\n'; auto sh = compile_shader(str.c_str(), type); if (sh == (uint)-1) errio << "Cannot open shader file " << path << "." << std::endl; return sh; } /* const char *getStrSrc(GLenum src) { if(src == GL_DEBUG_SOURCE_API )return "API"; if(src == GL_DEBUG_SOURCE_WINDOW_SYSTEM )return "WINDOW_SYSTEM"; if(src == GL_DEBUG_SOURCE_SHADER_COMPILER)return "SHADER_COMPILER"; if(src == GL_DEBUG_SOURCE_THIRD_PARTY )return "THIRD_PARTYB"; if(src == GL_DEBUG_SOURCE_APPLICATION )return "APPLICATIONB"; if(src == GL_DEBUG_SOURCE_OTHER )return "OTHER"; else return "UNKNOWN"; } const char *getStrType(GLenum type) { if(type==GL_DEBUG_TYPE_ERROR )return "ERROR"; if(type==GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR)return "DEPRECATED_BEHAVIOR"; if(type==GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR )return "UNDEFINED_BEHAVIOR"; if(type==GL_DEBUG_TYPE_PORTABILITY )return "PORTABILITY"; if(type==GL_DEBUG_TYPE_PERFORMANCE )return "PERFORMANCE"; if(type==GL_DEBUG_TYPE_OTHER )return "OTHER"; return "UNKNOWN"; } const char *getStrSeverity(GLenum severity) { if(severity == GL_DEBUG_SEVERITY_HIGH )return "HIGH"; if(severity == GL_DEBUG_SEVERITY_MEDIUM)return "MEDIUM"; if(severity == GL_DEBUG_SEVERITY_LOW )return "LOW"; if(severity == GL_DEBUG_SEVERITY_NOTIFICATION) return "NOTIFICATION"; return "UNKNOWN"; } void errorHandler(GLenum src, GLenum type, GLuint id, GLenum severity, GLsizei len, const GLchar *msg, const void *dummy) { // ignore notifications if(severity == GL_DEBUG_SEVERITY_NOTIFICATION) return; debug << "_______________________________________________\n"; debug << "GLES debug: \n"; debug << "Source: " << getStrSrc(src) << std::endl; debug << "Type: " << getStrType(type) << std::endl; debug << "ID: " << id << std::endl; debug << "Severity: " << getStrSeverity(severity) << std::endl; debug << "Msg: " << msg << std::endl;; debug << "_______________________________________________\n"; } */ #define load_program(suffix) \ GLuint fss_ ## suffix = load_shader(std::string(shaderSrcPath) \ .append("/frag_" #suffix ".glsl").c_str(), \ GL_FRAGMENT_SHADER); \ \ ctx->program_ ## suffix = GL_CALL(glCreateProgram());\ GL_CALL(glAttachShader(ctx->program_ ## suffix, vss));\ GL_CALL(glAttachShader(ctx->program_ ## suffix, fss_ ## suffix));\ GL_CALL(glLinkProgram(ctx->program_ ## suffix)); \ GL_CALL(glUseProgram(ctx->program_ ## suffix)) context_t* create_gles_context(wayfire_output *output, const char *shaderSrcPath) { context_t *ctx = new context_t; ctx->output = output; /* if (file_debug == &file_info) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(errorHandler, 0); } */ GLuint vss = load_shader(std::string(shaderSrcPath) .append("/vertex.glsl").c_str(), GL_VERTEX_SHADER); load_program(rgba); load_program(rgbx); load_program(egl); load_program(y_uv); load_program(y_u_v); load_program(y_xuxv); #undef load_program ctx->mvpID = GL_CALL(glGetUniformLocation(ctx->program_rgba, "MVP")); ctx->colorID = GL_CALL(glGetUniformLocation(ctx->program_rgba, "color")); ctx->w2ID = GL_CALL(glGetUniformLocation(ctx->program_rgba, "w2")); ctx->h2ID = GL_CALL(glGetUniformLocation(ctx->program_rgba, "h2")); ctx->position = GL_CALL(glGetAttribLocation(ctx->program_rgba, "position")); ctx->uvPosition = GL_CALL(glGetAttribLocation(ctx->program_rgba, "uvPosition")); return ctx; } void use_default_program(uint32_t bits) { GLuint program = bound->program_rgba; if (bits & TEXTURE_RGBX) program = bound->program_rgbx; if (bits & TEXTURE_EGL) program = bound->program_egl; if (bits & TEXTURE_Y_UV) program = bound->program_y_uv; if (bits & TEXTURE_Y_U_V) program = bound->program_y_u_v; if (bits & TEXTURE_Y_XUXV) program = bound->program_y_xuxv; GL_CALL(glUseProgram(program)); } void bind_context(context_t *ctx) { bound = ctx; bound->width = ctx->output->handle->width; bound->height = ctx->output->handle->height; } weston_geometry get_device_viewport() { return render_manager::renderer_api->get_output_gl_viewport(bound->output->handle); } void use_device_viewport() { const auto vp = get_device_viewport(); GL_CALL(glViewport(vp.x, vp.y, vp.width, vp.height)); } void release_context(context_t *ctx) { glDeleteProgram(ctx->program_rgba); glDeleteProgram(ctx->program_rgbx); delete ctx; } void render_texture(GLuint tex[], int n_tex, GLenum target, const weston_geometry& g, const texture_geometry& texg, uint32_t bits) { if ((bits & DONT_RELOAD_PROGRAM) == 0) use_default_program(bits); GL_CALL(glUniform1f(bound->w2ID, bound->width / 2)); GL_CALL(glUniform1f(bound->h2ID, bound->height / 2)); if ((bits & TEXTURE_TRANSFORM_USE_DEVCOORD)) { use_device_viewport(); } else { GL_CALL(glViewport(0, 0, bound->width, bound->height)); } float w2 = float(bound->width) / 2.; float h2 = float(bound->height) / 2.; float tlx = float(g.x) - w2, tly = h2 - float(g.y); float w = g.width; float h = g.height; if(bits & TEXTURE_TRANSFORM_INVERT_Y) { h *= -1; tly += h; } GLfloat vertexData[] = { tlx , tly - h, 0.f, // 1 tlx + w, tly - h, 0.f, // 2 tlx + w, tly , 0.f, // 3 tlx , tly , 0.f, // 4 }; GLfloat coordData[] = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, }; if (bits & TEXTURE_USE_TEX_GEOMETRY) { coordData[0] = texg.x1; coordData[1] = texg.y2; coordData[2] = texg.x2; coordData[3] = texg.y2; coordData[4] = texg.x2; coordData[5] = texg.y1; coordData[6] = texg.x1; coordData[7] = texg.y1; } GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); for (int i = 0; i < n_tex; i++) { GL_CALL(glBindTexture(target, tex[i])); GL_CALL(glActiveTexture(GL_TEXTURE0 + i)); GL_CALL(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); GL_CALL(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); } GL_CALL(glVertexAttribPointer(bound->position, 3, GL_FLOAT, GL_FALSE, 0, vertexData)); GL_CALL(glEnableVertexAttribArray(bound->position)); GL_CALL(glVertexAttribPointer(bound->uvPosition, 2, GL_FLOAT, GL_FALSE, 0, coordData)); GL_CALL(glEnableVertexAttribArray(bound->uvPosition)); GL_CALL(glDrawArrays (GL_TRIANGLE_FAN, 0, 4)); GL_CALL(glDisableVertexAttribArray(bound->position)); GL_CALL(glDisableVertexAttribArray(bound->uvPosition)); } void render_texture(GLuint tex, const weston_geometry& g, const texture_geometry& texg, uint32_t bits) { render_texture(&tex, 1, GL_TEXTURE_2D, g, texg, bits); } void render_transformed_texture(GLuint tex[], int n_tex, GLenum target, const weston_geometry& g, const texture_geometry& texg, glm::mat4 transform, glm::vec4 color, uint32_t bits) { use_default_program(bits); GL_CALL(glUniformMatrix4fv(bound->mvpID, 1, GL_FALSE, &transform[0][0])); GL_CALL(glUniform4fv(bound->colorID, 1, &color[0])); GL_CALL(glEnable(GL_BLEND)); GL_CALL(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); render_texture(tex, n_tex, target, g, texg, bits | DONT_RELOAD_PROGRAM); GL_CALL(glDisable(GL_BLEND)); } void render_transformed_texture(GLuint text, const weston_geometry& g, const texture_geometry& texg, glm::mat4 transform, glm::vec4 color, uint32_t bits) { render_transformed_texture(&text, 1, GL_TEXTURE_2D, g, texg, transform, color, bits); } void prepare_framebuffer(GLuint &fbuff, GLuint &texture, float scale_x, float scale_y) { if (fbuff == (uint)-1) GL_CALL(glGenFramebuffers(1, &fbuff)); GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, fbuff)); bool existing_texture = (texture != (uint)-1); if (!existing_texture) GL_CALL(glGenTextures(1, &texture)); GL_CALL(glBindTexture(GL_TEXTURE_2D, texture)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); if (!existing_texture) GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bound->width * scale_x, bound->height * scale_y, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); GL_CALL(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0)); auto status = GL_CALL(glCheckFramebufferStatus(GL_FRAMEBUFFER)); if (status != GL_FRAMEBUFFER_COMPLETE) errio << "Error in framebuffer!\n"; } GLuint duplicate_texture(GLuint tex, int w, int h) { GLuint dst_tex = -1; GLuint dst_fbuff = -1, src_fbuff = -1; prepare_framebuffer(dst_fbuff, dst_tex); GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); prepare_framebuffer(src_fbuff, tex); GL_CALL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst_fbuff)); GL_CALL(glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_LINEAR)); GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0)); GL_CALL(glDeleteFramebuffers(1, &dst_fbuff)); GL_CALL(glDeleteFramebuffers(1, &src_fbuff)); return dst_tex; } }
f75f669887e45d2fcd42a3cc5861bb3734c3e871
9fedb3257c0b03fce152628c68b1b218ffba82d0
/17计科3班 170201103795 李柏岐.cpp
bdb60a92a9e518873b6d0b29f4cb0bb2cf91e944
[]
no_license
libaiqi-gt/algorithm_code
211dbbc551dc85666e2684d6bfb580ab14537e13
d2b1b96b9e6690713ebe7e1763cf3cf48ac2abab
refs/heads/master
2020-09-21T17:00:48.184590
2019-12-30T06:16:32
2019-12-30T06:16:32
224,858,474
0
0
null
2019-11-29T13:21:21
2019-11-29T13:21:21
null
UTF-8
C++
false
false
371
cpp
17计科3班 170201103795 李柏岐.cpp
#include<stdio.h> int BinarySearch(int a[], const int& x,int n){ int left=0,right=n-1; while(left<=right) { int middle=(left+right)/2; if(x==a[middle]) { return middle; } if(x>a[middle]) { left=middle+1; } else { right=middle-1; } } return -1; } int main() { int a[]={1,3,5,7,11,14}; printf("%d\n",BinarySearch(a,11,6)); return 0; }
b966fe9e5d40a1ea18e93c0125d56961ff26e1f3
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/fc/68b2b14287ecd3/main.cpp
a81b549ee22066730abe147ca612e38e99146f44
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
main.cpp
#include "boost/variant.hpp" #include <iostream> #include <complex> struct structy { int a; }; std::ostream &operator<<(std::ostream &out, structy) { return out; } void times_two( boost::variant<int, std::string, std::complex<double>, structy> & v) { if (int* pi = boost::get<int>(&v)) *pi *= 2; else if (std::string* pstr = boost::get<std::string>(&v)) *pstr += *pstr; //No check for complex or structy - should silently returns. } int main() { boost::variant<int, std::string, std::complex<double>, structy> v; v = "hello"; std::string& str = boost::get<std::string>(v); str += " world! "; //As desired, the std::string contained by v now is equal to "hello world! ". Again, we can demonstrate this by streaming v to standard output: std::cout << v << std::endl; times_two(v); std::cout << v << std::endl; std::complex<double> a(5.0, 6.0); v = a; times_two(v); return 0; }
43d64bd21377e306a7bdc0c90ac7f58f46f29373
ea91bffc446ca53e5942a571c2f7090310376c9d
/src/syntax/CommonSyntaxNodes.cpp
947c8df4ab37db69cacaf49e89ee7e79bf7b75c2
[]
no_license
macro-l/polarphp
f7b1dc4b609f1aae23b4618fc1176b8c26531722
f6608c4dc26add94e61684ed0edd3d5c7e86e768
refs/heads/master
2022-07-21T23:37:02.237733
2019-08-15T10:32:06
2019-08-15T10:32:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,858
cpp
CommonSyntaxNodes.cpp
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2019/05/14. #include "polarphp/syntax/syntaxnode/CommonSyntaxNodes.h" #include "polarphp/syntax/TokenKinds.h" namespace polar::syntax { /// /// CodeBlockItemSyntax /// #ifdef POLAR_DEBUG_BUILD const NodeChoicesType CodeBlockItemSyntax::CHILD_NODE_CHOICES{ {CodeBlockItemSyntax::Cursor::Item, { SyntaxKind::Decl, SyntaxKind::Expr, SyntaxKind::Stmt, }} }; #endif // POLAR_DEBUG_BUILD void CodeBlockItemSyntax::validate() { auto raw = m_data->getRaw(); if (isMissing()) { return; } assert(raw->getLayout().size() == CodeBlockItemSyntax::CHILDREN_COUNT); /// validate every child token choices /// validate every child token text choices /// validate every child node choices if (auto &item = raw->getChild(Cursor::Item)) { bool declStatus = DeclSyntax::kindOf(item->getKind()); bool stmtStatus = StmtSyntax::kindOf(item->getKind()); bool exprStatus = ExprSyntax::kindOf(item->getKind()); assert(declStatus || stmtStatus || exprStatus); } } Syntax CodeBlockItemSyntax::getItem() { return Syntax{m_root, m_data->getChild(Cursor::Item).get()}; } TokenSyntax CodeBlockItemSyntax::getSemicolon() { return TokenSyntax{m_root, m_data->getChild(Cursor::Semicolon).get()}; } CodeBlockItemSyntax CodeBlockItemSyntax::withItem(std::optional<Syntax> item) { RefCountPtr<RawSyntax> rawItem; if (item.has_value()) { rawItem = item->getRaw(); } else { rawItem = RawSyntax::missing(SyntaxKind::Decl); } return m_data->replaceChild<CodeBlockItemSyntax>(rawItem, Cursor::Item); } CodeBlockItemSyntax CodeBlockItemSyntax::withSemicolon(std::optional<TokenSyntax> semicolon) { RefCountPtr<RawSyntax> rawSemicolon; if (semicolon.has_value()) { rawSemicolon = semicolon->getRaw(); } else { rawSemicolon = nullptr; } return m_data->replaceChild<CodeBlockItemSyntax>(rawSemicolon, Cursor::Item); } /// /// CodeBlockSyntax /// void CodeBlockSyntax::validate() { auto raw = m_data->getRaw(); if (isMissing()) { return; } assert(raw->getLayout().size() == CodeBlockSyntax::CHILDREN_COUNT); } TokenSyntax CodeBlockSyntax::getLeftBrace() { return TokenSyntax{m_root, m_data->getChild(Cursor::LeftBrace).get()}; } TokenSyntax CodeBlockSyntax::getRightBrace() { return TokenSyntax{m_root, m_data->getChild(Cursor::RightBrace).get()}; } CodeBlockItemListSyntax CodeBlockSyntax::getStatements() { return CodeBlockItemListSyntax{m_root, m_data->getChild(Cursor::Statements).get()}; } CodeBlockSyntax CodeBlockSyntax::addCodeBlockItem(CodeBlockItemSyntax codeBlockItem) { RefCountPtr<RawSyntax> statements = getRaw()->getChild(Cursor::Statements); if (statements) { statements = statements->append(codeBlockItem.getRaw()); } else { statements = RawSyntax::make(SyntaxKind::CodeBlockItemList, {codeBlockItem.getRaw()}, SourcePresence::Present); } return m_data->replaceChild<CodeBlockSyntax>(statements, Cursor::Statements); } CodeBlockSyntax CodeBlockSyntax::withLeftBrace(std::optional<TokenSyntax> leftBrace) { RefCountPtr<RawSyntax> rawLeftBrace; if (leftBrace.has_value()) { rawLeftBrace = leftBrace->getRaw(); } else { rawLeftBrace = RawSyntax::missing(TokenKindType::T_LEFT_BRACE, OwnedString::makeUnowned(get_token_text(TokenKindType::T_LEFT_BRACE))); } return m_data->replaceChild<CodeBlockSyntax>(rawLeftBrace, Cursor::LeftBrace); } CodeBlockSyntax CodeBlockSyntax::withRightBrace(std::optional<TokenSyntax> rightBrace) { RefCountPtr<RawSyntax> rawRightBrace; if (rightBrace.has_value()) { rawRightBrace = rightBrace->getRaw(); } else { rawRightBrace = RawSyntax::missing(TokenKindType::T_RIGHT_BRACE, OwnedString::makeUnowned(get_token_text(TokenKindType::T_RIGHT_BRACE))); } return m_data->replaceChild<CodeBlockSyntax>(rawRightBrace, Cursor::RightBrace); } CodeBlockSyntax CodeBlockSyntax::withStatements(std::optional<CodeBlockItemListSyntax> statements) { RefCountPtr<RawSyntax> rawStatements; if (statements.has_value()) { rawStatements = statements->getRaw(); } else { rawStatements = RawSyntax::missing(SyntaxKind::CodeBlockItemList); } return m_data->replaceChild<CodeBlockSyntax>(rawStatements, Cursor::Statements); } } // polar::syntax
29917b2407f95e1c77ea12f1569ebaf1d6aa6ee8
454c655e68a61f9927fb2609296a8c404126d342
/Frontline/ShaderClass.h
cb7e005d681f45b958e349af6fc3700a8b540561
[]
no_license
DavidQChuang/OldGameEngine
340fda1af202b1310af7ffbcc19853f1bf086540
885480b204d699d7c57b5881e0690a8ca551d858
refs/heads/master
2021-01-14T00:57:54.683765
2020-02-24T15:18:30
2020-02-24T15:18:30
242,543,935
0
0
null
null
null
null
UTF-8
C++
false
false
888
h
ShaderClass.h
#ifndef _SHADERCLASS_H_ #define _SHADERCLASS_H_ #include "D3DClass.h" #include "colorshader.h" #include "LightShaderClass.h" #include "RefractionShaderClass.h" #include "TextureShaderClass.h" #include "ColorTextureShader.h" #include "TransparencyShaderClass.h" #include "WaterShaderClass.h" #include "LightClass.h" class ShaderClass { public: ShaderClass(D3DClass*); ShaderClass(const ShaderClass&); ~ShaderClass(); bool Initialize(HWND); void Shutdown(); // 0 = fullscreen, 1 = windowed with titlebar(default), 2 = windowed without titlebar ColorShaderClass* m_ColorShader; LightShaderClass* m_LightShader; RefractionShaderClass* m_RefractionShader; ColorTextureShader* m_ColorTextureShader; TextureShaderClass* m_TextureShader; TransparencyShaderClass* m_TransparencyShader; WaterShaderClass* m_WaterShader; LightClass* m_Light; private: D3DClass* m_DirectX; }; #endif
964458414780fec80a42ccf12244423c01f5083a
86a085fbf5abde1d7d37450b1f4c828260b19234
/ch08/u8_1_13.cpp
3c9bda51e9bf2eed984da65da2035a565e9255f8
[]
no_license
crespo2014/cpp-exam
5eaa0f87e5839988974774a3766940bd3adfbf6f
8794f2945494873c610b6938571b13463c74e22a
refs/heads/master
2021-01-20T02:49:31.281036
2015-03-10T20:59:32
2015-03-10T20:59:32
26,771,078
0
0
null
null
null
null
UTF-8
C++
false
false
519
cpp
u8_1_13.cpp
/* * u8_1_13.cpp * * Created on: 25 Jan 2015 * Author: lester */ #include <iostream> using namespace std; int main() { int v = 100; bool b = true; double d = 100; cout<<"Without flags:\n"; cout<<v<<endl<<b<<endl<<d<<endl<<endl; cout<<"Flags set:\n"; cout.setf(ios::showpos); cout.setf(ios::boolalpha); cout.setf(ios::showpoint); cout<<v<<endl<<b<<endl<<d<<endl<<endl; return 0; } /* Console output: Without flags: 100 1 100 Flags set: +100 true +100.000 */
de9894db959293415581ede8a658ff5f85de66bb
8352ca72d4f1e8e8ebbbb7d6b07a4e0963be7f41
/DataServer/Yahoo_TIP/TA_BASE/transactive/app/YahooFinanceStock/YahooFinanceStockClient/src/StockTcpClientActor.cpp
7fecbaa82547db03478e269b919a3b92b66231cc
[]
no_license
radtek/slin_code
114f61695fc1a23a018da727452c3c42f64ebe39
a0073e52d600839f7836c2b7673b45b4266259e2
refs/heads/master
2020-06-04T15:03:56.618177
2015-04-27T10:27:47
2015-04-27T10:27:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,005
cpp
StockTcpClientActor.cpp
#include "StockTcpClientActor.h" #include <QtCore/QtCore> #include <QtNetwork/QtNetwork> #include "ClientComWorker.h" #include "BaseException.h" #include "TcpSocketHelper.h" #include "MessageManager.h" #include "SocketInfo.h" #include "Log4cppLogger.h" CDistributeTaskWorker::CDistributeTaskWorker( const QString& strServerIP, quint16 nServerPort, QObject* parent/*=0*/ ) { m_strServerIP = strServerIP; m_nServerPort = nServerPort; m_pComWorker = NULL; m_pMessageManager = NULL; m_WorkerState = WORK_STATE_BEGIN; } CDistributeTaskWorker::~CDistributeTaskWorker() { } void CDistributeTaskWorker::run() { MYLOG4CPP_DEBUG<<"CStockTcpClientActor::run()"; m_pComWorker = new CClientComWorker(m_strServerIP, m_nServerPort, this); QObject::connect(m_pComWorker, SIGNAL(signalDisconnected()), this, SLOT(slotDisconnected()), Qt::AutoConnection); QObject::connect(m_pComWorker, SIGNAL(signalConnected()), this, SLOT(slotConnected()), Qt::AutoConnection); QObject::connect(this, SIGNAL(signalConnectToServer()), m_pComWorker, SLOT(slotConnectToServer()), Qt::AutoConnection); // m_pMessageManager = new CMessageManager(this); QObject::connect(m_pComWorker, SIGNAL(signalProcessMessage(QByteArray*)), m_pMessageManager, SLOT(slotProcessMessage(QByteArray*)), Qt::AutoConnection); QObject::connect(m_pMessageManager, SIGNAL(signalWriteMessage(QByteArray*)), m_pComWorker, SLOT(slotWriteMessage(QByteArray*)), Qt::AutoConnection); m_pComWorker->start(); m_WorkerState = WORK_STATE_BEGIN; m_WorkerState = WORK_STATE_WORKING; //QThread::exec() waits until QThread::exit() called exec(); if (NULL != m_pComWorker) { m_pComWorker->terminateAndWait(); delete m_pComWorker; m_pComWorker = NULL; } if (NULL != m_pMessageManager) { delete m_pMessageManager; m_pMessageManager = NULL; } m_WorkerState = WORK_STATE_END; } void CDistributeTaskWorker::terminate() { return; } void CDistributeTaskWorker::slotDisconnected() { MYLOG4CPP_DEBUG<<" " <<" "<<"class:"<<" "<<"CStockTcpClientActor" <<" "<<"slot:"<<" "<<"slotDisconnected"; //TODO. this->msleep(1000*10); MYLOG4CPP_DEBUG<<" " <<" "<<"class:"<<" "<<"CStockTcpClientActor" <<" "<<"fun:"<<" "<<"slotDisconnected" <<" "<<"emit signalConnectToServer()"; emit signalConnectToServer(); } void CDistributeTaskWorker::slotConnected() { MYLOG4CPP_DEBUG<<" " <<" "<<"class:"<<" "<<"CStockTcpClientActor" <<" "<<"slot:"<<" "<<"slotConnected"; m_pMsgManager->send_login_req(); //m_pMsgManager->send_logout_req(); //m_pMsgManager->send_SynYahoo_req(); } /* void CTestMyThreadManager::do_test_mythread_2() { CSampleMyQtThread* pMyThreadTest = NULL; pMyThreadTest = new CSampleMyQtThread(); pMyThreadTest->start(); pMyThreadTest->join(); pMyThreadTest->my_msleep(1000* 10); pMyThreadTest->terminateAndWait(); delete pMyThreadTest; pMyThreadTest = NULL; } */
2494bc0ccc61b498e42975699fc89997049bad1b
9ca9d49c79edd03785ecf6a16c26ed2a887583f9
/master/alleyhoop_ros_master/include/alleyhoop_ros_core/alleyhoop_ros_controller.h
6cc078e25f92519e4750244f476a9beeb761d9d6
[]
no_license
AlleyHoop/alleyhoop_ros
872e3e9a89702e301a48103119485140a3edb47c
33ee6a315b867d6ff36e2cd51ddba8aef7a0db1d
refs/heads/master
2020-09-19T10:48:12.843466
2020-01-31T16:22:43
2020-01-31T16:22:43
224,226,376
1
0
null
null
null
null
UTF-8
C++
false
false
3,166
h
alleyhoop_ros_controller.h
#ifndef ALLEYHOOPROSCONTROLLER_H_ #define ALLEYHOOPROSCONTROLLER_H_ //required includes #include <ros/ros.h> #include "alleyhoop_mvc/controller.h" //sensor headers #include "alleyhoop_ros_sensors/alleyhoop_ros_ultrasonic_sensor.h" #include "alleyhoop_ros_sensors/alleyhoop_ros_mono_camera.h" #include "alleyhoop_ros_sensors/alleyhoop_ros_lidar.h" #include "alleyhoop_ros_sensors/alleyhoop_ros_depth_camera.h" #include "alleyhoop_ros_sensors/alleyhoop_ros_imu.h" #include "alleyhoop_ros_sensors/alleyhoop_ros_linetracker.h" namespace AlleyHoopROSCore { class FeatureFinder; class PathFinder; //* A ros controller implementation of the controller class from the alleyhoop_master package /** * Everything comes together in this class * 1. This class reads sensor data and passes them to the model to find features * 2. Based on a number of features the controller will instruct a path finder to find a path * 3. The controller will then instruct the vehicle to do some actions */ class Controller : public AlleyHoopMVC::Controller { public: /*! * \brief The constructor for the controller class * \param _nh the nodehandle to publish data on * \param v a pointer to the vehicle that is to be controlled, is required by the controller base class */ Controller(ros::NodeHandle* _nh, AlleyHoopMVC::Vehicle* v); /*! * \brief the destructor will delete the member variables featurefinder and pathfinder where after the base class destructor will be called */ ~Controller(); /*! * \brief update function, is generally called from the main process * \todo actually control the vehicle */ bool update(); static bool verboseMode; /**< a static bool, when true more print messages will be displayed on the console*/ protected: //ros ros::NodeHandle nh; /**< the nodehandle*/ //sensors AlleyHoopROSSensors::UltrasonicSensor* ultrasonic_sensor_1; /**< a pointer to a ultrasonic_sensor for near-object detection */ AlleyHoopROSSensors::MonoCamera* mono_camera_1; /**< a pointer to a mono camera for retrieving normal images */ AlleyHoopROSSensors::DepthCamera* depth_camera_1; /**< a pointer to a depth camera for retrieving pointcloud data */ AlleyHoopROSSensors::Lidar* lidar1; /**< a pointer to a laser tracer for depth measurement */ AlleyHoopROSSensors::Imu* imu; /**< a pointer to a intertial measurement unit for retrieving accelaration, velocity and angular movement data */ AlleyHoopROSSensors::LineTracker* linetracker_left; /**< a pointer to the left line tracker */ AlleyHoopROSSensors::LineTracker* linetracker_right; /**< a pointer to the right line tracker */ //finder FeatureFinder* featureFinder; /**< a pointer to a feature finder */ PathFinder* pathFinder; /**< a pointer to a pathfinder */ }; } #endif //! ALLEYHOOPROSCONTROLLER_H_
5a37c3b3cfdeaa7bce0f8e8ec63225282bb715dc
a31e7362f9f0205dd9a37ca4a491c5275aaca03a
/axengine/include/axlogic/game/gamenode.h
365c85e72a775cda671c8f25feaff75f933ccd52
[ "LicenseRef-scancode-warranty-disclaimer", "FTL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
teardemon/axonengine
56368abcffc7f2a0661523da5c4241176e74f08f
4e7539825d71c11fa4ef48973f6711439f55c267
refs/heads/master
2021-01-15T10:34:21.413244
2009-08-23T15:53:54
2009-08-23T15:53:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,264
h
gamenode.h
/* Copyright (c) 2009 AxonEngine Team This file is part of the AxonEngine project, and may only be used, modified, and distributed under the terms of the AxonEngine project license, license.txt. By continuing to use, modify, or distribute this file you indicate that you have read the license and understand and accept it fully. */ #ifndef AX_GAME_NODE_H #define AX_GAME_NODE_H namespace Axon { namespace Game { //-------------------------------------------------------------------------- // class Node //-------------------------------------------------------------------------- class AX_API Node : public Object { public: AX_DECLARE_CLASS(Node, Object, "Game.Node") AX_PROP(outdoorOnly) AX_PROP(castShadow) AX_PROP(recvShadow) AX_PROP(lodRatio) AX_END_CLASS() friend class World; enum Mode { Editing, Simulating, Gaming }; enum Update { MatrixSet = 1, Present = 2, Visual = 4, Animation = 8, Sound = 16, ReadPhysics = 32, SetPhysics = 64 }; typedef Flags_<Update> UpdateFlags; Node(); virtual ~Node(); // geometry virtual BoundingBox getLocalBoundingBox(); virtual BoundingBox getBoundingBox(); // for editor use virtual void doSelectTest() const; virtual void doDebugRender() const; // game logic virtual void doSpawn(); virtual void doRemove(); virtual bool isFixed() const { return false; } // read and write void writeXml(File* f, int indent=0); void readXml(const TiXmlElement* node); // matrix Vector3 getOrigin_p() const; void setOrigin_p(const Vector3& pos); const Matrix3& getAxis_p() const; void setAxis_p(const Matrix3& axis); void setMatrix_p(const AffineMat& matrix); const AffineMat& getMatrix_p() const; Vector3 getInstanceColor() const { return m_instanceColor_p; } void setInstanceColor(const Vector3& color); // properties bool get_outdoorOnly() const { return m_outdoorOnly; } void set_outdoorOnly(bool val) { m_outdoorOnly = val; } bool get_castShadow() const { return m_castShadow; } void set_castShadow(bool val) { m_castShadow = val; } bool get_recvShadow() const { return m_recvShadow; } void set_recvShadow(bool val) { m_recvShadow = val; } float get_lodRatio() const { return m_lodRatio; } void set_lodRatio(float val) { m_lodRatio = val; } protected: void setRenderEntity(RenderEntity* entity) { m_renderEntity = entity; } RenderEntity* getRenderEntity() const { return m_renderEntity; }; void setPhysicsEntity(PhysicsEntity* physics) { m_physicsEntity = physics; } PhysicsEntity* getPhysicsEntity() const { return m_physicsEntity; } void setSoundEntity(SoundEntity* entity) { m_soundEntity = entity; } SoundEntity* getSoundEntity() const { return m_soundEntity; } virtual void onMatrixChanged(); virtual void onPropertyChanged(); virtual void reload() {}; virtual void clear() {}; protected: AffineMat m_matrix_p; Vector3 m_instanceColor_p; bool m_matrixDirty; bool m_outdoorOnly; bool m_castShadow; bool m_recvShadow; float m_lodRatio; UpdateFlags m_updateFlags; bool m_spawned; private: RenderEntity* m_renderEntity; PhysicsEntity* m_physicsEntity; SoundEntity* m_soundEntity; }; }} // namespace Axon::Game #endif // end guardian
18d29156f1b43a79318f90698b426881bab41a85
57338e7af891aaee72cab07b4329d80a3bc358f5
/sonic-swss/orchagent/pfcwdorch.cpp
2a94f9ec26ca616e167465d27a78c8d2200e005f
[ "Apache-2.0" ]
permissive
tiglabs/sonic
18ecb2364be2bf70d239dc30a9d006911391d4b0
e10c5b82c4b1cdb439f7212579aca880aa9d7cd3
refs/heads/master
2021-07-10T18:38:28.814144
2017-10-12T03:36:51
2017-10-12T03:36:51
106,631,679
4
2
null
null
null
null
UTF-8
C++
false
false
15,693
cpp
pfcwdorch.cpp
#include "pfcwdorch.h" #include "saiserialize.h" #include "portsorch.h" #include "converter.h" #include "redisapi.h" #include "select.h" #define PFC_WD_ACTION "action" #define PFC_WD_DETECTION_TIME "detection_time" #define PFC_WD_RESTORATION_TIME "restoration_time" #define PFC_WD_DETECTION_TIME_MAX (5 * 1000) #define PFC_WD_DETECTION_TIME_MIN 100 #define PFC_WD_RESTORATION_TIME_MAX (60 * 1000) #define PFC_WD_RESTORATION_TIME_MIN 100 #define PFC_WD_TC_MAX 8 #define PFC_WD_POLL_TIMEOUT 5000 extern sai_port_api_t *sai_port_api; extern sai_queue_api_t *sai_queue_api; extern PortsOrch *gPortsOrch; template <typename DropHandler, typename ForwardHandler> PfcWdOrch<DropHandler, ForwardHandler>::PfcWdOrch(DBConnector *db, vector<string> &tableNames): Orch(db, tableNames), m_countersDb(new DBConnector(COUNTERS_DB, DBConnector::DEFAULT_UNIXSOCKET, 0)), m_countersTable(new Table(m_countersDb.get(), COUNTERS_TABLE)) { SWSS_LOG_ENTER(); } template <typename DropHandler, typename ForwardHandler> PfcWdOrch<DropHandler, ForwardHandler>::~PfcWdOrch(void) { SWSS_LOG_ENTER(); } template <typename DropHandler, typename ForwardHandler> void PfcWdOrch<DropHandler, ForwardHandler>::doTask(Consumer& consumer) { SWSS_LOG_ENTER(); auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { KeyOpFieldsValuesTuple t = it->second; string key = kfvKey(t); string op = kfvOp(t); if (op == SET_COMMAND) { createEntry(key, kfvFieldsValues(t)); } else if (op == DEL_COMMAND) { deleteEntry(key); } else { SWSS_LOG_ERROR("Unknown operation type %s\n", op.c_str()); } consumer.m_toSync.erase(it++); } } template <typename DropHandler, typename ForwardHandler> template <typename T> string PfcWdSwOrch<DropHandler, ForwardHandler>::counterIdsToStr( const vector<T> ids, string (*convert)(T)) { SWSS_LOG_ENTER(); string str; for (const auto& i: ids) { str += convert(i) + ","; } // Remove trailing ',' if (!str.empty()) { str.pop_back(); } return str; } template <typename DropHandler, typename ForwardHandler> PfcWdAction PfcWdOrch<DropHandler, ForwardHandler>::deserializeAction(const string& key) { SWSS_LOG_ENTER(); const map<string, PfcWdAction> actionMap = { { "forward", PfcWdAction::PFC_WD_ACTION_FORWARD }, { "drop", PfcWdAction::PFC_WD_ACTION_DROP }, }; if (actionMap.find(key) == actionMap.end()) { return PfcWdAction::PFC_WD_ACTION_UNKNOWN; } return actionMap.at(key); } template <typename DropHandler, typename ForwardHandler> void PfcWdOrch<DropHandler, ForwardHandler>::createEntry(const string& key, const vector<FieldValueTuple>& data) { SWSS_LOG_ENTER(); uint32_t detectionTime = 0; uint32_t restorationTime = 0; // According to requirements, drop action is default PfcWdAction action = PfcWdAction::PFC_WD_ACTION_DROP; Port port; if (!gPortsOrch->getPort(key, port)) { SWSS_LOG_ERROR("Invalid port interface %s", key.c_str()); return; } if (port.m_type != Port::PHY) { SWSS_LOG_ERROR("Interface %s is not physical port", key.c_str()); return; } for (auto i : data) { const auto &field = fvField(i); const auto &value = fvValue(i); try { if (field == PFC_WD_DETECTION_TIME) { detectionTime = to_uint<uint32_t>( value, PFC_WD_DETECTION_TIME_MIN, PFC_WD_DETECTION_TIME_MAX); } else if (field == PFC_WD_RESTORATION_TIME) { restorationTime = to_uint<uint32_t>(value, PFC_WD_RESTORATION_TIME_MIN, PFC_WD_RESTORATION_TIME_MAX); } else if (field == PFC_WD_ACTION) { action = deserializeAction(value); if (action == PfcWdAction::PFC_WD_ACTION_UNKNOWN) { SWSS_LOG_ERROR("Invalid PFC Watchdog action %s", value.c_str()); return; } } else { SWSS_LOG_ERROR( "Failed to parse PFC Watchdog %s configuration. Unknown attribute %s.\n", key.c_str(), field.c_str()); return; } } catch (const exception& e) { SWSS_LOG_ERROR( "Failed to parse PFC Watchdog %s attribute %s error: %s.", key.c_str(), field.c_str(), e.what()); return; } catch (...) { SWSS_LOG_ERROR( "Failed to parse PFC Watchdog %s attribute %s. Unknown error has been occurred", key.c_str(), field.c_str()); return; } } // Validation if (detectionTime == 0) { SWSS_LOG_ERROR("%s missing", PFC_WD_DETECTION_TIME); return; } if (restorationTime == 0) { SWSS_LOG_ERROR("%s missing", PFC_WD_RESTORATION_TIME); return; } if (!startWdOnPort(port, detectionTime, restorationTime, action)) { SWSS_LOG_ERROR("Failed to start PFC Watchdog on port %s", port.m_alias.c_str()); return; } SWSS_LOG_NOTICE("Started PFC Watchdog on port %s", port.m_alias.c_str()); } template <typename DropHandler, typename ForwardHandler> void PfcWdOrch<DropHandler, ForwardHandler>::deleteEntry(const string& name) { SWSS_LOG_ENTER(); Port port; gPortsOrch->getPort(name, port); if (!stopWdOnPort(port)) { SWSS_LOG_ERROR("Failed to stop PFC Watchdog on port %s", name.c_str()); return; } SWSS_LOG_NOTICE("Stopped PFC Watchdog on port %s", name.c_str()); } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::registerInWdDb(const Port& port, uint32_t detectionTime, uint32_t restorationTime, PfcWdAction action) { SWSS_LOG_ENTER(); sai_attribute_t attr; attr.id = SAI_PORT_ATTR_PRIORITY_FLOW_CONTROL; sai_status_t status = sai_port_api->get_port_attribute(port.m_port_id, 1, &attr); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to get PFC mask on port %s: %d", port.m_alias.c_str(), status); return; } if (!c_portStatIds.empty()) { vector<FieldValueTuple> fieldValues; string str = counterIdsToStr(c_portStatIds, &sai_serialize_port_stat); fieldValues.emplace_back(PFC_WD_PORT_COUNTER_ID_LIST, str); m_pfcWdTable->set( sai_serialize_object_id(port.m_port_id), fieldValues); } uint8_t pfcMask = attr.value.u8; for (uint8_t i = 0; i < PFC_WD_TC_MAX; i++) { if ((pfcMask & (1 << i)) == 0) { continue; } sai_object_id_t queueId = port.m_queue_ids[i]; string queueIdStr = sai_serialize_object_id(queueId); // Store detection and restoration time for plugins vector<FieldValueTuple> countersFieldValues; countersFieldValues.emplace_back("PFC_WD_DETECTION_TIME", to_string(detectionTime * 1000)); countersFieldValues.emplace_back("PFC_WD_RESTORATION_TIME", to_string(restorationTime * 1000)); PfcWdOrch<DropHandler, ForwardHandler>::getCountersTable()->set(queueIdStr, countersFieldValues); // We register our queues in PFC_WD table so that syncd will know that it must poll them vector<FieldValueTuple> queueFieldValues; if (!c_queueStatIds.empty()) { string str = counterIdsToStr(c_queueStatIds, sai_serialize_queue_stat); queueFieldValues.emplace_back(PFC_WD_QUEUE_COUNTER_ID_LIST, str); } // Create internal entry m_entryMap.emplace(queueId, PfcWdQueueEntry(action, port.m_port_id, i)); m_pfcWdTable->set(queueIdStr, queueFieldValues); // Initialize PFC WD related counters PfcWdActionHandler::initWdCounters( PfcWdOrch<DropHandler, ForwardHandler>::getCountersTable(), sai_serialize_object_id(queueId)); } } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::unregisterFromWdDb(const Port& port) { SWSS_LOG_ENTER(); for (uint8_t i = 0; i < PFC_WD_TC_MAX; i++) { sai_object_id_t queueId = port.m_queue_ids[i]; // Unregister in syncd m_pfcWdTable->del(sai_serialize_object_id(queueId)); m_entryMap.erase(queueId); } } template <typename DropHandler, typename ForwardHandler> PfcWdSwOrch<DropHandler, ForwardHandler>::PfcWdSwOrch( DBConnector *db, vector<string> &tableNames, vector<sai_port_stat_t> portStatIds, vector<sai_queue_stat_t> queueStatIds): PfcWdOrch<DropHandler, ForwardHandler>(db, tableNames), m_pfcWdDb(new DBConnector(PFC_WD_DB, DBConnector::DEFAULT_UNIXSOCKET, 0)), m_pfcWdTable(new ProducerStateTable(m_pfcWdDb.get(), PFC_WD_STATE_TABLE)), c_portStatIds(portStatIds), c_queueStatIds(queueStatIds) { SWSS_LOG_ENTER(); string platform = getenv("platform") ? getenv("platform") : ""; if (platform == "") { SWSS_LOG_ERROR("Platform environment variable is not defined"); return; } string detectSha, restoreSha; string detectPluginName = "pfc_detect_" + platform + ".lua"; string restorePluginName = "pfc_restore_" + platform + ".lua"; try { string detectLuaScript = swss::loadLuaScript(detectPluginName); detectSha = swss::loadRedisScript( PfcWdOrch<DropHandler, ForwardHandler>::getCountersDb().get(), detectLuaScript); string restoreLuaScript = swss::loadLuaScript(restorePluginName); restoreSha = swss::loadRedisScript( PfcWdOrch<DropHandler, ForwardHandler>::getCountersDb().get(), restoreLuaScript); vector<FieldValueTuple> fieldValues; fieldValues.emplace_back(SAI_OBJECT_TYPE, sai_serialize_object_type(SAI_OBJECT_TYPE_QUEUE)); auto pluginTable = ProducerStateTable(m_pfcWdDb.get(), PLUGIN_TABLE); pluginTable.set(detectSha, fieldValues); pluginTable.set(restoreSha, fieldValues); } catch (...) { SWSS_LOG_WARN("Lua scripts for PFC watchdog were not loaded"); } } template <typename DropHandler, typename ForwardHandler> PfcWdSwOrch<DropHandler, ForwardHandler>::~PfcWdSwOrch(void) { SWSS_LOG_ENTER(); } template <typename DropHandler, typename ForwardHandler> PfcWdSwOrch<DropHandler, ForwardHandler>::PfcWdQueueEntry::PfcWdQueueEntry( PfcWdAction action, sai_object_id_t port, uint8_t idx): action(action), portId(port), index(idx) { SWSS_LOG_ENTER(); } template <typename DropHandler, typename ForwardHandler> bool PfcWdSwOrch<DropHandler, ForwardHandler>::startWdOnPort(const Port& port, uint32_t detectionTime, uint32_t restorationTime, PfcWdAction action) { SWSS_LOG_ENTER(); registerInWdDb(port, detectionTime, restorationTime, action); if (!m_runPfcWdSwOrchThread.load()) { startWatchdogThread(); } return true; } template <typename DropHandler, typename ForwardHandler> bool PfcWdSwOrch<DropHandler, ForwardHandler>::stopWdOnPort(const Port& port) { SWSS_LOG_ENTER(); if (m_runPfcWdSwOrchThread.load()) { endWatchdogThread(); } unregisterFromWdDb(port); return true; } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::handleWdNotification(swss::NotificationConsumer& wdNotification) { SWSS_LOG_ENTER(); string queueIdStr; string event; vector<swss::FieldValueTuple> values; wdNotification.pop(queueIdStr, event, values); sai_object_id_t queueId = SAI_NULL_OBJECT_ID; sai_deserialize_object_id(queueIdStr, queueId); auto entry = m_entryMap.find(queueId); if (entry == m_entryMap.end()) { SWSS_LOG_ERROR("Queue %s is not registered", queueIdStr.c_str()); return; } if (event == "storm") { if (entry->second.action == PfcWdAction::PFC_WD_ACTION_DROP) { entry->second.handler = make_shared<DropHandler>( entry->second.portId, entry->first, entry->second.index, PfcWdOrch<DropHandler, ForwardHandler>::getCountersTable()); } else if (entry->second.action == PfcWdAction::PFC_WD_ACTION_FORWARD) { entry->second.handler = make_shared<ForwardHandler>( entry->second.portId, entry->first, entry->second.index, PfcWdOrch<DropHandler, ForwardHandler>::getCountersTable()); } else { throw runtime_error("Unknown PFC WD action"); } } else if (event == "restore") { entry->second.handler = nullptr; } else { SWSS_LOG_ERROR("Received unknown event from plugin"); } } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::pfcWatchdogThread(void) { SWSS_LOG_ENTER(); DBConnector db(COUNTERS_DB, DBConnector::DEFAULT_UNIXSOCKET, 0); swss::Select s; shared_ptr<swss::NotificationConsumer> wdNotification = make_shared<swss::NotificationConsumer>( PfcWdSwOrch<DropHandler, ForwardHandler>::getCountersDb().get(), "PFC_WD"); s.addSelectable(wdNotification.get()); while(m_runPfcWdSwOrchThread) { unique_lock<mutex> lk(m_pfcWdMutex); swss::Selectable *sel = NULL; int fd; int result = s.select(&sel, &fd, PFC_WD_POLL_TIMEOUT); if (sel == wdNotification.get()) { handleWdNotification(*wdNotification.get()); } else if (result == swss::Select::TIMEOUT) { // Do nothing } else { SWSS_LOG_ERROR("Received unexpected object on select"); } } } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::startWatchdogThread(void) { SWSS_LOG_ENTER(); if (m_runPfcWdSwOrchThread.load()) { return; } m_runPfcWdSwOrchThread = true; m_pfcWatchdogThread = shared_ptr<thread>( new thread(&PfcWdSwOrch::pfcWatchdogThread, this)); SWSS_LOG_INFO("PFC Watchdog thread started"); } template <typename DropHandler, typename ForwardHandler> void PfcWdSwOrch<DropHandler, ForwardHandler>::endWatchdogThread(void) { SWSS_LOG_ENTER(); if (!m_runPfcWdSwOrchThread.load()) { return; } m_runPfcWdSwOrchThread = false; if (m_pfcWatchdogThread != nullptr) { SWSS_LOG_INFO("Wait for PFC Watchdog thread to end"); m_pfcWatchdogThread->join(); } SWSS_LOG_INFO("PFC Watchdog thread ended"); } // Trick to keep member functions in a separate file template class PfcWdSwOrch<PfcWdZeroBufferHandler, PfcWdLossyHandler>;
c35280ab1a4769b17b03fdfe80d950076e4041bd
7ac55f7ae68e1818b210f9c4971d05fb20c84eb4
/BuilderPattern/BuilderPattern/BuilderPattern.cpp
a30b77004a63a83a6336662076b8fed110ebeb62
[]
no_license
yiminyangguang520/DesignPattern
e45495b0399e8304db6841e13be3d49fb7de1359
2628d6e3bf4964c96844964916c713d06c913ac6
refs/heads/master
2020-12-14T10:34:28.872735
2017-09-22T05:35:00
2017-09-22T05:35:14
46,867,893
4
4
null
null
null
null
GB18030
C++
false
false
276
cpp
BuilderPattern.cpp
// BuilderPattern.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "builder.h" #include "director.h" int main() { Director* pBuilder = new Director(new ConcreteBuilder()); pBuilder->construct(); system("pause"); return 0; }
ed8468b5db51cc94931221a082ffaddf5f130170
022cb1c48475cf0ff8c62f458e9b8372ca6ef5e3
/linux/src/movie.cpp
97d47d3e91c93021ef9ba6ca359af6dec6c3afd5
[]
no_license
gitScald/C-Recommender
f22772bbf761dc30e6e07e0113ab9cbd95014542
21ed951e42db3254e1a012cec46a02b71e0fadee
refs/heads/master
2021-05-09T13:59:09.724223
2017-11-22T01:53:56
2017-11-22T01:53:56
119,052,414
0
0
null
null
null
null
UTF-8
C++
false
false
633
cpp
movie.cpp
#include "movie.h" #include "word_tokenizer.h" #include <sstream> /*! \param os is a Output Stream Object \param m is a Movie Object \return Output Stream Object os containing in its buffer the name, id, release date and summary of Movie Object m */ std::ostream& operator<<(std::ostream& os, const Movie& m) { // provides output for movie data members os << "[" << m.id_ << "] \"" << m.name_ << "\" (released " << m.release_date_ << ")" << std::endl << std::endl << m.content_; return os; } void Movie::init() { // create movie document object doc = Document(name_, content_); }
87823fdd7e61f8155a8080a0f978bed6796856bd
fb1c4f630a2d4db6a9211a1ca3362f461f6916fb
/Src/Hardware/MCU/Virtual/Src/Adc_Virtual.cpp
4dbaa0033fdf48fce81e7dce5879ab7e73b50e6a
[ "MIT" ]
permissive
ThBreuer/EmbSysLib
a7e445f86564a68387e47e10b4b652535236de1b
1372c29aa1b9a6400b7ac2aeeb23aa1ed09c37a4
refs/heads/main
2023-04-07T02:54:17.452717
2023-04-06T10:16:37
2023-04-06T10:16:37
53,247,108
1
1
null
null
null
null
UTF-8
C++
false
false
2,256
cpp
Adc_Virtual.cpp
//******************************************************************* /*! \file Adc_Virtual.cpp \author Thomas Breuer (Bonn-Rhein-Sieg University of Applied Sciences) \date 15.10.2013 License: See file "LICENSE" */ //******************************************************************* #include "Adc_Virtual.h" #include "Hardware/ReportID_Hw.h" //******************************************************************* namespace EmbSysLib { namespace Hw { //******************************************************************* // // Adc_Virtual // //******************************************************************* //------------------------------------------------------------------- Adc_Virtual::Adc_Virtual( const char *server, Timer &timer ) : Adc( ReportID_Hw::Module::ADC_VIRTUAL, 255, timer ) , client( server ) { } //------------------------------------------------------------------- void Adc_Virtual::configCh( BYTE ch, BYTE para ) { } //------------------------------------------------------------------- inline WORD Adc_Virtual::getResult( void ) { return( currentValue ); } //------------------------------------------------------------------- inline void Adc_Virtual::startCh( BYTE ch ) { data.header.cmd = 0; data.ch = ch; client.send((BYTE*)&data, sizeof(Data)); if( client.receive((BYTE*)&data, sizeof(Data))) { currentValue = (WORD)data.value; } else { currentValue = 0; } // simulate ADC interrupt: isr(); } //******************************************************************* // // Adc_Virtual::Handler // //******************************************************************* //------------------------------------------------------------------- Adc_Virtual::Handler::Handler( UDPserver &server ) : UDPserver::Handler( server ) { } //----------------------------------------------------------- bool Adc_Virtual::Handler::update( BYTE *data, WORD plen ) { BYTE mode = data[0]; if( mode == UDP_MsgHeader::ADC ) { Adc_Virtual::Data *dataPtr = (Adc_Virtual::Data*)data; dataPtr->value = onGetValue( dataPtr->ch ); server.send( (BYTE*)dataPtr,sizeof(Adc_Virtual::Data) ); return true; } return false; } } } //namespace //EOF
03d7409434985c237fd4f8334a4cf56ad999104f
28a2707c03a69c3e8e131e644bb365f684812a84
/tp2_1_1.cpp
c2cdc41f43140ffa309fc51bc5a5c5a667841733
[]
no_license
TallerDeLenguajes1/tpn2-alamodeg
a963f36c7e034d17a37cc6997d4eb3388fdc0f44
ec02e4fd85cdfdeb4a48da87c34b0fe107bd8555
refs/heads/master
2021-05-24T16:48:19.542315
2020-04-23T05:30:20
2020-04-23T05:30:20
253,662,426
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
tp2_1_1.cpp
#include <stdio.h> #define FILA 4 #define COLUMNA 5 int main(){ int f,c; double Matriz[FILA][COLUMNA]; for(f = 0;f<FILA; f++) { for(c = 0;c<COLUMNA; c++) { printf("%lf ", Matriz[f][c]); } printf("\n"); } getchar(); return 0; }
77076ad44b4ee44d229fde1964becb4ce71ed0fe
66deb611781cae17567efc4fd3717426d7df5e85
/pcmanager/src/publish/softmgr/IDTManager.h
aec3af7e74b258311f21877c68c8cdc7d718fa27
[ "Apache-2.0" ]
permissive
heguoxing98/knoss-pcmanager
4671548e14b8b080f2d3a9f678327b06bf9660c9
283ca2e3b671caa85590b0f80da2440a3fab7205
refs/heads/master
2023-03-19T02:11:01.833194
2020-01-03T01:45:24
2020-01-03T01:45:24
504,422,245
1
0
null
2022-06-17T06:40:03
2022-06-17T06:40:02
null
GB18030
C++
false
false
2,070
h
IDTManager.h
/** * @file IDtManager.h * @brief 下载管理 * @author liveck * @date 2010/04/09 20:11 */ #pragma once enum DTManager_Stat{TASK_DONE=0,TASK_DOWNING,TASK_PAUSED,TASK_CONECTING,TASK_ERROR,TASK_ERROR_MD5}; typedef void (*GetTaskCallback)(void* tk,void* para); static void GetTaskCallbackByArr(void* tk,void* para) { CAtlArray<void*>* tasks=(CAtlArray<void*>*)para; tasks->Add(tk); } //获取任务信息的回调 typedef void (*InfoCallBack)(__int64 cur,__int64 all,__int64 speed,DWORD time,void* para); //任务进度发生变化的回调 /** * tk是任务上下文 * para是自定义回调的参数 * */ typedef void (*DtStateChangeNotifyCallBack)(DTManager_Stat st,void* tk,void* para); class __declspec(uuid("43D2ACDB-2D19-4637-8BE9-4B5FF020A2E3")) IDTManager { public: virtual void Init(CAtlMap<DtStateChangeNotifyCallBack,void*>* calls)=0; /** * 新建任务,下载从cur开始 * @return void* * @param CAtlArray<CString> * urls 最后一个url会被单线程处理 * @param CString localfile * @param int64 cur */ virtual void* NewTask(CAtlArray<CString>* urls,CString md5,CString localfile)=0; /** * 恢复被停止的任务 * @return void * @param void * context * @remark 多次resume会死机哦! */ virtual void ResumeTask(void* context)=0; /** * 停止任务 * @return void * @param void * context */ virtual void PauseTask(void* context)=0; /** * 停止任务 * @return void * @param void * context */ virtual void StopTask(void* context)=0; /** * 取消任务,回收context * @return void * @param void * context */ virtual void CancelTask(void* context)=0; /** * 查询任务数量 * @return size_t */ virtual size_t GetTaskCount()=0; virtual int GetTasks(GetTaskCallback func,void* para )=0; /** * 查询任务信息 * @return void * @param void * tk * @param InfoCallBack func * @param void * para */ virtual void QueryTask(void* tk,InfoCallBack func,void* para)=0; };
86256cab1847ba506928aa2ad100ed92459a3461
e50c0284b5f7643bc16cf8143eb5a5f225c3fb06
/source/App/agent_broker.h
95cc80094c3034775cae00ead647efb751199e0d
[]
no_license
shinkw83/ThermogramCamera
b98daf64bebcbc0179f5fbf4a55b6798ee78f381
5c62e730bd05cd28919625fd943101aea53efc57
refs/heads/main
2023-03-04T18:49:35.871254
2021-01-15T02:25:39
2021-01-15T02:25:39
305,238,752
0
0
null
null
null
null
UTF-8
C++
false
false
414
h
agent_broker.h
#pragma once #include "global.hpp" #include <raspicam/raspicam_cv.h> class agent_broker { public: agent_broker(); ~agent_broker(); void set_picam(std::weak_ptr<raspicam::RaspiCam_Cv> picam); std::weak_ptr<raspicam::RaspiCam_Cv> picam(); void update_thermogram_index(); uint32_t thermogram_index(); private: private: std::weak_ptr<raspicam::RaspiCam_Cv> picam_; uint32_t cur_thermogram_index_ = 0; };
7de4f5bf2d497613d4758a8e3aa002d59870f466
bcdacb31ebb2da2e9da0efe9190a00ff0407edf5
/蓝桥杯 programming /5-17 汉诺塔的非递归实现/5-17 汉诺塔的非递归实现/main.cpp
f7c676ff64ff1d41133801b1fb2c8b430db3882a
[]
no_license
guohaoyu110/Self-Learning-DataStructure
08fe60fccb4b48e8503dd95f469ed82f7f109059
0d1533f70cf46aa28be5a5be84b9ce6cd4cc5dda
refs/heads/master
2022-02-22T07:23:21.956554
2019-10-12T22:52:02
2019-10-12T22:52:02
109,500,323
0
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
main.cpp
// // main.cpp // 5-17 汉诺塔的非递归实现 // // Created by Haoyu Guo on 17/01/2017. // Copyright © 2017 Haoyu Guo. All rights reserved. // /* 借助堆栈以非递归(循环)方式求解汉诺塔的问题(n, a, b, c),即将N个盘子从起始柱(标记为“a”)通过借助柱(标记为“b”)移动到目标柱(标记为“c”),并保证每个移动符合汉诺塔问题的要求。 输入格式: 输入为一个正整数N,即起始柱上的盘数。 输出格式: 每个操作(移动)占一行,按柱1 -> 柱2的格式输出。 输入样例: 3 输出样例: a -> c a -> b c -> b a -> c b -> a b -> c a -> c */ #include<iostream> #include<stack> using namespace std; int main() { return 0; }
cf6ac4e8507a9bad9eae88d6d5642a9251a7776c
fb6c14ed4e67707173d9457879a0ba0954222fff
/catkin_ws_ladybug/build/localization_beacons_stack/localization_ekf_beacons/include/localization_ekf_beacons/moc_localization_ekf_beacons_interface.cxx
96c9c784d8a254b52676cf0b96b59b06f4fb441f
[]
no_license
up201305747/tese_ladybug
adb7774a7e794d42bf4cbc26e1c6f92a5f8ef7da
c519813de241a618b6cb2b1fb1c5aa1256c2fc67
refs/heads/master
2020-03-18T12:11:10.770529
2018-05-24T12:40:33
2018-05-24T12:40:33
134,713,515
0
0
null
null
null
null
UTF-8
C++
false
false
4,576
cxx
moc_localization_ekf_beacons_interface.cxx
/**************************************************************************** ** Meta object code from reading C++ file 'localization_ekf_beacons_interface.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.7) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../src/localization_beacons_stack/localization_ekf_beacons/include/localization_ekf_beacons/localization_ekf_beacons_interface.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'localization_ekf_beacons_interface.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.7. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_localization_ekf_beacons__TLocalizationEkfBeaconsInterface[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 60, 59, 59, 59, 0x05, // slots: signature, parameters, type, tag, flags 95, 59, 59, 59, 0x08, 119, 59, 59, 59, 0x08, 145, 59, 59, 59, 0x08, 166, 59, 59, 59, 0x08, 195, 59, 59, 59, 0x08, 0 // eod }; static const char qt_meta_stringdata_localization_ekf_beacons__TLocalizationEkfBeaconsInterface[] = { "localization_ekf_beacons::TLocalizationEkfBeaconsInterface\0" "\0MeasureObservationVarianceSignal()\0" "NewBeaconsMapCallBack()\0" "BeaconsDataOdomCallBack()\0" "InicalPoseCallBack()\0DynamicReconfigureCallBack()\0" "MeasureObservationVarianceServiceCallBack()\0" }; void localization_ekf_beacons::TLocalizationEkfBeaconsInterface::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); TLocalizationEkfBeaconsInterface *_t = static_cast<TLocalizationEkfBeaconsInterface *>(_o); switch (_id) { case 0: _t->MeasureObservationVarianceSignal(); break; case 1: _t->NewBeaconsMapCallBack(); break; case 2: _t->BeaconsDataOdomCallBack(); break; case 3: _t->InicalPoseCallBack(); break; case 4: _t->DynamicReconfigureCallBack(); break; case 5: _t->MeasureObservationVarianceServiceCallBack(); break; default: ; } } Q_UNUSED(_a); } const QMetaObjectExtraData localization_ekf_beacons::TLocalizationEkfBeaconsInterface::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject localization_ekf_beacons::TLocalizationEkfBeaconsInterface::staticMetaObject = { { &TLocalizationEkfBeacons::staticMetaObject, qt_meta_stringdata_localization_ekf_beacons__TLocalizationEkfBeaconsInterface, qt_meta_data_localization_ekf_beacons__TLocalizationEkfBeaconsInterface, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &localization_ekf_beacons::TLocalizationEkfBeaconsInterface::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *localization_ekf_beacons::TLocalizationEkfBeaconsInterface::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *localization_ekf_beacons::TLocalizationEkfBeaconsInterface::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_localization_ekf_beacons__TLocalizationEkfBeaconsInterface)) return static_cast<void*>(const_cast< TLocalizationEkfBeaconsInterface*>(this)); return TLocalizationEkfBeacons::qt_metacast(_clname); } int localization_ekf_beacons::TLocalizationEkfBeaconsInterface::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = TLocalizationEkfBeacons::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } return _id; } // SIGNAL 0 void localization_ekf_beacons::TLocalizationEkfBeaconsInterface::MeasureObservationVarianceSignal() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
6a17163754f156517b44704ebe57d663c6244bed
684c9beb8bd972daeabe5278583195b9e652c0c5
/src/cobalt/loader/resource_cache.h
617143943332461fbba6f83f99db3e14db9535db
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
elgamar/cobalt-clone
a7d4e62630218f0d593fa74208456dd376059304
8a7c8792318a721e24f358c0403229570da8402b
refs/heads/master
2022-11-27T11:30:31.314891
2018-10-26T15:54:41
2018-10-26T15:55:22
159,339,577
2
4
null
2022-11-17T01:03:37
2018-11-27T13:27:44
C++
UTF-8
C++
false
false
38,034
h
resource_cache.h
// Copyright 2015 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef COBALT_LOADER_RESOURCE_CACHE_H_ #define COBALT_LOADER_RESOURCE_CACHE_H_ #include <algorithm> #include <list> #include <map> #include <string> #include "base/bind.h" #include "base/containers/linked_hash_map.h" #include "base/hash_tables.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/stringprintf.h" #include "base/threading/thread_checker.h" #include "base/timer.h" #include "cobalt/base/c_val.h" #include "cobalt/csp/content_security_policy.h" #include "cobalt/loader/decoder.h" #include "cobalt/loader/fetcher_factory.h" #include "cobalt/loader/loader.h" #include "googleurl/src/gurl.h" namespace cobalt { namespace loader { // CacheType must provide the following: // typedef SpecificResourceType ResourceType; // static uint32 GetEstimatedSizeInBytes( // const scoped_refptr<ResourceType>& resource); template <typename CacheType> class ResourceCache; enum CallbackType { kOnLoadingSuccessCallbackType, kOnLoadingErrorCallbackType, kCallbackTypeCount, }; ////////////////////////////////////////////////////////////////////////// // CachedResource - Declarations ////////////////////////////////////////////////////////////////////////// // CachedResource requests fetching and decoding a single resource and the // decoded resource is stored in |resource_|. CachedResource is created by // calling |CreateCachedResource| of the ResourceCache. template <typename CacheType> class CachedResource : public base::RefCountedThreadSafe<CachedResource<CacheType> > { public: typedef ResourceCache<CacheType> ResourceCacheType; typedef typename CacheType::ResourceType ResourceType; typedef base::Callback<scoped_ptr<Loader>( const GURL&, const Origin&, const csp::SecurityCallback&, const base::Callback<void(const scoped_refptr<ResourceType>&)>&, const base::Callback<void(const std::string&)>&)> CreateLoaderFunction; // This class can be used to attach success or error callbacks to // CachedResource objects that are executed when the resource finishes // loading. // The callbacks are removed when the object is destroyed. If the resource has // already been loaded, execute the callback immediately. class OnLoadedCallbackHandler { public: OnLoadedCallbackHandler( const scoped_refptr<CachedResource>& cached_resource, const base::Closure& success_callback, const base::Closure& error_callback); ~OnLoadedCallbackHandler(); private: typedef std::list<base::Closure>::iterator CallbackListIterator; scoped_refptr<CachedResource> cached_resource_; base::Closure success_callback_; base::Closure error_callback_; CallbackListIterator success_callback_list_iterator_; CallbackListIterator error_callback_list_iterator_; DISALLOW_COPY_AND_ASSIGN(OnLoadedCallbackHandler); }; // Request fetching and decoding a single resource based on the url. CachedResource(const GURL& url, const Origin& origin, ResourceCacheType* resource_cache); // Resource is available. CachedResource is a wrapper of the resource // and there is no need to fetch or load this resource again. |loader_| // is NULL in this case. CachedResource(const GURL& url, ResourceType* resource, ResourceCacheType* resource_cache); // If the resource is available in the cache, simply returns the resource. If // the resource loader is in loading status or encounters an error, still // returns |resource_| even if it is NULL to indicate no resource is // available. scoped_refptr<ResourceType> TryGetResource(); // Whether not the resource located at |url_| is finished loading. bool IsLoadingComplete(); const GURL& url() const { return url_; } const Origin& origin() const { return origin_; } private: friend class base::RefCountedThreadSafe<CachedResource>; friend class OnLoadedCallbackHandler; friend class ResourceCache<CacheType>; typedef std::list<base::Closure> CallbackList; typedef std::list<base::Closure>::iterator CallbackListIterator; ~CachedResource(); // Start loading the resource located at |url_|. This encompasses both // fetching and decoding it. void StartLoading(); // Schedule a loading retry on the resource located at |url_|. While there is // no limit on the number of retry attempts that can occur, the retry // scheduling uses an exponential backoff. The wait time doubles with each // subsequent attempt until a maximum wait time of 1024 seconds (~17 minutes) // is reached. void ScheduleLoadingRetry(); // Callbacks for decoders. // // Notify that the resource is loaded successfully. void OnLoadingSuccess(const scoped_refptr<ResourceType>& resource); // Notify the loading error. void OnLoadingError(const std::string& error); // Called by |CachedResourceLoadedCallbackHandler|. CallbackListIterator AddCallback(CallbackType type, const base::Closure& callback); void RemoveCallback(CallbackType type, CallbackListIterator iterator); void RunCallbacks(CallbackType type); void EnableCompletionCallbacks(); const GURL url_; const Origin origin_; scoped_refptr<ResourceType> resource_; ResourceCacheType* const resource_cache_; scoped_ptr<Loader> loader_; CallbackList callback_lists[kCallbackTypeCount]; base::ThreadChecker cached_resource_thread_checker_; // In some cases (such as when the resource input data is stored in memory), // completion callbacks (e.g. resource fetch success/failure) could be // triggered from within the resource initialization callstack, and we are // not prepared to handle that. These members let us ensure that we are fully // initialized before we proceed with any completion callbacks. bool are_completion_callbacks_enabled_; base::Closure completion_callback_; // When the resource cache is set to allow retries and a transient loading // error causes a resource to fail to load, a retry is scheduled. int retry_count_; scoped_ptr<base::Timer> retry_timer_; DISALLOW_COPY_AND_ASSIGN(CachedResource); }; ////////////////////////////////////////////////////////////////////////// // CachedResource::OnLoadedCallbackHandler - Definitions ////////////////////////////////////////////////////////////////////////// template <typename CacheType> CachedResource<CacheType>::OnLoadedCallbackHandler::OnLoadedCallbackHandler( const scoped_refptr<CachedResource>& cached_resource, const base::Closure& success_callback, const base::Closure& error_callback) : cached_resource_(cached_resource), success_callback_(success_callback), error_callback_(error_callback) { DCHECK(cached_resource_); if (!success_callback_.is_null()) { success_callback_list_iterator_ = cached_resource_->AddCallback( kOnLoadingSuccessCallbackType, success_callback_); if (cached_resource_->TryGetResource()) { success_callback_.Run(); } } if (!error_callback_.is_null()) { error_callback_list_iterator_ = cached_resource_->AddCallback( kOnLoadingErrorCallbackType, error_callback_); } } template <typename CacheType> CachedResource<CacheType>::OnLoadedCallbackHandler::~OnLoadedCallbackHandler() { if (!success_callback_.is_null()) { cached_resource_->RemoveCallback(kOnLoadingSuccessCallbackType, success_callback_list_iterator_); } if (!error_callback_.is_null()) { cached_resource_->RemoveCallback(kOnLoadingErrorCallbackType, error_callback_list_iterator_); } } ////////////////////////////////////////////////////////////////////////// // CachedResource - Definitions ////////////////////////////////////////////////////////////////////////// template <typename CacheType> CachedResource<CacheType>::CachedResource(const GURL& url, const Origin& origin, ResourceCacheType* resource_cache) : url_(url), origin_(origin), resource_cache_(resource_cache), are_completion_callbacks_enabled_(false), retry_count_(0) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); StartLoading(); } template <typename CacheType> CachedResource<CacheType>::CachedResource(const GURL& url, ResourceType* resource, ResourceCacheType* resource_cache) : url_(url), resource_(resource), resource_cache_(resource_cache), are_completion_callbacks_enabled_(false), retry_count_(0) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); } template <typename CacheType> CachedResource<CacheType>::~CachedResource() { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); if (retry_timer_) { retry_timer_->Stop(); } resource_cache_->NotifyResourceDestroyed(this); for (int i = 0; i < kCallbackTypeCount; ++i) { DCHECK(callback_lists[i].empty()); } } template <typename CacheType> scoped_refptr<typename CacheType::ResourceType> CachedResource<CacheType>::TryGetResource() { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); return resource_; } template <typename CacheType> void CachedResource<CacheType>::StartLoading() { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); DCHECK(!loader_); DCHECK(!retry_timer_ || !retry_timer_->IsRunning()); loader_ = resource_cache_->StartLoadingResource(this); } template <typename CacheType> bool CachedResource<CacheType>::IsLoadingComplete() { return !loader_ && !retry_timer_; } template <typename CacheType> void CachedResource<CacheType>::ScheduleLoadingRetry() { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); DCHECK(!loader_); DCHECK(!retry_timer_ || !retry_timer_->IsRunning()); LOG(WARNING) << "Scheduling loading retry for '" << url_ << "'"; resource_cache_->NotifyResourceLoadingRetryScheduled(this); // The delay starts at 1 second and doubles every subsequent retry until the // maxiumum delay of 1024 seconds (~17 minutes) is reached. After this, all // additional attempts also wait 1024 seconds. const int64 kBaseRetryDelayInMilliseconds = 1000; const int kMaxRetryCountShift = 10; int64 delay = kBaseRetryDelayInMilliseconds << std::min(kMaxRetryCountShift, retry_count_++); // The retry timer is lazily created the first time that it is needed. if (!retry_timer_) { retry_timer_.reset(new base::Timer(false, false)); } retry_timer_->Start( FROM_HERE, base::TimeDelta::FromMilliseconds(delay), base::Bind(&CachedResource::StartLoading, base::Unretained(this))); } template <typename CacheType> void CachedResource<CacheType>::OnLoadingSuccess( const scoped_refptr<ResourceType>& resource) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); resource_ = resource; loader_.reset(); retry_timer_.reset(); completion_callback_ = base::Bind(&ResourceCacheType::NotifyResourceLoadingComplete, base::Unretained(resource_cache_), base::Unretained(this), kOnLoadingSuccessCallbackType); if (are_completion_callbacks_enabled_) { completion_callback_.Run(); } } template <typename CacheType> void CachedResource<CacheType>::OnLoadingError(const std::string& error) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); LOG(WARNING) << " Error while loading '" << url_ << "': " << error; bool should_retry = resource_cache_->are_loading_retries_enabled() && loader_->DidFailFromTransientError(); loader_.reset(); if (should_retry) { ScheduleLoadingRetry(); } else { retry_timer_.reset(); completion_callback_ = base::Bind(&ResourceCacheType::NotifyResourceLoadingComplete, base::Unretained(resource_cache_), base::Unretained(this), kOnLoadingErrorCallbackType); if (are_completion_callbacks_enabled_) { completion_callback_.Run(); } } } template <typename CacheType> typename CachedResource<CacheType>::CallbackListIterator CachedResource<CacheType>::AddCallback(CallbackType callback_type, const base::Closure& callback) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); CallbackList& callback_list = callback_lists[callback_type]; callback_list.push_front(callback); return callback_list.begin(); } template <typename CacheType> void CachedResource<CacheType>::RemoveCallback(CallbackType type, CallbackListIterator iterator) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); CallbackList& callback_list = callback_lists[type]; callback_list.erase(iterator); } template <typename CacheType> void CachedResource<CacheType>::RunCallbacks(CallbackType type) { DCHECK(cached_resource_thread_checker_.CalledOnValidThread()); // To avoid the list getting altered in the callbacks. CallbackList callback_list = callback_lists[type]; CallbackListIterator callback_iter; for (callback_iter = callback_list.begin(); callback_iter != callback_list.end(); ++callback_iter) { callback_iter->Run(); } } template <typename CacheType> void CachedResource<CacheType>::EnableCompletionCallbacks() { are_completion_callbacks_enabled_ = true; if (!completion_callback_.is_null()) { completion_callback_.Run(); } } ////////////////////////////////////////////////////////////////////////// // CachedResourceReferenceWithCallbacks ////////////////////////////////////////////////////////////////////////// template <typename CacheType> class CachedResourceReferenceWithCallbacks { public: typedef CachedResource<CacheType> CachedResourceType; typedef typename CachedResourceType::OnLoadedCallbackHandler CachedResourceTypeOnLoadedCallbackHandler; typedef ScopedVector<CachedResourceReferenceWithCallbacks> CachedResourceReferenceVector; CachedResourceReferenceWithCallbacks( const scoped_refptr<CachedResourceType>& cached_resource, const base::Closure& success_callback, const base::Closure& error_callback) : cached_resource_(cached_resource), cached_resource_loaded_callback_handler_( new CachedResourceTypeOnLoadedCallbackHandler( cached_resource, success_callback, error_callback)) {} scoped_refptr<CachedResourceType> cached_resource() { return cached_resource_; } private: // A single cached resource. scoped_refptr<CachedResourceType> cached_resource_; // This handles adding and removing the resource loaded callbacks. scoped_ptr<CachedResourceTypeOnLoadedCallbackHandler> cached_resource_loaded_callback_handler_; }; ////////////////////////////////////////////////////////////////////////// // ResourceCache - Declarations ////////////////////////////////////////////////////////////////////////// // CachedResource is created by calling |CreateCachedResource| of ResourceCache. // ResourceCache can have observers and when a resource is loaded, // ResourceCache would notify its observers. For example, a DOM Document might // be an observer of ResourceCache. template <typename CacheType> class ResourceCache { public: typedef CachedResource<CacheType> CachedResourceType; typedef typename CacheType::ResourceType ResourceType; typedef typename CachedResourceType::CreateLoaderFunction CreateLoaderFunction; struct ResourceCallbackInfo { ResourceCallbackInfo(CachedResourceType* cached_resource, CallbackType callback_type) : cached_resource(cached_resource), callback_type(callback_type) {} CachedResourceType* cached_resource; CallbackType callback_type; }; ResourceCache(const std::string& name, uint32 cache_capacity, bool are_load_retries_enabled, const CreateLoaderFunction& create_loader_function); // |CreateCachedResource| returns CachedResource. If the CachedResource is not // in |cached_resource_map_| or its resource is not in // |unreference_cached_resource_map_|, creates a CachedResource with a loader // for it. If the CachedResource is in the cache map, return the // CachedResource or wrap the resource if necessary. scoped_refptr<CachedResourceType> CreateCachedResource(const GURL& url, const Origin& origin); // Set a callback that the loader will query to determine if the URL is safe // according to our document's security policy. void set_security_callback(const csp::SecurityCallback& security_callback) { security_callback_ = security_callback; } const csp::SecurityCallback& security_callback() const { return security_callback_; } uint32 capacity() const { return cache_capacity_; } void SetCapacity(uint32 capacity); void Purge(); // Processes all pending callbacks regardless of the state of // |callback_blocking_loading_resource_set_|. void ProcessPendingCallbacks(); void DisableCallbacks(); private: friend class CachedResource<CacheType>; typedef base::hash_map<std::string, CachedResourceType*> CachedResourceMap; typedef typename CachedResourceMap::iterator CachedResourceMapIterator; typedef base::hash_set<std::string> ResourceSet; typedef base::linked_hash_map<std::string, ResourceCallbackInfo> ResourceCallbackMap; typedef base::linked_hash_map<std::string, scoped_refptr<ResourceType> > ResourceMap; typedef typename ResourceMap::iterator ResourceMapIterator; scoped_ptr<Loader> StartLoadingResource(CachedResourceType* cached_resource); // Called by CachedResource objects after they finish loading. void NotifyResourceLoadingComplete(CachedResourceType* cached_resource, CallbackType callback_type); // Called by CachedResource objects when they fail to load as a result of a // transient error and are scheduling a retry. void NotifyResourceLoadingRetryScheduled(CachedResourceType* cached_resource); // Called by the destructor of CachedResource to remove CachedResource from // |cached_resource_map_| and either immediately free the resource from memory // or add it to |unreference_cached_resource_map_|, depending on whether the // cache is over its memory limit. void NotifyResourceDestroyed(CachedResourceType* cached_resource); // Reclaims memory from unreferenced cache objects until total cache memory // is reduced to |bytes_to_reclaim_down_to|. In the case where the desired // memory cannot be freed, pending callbacks are processed (potentially // enabling additional resources to be reclaimed), and memory reclamation is // attempted again. void ReclaimMemoryAndMaybeProcessPendingCallbacks( uint32 bytes_to_reclaim_down_to); // Releases unreferenced cache objects until our total cache memory usage is // less than or equal to |bytes_to_reclaim_down_to|, or until there are no // more unreferenced cache objects to release. void ReclaimMemory(uint32 bytes_to_reclaim_down_to, bool log_warning_if_over); // Calls ProcessPendingCallbacks() if // |callback_blocking_loading_resource_set_| is empty. void ProcessPendingCallbacksIfUnblocked(); bool are_loading_retries_enabled() const { return are_loading_retries_enabled_; } // The name of this resource cache object, useful while debugging. const std::string name_; uint32 cache_capacity_; bool are_loading_retries_enabled_; CreateLoaderFunction create_loader_function_; csp::SecurityCallback security_callback_; // The resource cache attempts to batch callbacks as much as possible to try // to ensure that events triggered by the callbacks occur together. It // accomplishes this by waiting for all active loads to complete before // processing any of their callbacks. However, to ensure that callbacks are // processed in a timely manner as well, active loads are placed into two // buckets: callback blocking and non-callback blocking. While no callbacks // are pending, all active loads are added as callback blocking. As soon as // a callback is pending, any additional load requests are added as // non-callback blocking. As soon as all of the callback blocking loads are // finished, the pending callbacks are processed, the non-callback blocking // loads become callback blocking loads, and the process repeats itself. // Currently loading resources that block any pending callbacks from running. ResourceSet callback_blocking_loading_resource_set_; // Currently loading resources that do not block the pending callbacks from // running. After pending callbacks run, these become blocking. ResourceSet non_callback_blocking_loading_resource_set_; // Resources that have completed loading and have callbacks pending. ResourceCallbackMap pending_callback_map_; // Timer used to ensure that pending callbacks are handled in a timely manner // when callbacks are being blocked by additional loading resources. base::OneShotTimer<ResourceCache<CacheType>> process_pending_callback_timer_; // Whether or not ProcessPendingCallbacks() is running. bool is_processing_pending_callbacks_; // Whether or not callbacks are currently disabled. bool are_callbacks_disabled_; // |cached_resource_map_| stores the cached resources that are currently // referenced. CachedResourceMap cached_resource_map_; // |unreference_cached_resource_map_| stores the cached resources that are // not referenced, but are being kept in memory as a result of the cache being // under its memory limit. ResourceMap unreference_cached_resource_map_; base::ThreadChecker resource_cache_thread_checker_; base::CVal<base::cval::SizeInBytes, base::CValPublic> memory_size_in_bytes_; base::CVal<base::cval::SizeInBytes, base::CValPublic> memory_capacity_in_bytes_; base::CVal<base::cval::SizeInBytes, base::CValPublic> memory_resources_loaded_in_bytes_; base::CVal<int, base::CValPublic> count_resources_requested_; base::CVal<int, base::CValPublic> count_resources_loading_; base::CVal<int, base::CValPublic> count_resources_loaded_; base::CVal<int, base::CValPublic> count_pending_callbacks_; DISALLOW_COPY_AND_ASSIGN(ResourceCache); }; ////////////////////////////////////////////////////////////////////////// // ResourceCache - Definitions ////////////////////////////////////////////////////////////////////////// template <typename CacheType> ResourceCache<CacheType>::ResourceCache( const std::string& name, uint32 cache_capacity, bool are_loading_retries_enabled, const CreateLoaderFunction& create_loader_function) : name_(name), cache_capacity_(cache_capacity), are_loading_retries_enabled_(are_loading_retries_enabled), create_loader_function_(create_loader_function), is_processing_pending_callbacks_(false), are_callbacks_disabled_(false), memory_size_in_bytes_( base::StringPrintf("Memory.%s.Size", name_.c_str()), 0, "Total number of bytes currently used by the cache."), memory_capacity_in_bytes_( base::StringPrintf("Memory.%s.Capacity", name_.c_str()), cache_capacity_, "The capacity, in bytes, of the resource cache. " "Exceeding this results in *unused* resources being " "purged."), memory_resources_loaded_in_bytes_( base::StringPrintf("Memory.%s.Resource.Loaded", name_.c_str()), 0, "Combined size in bytes of all resources that have been loaded by " "the cache."), count_resources_requested_( base::StringPrintf("Count.%s.Resource.Requested", name_.c_str()), 0, "The total number of resources that have been requested."), count_resources_loading_( base::StringPrintf("Count.%s.Resource.Loading", name_.c_str()), 0, "The number of resources that are currently loading."), count_resources_loaded_( base::StringPrintf("Count.%s.Resource.Loaded", name_.c_str()), 0, "The total number of resources that have been successfully loaded."), count_pending_callbacks_( base::StringPrintf("Count.%s.PendingCallbacks", name_.c_str()), 0, "The number of loading completed resources that have pending " "callbacks.") { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); DCHECK(!create_loader_function_.is_null()); } template <typename CacheType> scoped_refptr<CachedResource<CacheType> > ResourceCache<CacheType>::CreateCachedResource(const GURL& url, const Origin& origin) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); DCHECK(url.is_valid()); // Try to find the resource from |cached_resource_map_|. CachedResourceMapIterator cached_resource_iterator = cached_resource_map_.find(url.spec()); if (cached_resource_iterator != cached_resource_map_.end()) { return cached_resource_iterator->second; } // Try to find the resource from |unreference_cached_resource_map_|. ResourceMapIterator resource_iterator = unreference_cached_resource_map_.find(url.spec()); if (resource_iterator != unreference_cached_resource_map_.end()) { scoped_refptr<CachedResourceType> cached_resource( new CachedResourceType(url, resource_iterator->second, this)); cached_resource_map_.insert( std::make_pair(url.spec(), cached_resource.get())); unreference_cached_resource_map_.erase(url.spec()); return cached_resource; } // If we reach this point, then the resource doesn't exist yet. ++count_resources_requested_; // Create the cached resource and fetch its resource based on the url. scoped_refptr<CachedResourceType> cached_resource( new CachedResourceType(url, origin, this)); cached_resource_map_.insert( std::make_pair(url.spec(), cached_resource.get())); // Only now that we are finished initializing |cached_resource|, allow // completion callbacks to proceed. This can be an issue for resources that // load and decode synchronously and immediately. cached_resource->EnableCompletionCallbacks(); return cached_resource; } template <typename CacheType> void ResourceCache<CacheType>::SetCapacity(uint32 capacity) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); cache_capacity_ = capacity; memory_capacity_in_bytes_ = capacity; ReclaimMemoryAndMaybeProcessPendingCallbacks(cache_capacity_); } template <typename CacheType> void ResourceCache<CacheType>::Purge() { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); ProcessPendingCallbacks(); ReclaimMemory(0, true); } template <typename CacheType> void ResourceCache<CacheType>::ProcessPendingCallbacks() { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); process_pending_callback_timer_.Stop(); // If callbacks are disabled, simply return. if (are_callbacks_disabled_) { return; } is_processing_pending_callbacks_ = true; while (!pending_callback_map_.empty()) { ResourceCallbackInfo& callback_info = pending_callback_map_.front().second; // To avoid the last reference of this object getting deleted in the // callbacks. scoped_refptr<CachedResourceType> holder(callback_info.cached_resource); callback_info.cached_resource->RunCallbacks(callback_info.callback_type); pending_callback_map_.erase(pending_callback_map_.begin()); } is_processing_pending_callbacks_ = false; count_pending_callbacks_ = 0; } template <typename CacheType> void ResourceCache<CacheType>::DisableCallbacks() { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); are_callbacks_disabled_ = true; } template <typename CacheType> scoped_ptr<Loader> ResourceCache<CacheType>::StartLoadingResource( CachedResourceType* cached_resource) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); const std::string& url = cached_resource->url().spec(); // The resource should not already be in either of the loading sets. DCHECK(callback_blocking_loading_resource_set_.find(url) == callback_blocking_loading_resource_set_.end()); DCHECK(non_callback_blocking_loading_resource_set_.find(url) == non_callback_blocking_loading_resource_set_.end()); // Add the resource to a loading set. If no current resources have pending // callbacks, then this resource will block callbacks until it is decoded. // However, if there are resources with pending callbacks, then the decoding // of this resource won't block the callbacks from occurring. This ensures // that a steady stream of new resources won't prevent callbacks from ever // occurring. if (pending_callback_map_.empty()) { callback_blocking_loading_resource_set_.insert(url); } else { non_callback_blocking_loading_resource_set_.insert(url); } ++count_resources_loading_; return create_loader_function_.Run( cached_resource->url(), cached_resource->origin(), security_callback_, base::Bind(&CachedResourceType::OnLoadingSuccess, base::Unretained(cached_resource)), base::Bind(&CachedResourceType::OnLoadingError, base::Unretained(cached_resource))); } template <typename CacheType> void ResourceCache<CacheType>::NotifyResourceLoadingComplete( CachedResourceType* cached_resource, CallbackType callback_type) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); const std::string& url = cached_resource->url().spec(); if (cached_resource->TryGetResource()) { uint32 estimated_size_in_bytes = CacheType::GetEstimatedSizeInBytes(cached_resource->TryGetResource()); memory_size_in_bytes_ += estimated_size_in_bytes; memory_resources_loaded_in_bytes_ += estimated_size_in_bytes; ++count_resources_loaded_; } // Remove the resource from its loading set. It should exist in exactly one // of the loading sets. if (callback_blocking_loading_resource_set_.erase(url)) { DCHECK(non_callback_blocking_loading_resource_set_.find(url) == non_callback_blocking_loading_resource_set_.end()); } else if (!non_callback_blocking_loading_resource_set_.erase(url)) { DCHECK(false); } // Add a callback for the resource that just finished loading to the pending // callbacks. pending_callback_map_.insert(std::make_pair( url, ResourceCallbackInfo(cached_resource, callback_type))); // Update the loading resources and pending callbacks count. The callbacks are // incremented first to ensure that the total of the two counts always remains // above 0. ++count_pending_callbacks_; --count_resources_loading_; ProcessPendingCallbacksIfUnblocked(); ReclaimMemoryAndMaybeProcessPendingCallbacks(cache_capacity_); } template <typename CacheType> void ResourceCache<CacheType>::NotifyResourceLoadingRetryScheduled( CachedResourceType* cached_resource) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); const std::string& url = cached_resource->url().spec(); // Remove the resource from those currently loading. It'll be re-added once // the retry starts. // Remove the resource from its loading set. It should exist in exactly one // of the loading sets. if (callback_blocking_loading_resource_set_.erase(url)) { DCHECK(non_callback_blocking_loading_resource_set_.find(url) == non_callback_blocking_loading_resource_set_.end()); } else if (!non_callback_blocking_loading_resource_set_.erase(url)) { DCHECK(false); } --count_resources_loading_; ProcessPendingCallbacksIfUnblocked(); } template <typename CacheType> void ResourceCache<CacheType>::NotifyResourceDestroyed( CachedResourceType* cached_resource) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); const std::string& url = cached_resource->url().spec(); cached_resource_map_.erase(url); DCHECK(unreference_cached_resource_map_.find(url) == unreference_cached_resource_map_.end()); // Check to see if this was a loaded resource. if (cached_resource->TryGetResource()) { // Add it into the unreferenced cached resource map, so that it will be // retained while memory is available for it in the cache. unreference_cached_resource_map_.insert( std::make_pair(url, cached_resource->TryGetResource())); } // Remove the resource from any loading or pending container that it is in. // It should never exist in more than one of the containers. if (callback_blocking_loading_resource_set_.erase(url)) { DCHECK(non_callback_blocking_loading_resource_set_.find(url) == non_callback_blocking_loading_resource_set_.end()); DCHECK(pending_callback_map_.find(url) == pending_callback_map_.end()); --count_resources_loading_; } else if (non_callback_blocking_loading_resource_set_.erase(url)) { DCHECK(pending_callback_map_.find(url) == pending_callback_map_.end()); --count_resources_loading_; } else if (pending_callback_map_.erase(url)) { --count_pending_callbacks_; } // Only process pending callbacks and attempt to reclaim memory if // NotifyResourceDestroyed() wasn't called from within // ProcessPendingCallbacks(). This prevents recursion and redundant // processing. if (!is_processing_pending_callbacks_) { ProcessPendingCallbacksIfUnblocked(); ReclaimMemory(cache_capacity_, true /*log_warning_if_over*/); } } template <typename CacheType> void ResourceCache<CacheType>::ReclaimMemoryAndMaybeProcessPendingCallbacks( uint32 bytes_to_reclaim_down_to) { ReclaimMemory(bytes_to_reclaim_down_to, false /*log_warning_if_over*/); // If the current size of the cache is still greater than // |bytes_to_reclaim_down_to| after reclaiming memory, then process any // pending callbacks and try again. References to the cached resources are // potentially being held until the callbacks run, so processing them may // enable more memory to be reclaimed. if (memory_size_in_bytes_ > bytes_to_reclaim_down_to) { ProcessPendingCallbacks(); ReclaimMemory(bytes_to_reclaim_down_to, true /*log_warning_if_over*/); } } template <typename CacheType> void ResourceCache<CacheType>::ReclaimMemory(uint32 bytes_to_reclaim_down_to, bool log_warning_if_over) { DCHECK(resource_cache_thread_checker_.CalledOnValidThread()); while (memory_size_in_bytes_ > bytes_to_reclaim_down_to && !unreference_cached_resource_map_.empty()) { // The first element is the earliest-inserted element. scoped_refptr<ResourceType> resource = unreference_cached_resource_map_.begin()->second; uint32 first_resource_size = resource->GetEstimatedSizeInBytes(); // Erase the earliest-inserted element. // TODO: Erasing the earliest-inserted element could be a function // in linked_hash_map. Add that function and related unit test. unreference_cached_resource_map_.erase( unreference_cached_resource_map_.begin()); memory_size_in_bytes_ -= first_resource_size; } if (log_warning_if_over) { // Log a warning if we're still over |bytes_to_reclaim_down_to| after // attempting to reclaim memory. This can occur validly when the size of // the referenced images exceeds the target size. DLOG_IF(WARNING, memory_size_in_bytes_ > bytes_to_reclaim_down_to) << "cached size: " << memory_size_in_bytes_ << ", target size: " << bytes_to_reclaim_down_to; } } template <typename CacheType> void ResourceCache<CacheType>::ProcessPendingCallbacksIfUnblocked() { // If there are no callback blocking resources, then simply process any // pending callbacks now; otherwise, start |process_pending_callback_timer_|, // which ensures that the callbacks are handled in a timely manner while still // allowing them to be batched. if (callback_blocking_loading_resource_set_.empty()) { ProcessPendingCallbacks(); // Now that we've processed the callbacks, if there are any non-blocking // loading resources, then they're becoming blocking. Simply swap the two // sets, rather than copying the contents over. if (!non_callback_blocking_loading_resource_set_.empty()) { callback_blocking_loading_resource_set_.swap( non_callback_blocking_loading_resource_set_); } } else if (!pending_callback_map_.empty() && !process_pending_callback_timer_.IsRunning()) { // The maximum delay for a pending callback is set to 500ms. After that, the // callback will be processed regardless of how many callback blocking // loading resources remain. This specific value maximizes callback batching // on fast networks while also keeping the callback delay on slow networks // to a minimum and is based on significant testing. const int64 kMaxPendingCallbackDelayInMilliseconds = 500; process_pending_callback_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds( kMaxPendingCallbackDelayInMilliseconds), this, &ResourceCache::ProcessPendingCallbacks); } } } // namespace loader } // namespace cobalt #endif // COBALT_LOADER_RESOURCE_CACHE_H_
8ede94f21f073e5bcd87dc9998bccd2e504306ab
198d4618cd8ccf9ca75f60d167f26c7eec2a0ec0
/chp-2/merge_sort.cpp
1f5114aad4cef13a63e0abecedb8cf5902048e59
[]
no_license
ajinkyashukla/programs-cormen
c87884e44e45fd6962ac4b0ad196d78f965f1691
e7f215fe66cbc5f1eb0217cc3fbbe471f254da77
refs/heads/master
2021-01-21T12:02:57.625485
2014-02-15T18:33:36
2014-02-15T18:33:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
merge_sort.cpp
/** * Simple Merge sort program * @version 1.0 * @author ajinkya shukla <ajinkyashukla02@gmail.com> */ #include<iostream> using namespace std; void split(int*,int*,int,int); void merge(int*,int*,int,int,int); int main() { int n; cout << "Enter the number of integers to be sorted: "; cin >> n; int a[n]; int b[n]; cout << "Enter the integers: "; for(int i=0;i<n;i++) cin >> a[i]; split(a,b,0,n-1); cout << "Sorted Integers: "; for(int i=0;i<n;i++) cout << a[i]; return 0; } void split(int* a,int* b,int p,int r) { int q=(p+r)/2; if(p<r) { split(a,b,p,q); split(a,b,q+1,r); merge(a,b,p,q,r); } } void merge(int* a,int* b,int p,int q,int r) { int i=0,j=p,l=p,k=q+1; while(j<=q && k<=r) if(a[j]<a[k]) b[p++]=a[j++]; else b[p++]=a[k++]; if(k>r) for(i=j;i<=q;i++) b[p++]=a[j++]; if(j>q) for(i=k;i<=r;i++) b[p++]=a[k++]; for(i=l;i<=r;i++) a[i]=b[i]; }
cdd1485856b745af3bc4ad14586a346a76113064
8549362e40f65ce6f5f4e1b5c946cd9e61fa20b0
/Gierek/Market.h
2dcb60b7ae710b44cfe790fe005d0475980fd799
[]
no_license
zasoniak/Gierek_XAML
a80209ced98569d96c330d278304777ca01f51c7
2fa5926c73e03deda030e8b5d82e5f69e624417f
refs/heads/master
2020-12-24T16:42:31.322894
2014-05-07T15:50:18
2014-05-07T15:50:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
217
h
Market.h
#pragma once #include "Order.h" class Market { public: std::vector<Order> orderList; std::vector<Order> offerList; public: Market(); void AddOrder(Order *newOrder); Order AccomplishTransaction(Order *offer); };
d64704bd5a3b3c4299bdbafa1fdb86f370d3da89
382155912f0501a163fd6b65e9dc3e4c6aeb3a19
/Homework/Homework1/starter_file/hashtable.h
d6e3ee32ffd6fbcbf5eab2a49ab01b5bc3a916db
[]
no_license
Roihn/VE281
86757f2d50948cdecca1e3c78318d80f47447c1f
2bd108de91d5a1a6c1bce1a04862d31ee7204b5a
refs/heads/master
2023-07-12T22:14:17.515408
2021-08-16T08:37:14
2021-08-16T08:37:14
364,315,773
3
1
null
null
null
null
UTF-8
C++
false
false
2,316
h
hashtable.h
#ifndef HASHTABLE_H #define HASHTABLE_H // INSTRUCTIONS: // fill out the methods in the class below. // You may assume that the key and value types can be copied and have default // constructors. // You can also assume that the key type has (==) and (!=) methods. // You may assume that Hasher is a functor type with a // size_t operator()(const Keyey&) overload. // The key/value types aren't guaranteed to support any other operations. // Do not add, remove, or change any of the class's member variables. // The num_deleted counter is *optional*. You might find it helpful, but it // is not required to pass the lab assignment. // Do not change the Bucket type. #include <cstdint> #include <functional> // where std::hash lives #include <vector> #include <cassert> // useful for debugging! // A bucket's type tells you whether it's empty, occupied, // or contains a deleted element. enum class BucketType { Empty, Occupied, Deleted }; template<typename Key, typename Value, typename Hasher = std::hash<Key>> class HashTable { public: // A bucket has a type, a key, and a value. struct Bucket { // Do not modify Bucket. BucketType type = BucketType::Empty; Key key; Value val; }; HashTable() { // TODO: a default constructor (possibly empty). // Suppose the initial size of buckets are 23. } size_t size() const { return num_elements; } // returns a reference to the value in the bucket with the key, if it // already exists. Otherwise, insert it with a default value, and return // a reference to the resulting bucket. Value &operator[](const Key &key) { // TODO } // insert returns whether inserted successfully // (if the key already exists in the table, do nothing and return false). bool insert(const Key &key, const Value &val) { // TODO } // erase returns the number of items remove (0 or 1) size_t erase(const Key &key) { // TODO } private: size_t num_elements = 0; size_t num_deleted = 0; // OPTIONAL: you don't need to use this to pass std::vector<Bucket> buckets; void rehash_and_grow() { // TODO (optional) } // You can add methods here if you like. }; #endif // HASHTABLE_H
daa6c7e62149f5a44102f83b59c64633744d075e
a3ecac890fc4734b00f00a7c6a432e894f61d750
/Coursework/src/Enemy.h
b9c5da14afad815c0231a66a5e60dd6dba5b8c50
[]
no_license
Cladorhiza/2021GraphicsCoursework
98d8b9a9a8b2a25dd3bc17ac604f972ce880b90b
0d832304ac84779a0a593411a6c0b2dd7d8314ac
refs/heads/main
2023-04-14T18:29:47.593419
2021-05-04T11:52:26
2021-05-04T11:52:26
347,311,128
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
Enemy.h
#pragma once #include "Moveable.h" #include "Character.h" class Enemy : public Moveable { protected: float speed; bool alive; public: Enemy(float width, float height, float positionX, float positionY, float positionZ, float size, float speed); ~Enemy(); inline bool IsAlive() { return alive; } };
66af3a2933674761dac6366b602579fb875b8fde
b00c54389a95d81a22e361fa9f8bdf5a2edc93e3
/art/compiler/elf_writer_quick.cc
5151aaebc81aa9fe0bf01eb2e2074f89319a0d1e
[ "NCSA", "Apache-2.0" ]
permissive
mirek190/x86-android-5.0
9d1756fa7ff2f423887aa22694bd737eb634ef23
eb1029956682072bb7404192a80214189f0dc73b
refs/heads/master
2020-05-27T01:09:51.830208
2015-10-07T22:47:36
2015-10-07T22:47:36
41,942,802
15
20
null
2020-03-09T00:21:03
2015-09-05T00:11:19
null
UTF-8
C++
false
false
57,202
cc
elf_writer_quick.cc
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "elf_writer_quick.h" #include <unordered_map> #include "base/logging.h" #include "base/stl_util.h" #include "base/unix_file/fd_file.h" #include "buffered_output_stream.h" #include "driver/compiler_driver.h" #include "dwarf.h" #include "elf_file.h" #include "elf_utils.h" #include "file_output_stream.h" #include "globals.h" #include "leb128.h" #include "oat.h" #include "oat_writer.h" #include "utils.h" namespace art { static constexpr Elf32_Word NextOffset(const Elf32_Shdr& cur, const Elf32_Shdr& prev) { return RoundUp(prev.sh_size + prev.sh_offset, cur.sh_addralign); } static uint8_t MakeStInfo(uint8_t binding, uint8_t type) { return ((binding) << 4) + ((type) & 0xf); } class ElfFilePiece { public: virtual ~ElfFilePiece() {} virtual bool Write(File* elf_file) { if (static_cast<off_t>(offset_) != lseek(elf_file->Fd(), offset_, SEEK_SET)) { PLOG(ERROR) << "Failed to seek to " << GetDescription() << " offset " << offset_ << " for " << elf_file->GetPath(); return false; } return DoActualWrite(elf_file); } static bool Compare(ElfFilePiece* a, ElfFilePiece* b) { return a->offset_ < b->offset_; } protected: explicit ElfFilePiece(Elf32_Word offset) : offset_(offset) {} virtual std::string GetDescription() = 0; virtual bool DoActualWrite(File* elf_file) = 0; Elf32_Word offset_; }; class ElfFileMemoryPiece : public ElfFilePiece { public: ElfFileMemoryPiece(const std::string& name, Elf32_Word offset, const void* data, Elf32_Word size) : ElfFilePiece(offset), dbg_name_(name), data_(data), size_(size) {} bool DoActualWrite(File* elf_file) OVERRIDE { DCHECK(data_ != nullptr || size_ == 0U) << dbg_name_ << " " << size_; if (!elf_file->WriteFully(data_, size_)) { PLOG(ERROR) << "Failed to write " << dbg_name_ << " for " << elf_file->GetPath(); return false; } return true; } std::string GetDescription() OVERRIDE { return dbg_name_; } private: const std::string& dbg_name_; const void *data_; Elf32_Word size_; }; class ElfFileRodataPiece : public ElfFilePiece { public: ElfFileRodataPiece(Elf32_Word offset, OatWriter* oat_writer) : ElfFilePiece(offset), oat_writer_(oat_writer) {} bool DoActualWrite(File* elf_file) OVERRIDE { std::unique_ptr<BufferedOutputStream> output_stream( new BufferedOutputStream(new FileOutputStream(elf_file))); if (!oat_writer_->Write(output_stream.get())) { PLOG(ERROR) << "Failed to write .rodata and .text for " << elf_file->GetPath(); return false; } return true; } std::string GetDescription() OVERRIDE { return ".rodata"; } private: OatWriter* oat_writer_; }; class ElfFileOatTextPiece : public ElfFilePiece { public: ElfFileOatTextPiece(Elf32_Word offset, OatWriter* oat_writer) : ElfFilePiece(offset), oat_writer_(oat_writer) {} bool DoActualWrite(File* elf_file) OVERRIDE { // All data is written by the ElfFileRodataPiece right now, as the oat writer writes in one // piece. This is for future flexibility. UNUSED(oat_writer_); return true; } std::string GetDescription() OVERRIDE { return ".text"; } private: OatWriter* oat_writer_; }; static bool WriteOutFile(const std::vector<ElfFilePiece*>& pieces, File* elf_file) { // TODO It would be nice if this checked for overlap. for (auto it = pieces.begin(); it != pieces.end(); ++it) { if (!(*it)->Write(elf_file)) { return false; } } return true; } static void PushByte(std::vector<uint8_t>* buf, int data) { buf->push_back(data & 0xff); } static uint32_t PushStr(std::vector<uint8_t>* buf, const char* str, const char* def = nullptr) { if (str == nullptr) { str = def; } uint32_t offset = buf->size(); for (size_t i = 0; str[i] != '\0'; ++i) { buf->push_back(str[i]); } buf->push_back('\0'); return offset; } static uint32_t PushStr(std::vector<uint8_t>* buf, const std::string &str) { uint32_t offset = buf->size(); buf->insert(buf->end(), str.begin(), str.end()); buf->push_back('\0'); return offset; } static void UpdateWord(std::vector<uint8_t>* buf, int offset, int data) { (*buf)[offset+0] = data; (*buf)[offset+1] = data >> 8; (*buf)[offset+2] = data >> 16; (*buf)[offset+3] = data >> 24; } static void PushHalf(std::vector<uint8_t>* buf, int data) { buf->push_back(data & 0xff); buf->push_back((data >> 8) & 0xff); } bool ElfWriterQuick::ElfBuilder::Init() { // The basic layout of the elf file. Order may be different in final output. // +-------------------------+ // | Elf32_Ehdr | // +-------------------------+ // | Elf32_Phdr PHDR | // | Elf32_Phdr LOAD R | .dynsym .dynstr .hash .rodata // | Elf32_Phdr LOAD R X | .text // | Elf32_Phdr LOAD RW | .dynamic // | Elf32_Phdr DYNAMIC | .dynamic // +-------------------------+ // | .dynsym | // | Elf32_Sym STN_UNDEF | // | Elf32_Sym oatdata | // | Elf32_Sym oatexec | // | Elf32_Sym oatlastword | // +-------------------------+ // | .dynstr | // | \0 | // | oatdata\0 | // | oatexec\0 | // | oatlastword\0 | // | boot.oat\0 | // +-------------------------+ // | .hash | // | Elf32_Word nbucket = b | // | Elf32_Word nchain = c | // | Elf32_Word bucket[0] | // | ... | // | Elf32_Word bucket[b - 1]| // | Elf32_Word chain[0] | // | ... | // | Elf32_Word chain[c - 1] | // +-------------------------+ // | .rodata | // | oatdata..oatexec-4 | // +-------------------------+ // | .text | // | oatexec..oatlastword | // +-------------------------+ // | .dynamic | // | Elf32_Dyn DT_SONAME | // | Elf32_Dyn DT_HASH | // | Elf32_Dyn DT_SYMTAB | // | Elf32_Dyn DT_SYMENT | // | Elf32_Dyn DT_STRTAB | // | Elf32_Dyn DT_STRSZ | // | Elf32_Dyn DT_NULL | // +-------------------------+ (Optional) // | .strtab | (Optional) // | program symbol names | (Optional) // +-------------------------+ (Optional) // | .symtab | (Optional) // | program symbols | (Optional) // +-------------------------+ // | .shstrtab | // | \0 | // | .dynamic\0 | // | .dynsym\0 | // | .dynstr\0 | // | .hash\0 | // | .rodata\0 | // | .text\0 | // | .shstrtab\0 | // | .symtab\0 | (Optional) // | .strtab\0 | (Optional) // | .debug_str\0 | (Optional) // | .debug_info\0 | (Optional) // | .eh_frame\0 | (Optional) // | .debug_line\0 | (Optional) // | .debug_abbrev\0 | (Optional) // +-------------------------+ (Optional) // | .debug_info | (Optional) // +-------------------------+ (Optional) // | .debug_abbrev | (Optional) // +-------------------------+ (Optional) // | .eh_frame | (Optional) // +-------------------------+ (Optional) // | .debug_line | (Optional) // +-------------------------+ (Optional) // | .debug_str | (Optional) // +-------------------------+ (Optional) // | Elf32_Shdr NULL | // | Elf32_Shdr .dynsym | // | Elf32_Shdr .dynstr | // | Elf32_Shdr .hash | // | Elf32_Shdr .text | // | Elf32_Shdr .rodata | // | Elf32_Shdr .dynamic | // | Elf32_Shdr .shstrtab | // | Elf32_Shdr .debug_info | (Optional) // | Elf32_Shdr .debug_abbrev| (Optional) // | Elf32_Shdr .eh_frame | (Optional) // | Elf32_Shdr .debug_line | (Optional) // | Elf32_Shdr .debug_str | (Optional) // +-------------------------+ if (fatal_error_) { return false; } // Step 1. Figure out all the offsets. if (debug_logging_) { LOG(INFO) << "phdr_offset=" << PHDR_OFFSET << std::hex << " " << PHDR_OFFSET; LOG(INFO) << "phdr_size=" << PHDR_SIZE << std::hex << " " << PHDR_SIZE; } memset(&program_headers_, 0, sizeof(program_headers_)); program_headers_[PH_PHDR].p_type = PT_PHDR; program_headers_[PH_PHDR].p_offset = PHDR_OFFSET; program_headers_[PH_PHDR].p_vaddr = PHDR_OFFSET; program_headers_[PH_PHDR].p_paddr = PHDR_OFFSET; program_headers_[PH_PHDR].p_filesz = sizeof(program_headers_); program_headers_[PH_PHDR].p_memsz = sizeof(program_headers_); program_headers_[PH_PHDR].p_flags = PF_R; program_headers_[PH_PHDR].p_align = sizeof(Elf32_Word); program_headers_[PH_LOAD_R__].p_type = PT_LOAD; program_headers_[PH_LOAD_R__].p_offset = 0; program_headers_[PH_LOAD_R__].p_vaddr = 0; program_headers_[PH_LOAD_R__].p_paddr = 0; program_headers_[PH_LOAD_R__].p_flags = PF_R; program_headers_[PH_LOAD_R_X].p_type = PT_LOAD; program_headers_[PH_LOAD_R_X].p_flags = PF_R | PF_X; program_headers_[PH_LOAD_RW_].p_type = PT_LOAD; program_headers_[PH_LOAD_RW_].p_flags = PF_R | PF_W; program_headers_[PH_DYNAMIC].p_type = PT_DYNAMIC; program_headers_[PH_DYNAMIC].p_flags = PF_R | PF_W; // Get the dynstr string. dynstr_ = dynsym_builder_.GenerateStrtab(); // Add the SONAME to the dynstr. dynstr_soname_offset_ = dynstr_.size(); std::string file_name(elf_file_->GetPath()); size_t directory_separator_pos = file_name.rfind('/'); if (directory_separator_pos != std::string::npos) { file_name = file_name.substr(directory_separator_pos + 1); } dynstr_ += file_name; dynstr_ += '\0'; if (debug_logging_) { LOG(INFO) << "dynstr size (bytes) =" << dynstr_.size() << std::hex << " " << dynstr_.size(); LOG(INFO) << "dynsym size (elements)=" << dynsym_builder_.GetSize() << std::hex << " " << dynsym_builder_.GetSize(); } // Get the section header string table. shstrtab_ += '\0'; // Setup sym_undef memset(&null_hdr_, 0, sizeof(null_hdr_)); null_hdr_.sh_type = SHT_NULL; null_hdr_.sh_link = SHN_UNDEF; section_ptrs_.push_back(&null_hdr_); section_index_ = 1; // setup .dynsym section_ptrs_.push_back(&dynsym_builder_.section_); AssignSectionStr(&dynsym_builder_, &shstrtab_); dynsym_builder_.section_index_ = section_index_++; // Setup .dynstr section_ptrs_.push_back(&dynsym_builder_.strtab_.section_); AssignSectionStr(&dynsym_builder_.strtab_, &shstrtab_); dynsym_builder_.strtab_.section_index_ = section_index_++; // Setup .hash section_ptrs_.push_back(&hash_builder_.section_); AssignSectionStr(&hash_builder_, &shstrtab_); hash_builder_.section_index_ = section_index_++; // Setup .rodata section_ptrs_.push_back(&rodata_builder_.section_); AssignSectionStr(&rodata_builder_, &shstrtab_); rodata_builder_.section_index_ = section_index_++; // Setup .text section_ptrs_.push_back(&text_builder_.section_); AssignSectionStr(&text_builder_, &shstrtab_); text_builder_.section_index_ = section_index_++; // Setup .dynamic section_ptrs_.push_back(&dynamic_builder_.section_); AssignSectionStr(&dynamic_builder_, &shstrtab_); dynamic_builder_.section_index_ = section_index_++; // Fill in the hash section. hash_ = dynsym_builder_.GenerateHashContents(); if (debug_logging_) { LOG(INFO) << ".hash size (bytes)=" << hash_.size() * sizeof(Elf32_Word) << std::hex << " " << hash_.size() * sizeof(Elf32_Word); } Elf32_Word base_offset = sizeof(Elf32_Ehdr) + sizeof(program_headers_); // Get the layout in the sections. // // Get the layout of the dynsym section. dynsym_builder_.section_.sh_offset = RoundUp(base_offset, dynsym_builder_.section_.sh_addralign); dynsym_builder_.section_.sh_addr = dynsym_builder_.section_.sh_offset; dynsym_builder_.section_.sh_size = dynsym_builder_.GetSize() * sizeof(Elf32_Sym); dynsym_builder_.section_.sh_link = dynsym_builder_.GetLink(); // Get the layout of the dynstr section. dynsym_builder_.strtab_.section_.sh_offset = NextOffset(dynsym_builder_.strtab_.section_, dynsym_builder_.section_); dynsym_builder_.strtab_.section_.sh_addr = dynsym_builder_.strtab_.section_.sh_offset; dynsym_builder_.strtab_.section_.sh_size = dynstr_.size(); dynsym_builder_.strtab_.section_.sh_link = dynsym_builder_.strtab_.GetLink(); // Get the layout of the hash section hash_builder_.section_.sh_offset = NextOffset(hash_builder_.section_, dynsym_builder_.strtab_.section_); hash_builder_.section_.sh_addr = hash_builder_.section_.sh_offset; hash_builder_.section_.sh_size = hash_.size() * sizeof(Elf32_Word); hash_builder_.section_.sh_link = hash_builder_.GetLink(); // Get the layout of the rodata section. rodata_builder_.section_.sh_offset = NextOffset(rodata_builder_.section_, hash_builder_.section_); rodata_builder_.section_.sh_addr = rodata_builder_.section_.sh_offset; rodata_builder_.section_.sh_size = rodata_builder_.size_; rodata_builder_.section_.sh_link = rodata_builder_.GetLink(); // Get the layout of the text section. text_builder_.section_.sh_offset = NextOffset(text_builder_.section_, rodata_builder_.section_); text_builder_.section_.sh_addr = text_builder_.section_.sh_offset; text_builder_.section_.sh_size = text_builder_.size_; text_builder_.section_.sh_link = text_builder_.GetLink(); CHECK_ALIGNED(rodata_builder_.section_.sh_offset + rodata_builder_.section_.sh_size, kPageSize); // Get the layout of the dynamic section. dynamic_builder_.section_.sh_offset = NextOffset(dynamic_builder_.section_, text_builder_.section_); dynamic_builder_.section_.sh_addr = dynamic_builder_.section_.sh_offset; dynamic_builder_.section_.sh_size = dynamic_builder_.GetSize() * sizeof(Elf32_Dyn); dynamic_builder_.section_.sh_link = dynamic_builder_.GetLink(); if (debug_logging_) { LOG(INFO) << "dynsym off=" << dynsym_builder_.section_.sh_offset << " dynsym size=" << dynsym_builder_.section_.sh_size; LOG(INFO) << "dynstr off=" << dynsym_builder_.strtab_.section_.sh_offset << " dynstr size=" << dynsym_builder_.strtab_.section_.sh_size; LOG(INFO) << "hash off=" << hash_builder_.section_.sh_offset << " hash size=" << hash_builder_.section_.sh_size; LOG(INFO) << "rodata off=" << rodata_builder_.section_.sh_offset << " rodata size=" << rodata_builder_.section_.sh_size; LOG(INFO) << "text off=" << text_builder_.section_.sh_offset << " text size=" << text_builder_.section_.sh_size; LOG(INFO) << "dynamic off=" << dynamic_builder_.section_.sh_offset << " dynamic size=" << dynamic_builder_.section_.sh_size; } return true; } bool ElfWriterQuick::ElfBuilder::Write() { std::vector<ElfFilePiece*> pieces; Elf32_Shdr prev = dynamic_builder_.section_; std::string strtab; if (IncludingDebugSymbols()) { // Setup .symtab section_ptrs_.push_back(&symtab_builder_.section_); AssignSectionStr(&symtab_builder_, &shstrtab_); symtab_builder_.section_index_ = section_index_++; // Setup .strtab section_ptrs_.push_back(&symtab_builder_.strtab_.section_); AssignSectionStr(&symtab_builder_.strtab_, &shstrtab_); symtab_builder_.strtab_.section_index_ = section_index_++; strtab = symtab_builder_.GenerateStrtab(); if (debug_logging_) { LOG(INFO) << "strtab size (bytes) =" << strtab.size() << std::hex << " " << strtab.size(); LOG(INFO) << "symtab size (elements) =" << symtab_builder_.GetSize() << std::hex << " " << symtab_builder_.GetSize(); } } // Setup all the other sections. for (ElfRawSectionBuilder *builder = other_builders_.data(), *end = builder + other_builders_.size(); builder != end; ++builder) { section_ptrs_.push_back(&builder->section_); AssignSectionStr(builder, &shstrtab_); builder->section_index_ = section_index_++; } // Setup shstrtab section_ptrs_.push_back(&shstrtab_builder_.section_); AssignSectionStr(&shstrtab_builder_, &shstrtab_); shstrtab_builder_.section_index_ = section_index_++; if (debug_logging_) { LOG(INFO) << ".shstrtab size (bytes) =" << shstrtab_.size() << std::hex << " " << shstrtab_.size(); LOG(INFO) << "section list size (elements)=" << section_ptrs_.size() << std::hex << " " << section_ptrs_.size(); } if (IncludingDebugSymbols()) { // Get the layout of the symtab section. symtab_builder_.section_.sh_offset = NextOffset(symtab_builder_.section_, dynamic_builder_.section_); symtab_builder_.section_.sh_addr = 0; // Add to leave space for the null symbol. symtab_builder_.section_.sh_size = symtab_builder_.GetSize() * sizeof(Elf32_Sym); symtab_builder_.section_.sh_link = symtab_builder_.GetLink(); // Get the layout of the dynstr section. symtab_builder_.strtab_.section_.sh_offset = NextOffset(symtab_builder_.strtab_.section_, symtab_builder_.section_); symtab_builder_.strtab_.section_.sh_addr = 0; symtab_builder_.strtab_.section_.sh_size = strtab.size(); symtab_builder_.strtab_.section_.sh_link = symtab_builder_.strtab_.GetLink(); prev = symtab_builder_.strtab_.section_; if (debug_logging_) { LOG(INFO) << "symtab off=" << symtab_builder_.section_.sh_offset << " symtab size=" << symtab_builder_.section_.sh_size; LOG(INFO) << "strtab off=" << symtab_builder_.strtab_.section_.sh_offset << " strtab size=" << symtab_builder_.strtab_.section_.sh_size; } } // Get the layout of the extra sections. (This will deal with the debug // sections if they are there) for (auto it = other_builders_.begin(); it != other_builders_.end(); ++it) { it->section_.sh_offset = NextOffset(it->section_, prev); it->section_.sh_addr = 0; it->section_.sh_size = it->GetBuffer()->size(); it->section_.sh_link = it->GetLink(); // We postpone adding an ElfFilePiece to keep the order in "pieces." prev = it->section_; if (debug_logging_) { LOG(INFO) << it->name_ << " off=" << it->section_.sh_offset << " " << it->name_ << " size=" << it->section_.sh_size; } } // Get the layout of the shstrtab section shstrtab_builder_.section_.sh_offset = NextOffset(shstrtab_builder_.section_, prev); shstrtab_builder_.section_.sh_addr = 0; shstrtab_builder_.section_.sh_size = shstrtab_.size(); shstrtab_builder_.section_.sh_link = shstrtab_builder_.GetLink(); if (debug_logging_) { LOG(INFO) << "shstrtab off=" << shstrtab_builder_.section_.sh_offset << " shstrtab size=" << shstrtab_builder_.section_.sh_size; } // The section list comes after come after. Elf32_Word sections_offset = RoundUp( shstrtab_builder_.section_.sh_offset + shstrtab_builder_.section_.sh_size, sizeof(Elf32_Word)); // Setup the actual symbol arrays. std::vector<Elf32_Sym> dynsym = dynsym_builder_.GenerateSymtab(); CHECK_EQ(dynsym.size() * sizeof(Elf32_Sym), dynsym_builder_.section_.sh_size); std::vector<Elf32_Sym> symtab; if (IncludingDebugSymbols()) { symtab = symtab_builder_.GenerateSymtab(); CHECK_EQ(symtab.size() * sizeof(Elf32_Sym), symtab_builder_.section_.sh_size); } // Setup the dynamic section. // This will add the 2 values we cannot know until now time, namely the size // and the soname_offset. std::vector<Elf32_Dyn> dynamic = dynamic_builder_.GetDynamics(dynstr_.size(), dynstr_soname_offset_); CHECK_EQ(dynamic.size() * sizeof(Elf32_Dyn), dynamic_builder_.section_.sh_size); // Finish setup of the program headers now that we know the layout of the // whole file. Elf32_Word load_r_size = rodata_builder_.section_.sh_offset + rodata_builder_.section_.sh_size; program_headers_[PH_LOAD_R__].p_filesz = load_r_size; program_headers_[PH_LOAD_R__].p_memsz = load_r_size; program_headers_[PH_LOAD_R__].p_align = rodata_builder_.section_.sh_addralign; Elf32_Word load_rx_size = text_builder_.section_.sh_size; program_headers_[PH_LOAD_R_X].p_offset = text_builder_.section_.sh_offset; program_headers_[PH_LOAD_R_X].p_vaddr = text_builder_.section_.sh_offset; program_headers_[PH_LOAD_R_X].p_paddr = text_builder_.section_.sh_offset; program_headers_[PH_LOAD_R_X].p_filesz = load_rx_size; program_headers_[PH_LOAD_R_X].p_memsz = load_rx_size; program_headers_[PH_LOAD_R_X].p_align = text_builder_.section_.sh_addralign; program_headers_[PH_LOAD_RW_].p_offset = dynamic_builder_.section_.sh_offset; program_headers_[PH_LOAD_RW_].p_vaddr = dynamic_builder_.section_.sh_offset; program_headers_[PH_LOAD_RW_].p_paddr = dynamic_builder_.section_.sh_offset; program_headers_[PH_LOAD_RW_].p_filesz = dynamic_builder_.section_.sh_size; program_headers_[PH_LOAD_RW_].p_memsz = dynamic_builder_.section_.sh_size; program_headers_[PH_LOAD_RW_].p_align = dynamic_builder_.section_.sh_addralign; program_headers_[PH_DYNAMIC].p_offset = dynamic_builder_.section_.sh_offset; program_headers_[PH_DYNAMIC].p_vaddr = dynamic_builder_.section_.sh_offset; program_headers_[PH_DYNAMIC].p_paddr = dynamic_builder_.section_.sh_offset; program_headers_[PH_DYNAMIC].p_filesz = dynamic_builder_.section_.sh_size; program_headers_[PH_DYNAMIC].p_memsz = dynamic_builder_.section_.sh_size; program_headers_[PH_DYNAMIC].p_align = dynamic_builder_.section_.sh_addralign; // Finish setup of the Ehdr values. elf_header_.e_phoff = PHDR_OFFSET; elf_header_.e_shoff = sections_offset; elf_header_.e_phnum = PH_NUM; elf_header_.e_shnum = section_ptrs_.size(); elf_header_.e_shstrndx = shstrtab_builder_.section_index_; // Add the rest of the pieces to the list. pieces.push_back(new ElfFileMemoryPiece("Elf Header", 0, &elf_header_, sizeof(elf_header_))); pieces.push_back(new ElfFileMemoryPiece("Program headers", PHDR_OFFSET, &program_headers_, sizeof(program_headers_))); pieces.push_back(new ElfFileMemoryPiece(".dynamic", dynamic_builder_.section_.sh_offset, dynamic.data(), dynamic_builder_.section_.sh_size)); pieces.push_back(new ElfFileMemoryPiece(".dynsym", dynsym_builder_.section_.sh_offset, dynsym.data(), dynsym.size() * sizeof(Elf32_Sym))); pieces.push_back(new ElfFileMemoryPiece(".dynstr", dynsym_builder_.strtab_.section_.sh_offset, dynstr_.c_str(), dynstr_.size())); pieces.push_back(new ElfFileMemoryPiece(".hash", hash_builder_.section_.sh_offset, hash_.data(), hash_.size() * sizeof(Elf32_Word))); pieces.push_back(new ElfFileRodataPiece(rodata_builder_.section_.sh_offset, oat_writer_)); pieces.push_back(new ElfFileOatTextPiece(text_builder_.section_.sh_offset, oat_writer_)); if (IncludingDebugSymbols()) { pieces.push_back(new ElfFileMemoryPiece(".symtab", symtab_builder_.section_.sh_offset, symtab.data(), symtab.size() * sizeof(Elf32_Sym))); pieces.push_back(new ElfFileMemoryPiece(".strtab", symtab_builder_.strtab_.section_.sh_offset, strtab.c_str(), strtab.size())); } pieces.push_back(new ElfFileMemoryPiece(".shstrtab", shstrtab_builder_.section_.sh_offset, &shstrtab_[0], shstrtab_.size())); for (uint32_t i = 0; i < section_ptrs_.size(); ++i) { // Just add all the sections in individually since they are all over the // place on the heap/stack. Elf32_Word cur_off = sections_offset + i * sizeof(Elf32_Shdr); pieces.push_back(new ElfFileMemoryPiece("section table piece", cur_off, section_ptrs_[i], sizeof(Elf32_Shdr))); } // Postponed debug info. for (auto it = other_builders_.begin(); it != other_builders_.end(); ++it) { pieces.push_back(new ElfFileMemoryPiece(it->name_, it->section_.sh_offset, it->GetBuffer()->data(), it->GetBuffer()->size())); } if (!WriteOutFile(pieces, elf_file_)) { LOG(ERROR) << "Unable to write to file " << elf_file_->GetPath(); STLDeleteElements(&pieces); // Have to manually clean pieces. return false; } STLDeleteElements(&pieces); // Have to manually clean pieces. return true; } void ElfWriterQuick::ElfBuilder::SetupDynamic() { dynamic_builder_.AddDynamicTag(DT_HASH, 0, &hash_builder_); dynamic_builder_.AddDynamicTag(DT_STRTAB, 0, &dynsym_builder_.strtab_); dynamic_builder_.AddDynamicTag(DT_SYMTAB, 0, &dynsym_builder_); dynamic_builder_.AddDynamicTag(DT_SYMENT, sizeof(Elf32_Sym)); } void ElfWriterQuick::ElfBuilder::SetupRequiredSymbols() { dynsym_builder_.AddSymbol("oatdata", &rodata_builder_, 0, true, rodata_builder_.size_, STB_GLOBAL, STT_OBJECT); dynsym_builder_.AddSymbol("oatexec", &text_builder_, 0, true, text_builder_.size_, STB_GLOBAL, STT_OBJECT); dynsym_builder_.AddSymbol("oatlastword", &text_builder_, text_builder_.size_ - 4, true, 4, STB_GLOBAL, STT_OBJECT); } void ElfWriterQuick::ElfDynamicBuilder::AddDynamicTag(Elf32_Sword tag, Elf32_Word d_un) { if (tag == DT_NULL) { return; } dynamics_.push_back({nullptr, tag, d_un}); } void ElfWriterQuick::ElfDynamicBuilder::AddDynamicTag(Elf32_Sword tag, Elf32_Word d_un, ElfSectionBuilder* section) { if (tag == DT_NULL) { return; } dynamics_.push_back({section, tag, d_un}); } std::vector<Elf32_Dyn> ElfWriterQuick::ElfDynamicBuilder::GetDynamics(Elf32_Word strsz, Elf32_Word soname) { std::vector<Elf32_Dyn> ret; for (auto it = dynamics_.cbegin(); it != dynamics_.cend(); ++it) { if (it->section_) { // We are adding an address relative to a section. ret.push_back( {it->tag_, {it->off_ + it->section_->section_.sh_addr}}); } else { ret.push_back({it->tag_, {it->off_}}); } } ret.push_back({DT_STRSZ, {strsz}}); ret.push_back({DT_SONAME, {soname}}); ret.push_back({DT_NULL, {0}}); return ret; } std::vector<Elf32_Sym> ElfWriterQuick::ElfSymtabBuilder::GenerateSymtab() { std::vector<Elf32_Sym> ret; Elf32_Sym undef_sym; memset(&undef_sym, 0, sizeof(undef_sym)); undef_sym.st_shndx = SHN_UNDEF; ret.push_back(undef_sym); for (auto it = symbols_.cbegin(); it != symbols_.cend(); ++it) { Elf32_Sym sym; memset(&sym, 0, sizeof(sym)); sym.st_name = it->name_idx_; if (it->is_relative_) { sym.st_value = it->addr_ + it->section_->section_.sh_offset; } else { sym.st_value = it->addr_; } sym.st_size = it->size_; sym.st_other = it->other_; sym.st_shndx = it->section_->section_index_; sym.st_info = it->info_; ret.push_back(sym); } return ret; } std::string ElfWriterQuick::ElfSymtabBuilder::GenerateStrtab() { std::string tab; tab += '\0'; for (auto it = symbols_.begin(); it != symbols_.end(); ++it) { it->name_idx_ = tab.size(); tab += it->name_; tab += '\0'; } strtab_.section_.sh_size = tab.size(); return tab; } void ElfWriterQuick::ElfBuilder::AssignSectionStr( ElfSectionBuilder* builder, std::string* strtab) { builder->section_.sh_name = strtab->size(); *strtab += builder->name_; *strtab += '\0'; if (debug_logging_) { LOG(INFO) << "adding section name \"" << builder->name_ << "\" " << "to shstrtab at offset " << builder->section_.sh_name; } } // from bionic static unsigned elfhash(const char *_name) { const unsigned char *name = (const unsigned char *) _name; unsigned h = 0, g; while (*name) { h = (h << 4) + *name++; g = h & 0xf0000000; h ^= g; h ^= g >> 24; } return h; } std::vector<Elf32_Word> ElfWriterQuick::ElfSymtabBuilder::GenerateHashContents() { // Here is how The ELF hash table works. // There are 3 arrays to worry about. // * The symbol table where the symbol information is. // * The bucket array which is an array of indexes into the symtab and chain. // * The chain array which is also an array of indexes into the symtab and chain. // // Lets say the state is something like this. // +--------+ +--------+ +-----------+ // | symtab | | bucket | | chain | // | null | | 1 | | STN_UNDEF | // | <sym1> | | 4 | | 2 | // | <sym2> | | | | 5 | // | <sym3> | | | | STN_UNDEF | // | <sym4> | | | | 3 | // | <sym5> | | | | STN_UNDEF | // +--------+ +--------+ +-----------+ // // The lookup process (in python psudocode) is // // def GetSym(name): // # NB STN_UNDEF == 0 // indx = bucket[elfhash(name) % num_buckets] // while indx != STN_UNDEF: // if GetSymbolName(symtab[indx]) == name: // return symtab[indx] // indx = chain[indx] // return SYMBOL_NOT_FOUND // // Between bucket and chain arrays every symtab index must be present exactly // once (except for STN_UNDEF, which must be present 1 + num_bucket times). // Select number of buckets. // This is essentially arbitrary. Elf32_Word nbuckets; Elf32_Word chain_size = GetSize(); if (symbols_.size() < 8) { nbuckets = 2; } else if (symbols_.size() < 32) { nbuckets = 4; } else if (symbols_.size() < 256) { nbuckets = 16; } else { // Have about 32 ids per bucket. nbuckets = RoundUp(symbols_.size()/32, 2); } std::vector<Elf32_Word> hash; hash.push_back(nbuckets); hash.push_back(chain_size); uint32_t bucket_offset = hash.size(); uint32_t chain_offset = bucket_offset + nbuckets; hash.resize(hash.size() + nbuckets + chain_size, 0); Elf32_Word* buckets = hash.data() + bucket_offset; Elf32_Word* chain = hash.data() + chain_offset; // Set up the actual hash table. for (Elf32_Word i = 0; i < symbols_.size(); i++) { // Add 1 since we need to have the null symbol that is not in the symbols // list. Elf32_Word index = i + 1; Elf32_Word hash_val = static_cast<Elf32_Word>(elfhash(symbols_[i].name_.c_str())) % nbuckets; if (buckets[hash_val] == 0) { buckets[hash_val] = index; } else { hash_val = buckets[hash_val]; CHECK_LT(hash_val, chain_size); while (chain[hash_val] != 0) { hash_val = chain[hash_val]; CHECK_LT(hash_val, chain_size); } chain[hash_val] = index; // Check for loops. Works because if this is non-empty then there must be // another cell which already contains the same symbol index as this one, // which means some symbol has more then one name, which isn't allowed. CHECK_EQ(chain[index], static_cast<Elf32_Word>(0)); } } return hash; } void ElfWriterQuick::ElfBuilder::SetupEhdr() { memset(&elf_header_, 0, sizeof(elf_header_)); elf_header_.e_ident[EI_MAG0] = ELFMAG0; elf_header_.e_ident[EI_MAG1] = ELFMAG1; elf_header_.e_ident[EI_MAG2] = ELFMAG2; elf_header_.e_ident[EI_MAG3] = ELFMAG3; elf_header_.e_ident[EI_CLASS] = ELFCLASS32; elf_header_.e_ident[EI_DATA] = ELFDATA2LSB; elf_header_.e_ident[EI_VERSION] = EV_CURRENT; elf_header_.e_ident[EI_OSABI] = ELFOSABI_LINUX; elf_header_.e_ident[EI_ABIVERSION] = 0; elf_header_.e_type = ET_DYN; elf_header_.e_version = 1; elf_header_.e_entry = 0; elf_header_.e_ehsize = sizeof(Elf32_Ehdr); elf_header_.e_phentsize = sizeof(Elf32_Phdr); elf_header_.e_shentsize = sizeof(Elf32_Shdr); elf_header_.e_phoff = sizeof(Elf32_Ehdr); } void ElfWriterQuick::ElfBuilder::SetISA(InstructionSet isa) { switch (isa) { case kArm: // Fall through. case kThumb2: { elf_header_.e_machine = EM_ARM; elf_header_.e_flags = EF_ARM_EABI_VER5; break; } case kArm64: { elf_header_.e_machine = EM_AARCH64; elf_header_.e_flags = 0; break; } case kX86: { elf_header_.e_machine = EM_386; elf_header_.e_flags = 0; break; } case kX86_64: { elf_header_.e_machine = EM_X86_64; elf_header_.e_flags = 0; break; } case kMips: { elf_header_.e_machine = EM_MIPS; elf_header_.e_flags = (EF_MIPS_NOREORDER | EF_MIPS_PIC | EF_MIPS_CPIC | EF_MIPS_ABI_O32 | EF_MIPS_ARCH_32R2); break; } default: { fatal_error_ = true; LOG(FATAL) << "Unknown instruction set: " << isa; break; } } } void ElfWriterQuick::ElfSymtabBuilder::AddSymbol( const std::string& name, const ElfSectionBuilder* section, Elf32_Addr addr, bool is_relative, Elf32_Word size, uint8_t binding, uint8_t type, uint8_t other) { CHECK(section); ElfSymtabBuilder::ElfSymbolState state {name, section, addr, size, is_relative, MakeStInfo(binding, type), other, 0}; symbols_.push_back(state); } bool ElfWriterQuick::Create(File* elf_file, OatWriter* oat_writer, const std::vector<const DexFile*>& dex_files, const std::string& android_root, bool is_host, const CompilerDriver& driver) { ElfWriterQuick elf_writer(driver, elf_file); return elf_writer.Write(oat_writer, dex_files, android_root, is_host); } // Add patch information to this section. Each patch is a Elf32_Word that // identifies an offset from the start of the text section void ElfWriterQuick::ReservePatchSpace(std::vector<uint8_t>* buffer, bool debug) { size_t size = compiler_driver_->GetCodeToPatch().size() + compiler_driver_->GetMethodsToPatch().size() + compiler_driver_->GetClassesToPatch().size(); if (size == 0) { if (debug) { LOG(INFO) << "No patches to record"; } return; } buffer->resize(size * sizeof(uintptr_t)); if (debug) { LOG(INFO) << "Patches reserved for " << size; } } std::vector<uint8_t>* ConstructCIEFrameX86(bool is_x86_64) { std::vector<uint8_t>* cfi_info = new std::vector<uint8_t>; // Length (will be filled in later in this routine). if (is_x86_64) { PushWord(cfi_info, 0xffffffff); // Indicates 64bit PushWord(cfi_info, 0); PushWord(cfi_info, 0); } else { PushWord(cfi_info, 0); } // CIE id: always 0. if (is_x86_64) { PushWord(cfi_info, 0); PushWord(cfi_info, 0); } else { PushWord(cfi_info, 0); } // Version: always 1. cfi_info->push_back(0x01); // Augmentation: 'zR\0' cfi_info->push_back(0x7a); cfi_info->push_back(0x52); cfi_info->push_back(0x0); // Code alignment: 1. EncodeUnsignedLeb128(1, cfi_info); // Data alignment. if (is_x86_64) { EncodeSignedLeb128(-8, cfi_info); } else { EncodeSignedLeb128(-4, cfi_info); } // Return address register. if (is_x86_64) { // R16(RIP) cfi_info->push_back(0x10); } else { // R8(EIP) cfi_info->push_back(0x08); } // Augmentation length: 1. cfi_info->push_back(1); // Augmentation data. if (is_x86_64) { // 0x04 ((DW_EH_PE_absptr << 4) | DW_EH_PE_udata8). cfi_info->push_back(0x04); } else { // 0x03 ((DW_EH_PE_absptr << 4) | DW_EH_PE_udata4). cfi_info->push_back(0x03); } // Initial instructions. if (is_x86_64) { // DW_CFA_def_cfa R7(RSP) 8. cfi_info->push_back(0x0c); cfi_info->push_back(0x07); cfi_info->push_back(0x08); // DW_CFA_offset R16(RIP) 1 (* -8). cfi_info->push_back(0x90); cfi_info->push_back(0x01); } else { // DW_CFA_def_cfa R4(ESP) 4. cfi_info->push_back(0x0c); cfi_info->push_back(0x04); cfi_info->push_back(0x04); // DW_CFA_offset R8(EIP) 1 (* -4). cfi_info->push_back(0x88); cfi_info->push_back(0x01); } // Padding to a multiple of 4 while ((cfi_info->size() & 3) != 0) { // DW_CFA_nop is encoded as 0. cfi_info->push_back(0); } // Set the length of the CIE inside the generated bytes. if (is_x86_64) { uint32_t length = cfi_info->size() - 12; UpdateWord(cfi_info, 4, length); } else { uint32_t length = cfi_info->size() - 4; UpdateWord(cfi_info, 0, length); } return cfi_info; } std::vector<uint8_t>* ConstructCIEFrame(InstructionSet isa) { switch (isa) { case kX86: return ConstructCIEFrameX86(false); case kX86_64: return ConstructCIEFrameX86(true); default: // Not implemented. return nullptr; } } bool ElfWriterQuick::Write(OatWriter* oat_writer, const std::vector<const DexFile*>& dex_files_unused, const std::string& android_root_unused, bool is_host_unused) { constexpr bool debug = false; const OatHeader& oat_header = oat_writer->GetOatHeader(); Elf32_Word oat_data_size = oat_header.GetExecutableOffset(); uint32_t oat_exec_size = oat_writer->GetSize() - oat_data_size; ElfBuilder builder(oat_writer, elf_file_, compiler_driver_->GetInstructionSet(), 0, oat_data_size, oat_data_size, oat_exec_size, compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols(), debug); if (!builder.Init()) { return false; } if (compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) { WriteDebugSymbols(&builder, oat_writer); } if (compiler_driver_->GetCompilerOptions().GetIncludePatchInformation()) { ElfRawSectionBuilder oat_patches(".oat_patches", SHT_OAT_PATCH, 0, NULL, 0, sizeof(uintptr_t), sizeof(uintptr_t)); ReservePatchSpace(oat_patches.GetBuffer(), debug); builder.RegisterRawSection(oat_patches); } return builder.Write(); } void ElfWriterQuick::WriteDebugSymbols(ElfBuilder* builder, OatWriter* oat_writer) { std::unique_ptr<std::vector<uint8_t>> cfi_info( ConstructCIEFrame(compiler_driver_->GetInstructionSet())); Elf32_Addr text_section_address = builder->text_builder_.section_.sh_addr; // Iterate over the compiled methods. const std::vector<OatWriter::DebugInfo>& method_info = oat_writer->GetCFIMethodInfo(); ElfSymtabBuilder* symtab = &builder->symtab_builder_; for (auto it = method_info.begin(); it != method_info.end(); ++it) { symtab->AddSymbol(it->method_name_, &builder->text_builder_, it->low_pc_, true, it->high_pc_ - it->low_pc_, STB_GLOBAL, STT_FUNC); // Include CFI for compiled method, if possible. if (cfi_info.get() != nullptr) { DCHECK(it->compiled_method_ != nullptr); // Copy in the FDE, if present const std::vector<uint8_t>* fde = it->compiled_method_->GetCFIInfo(); if (fde != nullptr) { // Copy the information into cfi_info and then fix the address in the new copy. int cur_offset = cfi_info->size(); cfi_info->insert(cfi_info->end(), fde->begin(), fde->end()); bool is_64bit = *(reinterpret_cast<const uint32_t*>(fde->data())) == 0xffffffff; // Set the 'CIE_pointer' field. uint64_t CIE_pointer = cur_offset + (is_64bit ? 12 : 4); uint64_t offset_to_update = CIE_pointer; if (is_64bit) { (*cfi_info)[offset_to_update+0] = CIE_pointer; (*cfi_info)[offset_to_update+1] = CIE_pointer >> 8; (*cfi_info)[offset_to_update+2] = CIE_pointer >> 16; (*cfi_info)[offset_to_update+3] = CIE_pointer >> 24; (*cfi_info)[offset_to_update+4] = CIE_pointer >> 32; (*cfi_info)[offset_to_update+5] = CIE_pointer >> 40; (*cfi_info)[offset_to_update+6] = CIE_pointer >> 48; (*cfi_info)[offset_to_update+7] = CIE_pointer >> 56; } else { (*cfi_info)[offset_to_update+0] = CIE_pointer; (*cfi_info)[offset_to_update+1] = CIE_pointer >> 8; (*cfi_info)[offset_to_update+2] = CIE_pointer >> 16; (*cfi_info)[offset_to_update+3] = CIE_pointer >> 24; } // Set the 'initial_location' field. offset_to_update += is_64bit ? 8 : 4; if (is_64bit) { const uint64_t quick_code_start = it->low_pc_ + text_section_address; (*cfi_info)[offset_to_update+0] = quick_code_start; (*cfi_info)[offset_to_update+1] = quick_code_start >> 8; (*cfi_info)[offset_to_update+2] = quick_code_start >> 16; (*cfi_info)[offset_to_update+3] = quick_code_start >> 24; (*cfi_info)[offset_to_update+4] = quick_code_start >> 32; (*cfi_info)[offset_to_update+5] = quick_code_start >> 40; (*cfi_info)[offset_to_update+6] = quick_code_start >> 48; (*cfi_info)[offset_to_update+7] = quick_code_start >> 56; } else { const uint32_t quick_code_start = it->low_pc_ + text_section_address; (*cfi_info)[offset_to_update+0] = quick_code_start; (*cfi_info)[offset_to_update+1] = quick_code_start >> 8; (*cfi_info)[offset_to_update+2] = quick_code_start >> 16; (*cfi_info)[offset_to_update+3] = quick_code_start >> 24; } } } } bool hasCFI = (cfi_info.get() != nullptr); bool hasLineInfo = false; for (auto& dbg_info : oat_writer->GetCFIMethodInfo()) { if (dbg_info.dbgstream_ != nullptr && !dbg_info.compiled_method_->GetSrcMappingTable().empty()) { hasLineInfo = true; break; } } if (hasLineInfo || hasCFI) { ElfRawSectionBuilder debug_info(".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0); ElfRawSectionBuilder debug_abbrev(".debug_abbrev", SHT_PROGBITS, 0, nullptr, 0, 1, 0); ElfRawSectionBuilder debug_str(".debug_str", SHT_PROGBITS, 0, nullptr, 0, 1, 0); ElfRawSectionBuilder debug_line(".debug_line", SHT_PROGBITS, 0, nullptr, 0, 1, 0); FillInCFIInformation(oat_writer, debug_info.GetBuffer(), debug_abbrev.GetBuffer(), debug_str.GetBuffer(), hasLineInfo ? debug_line.GetBuffer() : nullptr, text_section_address); builder->RegisterRawSection(debug_info); builder->RegisterRawSection(debug_abbrev); if (hasCFI) { ElfRawSectionBuilder eh_frame(".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0); eh_frame.SetBuffer(std::move(*cfi_info.get())); builder->RegisterRawSection(eh_frame); } if (hasLineInfo) { builder->RegisterRawSection(debug_line); } builder->RegisterRawSection(debug_str); } } class LineTableGenerator FINAL : public Leb128Encoder { public: LineTableGenerator(int line_base, int line_range, int opcode_base, std::vector<uint8_t>* data, uintptr_t current_address, size_t current_line) : Leb128Encoder(data), line_base_(line_base), line_range_(line_range), opcode_base_(opcode_base), current_address_(current_address), current_line_(current_line), current_file_index_(0) {} void PutDelta(unsigned delta_addr, int delta_line) { current_line_ += delta_line; current_address_ += delta_addr; if (delta_line >= line_base_ && delta_line < line_base_ + line_range_) { unsigned special_opcode = (delta_line - line_base_) + (line_range_ * delta_addr) + opcode_base_; if (special_opcode <= 255) { PushByte(data_, special_opcode); return; } } // generate standart opcode for address advance if (delta_addr != 0) { PushByte(data_, DW_LNS_advance_pc); PushBackUnsigned(delta_addr); } // generate standart opcode for line delta if (delta_line != 0) { PushByte(data_, DW_LNS_advance_line); PushBackSigned(delta_line); } // generate standart opcode for new LTN entry PushByte(data_, DW_LNS_copy); } void SetAddr(uintptr_t addr) { if (current_address_ == addr) { return; } current_address_ = addr; PushByte(data_, 0); // extended opcode: PushByte(data_, 1 + 4); // length: opcode_size + address_size PushByte(data_, DW_LNE_set_address); PushWord(data_, addr); } void SetLine(unsigned line) { int delta_line = line - current_line_; if (delta_line) { current_line_ = line; PushByte(data_, DW_LNS_advance_line); PushBackSigned(delta_line); } } void SetFile(unsigned file_index) { if (current_file_index_ != file_index) { current_file_index_ = file_index; PushByte(data_, DW_LNS_set_file); PushBackUnsigned(file_index); } } void EndSequence() { // End of Line Table Program // 0(=ext), 1(len), DW_LNE_end_sequence PushByte(data_, 0); PushByte(data_, 1); PushByte(data_, DW_LNE_end_sequence); } private: const int line_base_; const int line_range_; const int opcode_base_; uintptr_t current_address_; size_t current_line_; unsigned current_file_index_; DISALLOW_COPY_AND_ASSIGN(LineTableGenerator); }; // TODO: rewriting it using DexFile::DecodeDebugInfo needs unneeded stuff. static void GetLineInfoForJava(const uint8_t* dbgstream, const SrcMap& pc2dex, SrcMap* result, uint32_t start_pc = 0) { if (dbgstream == nullptr) { return; } int adjopcode; uint32_t dex_offset = 0; uint32_t java_line = DecodeUnsignedLeb128(&dbgstream); // skip parameters for (uint32_t param_count = DecodeUnsignedLeb128(&dbgstream); param_count != 0; --param_count) { DecodeUnsignedLeb128(&dbgstream); } for (bool is_end = false; is_end == false; ) { uint8_t opcode = *dbgstream; dbgstream++; switch (opcode) { case DexFile::DBG_END_SEQUENCE: is_end = true; break; case DexFile::DBG_ADVANCE_PC: dex_offset += DecodeUnsignedLeb128(&dbgstream); break; case DexFile::DBG_ADVANCE_LINE: java_line += DecodeSignedLeb128(&dbgstream); break; case DexFile::DBG_START_LOCAL: case DexFile::DBG_START_LOCAL_EXTENDED: DecodeUnsignedLeb128(&dbgstream); DecodeUnsignedLeb128(&dbgstream); DecodeUnsignedLeb128(&dbgstream); if (opcode == DexFile::DBG_START_LOCAL_EXTENDED) { DecodeUnsignedLeb128(&dbgstream); } break; case DexFile::DBG_END_LOCAL: case DexFile::DBG_RESTART_LOCAL: DecodeUnsignedLeb128(&dbgstream); break; case DexFile::DBG_SET_PROLOGUE_END: case DexFile::DBG_SET_EPILOGUE_BEGIN: case DexFile::DBG_SET_FILE: break; default: adjopcode = opcode - DexFile::DBG_FIRST_SPECIAL; dex_offset += adjopcode / DexFile::DBG_LINE_RANGE; java_line += DexFile::DBG_LINE_BASE + (adjopcode % DexFile::DBG_LINE_RANGE); for (SrcMap::const_iterator found = pc2dex.FindByTo(dex_offset); found != pc2dex.end() && found->to_ == static_cast<int32_t>(dex_offset); found++) { result->push_back({found->from_ + start_pc, static_cast<int32_t>(java_line)}); } break; } } } void ElfWriterQuick::FillInCFIInformation(OatWriter* oat_writer, std::vector<uint8_t>* dbg_info, std::vector<uint8_t>* dbg_abbrev, std::vector<uint8_t>* dbg_str, std::vector<uint8_t>* dbg_line, uint32_t text_section_offset) { const std::vector<OatWriter::DebugInfo>& method_info = oat_writer->GetCFIMethodInfo(); uint32_t producer_str_offset = PushStr(dbg_str, "Android dex2oat"); // Create the debug_abbrev section with boilerplate information. // We only care about low_pc and high_pc right now for the compilation // unit and methods. // Tag 1: Compilation unit: DW_TAG_compile_unit. PushByte(dbg_abbrev, 1); PushByte(dbg_abbrev, DW_TAG_compile_unit); // There are children (the methods). PushByte(dbg_abbrev, DW_CHILDREN_yes); // DW_AT_producer DW_FORM_data1. // REVIEW: we can get rid of dbg_str section if // DW_FORM_string (immediate string) was used everywhere instead of // DW_FORM_strp (ref to string from .debug_str section). // DW_FORM_strp makes sense only if we reuse the strings. PushByte(dbg_abbrev, DW_AT_producer); PushByte(dbg_abbrev, DW_FORM_strp); // DW_LANG_Java DW_FORM_data1. PushByte(dbg_abbrev, DW_AT_language); PushByte(dbg_abbrev, DW_FORM_data1); // DW_AT_low_pc DW_FORM_addr. PushByte(dbg_abbrev, DW_AT_low_pc); PushByte(dbg_abbrev, DW_FORM_addr); // DW_AT_high_pc DW_FORM_addr. PushByte(dbg_abbrev, DW_AT_high_pc); PushByte(dbg_abbrev, DW_FORM_addr); if (dbg_line != nullptr) { // DW_AT_stmt_list DW_FORM_sec_offset. PushByte(dbg_abbrev, DW_AT_stmt_list); PushByte(dbg_abbrev, DW_FORM_sec_offset); } // End of DW_TAG_compile_unit. PushHalf(dbg_abbrev, 0); // Tag 2: Compilation unit: DW_TAG_subprogram. PushByte(dbg_abbrev, 2); PushByte(dbg_abbrev, DW_TAG_subprogram); // There are no children. PushByte(dbg_abbrev, DW_CHILDREN_no); // Name of the method. PushByte(dbg_abbrev, DW_AT_name); PushByte(dbg_abbrev, DW_FORM_strp); // DW_AT_low_pc DW_FORM_addr. PushByte(dbg_abbrev, DW_AT_low_pc); PushByte(dbg_abbrev, DW_FORM_addr); // DW_AT_high_pc DW_FORM_addr. PushByte(dbg_abbrev, DW_AT_high_pc); PushByte(dbg_abbrev, DW_FORM_addr); // End of DW_TAG_subprogram. PushHalf(dbg_abbrev, 0); // Start the debug_info section with the header information // 'unit_length' will be filled in later. int cunit_length = dbg_info->size(); PushWord(dbg_info, 0); // 'version' - 3. PushHalf(dbg_info, 3); // Offset into .debug_abbrev section (always 0). PushWord(dbg_info, 0); // Address size: 4. PushByte(dbg_info, 4); // Start the description for the compilation unit. // This uses tag 1. PushByte(dbg_info, 1); // The producer is Android dex2oat. PushWord(dbg_info, producer_str_offset); // The language is Java. PushByte(dbg_info, DW_LANG_Java); // low_pc and high_pc. uint32_t cunit_low_pc = 0 - 1; uint32_t cunit_high_pc = 0; int cunit_low_pc_pos = dbg_info->size(); PushWord(dbg_info, 0); PushWord(dbg_info, 0); if (dbg_line == nullptr) { for (size_t i = 0; i < method_info.size(); ++i) { const OatWriter::DebugInfo &dbg = method_info[i]; cunit_low_pc = std::min(cunit_low_pc, dbg.low_pc_); cunit_high_pc = std::max(cunit_high_pc, dbg.high_pc_); // Start a new TAG: subroutine (2). PushByte(dbg_info, 2); // Enter name, low_pc, high_pc. PushWord(dbg_info, PushStr(dbg_str, dbg.method_name_)); PushWord(dbg_info, dbg.low_pc_ + text_section_offset); PushWord(dbg_info, dbg.high_pc_ + text_section_offset); } } else { // TODO: in gdb info functions <regexp> - reports Java functions, but // source file is <unknown> because .debug_line is formed as one // compilation unit. To fix this it is possible to generate // a separate compilation unit for every distinct Java source. // Each of the these compilation units can have several non-adjacent // method ranges. // Line number table offset PushWord(dbg_info, dbg_line->size()); size_t lnt_length = dbg_line->size(); PushWord(dbg_line, 0); PushHalf(dbg_line, 4); // LNT Version DWARF v4 => 4 size_t lnt_hdr_length = dbg_line->size(); PushWord(dbg_line, 0); // TODO: 64-bit uses 8-byte here PushByte(dbg_line, 1); // minimum_instruction_length (ubyte) PushByte(dbg_line, 1); // maximum_operations_per_instruction (ubyte) = always 1 PushByte(dbg_line, 1); // default_is_stmt (ubyte) const int8_t LINE_BASE = -5; PushByte(dbg_line, LINE_BASE); // line_base (sbyte) const uint8_t LINE_RANGE = 14; PushByte(dbg_line, LINE_RANGE); // line_range (ubyte) const uint8_t OPCODE_BASE = 13; PushByte(dbg_line, OPCODE_BASE); // opcode_base (ubyte) // Standard_opcode_lengths (array of ubyte). PushByte(dbg_line, 0); PushByte(dbg_line, 1); PushByte(dbg_line, 1); PushByte(dbg_line, 1); PushByte(dbg_line, 1); PushByte(dbg_line, 0); PushByte(dbg_line, 0); PushByte(dbg_line, 0); PushByte(dbg_line, 1); PushByte(dbg_line, 0); PushByte(dbg_line, 0); PushByte(dbg_line, 1); PushByte(dbg_line, 0); // include_directories (sequence of path names) = EMPTY // File_names (sequence of file entries). std::unordered_map<const char*, size_t> files; for (size_t i = 0; i < method_info.size(); ++i) { const OatWriter::DebugInfo &dbg = method_info[i]; // TODO: add package directory to the file name const char* file_name = dbg.src_file_name_ == nullptr ? "null" : dbg.src_file_name_; auto found = files.find(file_name); if (found == files.end()) { size_t file_index = 1 + files.size(); files[file_name] = file_index; PushStr(dbg_line, file_name); PushByte(dbg_line, 0); // include directory index = LEB128(0) - no directory PushByte(dbg_line, 0); // modification time = LEB128(0) - NA PushByte(dbg_line, 0); // file length = LEB128(0) - NA } } PushByte(dbg_line, 0); // End of file_names. // Set lnt header length. UpdateWord(dbg_line, lnt_hdr_length, dbg_line->size() - lnt_hdr_length - 4); // Generate Line Number Program code, one long program for all methods. LineTableGenerator line_table_generator(LINE_BASE, LINE_RANGE, OPCODE_BASE, dbg_line, 0, 1); SrcMap pc2java_map; for (size_t i = 0; i < method_info.size(); ++i) { const OatWriter::DebugInfo &dbg = method_info[i]; const char* file_name = (dbg.src_file_name_ == nullptr) ? "null" : dbg.src_file_name_; size_t file_index = files[file_name]; DCHECK_NE(file_index, 0U) << file_name; cunit_low_pc = std::min(cunit_low_pc, dbg.low_pc_); cunit_high_pc = std::max(cunit_high_pc, dbg.high_pc_); // Start a new TAG: subroutine (2). PushByte(dbg_info, 2); // Enter name, low_pc, high_pc. PushWord(dbg_info, PushStr(dbg_str, dbg.method_name_)); PushWord(dbg_info, dbg.low_pc_ + text_section_offset); PushWord(dbg_info, dbg.high_pc_ + text_section_offset); GetLineInfoForJava(dbg.dbgstream_, dbg.compiled_method_->GetSrcMappingTable(), &pc2java_map, dbg.low_pc_); pc2java_map.DeltaFormat({dbg.low_pc_, 1}, dbg.high_pc_); if (!pc2java_map.empty()) { line_table_generator.SetFile(file_index); line_table_generator.SetAddr(dbg.low_pc_ + text_section_offset); line_table_generator.SetLine(1); for (auto& src_map_elem : pc2java_map) { line_table_generator.PutDelta(src_map_elem.from_, src_map_elem.to_); } pc2java_map.clear(); } } // End Sequence should have the highest address set. line_table_generator.SetAddr(cunit_high_pc + text_section_offset); line_table_generator.EndSequence(); // set lnt length UpdateWord(dbg_line, lnt_length, dbg_line->size() - lnt_length - 4); } // One byte terminator PushByte(dbg_info, 0); // Fill in cunit's low_pc and high_pc. UpdateWord(dbg_info, cunit_low_pc_pos, cunit_low_pc + text_section_offset); UpdateWord(dbg_info, cunit_low_pc_pos + 4, cunit_high_pc + text_section_offset); // We have now walked all the methods. Fill in lengths. UpdateWord(dbg_info, cunit_length, dbg_info->size() - cunit_length - 4); } } // namespace art
778c04bc7fd8d8b523bbf5a1f507c7fa3527d40c
15e818aada2b18047fa895690bc1c2afda6d7273
/lib/json_load/json_load_or_die.h
20eb95524bc7a0edd372c68a5d2f99a6d37e83cb
[ "Apache-2.0" ]
permissive
ghomsy/makani
4ee34c4248fb0ac355f65aaed35718b1f5eabecf
818ae8b7119b200a28af6b3669a3045f30e0dc64
refs/heads/master
2023-01-11T18:46:21.939471
2020-11-10T00:23:31
2020-11-10T00:23:31
301,863,147
0
0
Apache-2.0
2020-11-10T00:23:32
2020-10-06T21:51:21
null
UTF-8
C++
false
false
1,421
h
json_load_or_die.h
/* * Copyright 2020 Makani Technologies LLC * * 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. */ // Simple wrappers for json_load_basic that die on error. #ifndef LIB_JSON_LOAD_JSON_LOAD_OR_DIE_H_ #define LIB_JSON_LOAD_JSON_LOAD_OR_DIE_H_ #include <jansson.h> #include <stdint.h> #include <string> #include <vector> namespace json_load { json_t *LoadFileOrDie(const std::string &filename); json_t *LoadFieldOrDie(const json_t *obj, const std::string &key); int32_t LoadInt32OrDie(const json_t *obj, const std::string &key); double LoadDoubleOrDie(const json_t *obj, const std::string &key); void LoadArray1D_DoubleOrDie(const json_t *obj, int32_t length, std::vector<double> *out); void LoadArray1D_Int32OrDie(const json_t *obj, int32_t length, std::vector<int32_t> *out); } // namespace json_load #endif // LIB_JSON_LOAD_JSON_LOAD_OR_DIE_H_
f46127789a504f898146ac5445c6b4827af16fbb
a26be2a476c6ef9570fc7525524804e83d779d29
/Labs/Lab4.2/HuffmanEncoding.cpp
6f93ce8d05c6d22932f886450a909bbf80c55e9e
[]
no_license
AaronCGoidel/DSA
8389eca153af02239474bc8d7e9c7a1bfcfd01b3
440332905b979be4f09a988d0049b4e36dba9511
refs/heads/master
2020-03-26T20:45:10.024361
2019-04-09T15:32:07
2019-04-09T15:32:07
138,738,343
0
0
null
null
null
null
UTF-8
C++
false
false
3,536
cpp
HuffmanEncoding.cpp
/* Huffman Encoding * 2019 * Starter Code */ #include "HuffNode.h" #include "HuffHeap.h" #include <iostream> #include <fstream> #include <map> using namespace std; map<char, uint32_t> counts; HuffHeap* makeHeap(string fileName){ //takes in a file name, counts the characters and creates the heap //consider making a helper file to count all characters //and then puts them all into a heap // count number of times each character appears ifstream is(fileName); char c; while(is.get(c)){ counts[c]++; } is.close(); // make heap HuffHeap* pQueue = new HuffHeap(); map<char, uint32_t>::iterator iter; for(iter = counts.begin(); iter != counts.end(); iter++){ HuffNode* node = new HuffNode(iter->first, iter->second); pQueue->insert(node); } // pQueue->display(); // for(int i = 0; i < pQueue->getSize(); i++){ // cout << pQueue->get(i)->getChar() << ", " << pQueue->get(i)->getCount() << endl; // } return pQueue; } HuffNode* makeTrie(HuffHeap* heap){ // takes the heap and makes it into the tree HuffNode* root = NULL; while(heap->getSize() != 1){ HuffNode* left = heap->remove(); HuffNode* right = heap->remove(); root = new HuffNode(left, right); heap->insert(root); } // heap->display(); return root; } bool lookup(HuffNode* root, char c, string &code, string direction){ code += direction; if(!root->isLeaf()){ if(lookup(root->getLeft(), c, code, "0")){ return true; }else{ code.pop_back(); } if(lookup(root->getRight(), c, code, "1")){ return true; }else{ code.pop_back(); } }else{ if(root->getChar() == c){ return true; }else{ return false; } } return false; } string encodeChar(HuffNode* trie, char c){ string code; lookup(trie, c, code, ""); return code; } string encode(HuffNode* trie, string fileName){ // takes in the trie and filename and uses encodeChar to encode each char // creating a string of 0s and 1s as output string out = ""; ifstream is(fileName); char c; while(is.get(c)){ out += encodeChar(trie, c); } is.close(); return out; } void tester(){ cout << "------TEST ONE------" << endl; string file = "HuffTest1.txt"; HuffNode* trie = makeTrie(makeHeap(file)); cout << encode(trie, file) << endl; cout << "------TEST TWO------" << endl; file = "HuffTest2.txt"; trie = makeTrie(makeHeap(file)); cout << encode(trie, file) << endl; cout << "------TEST THREE------" << endl; file = "HuffTest3.txt"; trie = makeTrie(makeHeap(file)); cout << encode(trie, file) << endl; } void testfiles(){ string filename; HuffNode* trie; ofstream out; filename = "HuffTest1.txt"; trie = makeTrie(makeHeap(filename)); out.open("Output1.txt"); out << encode(trie, filename); out.close(); filename = "HuffTest2.txt"; trie = makeTrie(makeHeap(filename)); out.open("Output2.txt"); out << encode(trie, filename); out.close(); filename = "HuffTest3.txt"; trie = makeTrie(makeHeap(filename)); out.open("Output3.txt"); out << encode(trie, filename); out.close(); } int main(int argc, char const* argv[]){ if(argc != 3){ std::cerr << "Usage: " << argv[0] << " input.txt output.txt" << std::endl; return 1; } HuffNode* trie = makeTrie(makeHeap(argv[1])); ofstream output(argv[2]); output << encode(trie, argv[1]); output.close(); string treefile = "Tree"; output.open(treefile + argv[2]); output << trie->toString(1); output.close(); }
149b2ead2eaac03c8105d48daa6b36a406b35841
b953a775acdae5c0e8c8d30d9f491b7394da2c26
/rma.h
4f9a826aae84b66c11ec1f8a7ddd73c55dcdc354
[]
no_license
shweaye810/discrepancy
7ea0175fb690b7dd5a3a9147b48db93704d40517
8441d95a6b09075a9b35c0c571611470ea417bb1
refs/heads/master
2020-12-25T15:17:34.913391
2016-08-23T16:50:48
2016-08-23T16:50:48
62,466,028
1
0
null
null
null
null
UTF-8
C++
false
false
495
h
rma.h
#include <map> #include "info.h" #include "tokenizer.h" #ifndef RMA_H #define RMA_H /* * @m_info: string -> RMA */ class RMA{ public: RMA(); void add(); void print(std::ostream &, const std::string &s) const; void substitute_PN(); void calc_qty(); private: std::map<std::string, std::vector<Info> > m_info; void proc_loc(Info &, const std::string &, int); void substitute_full_PN(); void substitute_all(); }; #endif
022b13c1c9d6c0c1dc296498466174ca2da8b353
b504c574da6f77ca14d19284e7e24cfc12c06a21
/day03/ex01/main.cpp
64ff62a435dc2719d72f5ee89d833b2cb88aa7c5
[]
no_license
benlyazid/piscine-CPP
93c2dfd5aa1e7e835d521518b94b1b20a0bc3826
c7eb0b6cff163591e174b7b93f978de42966f575
refs/heads/master
2023-08-01T05:43:49.119629
2021-09-24T16:59:47
2021-09-24T16:59:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
main.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kbenlyaz < kbenlyaz@student.1337.ma > +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/05 10:16:28 by kbenlyaz #+# #+# */ /* Updated: 2021/09/10 15:35:54 by kbenlyaz ### ########.fr */ /* */ /* ************************************************************************** */ #include "ClapTrap.hpp" #include "ScavTrap.hpp" int main() { ScavTrap scave; ScavTrap scave1("SCAVE_TRAP"); scave.attack("Enemy"); return 0; }
c488df37acb894fa4573135ae201309f2b71a438
9f075f47ecb22f95985add4224ae84357ce8e03c
/lib_compiler/src/compilers/unit.cpp
f6225d65541db6a64cc9a279bf29cdfd8980ce6f
[ "Zlib" ]
permissive
ApiO/pgtech
5b2a2688a43f3fe839cf5ce732766a51108b9563
e7c03ea1a269a96fca27b60a417cf4a5759d40ba
refs/heads/master
2020-05-24T18:21:53.067826
2019-05-18T22:37:25
2019-05-18T22:37:25
187,404,856
0
0
null
null
null
null
UTF-8
C++
false
false
15,095
cpp
unit.cpp
#include <runtime/types.h> #include <runtime/temp_allocator.h> #include <runtime/trace.h> #include <data/unit.h> #include <data/mover.h> #include "compiler_types.h" #include "compiler.h" namespace { using namespace pge; struct NodeKey { u64 node; u32 name; u32 parent_name; i32 parent_index; }; struct AnimsetData { struct SpriteData { u32 index; u32 first_frame; u32 num_frames; }; AnimsetData(Allocator &a) : bone_name_to_index(a), sprite_data(a), frame_names(a) {} Hash<u32> bone_name_to_index; Hash<SpriteData> sprite_data; Array<u32> frame_names; }; // make the sort keys and place the root first (node without parent) bool make_node_keys(Work &w, const Json &input, u64 nodes, Array<NodeKey> &node_keys) { const u32 num_nodes = json::size(input, nodes); array::resize(node_keys, num_nodes); i32 iroot = -1; for (u32 i = 0; i < num_nodes; i++) { const Json::Node &n = json::get_node(input, nodes, i); node_keys[i].node = n.id; node_keys[i].name = compiler::create_id_string(w, n.name); const char *parent = json::get_string(input, n.id, "parent", NULL); if (parent) { if (!json::has(input, nodes, parent)){ LOG("The node named \"%s\" could not be found", parent); return false; } } else { if (iroot >= 0){ LOG("Only one root can be defined. Please attach the \"%s\" node to another node", n.name); return false; } iroot = i; parent = "root"; } node_keys[i].parent_name = compiler::create_id_string(w, parent); node_keys[i].parent_index = -1; } if (iroot != 0) { // swap the root with the first node NodeKey tmp = node_keys[0]; node_keys[0] = node_keys[iroot]; node_keys[iroot] = tmp; } return true; } void sort_node_keys(Array<NodeKey> &node_keys) { const u32 num_nodes = array::size(node_keys); u32 num_sorted = 1; // root is already first for (u32 i = 0; i < num_nodes; i++) { u32 parent_name = node_keys[i].name; u32 parent_index = i; // skip already sorted nodes while (node_keys[num_sorted].parent_name == parent_name && num_sorted < num_nodes) { node_keys[num_sorted].parent_index = parent_index; ++num_sorted; } for (u32 child = num_sorted; child < num_nodes; child++) { if (node_keys[child].parent_name == parent_name) { NodeKey tmp = node_keys[num_sorted]; node_keys[num_sorted] = node_keys[child]; node_keys[num_sorted].parent_index = parent_index; node_keys[child] = tmp; ++num_sorted; } } } } void load_animset_data(Work &w, Json &src, const char *animset_name, AnimsetData &data) { Allocator &a = *data.sprite_data._data._allocator; Json animset_doc(a, *src._string_pool); compiler::load_dependency(w, RESOURCE_TYPE_ANIMSET, animset_name, animset_doc); if (!json::has(animset_doc, json::root(animset_doc), "tracks")) return; const u64 tracks = json::get_id(animset_doc, json::root(animset_doc), "tracks"); if (json::has(animset_doc, tracks, "bone")) { const u64 bone_tracks = json::get_id(animset_doc, tracks, "bone"); const u32 num_bone_tracks = (u32)json::size(animset_doc, bone_tracks); for (u32 i = 0; i < num_bone_tracks; i++) hash::set(data.bone_name_to_index, compiler::create_id_string(w, json::get_node(animset_doc, bone_tracks, i).name), i); } if (json::has(animset_doc, tracks, "sprite")) { const u64 sprite_tracks = json::get_id(animset_doc, tracks, "sprite"); const u32 num_sprite_tracks = (u32)json::size(animset_doc, sprite_tracks); for (u32 i = 0; i < num_sprite_tracks; i++) { const Json::Node &sn = json::get_node(animset_doc, sprite_tracks, i); AnimsetData::SpriteData sd; sd.index = i; sd.num_frames = json::size(animset_doc, sn.id); sd.first_frame = array::size(data.frame_names); hash::set(data.sprite_data, compiler::create_id_string(w, sn.name), sd); array::resize(data.frame_names, sd.first_frame + sd.num_frames); for (u32 j = 0; j < sd.num_frames; j++) data.frame_names[sd.first_frame + j] = compiler::create_id_string(w, json::get_string(animset_doc, sn.id, j)); } } } bool write_nodes(Work &w, const Json &input, u64 nodes, u32 num_nodes, Hash<u32> &node_name_to_index) { TempAllocator256 ta; Array<NodeKey> node_keys(ta); UnitResource::Node rn; if (!make_node_keys(w, input, nodes, node_keys)) return false; sort_node_keys(node_keys); // put the parent before the children and set parent_index for (u32 i = 0; i < num_nodes; i++) { const NodeKey &nkey = node_keys[i]; const Json::Node &n = json::get_node(input, nkey.node); rn.name = nkey.name; rn.parent = nkey.parent_index; compiler::read_json_pose(input, n.id, rn.pose); fwrite(&rn, sizeof(UnitResource::Node), 1, w.data); hash::set(node_name_to_index, nkey.name, i); } return true; } bool write_sprites(Work &w, const Json &jsn, u64 sprites, u32 num_sprites, const Hash<u32> &node_name_to_index, Hash<u32> &sprite_name_to_index) { UnitResource::Sprite s; for (u32 i = 0; i < num_sprites; i++) { const Json::Node &node = json::get_node(jsn, sprites, i); s.name = compiler::create_id_string(w, node.name); s.tpl = compiler::create_id_string(w, json::get_string(jsn, node.id, "template")); s.node = hash::get(node_name_to_index, (u64)compiler::create_id_string(w, json::get_string(jsn, node.id, "node")), UINT_MAX); s.order = json::get_integer(jsn, node.id, "order", 0); compiler::read_json_color(jsn, node.id, s.color, "color"); compiler::read_json_pose(jsn, node.id, s.pose); if (s.node == UINT_MAX) { LOG("could not find the node named %s.", json::get_string(jsn, node.id, "node")); return false; } fwrite(&s, sizeof(UnitResource::Sprite), 1, w.data); hash::set(sprite_name_to_index, (u64)s.name, i); } return true; } void write_actors(Work &w, const Json &jsn, u64 actors, u32 num_actors, const Hash<u32> &node_name_to_index) { UnitResource::Actor actor; for (u32 i = 0; i < num_actors; i++) { const Json::Node &node = json::get_node(jsn, actors, i); actor.instance_name = compiler::create_id_string(w, node.name); actor.actor = compiler::create_id_string(w, json::get_string(jsn, node.id, "actor")); actor.node = hash::get(node_name_to_index, (u64)compiler::create_id_string(w, json::get_string(jsn, node.id, "node")), UINT_MAX); compiler::read_json_pose(jsn, node.id, actor.pose); fwrite(&actor, sizeof(UnitResource::Actor), 1, w.data); } } void write_movers(Work &w, const Json &jsn, u64 movers, u32 num_movers) { MoverResource m; for (u32 i = 0; i < num_movers; i++) { const Json::Node &n = json::get_node(jsn, movers, i); m.name = compiler::create_id_string(w, n.name); m.height = (f32)json::get_number(jsn, n.id, "height"); m.radius = (f32)json::get_number(jsn, n.id, "radius"); m.slope_limit = (f32)json::get_number(jsn, n.id, "slope_limit"); m.step_offset = (f32)json::get_number(jsn, n.id, "step_offset"); m.collision_filter = json::has(jsn, n.id, "collision_filter") ? compiler::create_id_string(w, json::get_string(jsn, n.id, "collision_filter")) : 0; m.offset[0] = 0; m.offset[1] = 0; if (json::has(jsn, n.id, "offset")) { const u64 offset = json::get_id(jsn, n.id, "offset"); m.offset[0] = (f32)json::get_number(jsn, offset, 0); m.offset[1] = (f32)json::get_number(jsn, offset, 1); } fwrite(&m, sizeof(MoverResource), 1, w.data); } } bool write_bone_tracks(Work &w, FILE *stream, const Json &jsn, u64 bone_tracks, u32 num_bone_tracks, const Hash<u32> & node_name_to_index, AnimsetData &animset_data) { for (u32 i = 0; i < num_bone_tracks; i++) { const Json::Node &node = json::get_node(jsn, bone_tracks, i); UnitResource::BoneTrack bt; bt.node = hash::get(node_name_to_index, (u64)compiler::create_id_string(w, node.name), UINT_MAX); bt.track = hash::get(animset_data.bone_name_to_index, compiler::create_id_string(w, node.value.string), UINT_MAX); if (bt.node == UINT_MAX) { LOG("could not find the node named %s.", node.name); return false; } if (bt.track == UINT_MAX) { LOG("could not find the bone track named %s.", node.value.string); return false; } fwrite(&bt, sizeof(UnitResource::BoneTrack), 1, stream); } return true; } bool write_sprite_tracks(Work &w, FILE *stream, const Json &jsn, u64 sprite_tracks, u32 num_sprite_tracks, const Hash<u32> & sprite_name_to_index, AnimsetData &animset_data) { u32 frame_offset = ftell(stream) + num_sprite_tracks * sizeof(UnitResource::SpriteTrack); // write sprite tracks for (u32 i = 0; i < num_sprite_tracks; i++) { const Json::Node &node = json::get_node(jsn, sprite_tracks, i); const u32 track_name = compiler::create_id_string(w, json::get_string(jsn, node.id, "track")); UnitResource::SpriteTrack st; st.sprite = hash::get(sprite_name_to_index, compiler::create_id_string(w, node.name), UINT_MAX); st.track = hash::has(animset_data.sprite_data, track_name) ? hash::get(animset_data.sprite_data, track_name)->index : UINT_MAX; st.frame_offset = frame_offset; if (st.sprite == UINT_MAX) { LOG("could not find the sprite named %s.", node.name); return false; } if (st.track == UINT_MAX) { LOG("could not find the sprite track named %s.", json::get_string(jsn, node.id, "track")); return false; } fwrite(&st, sizeof(UnitResource::SpriteTrack), 1, stream); const u32 num_frames = json::has(jsn, node.id, "frames") ? json::size(jsn, node.id, "frames") : 0; frame_offset += num_frames * sizeof(u16); } TempAllocator512 ta; Hash<u16> sf(ta); // write sprite track frames for (u32 i = 0; i < num_sprite_tracks; i++) { const Json::Node &node = json::get_node(jsn, sprite_tracks, i); const AnimsetData::SpriteData *sd = hash::get(animset_data.sprite_data, compiler::create_id_string(w, json::get_string(jsn, node.id, "track"))); const u64 sprite_frames = json::has(jsn, node.id, "frames") ? json::get_id(jsn, node.id, "frames") : json::NO_NODE; const u32 num_frames = sprite_frames != json::NO_NODE ? json::size(jsn, sprite_frames) : 0; hash::reserve(sf, num_frames); for (u16 j = 0; j < num_frames; j++) hash::set(sf, compiler::create_id_string(w, json::get_string(jsn, sprite_frames, j)), j); for (u32 j = 0; j < sd->num_frames; j++) { u16 frame = hash::get(sf, animset_data.frame_names[sd->first_frame + j], NO_FRAME); fwrite(&frame, sizeof(u16), 1, stream); } hash::clear(sf); } return true; } } namespace pge { UnitCompiler::UnitCompiler(Allocator &a, StringPool &sp) : JsonCompiler(a, RESOURCE_TYPE_UNIT, sp) {} bool UnitCompiler::compile(Work &w) { if (!load_json(w)) return false; Hash<u32> node_name_to_index(*a); Hash<u32> sprite_name_to_index(*a); const u64 root = json::root(jsn); const u64 nodes = json::get_id(jsn, root, "nodes"); const u64 actors = json::has(jsn, root, "actors") ? json::get_id(jsn, root, "actors") : json::NO_NODE; const u64 sprites = json::has(jsn, root, "sprites") ? json::get_id(jsn, root, "sprites") : json::NO_NODE; const u64 movers = json::has(jsn, root, "movers") ? json::get_id(jsn, root, "movers") : json::NO_NODE; const u64 animations = json::has(jsn, root, "animations") ? json::get_id(jsn, root, "animations") : json::NO_NODE; const u64 bone_tracks = json::has(jsn, animations, "bones") ? json::get_id(jsn, animations, "bones") : json::NO_NODE; const u64 sprite_tracks = json::has(jsn, animations, "sprites") ? json::get_id(jsn, animations, "sprites") : json::NO_NODE; UnitResource unit; unit.num_nodes = nodes == json::NO_NODE ? 0 : json::size(jsn, nodes); unit.num_actors = actors == json::NO_NODE ? 0 : json::size(jsn, actors); unit.num_sprites = sprites == json::NO_NODE ? 0 : json::size(jsn, sprites); unit.num_movers = movers == json::NO_NODE ? 0 : json::size(jsn, movers); unit.num_bone_tracks = bone_tracks == json::NO_NODE ? 0 : (u16)json::size(jsn, bone_tracks); unit.num_sprite_tracks = sprite_tracks == json::NO_NODE ? 0 : (u16)json::size(jsn, sprite_tracks); unit.animation_set = animations == json::NO_NODE ? 0 : compiler::create_id_string(w, json::get_string(jsn, animations, "set")); unit._actor_offset = sizeof(UnitResource)+(sizeof(UnitResource::Node) * unit.num_nodes); unit._sprite_offset = unit._actor_offset + (sizeof(UnitResource::Actor) * unit.num_actors); unit._mover_offset = unit._sprite_offset + (sizeof(UnitResource::Sprite) * unit.num_sprites); unit._bone_track_offset = unit._mover_offset + (sizeof(MoverResource)* unit.num_movers); unit._sprite_track_offset = unit._bone_track_offset + (sizeof(UnitResource::BoneTrack) * unit.num_bone_tracks); fwrite(&unit, sizeof(UnitResource), 1, w.data); if (!write_nodes(w, jsn, nodes, unit.num_nodes, node_name_to_index)) return false; write_actors(w, jsn, actors, unit.num_actors, node_name_to_index); if (!write_sprites(w, jsn, sprites, unit.num_sprites, node_name_to_index, sprite_name_to_index)) return false; /* if (strstr(w.src, "spineboy.pgunit")) { u32 index = *hash::get(node_name_to_index, compiler::create_id_string(w, "left_hand")); printf("%u\n", index); index = *hash::get(node_name_to_index, compiler::create_id_string(w, "right_hand")); printf("%u\n", index); } //*/ write_movers(w, jsn, movers, unit.num_movers); if (!unit.animation_set) return true; { AnimsetData ad(*a); load_animset_data(w, jsn, json::get_string(jsn, animations, "set"), ad); if (!write_bone_tracks(w, w.data, jsn, bone_tracks, unit.num_bone_tracks, node_name_to_index, ad)) return false; if (!write_sprite_tracks(w, w.data, jsn, sprite_tracks, unit.num_sprite_tracks, sprite_name_to_index, ad)) return false; } return true; } }
0fac9365b3a095e760242abe70f050f57b50b42a
10960f5be99deb61080b8a7ea800e00b17c17cca
/sparse_hough2d.cpp
32b1a3d943c477b8a256f7822e3315c3f236e848
[ "MIT" ]
permissive
Steve132/sphough
6e1f3991512e0c2d7df26659931cc2a382919664
e65d4fb2d0d674fb904af61c95204ab1876c2000
refs/heads/master
2023-01-01T13:06:39.795556
2020-10-14T18:48:24
2020-10-14T18:48:24
258,442,292
2
0
null
null
null
null
UTF-8
C++
false
false
3,514
cpp
sparse_hough2d.cpp
#include "sparse_hough2d.hpp" #include<vector> #include<iostream> #include<cmath> typedef std::array<size_t,2> p2i_t; static std::vector<p2i_t> find_all_window_points(const std::vector<bool>& f, const std::array<size_t,2>& fshape, const std::array<size_t,2>& shape, const std::array<size_t,2>& offset) { std::vector<p2i_t> points; points.reserve(shape[0]*shape[1]/64); for(size_t y=0;y<shape[1];y++) for(size_t x=0;x<shape[0];x++) { p2i_t lp{x+offset[0],y+offset[1]}; if(f[fshape[0]*lp[1]+lp[0]]) { points.push_back(p2i_t{lp[0],lp[1]}); } } return points; } static inline float atan_fast(float x) { return x+0.273f*x*(1.0f-std::abs(x)); } static inline float acos_fast(float x) { float negate = static_cast<float>(x < 0); x = std::fabs(x); float ret = -0.0187293; ret = ret * x; ret = ret + 0.0742610; ret = ret * x; ret = ret - 0.2121144; ret = ret * x; ret = ret + 1.5707288; ret = ret * sqrtf(1.0-x); ret = ret - 2 * negate * ret; return negate * 3.14159265358979 + ret; //this can be vectorized. } static inline p2i_t write_to_theta_rho( const p2i_t& v1, const p2i_t& v2, float theta_scale, float rho_scale) { float x=(float)v2[0]; float y=(float)v2[1]; float dx=x-(float)v1[0]; float dy=y-(float)v1[1]; float sf=1.0/sqrt(dx*dx+dy*dy); float a=-dy; float b=dx; if(b < 0.0f) { b=-b;a=-a; } float c=fabs((a*x+b*y)*sf); //actually we can guarantee that b is positive so we have to negate c it to make sure rho is positive. float t=acosf(a*sf); t*=theta_scale; c*=rho_scale; p2i_t out{static_cast<size_t>(t),static_cast<size_t>(c)}; return out; } void sparse_hough2d_lines::pairwise_hough(const std::vector<std::array<size_t,2>>& vin,std::vector<size_t>& ho) { const size_t N=vin.size(); for(size_t i=0;i<N;i++) { for(size_t j=0;j<i;j++) { p2i_t v1=vin[i]; p2i_t v2=vin[j]; p2i_t out=write_to_theta_rho(v1,v2,theta_scale,rho_scale); ho[out[1]*theta_n+out[0]]++; //size_t vp=out[0] | (out[1] << 32); //this doesn't work on 32 bit platforms! //ho.push_back(vp); } } } std::vector<std::array<size_t,2>> sparse_hough2d_lines::get_windows(size_t windowsize,size_t overlap_pixels) const { std::vector<std::array<size_t,2>> windows_out; size_t increment_amount=windowsize-overlap_pixels; for(size_t y=0;(y+windowsize) <= shape[1];y+=increment_amount) for(size_t x=0;(x+windowsize) <= shape[0];x+=increment_amount) { windows_out.push_back(p2i_t{x,y}); } return windows_out; } void sparse_hough2d_lines::load_hough() { const size_t N=windows.size(); //std::vector<size_t> hcache; write_to_theta_rho(p2i_t{25,0},p2i_t{1,25},theta_scale,rho_scale); for(size_t i=0;i<N;i++) { std::vector<p2i_t> wp=find_all_window_points(samples,shape,{windowsize,windowsize},windows[i]); //std::cerr << "Window " << windows[i][0] << "," << windows[i][1] << std::endl; pairwise_hough(wp,hough_out); } } sparse_hough2d_lines::sparse_hough2d_lines( const std::array<size_t,2>& tshape, const std::array<size_t,2>& ttheta_rho_shape,size_t twindowsize,size_t toverlap_pixels): samples(tshape[0]*tshape[1]), theta_n(ttheta_rho_shape[0]), rho_n(ttheta_rho_shape[1]), shape(tshape), windowsize(twindowsize) { rho_max=tshape[0]+tshape[1]; if(rho_n==0) { rho_n=static_cast<size_t>(rho_max); } if(theta_n==0) { theta_n=1800; } rho_scale=(rho_n-1)/rho_max; theta_scale=(theta_n-1)/M_PI; hough_out.resize(theta_n*rho_n,0); windows=get_windows(windowsize,toverlap_pixels); }
76510048f215e48d5140fd9b4ee1535324ce1dd9
7f25ac596812ed201f289248de52d8d616d81b93
/QAsQ/CF/724A - Checking the Calendar.cpp
da9b13c3fecedb21bbd03166c647c946ba151a29
[]
no_license
AplusB/ACEveryDay
dc6ff890f9926d328b95ff536abf6510cef57eb7
e958245213dcdba8c7134259a831bde8b3d511bb
refs/heads/master
2021-01-23T22:15:34.946922
2018-04-07T01:45:20
2018-04-07T01:45:20
58,846,919
25
49
null
2016-07-14T10:38:25
2016-05-15T06:08:55
C++
UTF-8
C++
false
false
591
cpp
724A - Checking the Calendar.cpp
#include<bits/stdc++.h> using namespace std; const int mon[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string wek[7] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}; int gid(string v){ for(int i=0;i<7;i++){ if(wek[i] == v) return i; } return -1; } bool check(int st,int ed){ for(int i=0;i+1<12;i++){ if((st+mon[i]) % 7 == ed) return true; } return false; } int main(){ string st,ed; cin>>st>>ed; if(check(gid(st),gid(ed))) cout<<"YES"; else cout<<"NO"; return 0; }
48197458be50a05d6e4dbf8cef970c5dff437388
12f8c029739c95c27435d44cd449d4feaf450f14
/Dungeon/Dungeon/GameOverKeyEvent.cpp
5cfe6f802db6cca5068471dc416d108baf49eaa0
[]
no_license
kagakububutyou/Siv3D
9851bded0aaba059d8293c184a8e26840efa9dfa
65a9dc76288237782de0fceccebc92afd5dd1ef6
refs/heads/master
2021-01-21T02:28:06.055792
2015-02-02T10:04:01
2015-02-02T10:04:01
21,087,796
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
GameOverKeyEvent.cpp
#include "GameOverKeyEvent.h" #include "Scene.h" #include "CharacterController.h" CGameOverKeyEvent::CGameOverKeyEvent() { } void CGameOverKeyEvent::ChangSceneMenu(std::shared_ptr<CSceneManager> scene) { //if (CharacterController::ChangeSceneKey()) if (Input::KeyC.clicked) { scene->ChangeScene(CSceneManager::Scene::Clear); } }
d4a5b1a5c887fdeb1e992ca9f77008be332d6086
f183719315d32b82b3658851d215b3d9d3f3c909
/046_Permutation_II.cpp
0edc1dfcff3e9342cce71de44be10226a8123202
[]
no_license
ashishskore/Leetcode
520bb19efa8cb86ece231aec9b7ca51c3a4d0f9e
18e81d1e7100d632c477b47549a64bab3f41e513
refs/heads/master
2023-05-07T04:58:28.389484
2021-05-28T11:10:14
2021-05-28T11:10:14
278,268,390
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
046_Permutation_II.cpp
/* Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] */ class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> vv; sort(nums.begin(), nums.end()); do{ vv.emplace_back(nums); } while(next_permutation(nums.begin(), nums.end())); return vv; } };
d8be75b4159897f9152ac71d12c391818d221536
f5553b723ea9ef30d9f403d4939145e7b598c9dc
/src/memory/registers/nr52.hh
88723b10a8e24e40e4276878647687dc361eda10
[]
no_license
fmichea/nebula
494681679cb27334647a9eb784c2a5d81313dced
2a20880511abec1f7cf3f5c7ddee0a304e7798a6
refs/heads/master
2021-01-25T12:19:44.481334
2016-10-23T13:42:06
2016-10-23T13:42:06
23,530,762
0
1
null
2015-03-31T01:54:01
2014-09-01T04:38:48
C++
UTF-8
C++
false
false
629
hh
nr52.hh
#ifndef NEBULA_MEMORY_REGISTERS_NR52_HH_ # define NEBULA_MEMORY_REGISTERS_NR52_HH_ # include "bitproxy.hh" # include "register.hh" # include "../../sound/constants.hh" class NR52Proxy : public RegisterProxy { public: NR52Proxy() : RegisterProxy() {} NR52Proxy(uint8_t* reg, uint16_t addr) : RegisterProxy(reg, addr) { this->sound_on = BitProxy(reg, 7, 0x1); for (unsigned int it = 0; it < NB_GB_CHANNELS; ++it) this->channel_on[it] = BitProxy(reg, it, 0x1); } BitProxy sound_on; BitProxy channel_on[NB_GB_CHANNELS]; }; #endif // !NEBULA_MEMORY_REGISTERS_NR52_HH_
797dd5ab12cbead8c4a9797c36fc5d64f58a891c
3e95c68b54231bb1482c4593dba87399d032db09
/src/selection.cxx
24602d59e33197f97379cdbb34e86a78c7cfb367
[]
no_license
mstoev/BaconJets
64a4159ab57a66c6136dbe34da1fdacc8fe0fef2
d66e5fadaf8248a734ffb8ab996e5e6a40e7efd7
refs/heads/master
2020-12-25T11:15:38.066429
2015-05-13T07:48:21
2015-05-13T07:48:21
32,583,517
0
0
null
2015-03-20T12:53:18
2015-03-20T12:53:18
null
UTF-8
C++
false
false
5,309
cxx
selection.cxx
#include "UHH2/BaconJets/include/selection.h" #include "UHH2/bacondataformats/interface/TJet.hh" #include "UHH2/bacondataformats/interface/TVertex.hh" namespace uhh2bacon { Selection::Selection(uhh2::Context & ctx) : context(ctx), event(0) { h_jets = context.declare_event_input<TClonesArray>("Jet05"); h_eventInfo = context.declare_event_input<baconhep::TEventInfo>("Info"); h_pv = context.declare_event_input<TClonesArray>("PV"); // h_jets = context.declare_event_autput<TClonesArray>("Jet05"); // h_eventInfo = context.declare_event_autput<baconhep::TEventInfo>("Info"); } void Selection::SetEvent(uhh2::Event& evt) { event = &evt; assert(event); } bool Selection::Trigger() { assert(event); const TClonesArray & js = event->get(h_jets); const baconhep::TEventInfo & info = event->get(h_eventInfo); // const baconhep::TJet * jet = dynamic_cast<const baconhep::TJet*>(js[0]); // assert(jet); baconhep::TEventInfo* eventInfo= new baconhep::TEventInfo(info); assert(eventInfo); baconhep::TJet* jet1 = (baconhep::TJet*)js[0]; baconhep::TJet* jet2 = (baconhep::TJet*)js[1]; double avePt = (jet1->pt + jet2->pt)/2; bool trigger40fired = false; bool trigger80fired = false; bool trigger140fired = false; bool trigger200fired = false; bool trigger260fired = false; bool trigger320fired = false; bool trigger400fired = false; if(eventInfo->triggerBits[0]==1) trigger40fired = true; if(eventInfo->triggerBits[1]==1) trigger80fired = true; if(eventInfo->triggerBits[2]==1) trigger140fired = true; if(eventInfo->triggerBits[3]==1) trigger200fired = true; if(eventInfo->triggerBits[4]==1) trigger260fired = true; if(eventInfo->triggerBits[5]==1) trigger320fired = true; if(eventInfo->triggerBits[6]==1) trigger400fired = true; if (avePt < 66) return false; if (avePt >= 66 && avePt < 107 && trigger40fired) return true; if (avePt >= 107 && avePt < 191 && trigger80fired) return true; if (avePt >= 191 && avePt < 240 && trigger140fired) return true; if (avePt >= 240 && avePt < 306 && trigger200fired) return true; if (avePt >= 306 && avePt < 379 && trigger260fired) return true; if (avePt >= 379 && avePt < 468 && trigger320fired) return true; if (avePt >= 468 && trigger400fired) return true; // double triggerThreshold[6] = {92,157,218,280,346,432}; // bool trigger_fired = false; // for (int j = 1; j < 7; j++) { // if(eventInfo->triggerBits[j]==1) { // if(avePt < triggerThreshold[j-1]){ // trigger_fired = true; // break; // } // } // } // if(eventInfo->triggerBits.none() || !trigger_fired) return false; return false; } bool Selection::DiJet() { assert(event); const TClonesArray & js = event->get(h_jets); const baconhep::TEventInfo & info = event->get(h_eventInfo); baconhep::TEventInfo* eventInfo= new baconhep::TEventInfo(info); assert(eventInfo); // const baconhep::TJet * jet = dynamic_cast<const baconhep::TJet*>(js[0]); // assert(jet); int njets = js.GetEntries(); // njets >= 2 if (njets>=2) return true; //std::cout << eventInfo->triggerBits << std::endl; return false; } bool Selection::DiJetAdvanced() { assert(event); const TClonesArray & js = event->get(h_jets); // const baconhep::TJet * jet = dynamic_cast<const baconhep::TJet*>(js[0]); // assert(jet); int njets = js.GetEntries(); // njets >= 2 if (njets<2) return false; baconhep::TJet* jet1 = (baconhep::TJet*)js[0]; baconhep::TJet* jet2 = (baconhep::TJet*)js[1]; // at least one barrel jet if((fabs(jet1->eta)>=1.3) && (fabs(jet2->eta)>=1.3)) return false; // delta phi < 2.7 double deltaPhi = std::min(std::abs(double(jet1->phi) - double(jet2->phi)),2*M_PI-std::abs(jet2->phi - jet1->phi)); if (deltaPhi < 2.7) return false; // |asymm| < 0.7 if (fabs((jet2->pt - jet1->pt) / (jet2->pt + jet1->pt)) > 0.7) return false; // p_t,rel < 0.2 if (njets>2){ baconhep::TJet* jet3 = (baconhep::TJet*)js[2]; //if ((2*(jet3->pt))/(jet1->pt + jet2->pt) > 0.2) return false; } return true; } bool Selection::goodPVertex() { assert(event); const baconhep::TEventInfo & info = event->get(h_eventInfo); baconhep::TEventInfo* eventInfo= new baconhep::TEventInfo(info); const TClonesArray & pvs = event->get(h_pv); // std::cout << "good prim vertex = "<< eventInfo->pvz<<std::endl; Int_t nvertices = pvs.GetEntries(); //std::cout << "1 number of vertex = "<< nvertices<<std::endl; // require in the event that there is at least one reconstructed vertex if(nvertices<=0) return false; float nPrVer = 0; // pick the first (i.e. highest sum pt) verte //const reco::Vertex* theVertex=&(vertices_h->front()); for (int i=0; i<nvertices; i++){ baconhep::TVertex* vertices = (baconhep::TVertex*)pvs[i]; // require that the vertex meets certain criteria if((vertices->ndof>5) && (fabs(vertices->z)<24.0) && (vertices->chi2>0.05)){ nPrVer++; // std::cout << "prim vertex = "<< vertices->z<<std::endl; } } //std::cout << "2 number of vertex = "<< nPrVer<<std::endl; return true; } bool Selection::FullSelection() { return Trigger()&&DiJet()&&DiJetAdvanced()&&goodPVertex(); } Selection::~Selection() { } }
88d207fc97431bfbf8e81a23742ff7ddf0250d96
1ef14a2a52d6844bd931f80a556629f5f9c11349
/goopdate/config_manager_unittest.cc
0f9684c4690f3b4ebe813f03e4ce9b0cb3326fb8
[ "Apache-2.0" ]
permissive
pauldotknopf/omaha
c61a58dee395a70e658f53a7b33cefab9fed5eb6
7f70869253aeebadb4f52db5306bde5571d71524
refs/heads/master
2020-04-11T12:21:03.800672
2011-08-17T01:07:48
2011-08-17T01:07:48
32,242,630
1
0
null
null
null
null
UTF-8
C++
false
false
73,461
cc
config_manager_unittest.cc
// Copyright 2007-2010 Google 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. // ======================================================================== #include <limits.h> #include "omaha/common/const_addresses.h" #include "omaha/common/constants.h" #include "omaha/common/file.h" #include "omaha/common/reg_key.h" #include "omaha/common/string.h" #include "omaha/common/system_info.h" #include "omaha/common/time.h" #include "omaha/common/utils.h" #include "omaha/common/vistautil.h" #include "omaha/goopdate/config_manager.h" #include "omaha/goopdate/const_goopdate.h" #include "omaha/testing/unit_test.h" namespace omaha { namespace { #define APP_GUID1 _T("{6762F466-8863-424f-817C-5757931F346E}") const TCHAR* const kAppGuid1 = APP_GUID1; const TCHAR* const kAppMachineClientStatePath1 = _T("HKLM\\Software\\Google\\Update\\ClientState\\") APP_GUID1; const TCHAR* const kAppUserClientStatePath1 = _T("HKCU\\Software\\Google\\Update\\ClientState\\") APP_GUID1; const TCHAR* const kAppMachineClientStateMediumPath1 = _T("HKLM\\Software\\Google\\Update\\ClientStateMedium\\") APP_GUID1; #define APP_GUID2 _T("{8A0FDD16-D4B7-4167-893F-1386F2A2F0FB}") const TCHAR* const kAppGuid2 = APP_GUID2; const TCHAR* const kAppMachineClientStatePath2 = _T("HKLM\\Software\\Google\\Update\\ClientState\\") APP_GUID2; const TCHAR* const kAppUserClientStatePath2 = _T("HKCU\\Software\\Google\\Update\\ClientState\\") APP_GUID2; const TCHAR* const kPolicyKey = _T("HKLM\\Software\\Policies\\Google\\Update\\"); const TCHAR* const kInstallPolicyApp1 = _T("Install") APP_GUID1; const TCHAR* const kInstallPolicyApp2 = _T("Install") APP_GUID2; const TCHAR* const kUpdatePolicyApp1 = _T("Update") APP_GUID1; const TCHAR* const kUpdatePolicyApp2 = _T("Update") APP_GUID2; // Helper to write policies to the registry. Eliminates ambiguity of which // overload of SetValue to use without the need for static_cast. HRESULT SetPolicy(const TCHAR* policy_name, DWORD value) { return RegKey::SetValue(kPolicyKey, policy_name, value); } } // namespace class ConfigManagerNoOverrideTest : public testing::Test { protected: ConfigManagerNoOverrideTest() : cm_(ConfigManager::Instance()) { } bool CanInstallApp(const TCHAR* guid) { return cm_->CanInstallApp(StringToGuid(guid)); } bool CanUpdateApp(const TCHAR* guid, bool is_manual) { return cm_->CanUpdateApp(StringToGuid(guid), is_manual); } ConfigManager* cm_; }; class ConfigManagerTest : public ConfigManagerNoOverrideTest { protected: ConfigManagerTest() : hive_override_key_name_(kRegistryHiveOverrideRoot) { } virtual void SetUp() { RegKey::DeleteKey(hive_override_key_name_, true); OverrideRegistryHives(hive_override_key_name_); } virtual void TearDown() { RestoreRegistryHives(); EXPECT_SUCCEEDED(RegKey::DeleteKey(hive_override_key_name_, true)); } void CanCollectStatsHelper(bool is_machine); void CanCollectStatsIgnoresOppositeHiveHelper(bool is_machine); HRESULT SetFirstInstallTime(bool is_machine, DWORD time); HRESULT DeleteFirstInstallTime(bool is_machine); HRESULT SetUpdateTime(bool is_machine, DWORD time); HRESULT DeleteUpdateTime(bool is_machine); CString hive_override_key_name_; }; void ConfigManagerTest::CanCollectStatsHelper(bool is_machine) { const TCHAR* app1_state_key_name = is_machine ? kAppMachineClientStatePath1 : kAppUserClientStatePath1; EXPECT_FALSE(cm_->CanCollectStats(is_machine)); // Test the 'UsageStats' override. EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueForceUsageStats, _T(""))); EXPECT_TRUE(cm_->CanCollectStats(is_machine)); EXPECT_SUCCEEDED(RegKey::DeleteValue(MACHINE_REG_UPDATE_DEV, kRegValueForceUsageStats)); DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(app1_state_key_name, _T("usagestats"), val)); EXPECT_TRUE(cm_->CanCollectStats(is_machine)); val = 2; // invalid value EXPECT_SUCCEEDED(RegKey::SetValue(app1_state_key_name, _T("usagestats"), val)); EXPECT_FALSE(cm_->CanCollectStats(is_machine)); val = 0; EXPECT_SUCCEEDED(RegKey::SetValue(app1_state_key_name, _T("usagestats"), val)); EXPECT_FALSE(cm_->CanCollectStats(is_machine)); // One 0 and one 1 results in true. The alphabetical order of the GUIDs is // important assuming GetSubkeyNameAt returns subkeys in alphabetical order. const TCHAR* app2_state_key_name = is_machine ? kAppMachineClientStatePath2 : kAppUserClientStatePath2; val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(app2_state_key_name, _T("usagestats"), val)); EXPECT_TRUE(cm_->CanCollectStats(is_machine)); } void ConfigManagerTest::CanCollectStatsIgnoresOppositeHiveHelper( bool is_machine) { const TCHAR* app1_state_key_name = is_machine ? kAppMachineClientStatePath1 : kAppUserClientStatePath1; EXPECT_FALSE(cm_->CanCollectStats(is_machine)); DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(app1_state_key_name, _T("usagestats"), val)); EXPECT_TRUE(cm_->CanCollectStats(is_machine)); EXPECT_FALSE(cm_->CanCollectStats(!is_machine)); } HRESULT ConfigManagerTest::SetFirstInstallTime(bool is_machine, DWORD time) { return RegKey::SetValue(cm_->registry_client_state_goopdate(is_machine), kRegValueInstallTimeSec, time); } HRESULT ConfigManagerTest::DeleteFirstInstallTime(bool is_machine) { if (!RegKey::HasValue(cm_->registry_client_state_goopdate(is_machine), kRegValueInstallTimeSec)) { return S_OK; } return RegKey::DeleteValue(cm_->registry_client_state_goopdate(is_machine), kRegValueInstallTimeSec); } HRESULT ConfigManagerTest::SetUpdateTime(bool is_machine, DWORD time) { return RegKey::SetValue(cm_->registry_client_state_goopdate(is_machine), kRegValueLastUpdateTimeSec, time); } HRESULT ConfigManagerTest::DeleteUpdateTime(bool is_machine) { if (!RegKey::HasValue(cm_->registry_client_state_goopdate(is_machine), kRegValueLastUpdateTimeSec)) { return S_OK; } return RegKey::DeleteValue(cm_->registry_client_state_goopdate(is_machine), kRegValueLastUpdateTimeSec); } TEST_F(ConfigManagerNoOverrideTest, RegistryKeys) { EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\Clients\\"), cm_->user_registry_clients()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\Clients\\"), cm_->machine_registry_clients()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\Clients\\"), cm_->registry_clients(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\Clients\\"), cm_->registry_clients(true)); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\Clients\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->user_registry_clients_goopdate()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\Clients\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->machine_registry_clients_goopdate()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\Clients\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->registry_clients_goopdate(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\Clients\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->registry_clients_goopdate(true)); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\ClientState\\"), cm_->user_registry_client_state()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\ClientState\\"), cm_->machine_registry_client_state()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\ClientState\\"), cm_->registry_client_state(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\ClientState\\"), cm_->registry_client_state(true)); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\ClientState\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->user_registry_client_state_goopdate()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\ClientState\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->machine_registry_client_state_goopdate()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\ClientState\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->registry_client_state_goopdate(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\ClientState\\") _T("{430FD4D0-B729-4F61-AA34-91526481799D}"), cm_->registry_client_state_goopdate(true)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\ClientStateMedium\\"), cm_->machine_registry_client_state_medium()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\"), cm_->user_registry_update()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\"), cm_->machine_registry_update()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\Update\\"), cm_->registry_update(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\Update\\"), cm_->registry_update(true)); EXPECT_STREQ(_T("HKCU\\Software\\Google\\"), cm_->user_registry_google()); EXPECT_STREQ(_T("HKLM\\Software\\Google\\"), cm_->machine_registry_google()); EXPECT_STREQ(_T("HKCU\\Software\\Google\\"), cm_->registry_google(false)); EXPECT_STREQ(_T("HKLM\\Software\\Google\\"), cm_->registry_google(true)); } TEST_F(ConfigManagerNoOverrideTest, GetUserCrashReportsDir) { const CString expected_path = GetGoogleUserPath() + _T("CrashReports"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetUserCrashReportsDir()); EXPECT_TRUE(File::Exists(expected_path)); } // Should run before the subdirectory tests to ensure the directory is created. TEST_F(ConfigManagerNoOverrideTest, GetUserGoopdateInstallDir) { const CString expected_path = GetGoogleUserPath() + _T("Update"); EXPECT_STREQ(expected_path, cm_->GetUserGoopdateInstallDir()); EXPECT_TRUE(File::Exists(expected_path)); } TEST_F(ConfigManagerNoOverrideTest, GetDownloadStorage) { const CString expected_path = GetGoogleUpdateUserPath() + _T("Download"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetUserDownloadStorageDir()); EXPECT_TRUE(File::Exists(expected_path)); } TEST_F(ConfigManagerNoOverrideTest, GetUserDownloadStorageDir) { const CString expected_path = GetGoogleUpdateUserPath() + _T("Download"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetUserDownloadStorageDir()); EXPECT_TRUE(File::Exists(expected_path)); } TEST_F(ConfigManagerNoOverrideTest, GetUserOfflineStorageDir) { const CString expected_path = GetGoogleUpdateUserPath() + _T("Offline"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetUserOfflineStorageDir()); EXPECT_TRUE(File::Exists(expected_path)); } TEST_F(ConfigManagerNoOverrideTest, IsRunningFromUserGoopdateInstallDir) { EXPECT_FALSE(cm_->IsRunningFromUserGoopdateInstallDir()); } TEST_F(ConfigManagerNoOverrideTest, GetMachineCrashReportsDir) { CString program_files; EXPECT_SUCCEEDED(GetFolderPath(CSIDL_PROGRAM_FILES, &program_files)); const CString expected_path = program_files + _T("\\Google\\CrashReports"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetMachineCrashReportsDir()); EXPECT_TRUE(File::Exists(expected_path) || !vista_util::IsUserAdmin()); } // Should run before the subdirectory tests to ensure the directory is created. TEST_F(ConfigManagerNoOverrideTest, GetMachineGoopdateInstallDir) { CString expected_path = GetGoogleUpdateMachinePath(); EXPECT_STREQ(expected_path, cm_->GetMachineGoopdateInstallDir()); EXPECT_TRUE(File::Exists(expected_path) || !vista_util::IsUserAdmin()); } TEST_F(ConfigManagerNoOverrideTest, GetMachineSecureDownloadStorageDir) { CString expected_path = GetGoogleUpdateMachinePath() + _T("\\Download"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetMachineSecureDownloadStorageDir()); EXPECT_TRUE(File::Exists(expected_path) || !vista_util::IsUserAdmin()); } TEST_F(ConfigManagerNoOverrideTest, GetMachineSecureOfflineStorageDir) { CString expected_path = GetGoogleUpdateMachinePath() + _T("\\Offline"); EXPECT_SUCCEEDED(DeleteDirectory(expected_path)); EXPECT_STREQ(expected_path, cm_->GetMachineSecureOfflineStorageDir()); EXPECT_TRUE(File::Exists(expected_path) || !vista_util::IsUserAdmin()); } TEST_F(ConfigManagerNoOverrideTest, IsRunningFromMachineGoopdateInstallDir) { EXPECT_FALSE(cm_->IsRunningFromMachineGoopdateInstallDir()); } // Tests the GetUpdateCheckUrl override. TEST_F(ConfigManagerTest, GetUpdateCheckUrl) { CString url; EXPECT_SUCCEEDED(cm_->GetUpdateCheckUrl(&url)); EXPECT_STREQ(url, kUrlUpdateCheck); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueNameUrl, _T("http://foo/"))); url.Empty(); EXPECT_TRUE(url.IsEmpty()); EXPECT_SUCCEEDED(cm_->GetUpdateCheckUrl(&url)); #ifdef DEBUG EXPECT_STREQ(url, _T("http://foo/")); #else EXPECT_STREQ(url, kUrlUpdateCheck); #endif } // Tests the GetPingUrl override. TEST_F(ConfigManagerTest, GetPingUrl) { CString url; EXPECT_SUCCEEDED(cm_->GetPingUrl(&url)); EXPECT_STREQ(url, kUrlPing); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueNamePingUrl, _T("http://bar/"))); url.Empty(); EXPECT_TRUE(url.IsEmpty()); EXPECT_SUCCEEDED(cm_->GetPingUrl(&url)); #ifdef DEBUG EXPECT_STREQ(url, _T("http://bar/")); #else EXPECT_STREQ(url, kUrlPing); #endif } // Tests LastCheckPeriodSec override. TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_Default) { bool is_overridden = true; if (cm_->IsGoogler()) { EXPECT_EQ(kLastCheckPeriodGooglerSec, cm_->GetLastCheckPeriodSec(&is_overridden)); } else { EXPECT_EQ(kLastCheckPeriodSec, cm_->GetLastCheckPeriodSec(&is_overridden)); } EXPECT_FALSE(is_overridden); } TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_UpdateDevOverride) { // Zero is a special value meaning disabled. DWORD val = 0; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec, val)); bool is_overridden = false; EXPECT_EQ(0, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); val = kMinLastCheckPeriodSec - 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec, val)); is_overridden = false; EXPECT_EQ(kMinLastCheckPeriodSec, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); val = INT_MAX + static_cast<uint32>(1); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec, val)); is_overridden = false; EXPECT_EQ(INT_MAX, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); val = 1000; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec, val)); is_overridden = false; EXPECT_EQ(1000, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); EXPECT_SUCCEEDED(RegKey::DeleteValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec)); is_overridden = true; if (cm_->IsGoogler()) { EXPECT_EQ(kLastCheckPeriodGooglerSec, cm_->GetLastCheckPeriodSec(&is_overridden)); } else { EXPECT_EQ(kLastCheckPeriodSec, cm_->GetLastCheckPeriodSec(&is_overridden)); } EXPECT_FALSE(is_overridden); } TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyOverride) { const DWORD kOverrideMinutes = 16000; const DWORD kExpectedSeconds = kOverrideMinutes * 60; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes)); bool is_overridden = false; EXPECT_EQ(kExpectedSeconds, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyOverride_TooLow) { const DWORD kOverrideMinutes = 1; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes)); bool is_overridden = false; EXPECT_EQ(kMinLastCheckPeriodSec, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyOverride_Zero) { const DWORD kOverrideMinutes = 0; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes)); bool is_overridden = false; EXPECT_EQ(0, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyOverride_Overflow_SecondsConversion) { const DWORD kOverrideMinutes = UINT_MAX; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes)); bool is_overridden = false; EXPECT_EQ(INT_MAX, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); const DWORD kOverrideMinutes2 = INT_MAX + static_cast<uint32>(1); EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes2)); is_overridden = false; EXPECT_EQ(INT_MAX, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); const DWORD kOverrideMinutes3 = 0xf0000000; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes3)); is_overridden = false; EXPECT_EQ(INT_MAX, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } // Overflow the integer but not the minutes to seconds conversion. TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyOverride_Overflow_Int) { const DWORD kOverrideMinutes = UINT_MAX / 60; EXPECT_GT(UINT_MAX, kOverrideMinutes); EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kOverrideMinutes)); bool is_overridden = false; EXPECT_EQ(INT_MAX, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } // UpdateDev takes precedence over the Group Policy override. TEST_F(ConfigManagerTest, GetLastCheckPeriodSec_GroupPolicyAndUpdateDevOverrides) { const DWORD kGroupPolicyOverrideMinutes = 100; EXPECT_SUCCEEDED(SetPolicy(_T("AutoUpdateCheckPeriodMinutes"), kGroupPolicyOverrideMinutes)); const DWORD kUpdateDevOverrideSeconds = 70; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueLastCheckPeriodSec, kUpdateDevOverrideSeconds)); bool is_overridden = false; EXPECT_EQ(kUpdateDevOverrideSeconds, cm_->GetLastCheckPeriodSec(&is_overridden)); EXPECT_TRUE(is_overridden); } // Legacy location is not checked. TEST_F(ConfigManagerTest, CanCollectStats_LegacyLocationAndName) { DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, kLegacyRegValueCollectUsageStats, val)); EXPECT_FALSE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_LegacyLocationNewName) { DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("usagestats"), val)); EXPECT_FALSE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_MachineOnly) { CanCollectStatsHelper(true); } TEST_F(ConfigManagerTest, CanCollectStats_UserOnly) { CanCollectStatsHelper(false); } // This tests that the legacy conversion is honored. TEST_F(ConfigManagerTest, CanCollectStats_GoopdateGuidIsChecked) { EXPECT_FALSE(cm_->CanCollectStats(true)); DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_CLIENT_STATE_GOOPDATE, _T("usagestats"), val)); EXPECT_TRUE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_MachineIgnoresUser) { CanCollectStatsIgnoresOppositeHiveHelper(true); } TEST_F(ConfigManagerTest, CanCollectStats_UserIgnoresMachine) { CanCollectStatsIgnoresOppositeHiveHelper(false); } // Unfortunately, the app's ClientStateMedium key is not checked if there is no // corresponding ClientState key. TEST_F(ConfigManagerTest, CanCollectStats_Machine_ClientStateMediumOnly_AppClientStateKeyMissing) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStateMediumPath1, _T("usagestats"), static_cast<DWORD>(1))); EXPECT_FALSE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_Machine_ClientStateMediumOnly_AppClientStateKeyExists) { EXPECT_SUCCEEDED(RegKey::CreateKey(kAppMachineClientStatePath1)); EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStateMediumPath1, _T("usagestats"), static_cast<DWORD>(1))); EXPECT_TRUE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_Machine_ClientStateMediumInvalid) { EXPECT_SUCCEEDED(RegKey::CreateKey(kAppMachineClientStatePath1)); EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStateMediumPath1, _T("usagestats"), static_cast<DWORD>(2))); EXPECT_FALSE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_User_ClientStateMediumOnly) { EXPECT_SUCCEEDED(RegKey::CreateKey(kAppUserClientStatePath1)); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKCU\\Software\\Google\\Update\\ClientStateMedium\\") APP_GUID1, _T("usagestats"), static_cast<DWORD>(1))); EXPECT_FALSE(cm_->CanCollectStats(false)); } TEST_F(ConfigManagerTest, CanCollectStats_Machine_ClientStateZeroClientStateMediumOne) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStatePath1, _T("usagestats"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanCollectStats(true)); EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStateMediumPath1, _T("usagestats"), static_cast<DWORD>(1))); EXPECT_TRUE(cm_->CanCollectStats(true)); } TEST_F(ConfigManagerTest, CanCollectStats_Machine_ClientStateOneClientStateMediumZero) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStatePath1, _T("usagestats"), static_cast<DWORD>(1))); EXPECT_TRUE(cm_->CanCollectStats(true)); EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStateMediumPath1, _T("usagestats"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanCollectStats(true)); } // Tests OverInstall override. TEST_F(ConfigManagerTest, CanOverInstall) { EXPECT_EQ(cm_->CanOverInstall(), !OFFICIAL_BUILD); DWORD val = 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueNameOverInstall, val)); #ifdef DEBUG EXPECT_TRUE(cm_->CanOverInstall()); #else EXPECT_EQ(!OFFICIAL_BUILD, cm_->CanOverInstall()); #endif val = 0; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueNameOverInstall, val)); #ifdef DEBUG EXPECT_FALSE(cm_->CanOverInstall()); #else EXPECT_EQ(!OFFICIAL_BUILD, cm_->CanOverInstall()); #endif } // Tests AuCheckPeriodMs override. TEST_F(ConfigManagerTest, GetAutoUpdateTimerIntervalMs) { EXPECT_EQ(cm_->IsGoogler() ? kAUCheckPeriodGooglerMs : kAUCheckPeriodMs, cm_->GetAutoUpdateTimerIntervalMs()); DWORD val = 0; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(kMinAUCheckPeriodMs, cm_->GetAutoUpdateTimerIntervalMs()); val = kMinAUCheckPeriodMs - 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(kMinAUCheckPeriodMs, cm_->GetAutoUpdateTimerIntervalMs()); val = 30000; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(val, cm_->GetAutoUpdateTimerIntervalMs()); val = INT_MAX; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(val, cm_->GetAutoUpdateTimerIntervalMs()); // Tests overflow with large positive numbers. val = INT_MAX; ++val; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(INT_MAX, cm_->GetAutoUpdateTimerIntervalMs()); val = UINT_MAX; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); EXPECT_EQ(INT_MAX, cm_->GetAutoUpdateTimerIntervalMs()); } // Tests CrCheckPeriodMs override. TEST_F(ConfigManagerTest, GetCodeRedTimerIntervalMs) { EXPECT_EQ(kCodeRedCheckPeriodMs, cm_->GetCodeRedTimerIntervalMs()); DWORD val = 0; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(kMinCodeRedCheckPeriodMs, cm_->GetCodeRedTimerIntervalMs()); val = kMinCodeRedCheckPeriodMs - 1; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(kMinCodeRedCheckPeriodMs, cm_->GetCodeRedTimerIntervalMs()); val = 60000; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(val, cm_->GetCodeRedTimerIntervalMs()); val = INT_MAX; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(val, cm_->GetCodeRedTimerIntervalMs()); // Tests overflow with large positive numbers. val = INT_MAX; ++val; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(INT_MAX, cm_->GetCodeRedTimerIntervalMs()); val = UINT_MAX; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueCrCheckPeriodMs, val)); EXPECT_EQ(INT_MAX, cm_->GetCodeRedTimerIntervalMs()); } // Tests CanLogEvents override. TEST_F(ConfigManagerTest, CanLogEvents_WithOutOverride) { EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_SUCCESS)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_ERROR_TYPE)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_WARNING_TYPE)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_INFORMATION_TYPE)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_AUDIT_SUCCESS)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_AUDIT_FAILURE)); } TEST_F(ConfigManagerTest, CanLogEvents) { EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_INFORMATION_TYPE)); DWORD val = LOG_EVENT_LEVEL_ALL; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueEventLogLevel, val)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_SUCCESS)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_ERROR_TYPE)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_WARNING_TYPE)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_INFORMATION_TYPE)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_AUDIT_SUCCESS)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_AUDIT_FAILURE)); val = LOG_EVENT_LEVEL_WARN_AND_ERROR; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueEventLogLevel, val)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_SUCCESS)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_ERROR_TYPE)); EXPECT_TRUE(cm_->CanLogEvents(EVENTLOG_WARNING_TYPE)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_INFORMATION_TYPE)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_AUDIT_SUCCESS)); EXPECT_FALSE(cm_->CanLogEvents(EVENTLOG_AUDIT_FAILURE)); } // Tests GetTestSource override. TEST_F(ConfigManagerTest, GetTestSource_Dev) { CString expected_value; #if DEBUG || !OFFICIAL_BUILD expected_value = kRegValueTestSourceAuto; #endif CString test_source = cm_->GetTestSource(); EXPECT_STREQ(expected_value, test_source); ASSERT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueTestSource, _T("dev"))); test_source = cm_->GetTestSource(); EXPECT_STREQ(_T("dev"), test_source); } TEST_F(ConfigManagerTest, GetTestSource_EmptyRegKey) { CString expected_value; #if DEBUG || !OFFICIAL_BUILD expected_value = kRegValueTestSourceAuto; #endif CString test_source = cm_->GetTestSource(); EXPECT_STREQ(expected_value, test_source); ASSERT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueTestSource, _T(""))); test_source = cm_->GetTestSource(); EXPECT_STREQ(kRegValueTestSourceAuto, test_source); } // // CanUseNetwork tests. // // Covers UpdateEulaAccepted case. TEST_F(ConfigManagerTest, CanUseNetwork_Machine_Normal) { EXPECT_TRUE(cm_->CanUseNetwork(true)); } // Covers UpdateEulaAccepted case. TEST_F(ConfigManagerTest, CanUseNetwork_User_Normal) { EXPECT_TRUE(cm_->CanUseNetwork(false)); } // These cover the not OEM install mode cases. TEST_F(ConfigManagerTest, CanUseNetwork_Machine_UpdateEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_Machine_UpdateEulaNotAccepted_AppEulaAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(1))); EXPECT_FALSE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_Machine_AppEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_TRUE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_Machine_AppEulaAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppMachineClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(1))); EXPECT_TRUE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_Machine_UserUpdateEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(USER_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_TRUE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_UpdateEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(USER_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanUseNetwork(false)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_UpdateEulaNotAccepted_AppEulaAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(USER_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_SUCCEEDED(RegKey::SetValue(kAppUserClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(1))); EXPECT_FALSE(cm_->CanUseNetwork(false)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_AppEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppUserClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_TRUE(cm_->CanUseNetwork(false)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_AppEulaAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(kAppUserClientStatePath1, _T("eulaaccepted"), static_cast<DWORD>(1))); EXPECT_TRUE(cm_->CanUseNetwork(false)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_MachineUpdateEulaNotAccepted) { EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_TRUE(cm_->CanUseNetwork(false)); } // Covers UpdateEulaAccepted case. TEST_F(ConfigManagerTest, CanUseNetwork_Machine_OemInstallTimeNow_NotAuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); EXPECT_TRUE(cm_->IsOemInstalling(true)); EXPECT_FALSE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_Machine_OemInstallTimeNow_NotAuditMode_UpdateEulaNotAccepted) { //NOLINT const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); EXPECT_TRUE(cm_->IsOemInstalling(true)); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanUseNetwork(true)); } // These cover the EULA accepted cases. TEST_F(ConfigManagerTest, CanUseNetwork_Machine_OemInstallTime73HoursAgo_NotAuditMode) { const DWORD kDesiredDifferenceSeconds = 73 * 60 * 60; // 73 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_GT(now_seconds, kDesiredDifferenceSeconds); const DWORD install_time_seconds = now_seconds - kDesiredDifferenceSeconds; EXPECT_LT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); EXPECT_FALSE(cm_->IsOemInstalling(true)); EXPECT_TRUE(cm_->CanUseNetwork(true)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_OemInstallTimeNow_AuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_FALSE(cm_->IsOemInstalling(false)); EXPECT_TRUE(cm_->CanUseNetwork(false)); } TEST_F(ConfigManagerTest, CanUseNetwork_User_OemInstallTimeNow_AuditMode_UpdateEulaNotAccepted) { //NOLINT const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_FALSE(cm_->IsOemInstalling(false)); EXPECT_SUCCEEDED(RegKey::SetValue(USER_REG_UPDATE, _T("eulaaccepted"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->CanUseNetwork(false)); } // // IsOemInstalling tests. // TEST_F(ConfigManagerTest, IsOemInstalling_Machine_Normal) { EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_User_Normal) { EXPECT_FALSE(cm_->IsOemInstalling(false)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeNow_NotAuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeNow_AuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime71HoursAgo_NotAuditMode) { const DWORD kDesiredDifferenceSeconds = 71 * 60 * 60; // 71 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_GT(now_seconds, kDesiredDifferenceSeconds); const DWORD install_time_seconds = now_seconds - kDesiredDifferenceSeconds; EXPECT_LT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime71HoursAgo_AuditMode) { const DWORD kDesiredDifferenceSeconds = 71 * 60 * 60; // 71 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_GT(now_seconds, kDesiredDifferenceSeconds); const DWORD install_time_seconds = now_seconds - kDesiredDifferenceSeconds; EXPECT_LT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime73HoursAgo_NotAuditMode) { const DWORD kDesiredDifferenceSeconds = 73 * 60 * 60; // 73 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_GT(now_seconds, kDesiredDifferenceSeconds); const DWORD install_time_seconds = now_seconds - kDesiredDifferenceSeconds; EXPECT_LT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime73HoursAgo_AuditMode) { const DWORD kDesiredDifferenceSeconds = 73 * 60 * 60; // 73 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_GT(now_seconds, kDesiredDifferenceSeconds); const DWORD install_time_seconds = now_seconds - kDesiredDifferenceSeconds; EXPECT_LT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime71HoursInFuture_NotAuditMode) { const DWORD kDesiredDifferenceSeconds = 71 * 60 * 60; // 71 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); const DWORD install_time_seconds = now_seconds + kDesiredDifferenceSeconds; EXPECT_GT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime71HoursInFuture_AuditMode) { const DWORD kDesiredDifferenceSeconds = 71 * 60 * 60; // 71 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); const DWORD install_time_seconds = now_seconds + kDesiredDifferenceSeconds; EXPECT_GT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_TRUE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime73HoursInFuture_NotAuditMode) { const DWORD kDesiredDifferenceSeconds = 73 * 60 * 60; // 73 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); const DWORD install_time_seconds = now_seconds + kDesiredDifferenceSeconds; EXPECT_GT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTime73HoursInFuture_AuditMode) { const DWORD kDesiredDifferenceSeconds = 73 * 60 * 60; // 73 hours. const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); const DWORD install_time_seconds = now_seconds + kDesiredDifferenceSeconds; EXPECT_GT(install_time_seconds, now_seconds); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), install_time_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeZero_NotAuditMode) { EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), static_cast<DWORD>(0))); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeZero_AuditMode) { EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), static_cast<DWORD>(0))); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeWrongType_NotAuditMode) { const uint32 now_seconds = Time64ToInt32(GetCurrent100NSTime()); const CString now_string = itostr(now_seconds); EXPECT_FALSE(now_string.IsEmpty()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_string)); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_OemInstallTimeWrongType_AuditMode) { const uint32 now_seconds = Time64ToInt32(GetCurrent100NSTime()); const CString now_string = itostr(now_seconds); EXPECT_FALSE(now_string.IsEmpty()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_string)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_Machine_NoOemInstallTime_AuditMode) { if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(true)); } TEST_F(ConfigManagerTest, IsOemInstalling_User_OemInstallTimeNow_NotAuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); EXPECT_FALSE(cm_->IsOemInstalling(false)); } TEST_F(ConfigManagerTest, IsOemInstalling_User_OemInstallTimeNow_AuditMode) { const DWORD now_seconds = Time64ToInt32(GetCurrent100NSTime()); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE, _T("OemInstallTime"), now_seconds)); if (vista_util::IsVistaOrLater()) { EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); } else { EXPECT_SUCCEEDED(RegKey::SetValue(_T("HKLM\\System\\Setup"), _T("AuditInProgress"), static_cast<DWORD>(1))); } EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_FALSE(cm_->IsOemInstalling(false)); } // TODO(omaha): Figure out a way to test the result. TEST_F(ConfigManagerTest, IsGoogler) { cm_->IsGoogler(); } TEST_F(ConfigManagerTest, IsWindowsInstalling_Normal) { EXPECT_FALSE(cm_->IsWindowsInstalling()); } // While this test passes, the return value of IsWindowsInstalling() is not // fully tested because the account is not Administrator. TEST_F(ConfigManagerTest, IsWindowsInstalling_Installing_Vista_InvalidValues) { if (!vista_util::IsVistaOrLater()) { return; } EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T(""))); EXPECT_FALSE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("foo"))); EXPECT_FALSE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), static_cast<DWORD>(1))); ExpectAsserts expect_asserts; // RegKey asserts because value type is wrong. EXPECT_FALSE(cm_->IsWindowsInstalling()); } // TODO(omaha): This test fails because the account is not Administrator. Maybe // just delete them if this is the final implementation of Audit Mode detection. TEST_F(ConfigManagerTest, DISABLED_IsWindowsInstalling_Installing_Vista_ValidStates) { if (!vista_util::IsVistaOrLater()) { return; } // These states return false in the original implementation. EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_COMPLETE"))); EXPECT_FALSE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE"))); EXPECT_FALSE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_SPECIALIZE_RESEAL_TO_OOBE"))); EXPECT_FALSE(cm_->IsWindowsInstalling()); // These states are specified in the original implementation. EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_UNDEPLOYABLE"))); EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_GENERALIZE_RESEAL_TO_AUDIT"))); EXPECT_TRUE(cm_->IsWindowsInstalling()); EXPECT_SUCCEEDED(RegKey::SetValue( _T("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State"), _T("ImageState"), _T("IMAGE_STATE_SPECIALIZE_RESEAL_TO_AUDIT"))); EXPECT_TRUE(cm_->IsWindowsInstalling()); } TEST_F(ConfigManagerTest, CanInstallApp_NoGroupPolicy) { EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DifferentAppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp2, 0)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_NoDefaultValue_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 0)); EXPECT_FALSE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_NoDefaultValue_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 1)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_NoDefaultValue_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 2)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultDisabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 0)); EXPECT_FALSE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultDisabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 0)); EXPECT_FALSE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultDisabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 1)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } // Invalid value defaulting to true overrides the InstallDefault disable. TEST_F(ConfigManagerTest, CanInstallApp_DefaultDisabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 2)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultEnabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 1)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultEnabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 0)); EXPECT_FALSE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultEnabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 1)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanInstallApp_DefaultEnabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("InstallDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kInstallPolicyApp1, 2)); EXPECT_TRUE(CanInstallApp(kAppGuid1)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_NoGroupPolicy) { EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DifferentAppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp2, 0)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DifferentAppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp2, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_NoDefaultValue_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_NoDefaultValue_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_NoDefaultValue_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultDisabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultDisabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultDisabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultDisabled_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } // Invalid value defaulting to true overrides the UpdateDefault disable. TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultDisabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultEnabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultEnabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultEnabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultEnabled_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultEnabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultManualOnly_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultManualOnly_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultManualOnly_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultManualOnly_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultManualOnly_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_DefaultInvalid_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_GoogleUpdate_DefaultDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_GoogleUpdate_DefaultManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Auto_GoogleUpdate_AppDisabled) { EXPECT_SUCCEEDED( SetPolicy(_T("Update{430FD4D0-B729-4F61-AA34-91526481799D}"), 0)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), false)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_NoGroupPolicy) { EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DifferentAppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp2, 0)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DifferentAppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp2, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_NoDefaultValue_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_NoDefaultValue_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_NoDefaultValue_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultDisabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultDisabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultDisabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultDisabled_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } // Invalid value defaulting to true overrides the UpdateDefault disable. TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultDisabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultEnabled_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultEnabled_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultEnabled_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultEnabled_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultEnabled_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 1)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultManualOnly_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultManualOnly_AppDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 0)); EXPECT_FALSE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultManualOnly_AppEnabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 1)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultManualOnly_AppManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 2)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Maual_DefaultManualOnly_AppInvalid) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_SUCCEEDED(SetPolicy(kUpdatePolicyApp1, 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_DefaultInvalid_NoAppValue) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 3)); EXPECT_TRUE(CanUpdateApp(kAppGuid1, true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_GoogleUpdate_DefaultDisabled) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 0)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_GoogleUpdate_DefaultManualOnly) { EXPECT_SUCCEEDED(SetPolicy(_T("UpdateDefault"), 2)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), true)); } TEST_F(ConfigManagerTest, CanUpdateApp_Manual_GoogleUpdate_AppDisabled) { EXPECT_SUCCEEDED( SetPolicy(_T("Update{430FD4D0-B729-4F61-AA34-91526481799D}"), 0)); EXPECT_TRUE(CanUpdateApp(_T("{430FD4D0-B729-4F61-AA34-91526481799D}"), true)); } TEST_F(ConfigManagerTest, LastCheckedTime) { DWORD time = 500; EXPECT_SUCCEEDED(cm_->SetLastCheckedTime(true, time)); EXPECT_EQ(time, cm_->GetLastCheckedTime(true)); time = 77003; EXPECT_SUCCEEDED(cm_->SetLastCheckedTime(false, time)); EXPECT_EQ(time, cm_->GetLastCheckedTime(false)); } // Tests GetDir indirectly. TEST_F(ConfigManagerTest, GetDir) { RestoreRegistryHives(); CString user_install_dir = cm_->GetUserGoopdateInstallDir(); CString user_profile; ASSERT_NE(0, ::GetEnvironmentVariable(_T("USERPROFILE"), CStrBuf(user_profile, MAX_PATH), MAX_PATH)); ASSERT_TRUE(String_StartsWith(user_install_dir, user_profile, true)); } TEST_F(ConfigManagerTest, GetUpdateWorkerStartUpDelayMs_Repeated) { if (!SystemInfo::IsRunningOnXPOrLater()) { std::wcout << _T("\tTest did not run because GenRandom breaks on Windows ") << _T("2000 if the registry keys are overridden.") << std::endl; return; } // Test the UpdateDelay multiple times. for (int i = 0; i < 10; ++i) { int random = cm_->GetUpdateWorkerStartUpDelayMs(); EXPECT_GE(random, kUpdateTimerStartupDelayMinMs); EXPECT_LE(random, kUpdateTimerStartupDelayMaxMs); } } TEST_F(ConfigManagerTest, GetUpdateWorkerStartUpDelayMs) { if (!SystemInfo::IsRunningOnXPOrLater()) { std::wcout << _T("\tTest did not run because GenRandom breaks on Windows ") << _T("2000 if the registry keys are overridden.") << std::endl; return; } int random = cm_->GetUpdateWorkerStartUpDelayMs(); EXPECT_GE(random, kUpdateTimerStartupDelayMinMs); EXPECT_LE(random, kUpdateTimerStartupDelayMaxMs); int num_times_to_try_for_diff_number = 3; // We run the method num_times_to_try_for_diff_number times to make // sure that at least one of these returns a number that is different // from the one that is returned above. This is needed, since the // method returns a number between kUpdateTimerStartupDelayMinMs and // kUpdateTimerStartupDelayMaxMs. // If this fails a lot we should disable the if check below. bool found_one_not_equal = false; for (int i = 0; i < num_times_to_try_for_diff_number; ++i) { int random_compare = cm_->GetUpdateWorkerStartUpDelayMs(); EXPECT_GE(random_compare, kUpdateTimerStartupDelayMinMs); EXPECT_LE(random_compare, kUpdateTimerStartupDelayMaxMs); if (random_compare != random) { found_one_not_equal = true; break; } } EXPECT_TRUE(found_one_not_equal); } TEST_F(ConfigManagerTest, GetUpdateWorkerStartUpDelayMs_Override) { // Test that the initial delay time to launch a worker can be overriden. DWORD val = 3320; EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueAuCheckPeriodMs, val)); int random = cm_->GetUpdateWorkerStartUpDelayMs(); EXPECT_EQ(val, random); } TEST_F(ConfigManagerTest, GetTimeSinceLastCheckedSec_User) { // First, there is no value present in the registry. uint32 now_sec = Time64ToInt32(GetCurrent100NSTime()); int time_since_last_checked_sec = cm_->GetTimeSinceLastCheckedSec(false); EXPECT_EQ(now_sec, time_since_last_checked_sec); // Second, write the 'now' time. EXPECT_HRESULT_SUCCEEDED(cm_->SetLastCheckedTime(false, now_sec)); time_since_last_checked_sec = cm_->GetTimeSinceLastCheckedSec(false); EXPECT_EQ(0, time_since_last_checked_sec); } TEST_F(ConfigManagerTest, GetTimeSinceLastCheckedSec_Machine) { uint32 now_sec = Time64ToInt32(GetCurrent100NSTime()); int time_since_last_checked_sec = cm_->GetTimeSinceLastCheckedSec(true); EXPECT_EQ(now_sec, time_since_last_checked_sec); EXPECT_HRESULT_SUCCEEDED(cm_->SetLastCheckedTime(true, now_sec)); time_since_last_checked_sec = cm_->GetTimeSinceLastCheckedSec(true); EXPECT_EQ(0, time_since_last_checked_sec); } TEST_F(ConfigManagerTest, GetNetConfig) { CString actual_value; EXPECT_HRESULT_FAILED(cm_->GetNetConfig(&actual_value)); const CString expected_value = _T("proxy:8080"); EXPECT_SUCCEEDED(RegKey::SetValue(MACHINE_REG_UPDATE_DEV, kRegValueNetConfig, expected_value)); EXPECT_HRESULT_SUCCEEDED(cm_->GetNetConfig(&actual_value)); EXPECT_STREQ(expected_value, actual_value); } TEST_F(ConfigManagerTest, GetInstallTime) { EXPECT_SUCCEEDED(DeleteUpdateTime(false)); EXPECT_SUCCEEDED(DeleteFirstInstallTime(false)); EXPECT_EQ(0, ConfigManager::GetInstallTime(false)); DWORD time = 500; EXPECT_SUCCEEDED(SetFirstInstallTime(false, time)); EXPECT_EQ(time, ConfigManager::GetInstallTime(false)); time = 1000; EXPECT_SUCCEEDED(SetUpdateTime(false, time)); EXPECT_EQ(time, ConfigManager::GetInstallTime(false)); EXPECT_SUCCEEDED(DeleteFirstInstallTime(false)); EXPECT_EQ(time, ConfigManager::GetInstallTime(false)); } TEST_F(ConfigManagerTest, Is24HoursSinceInstall) { const uint32 now = Time64ToInt32(GetCurrent100NSTime()); const int k12HourPeriodSec = 12 * 60 * 60; const int k48HourPeriodSec = 48 * 60 * 60; const uint32 first_install_12 = now - k12HourPeriodSec; const uint32 first_install_48 = now - k48HourPeriodSec; EXPECT_SUCCEEDED(SetFirstInstallTime(false, first_install_12)); EXPECT_FALSE(ConfigManager::Is24HoursSinceInstall(false)); EXPECT_SUCCEEDED(SetFirstInstallTime(false, first_install_48)); EXPECT_TRUE(ConfigManager::Is24HoursSinceInstall(false)); EXPECT_SUCCEEDED(SetUpdateTime(false, first_install_12)); EXPECT_FALSE(ConfigManager::Is24HoursSinceInstall(false)); EXPECT_SUCCEEDED(SetUpdateTime(false, first_install_48)); EXPECT_TRUE(ConfigManager::Is24HoursSinceInstall(false)); } } // namespace omaha
a00056506df2b8be83108118370455f3387bf2ee
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/WebRTC/rev.9862/lib/Win64/VS2013/include/webrtc/video_frame.h
d70a746daeb49334193c99d522cefd275615981c
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
6,776
h
video_frame.h
/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_VIDEO_FRAME_H_ #define WEBRTC_VIDEO_FRAME_H_ #include "webrtc/base/scoped_ref_ptr.h" #include "webrtc/common_video/interface/video_frame_buffer.h" #include "webrtc/common_video/rotation.h" #include "webrtc/typedefs.h" namespace webrtc { class VideoFrame { public: VideoFrame(); VideoFrame(const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer, uint32_t timestamp, int64_t render_time_ms, VideoRotation rotation); // TODO(pbos): Make all create/copy functions void, they should not be able to // fail (which should be DCHECK/CHECKed instead). // CreateEmptyFrame: Sets frame dimensions and allocates buffers based // on set dimensions - height and plane stride. // If required size is bigger than the allocated one, new buffers of adequate // size will be allocated. // Return value: 0 on success, -1 on error. int CreateEmptyFrame(int width, int height, int stride_y, int stride_u, int stride_v); // CreateFrame: Sets the frame's members and buffers. If required size is // bigger than allocated one, new buffers of adequate size will be allocated. // Return value: 0 on success, -1 on error. int CreateFrame(const uint8_t* buffer_y, const uint8_t* buffer_u, const uint8_t* buffer_v, int width, int height, int stride_y, int stride_u, int stride_v); // TODO(guoweis): remove the previous CreateFrame when chromium has this code. int CreateFrame(const uint8_t* buffer_y, const uint8_t* buffer_u, const uint8_t* buffer_v, int width, int height, int stride_y, int stride_u, int stride_v, VideoRotation rotation); // CreateFrame: Sets the frame's members and buffers. If required size is // bigger than allocated one, new buffers of adequate size will be allocated. // |buffer| must be a packed I420 buffer. // Return value: 0 on success, -1 on error. int CreateFrame(const uint8_t* buffer, int width, int height, VideoRotation rotation); // Deep copy frame: If required size is bigger than allocated one, new // buffers of adequate size will be allocated. // Return value: 0 on success, -1 on error. int CopyFrame(const VideoFrame& videoFrame); // Creates a shallow copy of |videoFrame|, i.e, the this object will retain a // reference to the video buffer also retained by |videoFrame|. void ShallowCopy(const VideoFrame& videoFrame); // Release frame buffer and reset time stamps. void Reset(); // Get pointer to buffer per plane. uint8_t* buffer(PlaneType type); // Overloading with const. const uint8_t* buffer(PlaneType type) const; // Get allocated size per plane. int allocated_size(PlaneType type) const; // Get allocated stride per plane. int stride(PlaneType type) const; // Get frame width. int width() const; // Get frame height. int height() const; // Set frame timestamp (90kHz). void set_timestamp(uint32_t timestamp) { timestamp_ = timestamp; } // Get frame timestamp (90kHz). uint32_t timestamp() const { return timestamp_; } // Set capture ntp time in miliseconds. void set_ntp_time_ms(int64_t ntp_time_ms) { ntp_time_ms_ = ntp_time_ms; } // Get capture ntp time in miliseconds. int64_t ntp_time_ms() const { return ntp_time_ms_; } // Naming convention for Coordination of Video Orientation. Please see // http://www.etsi.org/deliver/etsi_ts/126100_126199/126114/12.07.00_60/ts_126114v120700p.pdf // // "pending rotation" or "pending" = a frame that has a VideoRotation > 0. // // "not pending" = a frame that has a VideoRotation == 0. // // "apply rotation" = modify a frame from being "pending" to being "not // pending" rotation (a no-op for "unrotated"). // VideoRotation rotation() const { return rotation_; } void set_rotation(VideoRotation rotation) { rotation_ = rotation; } // Set render time in miliseconds. void set_render_time_ms(int64_t render_time_ms) { render_time_ms_ = render_time_ms; } // Get render time in miliseconds. int64_t render_time_ms() const { return render_time_ms_; } // Return true if underlying plane buffers are of zero size, false if not. bool IsZeroSize() const; // Return the handle of the underlying video frame. This is used when the // frame is backed by a texture. The object should be destroyed when it is no // longer in use, so the underlying resource can be freed. void* native_handle() const; // Return the underlying buffer. rtc::scoped_refptr<webrtc::VideoFrameBuffer> video_frame_buffer() const; // Set the underlying buffer. void set_video_frame_buffer( const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& buffer); // Convert native-handle frame to memory-backed I420 frame. Should not be // called on a non-native-handle frame. VideoFrame ConvertNativeToI420Frame() const; private: // An opaque reference counted handle that stores the pixel data. rtc::scoped_refptr<webrtc::VideoFrameBuffer> video_frame_buffer_; uint32_t timestamp_; int64_t ntp_time_ms_; int64_t render_time_ms_; VideoRotation rotation_; }; enum VideoFrameType { kKeyFrame = 0, kDeltaFrame = 1, kGoldenFrame = 2, kAltRefFrame = 3, kSkipFrame = 4 }; // TODO(pbos): Rename EncodedFrame and reformat this class' members. class EncodedImage { public: EncodedImage() : EncodedImage(nullptr, 0, 0) {} EncodedImage(uint8_t* buffer, size_t length, size_t size) : _buffer(buffer), _length(length), _size(size) {} uint32_t _encodedWidth = 0; uint32_t _encodedHeight = 0; uint32_t _timeStamp = 0; // NTP time of the capture time in local timebase in milliseconds. int64_t ntp_time_ms_ = 0; int64_t capture_time_ms_ = 0; // TODO(pbos): Use webrtc::FrameType directly (and remove VideoFrameType). VideoFrameType _frameType = kDeltaFrame; uint8_t* _buffer; size_t _length; size_t _size; bool _completeFrame = false; }; } // namespace webrtc #endif // WEBRTC_VIDEO_FRAME_H_
d539229f84b690074c371c9a0c80255fc62b2651
1a1d7a5b9801257e24173860f82b71140ffff0c4
/work2/sudoku/sudoku/generator.h
e724508b3f61825db48eb4da48d1f06ea78a1d37
[]
no_license
Ananileaf/rgsj
ed6656e975318cf5c509f78c6bf723fc3d16e981
e0c497f74364fcec0d195a86f7ed47fc50acf363
refs/heads/master
2021-01-23T15:16:55.035723
2017-09-10T13:07:43
2017-09-10T13:07:43
102,704,473
1
0
null
null
null
null
GB18030
C++
false
false
823
h
generator.h
#pragma once #include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #define mem(x, y) memset(x, y, sizeof(x)); #define mem0(x) mem(x,0) #define rep(i,a,b) for(int i=a;i<(b);++i) class generator { public: int n; //输入 int ans; //搜索到的方案数 int belong[10][10]; //每一个格子属于哪一个九宫格 char ways[10][10]; //搜索的方案 bool vis[10][10]; //每个九宫格中的数字标记 bool col[10][10]; //每一列中的数字标记 bool row[10][10]; //每一行的数字标记 bool flag; //搜索的剪枝,当查询到的方案数大于等于输入的方案数时生效 char put[200]; //输出 int cnt; //输出时需要使用到的变量 generator(); generator(int _n); void dfs(int t); void solve(int m); void init(); ~generator(); };
d12030668da960b1ffc21b0ac35e96db91113e35
6630e282d188fc42339d46dd5989e86ce79c7832
/sokoban_c++/main.cpp
0943130b72dfdd7dd3bb47e740e7e0a0da261b03
[]
no_license
izemaghilas/sokoban
e5e6e68be7583dd5328b40ee0cc686638d46d072
f7a363879c46ab5e11b083a1c1c687e3735fbfb6
refs/heads/master
2022-12-30T03:51:44.432629
2020-10-19T21:14:03
2020-10-19T21:14:03
298,287,297
0
0
null
null
null
null
UTF-8
C++
false
false
977
cpp
main.cpp
/** * point d'enter de programme sokoban */ #include <iostream> #include <SDL.h> #include <SDL_image.h> #include "initializer.h" #include "screenhandler.h" #include "eventhandler.h" using namespace std; const int WIDTH = 480; const int HEIGHT = 480; //window SDL_Window *sokoban_window = NULL; //main renderer SDL_Renderer *sokoban_renderer = NULL; int main(int argc, char** argv) { bool quit = false; SDL_Event sokoban_events; if (sokoban_init(WIDTH, HEIGHT, sokoban_window, sokoban_renderer)){ drawMenu(sokoban_renderer); while(!quit){ while(SDL_PollEvent(&sokoban_events) != 0){ if(sokoban_events.type == SDL_QUIT) quit = true; if(sokoban_events.type == SDL_KEYDOWN) handle_keyboard_event(&sokoban_events, sokoban_renderer); } } closeScreen(); sokoban_close(sokoban_window, sokoban_renderer); } return 0; }
65085bafef06c24383315e04d81df384fdab7b80
b7e38c7d1598dd459c33fb6522b0009acce7a30d
/11. 그래프 기본 탐색/BOJ_8111/BOJ_8111.cpp
267ea3306bc818b6d1a64fcb27a9346550bf9750
[]
no_license
reach0908/BOJ
a31def6073f7c2c427815db3a847370d5b27da0b
582af2e9a16df384828277b507f0b86f21093e4d
refs/heads/master
2023-04-06T08:23:09.026918
2021-04-18T14:37:07
2021-04-18T14:37:07
289,498,306
1
0
null
2021-04-18T14:37:08
2020-08-22T14:00:33
C++
UTF-8
C++
false
false
1,174
cpp
BOJ_8111.cpp
#include <iostream> #include <cstring> #include <queue> using namespace std; const int MAX = 20000+1; int t,n; bool visited[MAX]; pair<int,char> arr[MAX]; void BFS(){ queue<int> q; q.push(1); visited[1]=true; arr[1].first=-1; arr[1].second='1'; while (!q.empty()) { int temp = q.front(); q.pop(); int p[2]; p[0]= (temp*10)%n; p[1] = (p[0]+1)%n; for (int i = 0; i < 2; i++) { if(!visited[p[i]]){ arr[p[i]].first=temp; arr[p[i]].second=i+'0'; if(!p[i]){ return; } visited[p[i]]=true; q.push(p[i]); } } } } void printPath(int num){ if(num==-1){ return; } printPath(arr[num].first); cout << arr[num].second; } int main(int argc, char const *argv[]) { cin >> t; while (t--) { cin >> n; if(n==1){ cout << 1 << endl; continue; } memset(visited,false,sizeof(visited)); BFS(); printPath(0); cout << endl; } return 0; }
fad266f6734a67075b6c489833c2c4fa172d8967
4ac75107a576670f0843c87437b565b38358be5f
/src/model/jamp/jamp_pack_level.cpp
264c7e750992f9378c04e147749e80ed970de80b
[ "MIT" ]
permissive
fjorge/pg-sdk-marmalade
d82c5ef60b7b175554d6a6fb7f587e01f8c74747
258407779baa6af44335fa543e1be4575845a162
refs/heads/master
2021-01-17T06:32:14.982634
2015-12-03T13:42:37
2015-12-03T13:42:37
36,661,743
0
0
null
2015-06-01T13:15:32
2015-06-01T13:15:32
null
UTF-8
C++
false
false
1,217
cpp
jamp_pack_level.cpp
#include "jamp_pack_level.h" int32 JampPackLevel::Deserialize(std::string jsonSrc) { if (jsonSrc.length() == 0) return 0; Reader reader; Value value; reader.parse(jsonSrc, value, false); return DeserializeFromValue(value); } int32 JampPackLevel::DeserializeFromValue(Value src){ if (!src["levelId"].empty()) levelId = src["levelId"].asUInt64(); if (!src["starsWon"].empty()) starsWon = src["starsWon"].asUInt64(); if (!src["maxScore"].empty()) maxScore = src["maxScore"].asUInt64(); if (!src["blocked"].empty()) blocked = src["blocked"].asBool(); if (!src["grouping"].empty()) grouping = src["grouping"].asBool(); if (!src["packId"].empty()) packId = src["packId"].asInt64(); return 0; } std::string JampPackLevel::Serialize(){ FastWriter writer; return writer.write(SerializeToValue()); } Value JampPackLevel::SerializeToValue(){ Value root; if(levelId >= 0) root["levelId"] = levelId; if(starsWon >= 0) root["starsWon"] = starsWon; if(maxScore >= 0) root["maxScore"] = maxScore; root["blocked"] = blocked; root["grouping"] = grouping; if(packId >= 0) root["packId"] = packId; return root; }
3786961d1bc3c71266fb84c112c80098bea95d22
78506f31e499339cca8e0cef00a80e5444bc1e72
/utils/mnist_file_utils.h
68f473a5bfdc0fb619201836f1936a541e5085be
[]
no_license
smelvinsky/mnist-clink-clustering
e07a16e9746d0ecd15572da81aa3ef445be6d6bc
e574f4b2580fb655ca51a8cded7f6e84b2d9d3ab
refs/heads/master
2021-09-10T11:33:28.796354
2018-03-25T18:37:40
2018-03-25T18:37:40
113,115,599
0
0
null
null
null
null
UTF-8
C++
false
false
1,674
h
mnist_file_utils.h
/** * Created by smelvinsky on 04.12.17. */ #ifndef MNIST_UTILS_H #define MNIST_UTILS_H /* image width in pixels */ #define MNIST_IMG_WIDTH 28 /* image height in pixels */ #define MNIST_IMG_HEIGHT 28 #include <cstdint> #include <cstdio> namespace MNIST_Utils { typedef struct MNIST_Image MNIST_Image; typedef uint8_t MNIST_Label; /* Image structure containing 0-255 values of every pixel (flattened) */ struct MNIST_Image{ uint8_t pixel[28*28]; }; /* This structure is used for the header size reference only */ /* Fields are not used/declared */ /* See http://yann.lecun.com/exdb/mnist/ for details for more info */ struct MNISTImageFileHeader{ uint32_t magicNumber; uint32_t maxImages; uint32_t imgWidth; uint32_t imgHeight; }; /* This structure is used for the header size reference only */ /* Fields are not used/declared */ /* See http://yann.lecun.com/exdb/mnist/ for details for more info */ struct MNISTLabelFileHeader{ uint32_t magicNumber; uint32_t maxImages; }; uint32_t swapBytes(uint32_t highEndianNumber); FILE *openMNISTImageFile(char *filename); FILE *openMNISTLabelFile(char *filename); void readImageFileHeader(FILE *imageFile, MNISTImageFileHeader *imgFileHead); void readLabelFileHeader(FILE *imageFile, MNISTLabelFileHeader *lblFileHead); MNIST_Image getNextImage(FILE *imageFile); MNIST_Label getNextLabel(FILE *labelFile); void displayImage(MNIST_Image *img, int row, int col); } #endif //MNIST_UTILS_H
231db0ec52f2ce3541c050e700a9f94576a73952
964e032ab1c0d3c79f8040c5ecc5c86307325cdf
/BACKJOON/step1-9/step9/1002.cpp
a841d91b9c19357d479cadbc6283ade8788e9f89
[]
no_license
kebi3477/Algorithm
cde2ddbcd5b5377a145d58de7f7cb02c322c5c7c
77d9c4c6da712badeaadea795629f599ff2936eb
refs/heads/master
2023-01-04T00:03:32.884934
2020-10-30T07:48:36
2020-10-30T07:48:36
285,833,589
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
1002.cpp
#include <stdio.h> using namespace std; int main(void) { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { int x1, x2, y1, y2, r1, r2; scanf("%d %d %d %d %d %d", &x1, &y1, &r1, &x2, &y2, &r2); int d = (x2-x1) * (x2-x1) + (y2-y1) * (y2-y1); int sum = (r1 + r2) * (r1 + r2); int dif = (r1 - r2) * (r1 - r2); if(d == 0) { if(dif == 0) printf("-1\n"); else printf("0\n"); } else if(d == sum || d == dif) printf("1\n"); else if(dif < d && d < sum) printf("2\n"); else printf("0\n"); } return 0; }
865a97b6f543f404832290c2d32e1a7ed63adefe
38a724327679ba89a9a5383b79523476264c69b2
/1 term/Ded-C/Substring/Substring_functions.cpp
d5adb6cbd0e15354954f750a3383ea64a2f192aa
[]
no_license
alexeyqu/mipt-alexeyqu
3f0af5534a142082d8f9b10b36bbc9ae82daf6fe
1059b0e9a95855a95d0bc6c7da564799dfc7c449
refs/heads/master
2021-01-21T04:39:39.719665
2017-10-11T16:28:20
2017-10-11T16:28:20
51,085,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,957
cpp
Substring_functions.cpp
#include "Substring.h" int get_str (char* str, int MaxLen) { ASSERT (str); DBG printf ("Enter string: "); int len = 0; char c; while ((c = getchar()) != EOF) { if (c == '\n') { break; } if (len >= MaxLen - 1) { printf ("You've reached maximum length of string. \n"); printf ("Sorry, but the rest of the input will be considered" \ " as next values that you'll enter.\n"); printf ("It is NOT guaranteed that the program will work correctly\n"); break; } str[len++] = c; } str[len] = '\0'; return len; } int str_cmp (char* str_1, char* str_2, int MaxLen) { ASSERT (str_1); ASSERT (str_2); ASSERT ((str_1 != str_2)); int i = 0; for (i = 0; ; i++) { ASSERT ((i < MaxLen)); if (str_1[i] == '\0' && str_2[i] == '\0') return 0; if (str_1[i] != '\0' && str_2[i] == '\0') return 1; if (str_1[i] == '\0' && str_2[i] != '\0') return -1; if (str_1[i] == str_2[i]) continue; if (str_1[i] < str_2[i]) return -1; else return 1; } return 0; } int sub_str (char* haystack, char* needle, int MaxLen) { ASSERT (haystack); ASSERT (needle); ASSERT ((haystack != needle)); int i = 0, j = 0; int found = 0; for (i = 0; i <= str_len (haystack) - str_len (needle); i++) { ASSERT ((i < MaxLen)); if (haystack[i] == needle[0]) { found = 1; for (j = i; j - i < str_len (needle) - 1; j++) { ASSERT ((j < MaxLen)); if (haystack[j] != needle[j - i]) {found = 0; break;} } if (found) return SUBSTRING (i); } } return NOT_A_SUBSTRING; } int str_len (char* str) { ASSERT (str); int len = 0; while (str[len++] != '\0'); return len; }
d5a30d9351df099ad42d7ecb5c5ccef40d0e8099
66949a25a8764ff303887253f5dc3725b026336e
/HelloWorld/residueanalysis.cpp
70f4e1967b31f584744e0599f7ac9960a0780de1
[]
no_license
juniorprincewang/MRL
7526ef76a1c564b7e8b4314e55e46e68faa944bb
b76fa14749e6241ea493d49dbd7b462dbdb5c66e
refs/heads/master
2021-01-18T22:29:30.866122
2017-05-16T01:02:10
2017-05-16T01:02:10
72,534,367
0
0
null
null
null
null
UTF-8
C++
false
false
5,606
cpp
residueanalysis.cpp
#include "residueanalysis.h" ResidueAnalysis::ResidueAnalysis(QWidget *parent) :DataAnalysis(parent) { // 分布,残留计算方法,推荐残留值 QGridLayout *residuesLayout= new QGridLayout(); QLabel *distribution= new QLabel(QString("分布"), this); distributionText = new QLineEdit(this); QLabel *calcMethod= new QLabel(QString("残留计算方法"), this);; calcMethodText = new QLineEdit(this); QLabel *recommendation = new QLabel(QString("推荐残留值"), this);; recommendationText =new QLineEdit(this); residuesLayout->addWidget(distribution, 0, 0); residuesLayout->addWidget(distributionText, 0, 1); residuesLayout->addWidget(calcMethod, 1, 0); residuesLayout->addWidget(calcMethodText, 1, 1); residuesLayout->addWidget(recommendation, 2, 0); residuesLayout->addWidget(recommendationText, 2, 1); distributionText->setEnabled(false); calcMethodText->setEnabled(false); recommendationText->setEnabled(false); //残留量 mainLayout->addLayout(residuesLayout); // DataAnalysis::preset(); // fillWidget(); } void ResidueAnalysis::receiveSelectedData(PesticideData *p, int key) { DataAnalysis::receiveSelectedData(p, key); // qDebug()<< "Residue Analysis receiveSelectedData"; // qDebug() <<"this->residues.size() = " << this->residues.size(); fillWidget(); } void ResidueAnalysis::fillWidget() { DataAnalysis::fillWidget(); QString method; QString distribution; QString value; std::vector<QString> results; bool rounded = true; //生成对数QQ图 logNormalityPlot(); // 对数验证 Model model(this->residues.toStdVector()); if(isShapiroFranciaNormality()) { distribution = QString("对数正态分布"); method = QString("95/96 Rule"); results = model.NAFTA(rounded); value = results[2]; if(this->residues.size() <= 15) { results = model.UPLMedian95th(rounded); if(value > results[0]) { value = results[0]; method = QString("UCLMedian95th"); } } } else { normalityPlot(); if(isShapiroFranciaNormality()) { distribution = QString("正态分布"); method = QString("欧盟I"); results = model.EUMethodI(rounded); value = results[2]; } else { distribution = QString("自由分布"); method = QString("欧盟II"); results = model.EUMethodII(rounded); value = results[0]; } } this->distributionText->setText(distribution); this->calcMethodText->setText(method); this->recommendationText->setText(value); } void ResidueAnalysis::logNormalityPlot() { if(this->pesticide == NULL) { QMessageBox::critical(NULL, QString("错误提示!"), QString("未有选择数据,回到数据定义选择残留量数据!")); return; } QString trendLineName = QString("对数正态分布_%1_%2_%3").arg( this->pesticide->chineseName).arg( this->pesticide->chemicalName).arg( this->key); QString fileSavePath = QString("%1/%2.jpg").arg(this->currentDir).arg(trendLineName); QDir dir(fileSavePath); if(dir.exists()) { QMessageBox box; box.setText(QStringLiteral("确定")); box.setInformativeText(QStringLiteral("文件已存在,是否覆盖?")); box.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel ); int ret = box.exec(); if(QMessageBox::Save != ret) { qDebug() << "未保存成功!"; return; } } Excel * excel = new Excel(); excel->residues = this->residues; excel->trendLinesName = trendLineName; excel->pictureSavePath = fileSavePath; this->rSquared = excel->savePlot(); delete excel; // qDebug() << "图标保存成功,rSquaredValue = "<<this->rSquared; } void ResidueAnalysis::normalityPlot() { if(this->pesticide == NULL) { QMessageBox::critical(NULL, QString("错误提示!"), QString("未有选择数据,回到数据定义选择残留量数据!")); return; } QString trendLineName = QString("正态分布_%1_%2_%3").arg( this->pesticide->chineseName).arg( this->pesticide->chemicalName).arg( this->key); QString fileSavePath = QString("%1/%2.jpg").arg(this->currentDir).arg(trendLineName); QDir dir(fileSavePath); if(dir.exists()) { QMessageBox box; box.setText(QStringLiteral("确定")); box.setInformativeText(QStringLiteral("文件已存在,是否覆盖?")); box.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel ); int ret = box.exec(); if(QMessageBox::Save != ret) { qDebug() << "未保存成功!"; return; } } Excel * excel = new Excel(); excel->residues = this->residues; excel->trendLinesName = trendLineName; excel->pictureSavePath = fileSavePath; this->rSquared = excel->saveNormalityPlot(); delete excel; // qDebug() << "图标保存成功,rSquaredValue = "<<this->rSquared; } bool ResidueAnalysis::isShapiroFranciaNormality() { // 对数正态验证 Model model(this->residues.toStdVector()); int normality = model.ShapiroFranciaNormalityTest(this->rSquared); if(normality == 3) return true; return false; }
6a070e77e517e95a3d1567e4e52c4a91a88cf263
b3fd6c4697a7990ca7ba387adfb9b43842ffc589
/cf195D.cpp
06abfacb77f80b2296ae9d1e6392b8dff90b0d84
[]
no_license
jainrishabh98/CP
48ab325fbfced6174778ec74e286b0874df9d82b
3d244de1096c484bb663ac328655a879d1f28b54
refs/heads/master
2021-06-07T09:10:42.900663
2020-02-05T08:58:39
2020-02-05T08:58:39
150,934,959
0
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
cf195D.cpp
#include <bits/stdc++.h> using namespace std; long long int a[100005]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin >> n; long double k[n], b[n]; set<long double> s; for (int i = 0; i < n; i++) { cin >> k[i] >> b[i]; if (k[i] != 0) s.insert(-b[i] / k[i]); } int cnt = 1; map<long double, int> mp; for (auto k : s) { mp[k] = cnt; cnt++; } for (int i = 0; i < n; i++) { if(k[i]==0) continue; long double bb = -b[i] / k[i]; int nnn = mp[bb]; if (k[i] < 0) { a[nnn + 1] -= k[i]; a[1] += k[i]; } else if (k[i] > 0) { a[nnn + 1] += k[i]; } } int cnn = 0; for (int i = 2; i <= cnt; i++) { a[i] += a[i - 1]; if(a[i]-a[i-1]!=0) cnn++; } cout << cnn; }
77b36aaf544c1bf0e1ad76d52a0f9aa8faed1d45
58e37a43d291d1884234f86b855b5f7da55725ef
/string/Day18/Q3.cpp
2ea445ee50db2a1144dd2db970c38f24b8bbc142
[]
no_license
shashank9aug/DSA_CB
74337f8fb5dde5b94b380512dcec39a13e643690
1301329e4f9fd5105b4cb3c9d0f5c5772ed890ce
refs/heads/master
2023-08-18T05:35:42.946559
2021-10-15T10:04:52
2021-10-15T10:04:52
370,120,570
2
0
null
null
null
null
UTF-8
C++
false
false
1,428
cpp
Q3.cpp
//check if two given strings are isomorphic to each other /* isomorphic : Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order. */ // C++ program to check if two strings are isomorphic #include <iostream> #include <string.h> using namespace std; class Solution { public: //Function to check if two strings are isomorphic. bool areIsomorphic(string str1, string str2) { //Base case : size of both the string should be equal if (str1.length() != str2.length()) { return false; } int h1[26] = {0}; int h2[26] = {0}; for (int i = 0; i < str1.length(); i++) { if (h1[str1[i] - 'a'] == 0) { if (h2[str2[i] - 'a'] == 0) { h2[str2[i] - 'a']++; h1[str1[i] - 'a'] = str2[i]; } else { return false; } } else if (h1[str1[i] - 'a'] != str2[i]) { return false; } } return true; } }; int main() { string s1, s2; cin >> s1; cin >> s2; Solution obj; cout << obj.areIsomorphic(s1, s2) << endl; return 0; }
4c78da5ea406ac32a5480f28fbf94a8d8458ce2b
c6039302b95d66b7c270cc4431ea96485b040fb7
/include/SVF-FE/SymbolTableInfo.h
2e0e43f48ee6da32bfe90f0ed383b15feb94c7c5
[]
no_license
JasonZhongZexin/SVF-npm
81d0ffc5586f239ff56ec4ff6963f71d7a66cfac
e38a1ea6cc409e28f91a4ef8d47a0fc09f53b65f
refs/heads/master
2023-03-05T06:18:14.054656
2020-06-27T12:09:14
2020-06-27T12:09:14
275,357,174
0
0
null
2021-02-14T08:51:18
2020-06-27T11:22:57
C++
UTF-8
C++
false
false
13,428
h
SymbolTableInfo.h
//===- SymbolTableInfo.h -- Symbol information from IR------------------------// // // SVF: Static Value-Flow Analysis // // Copyright (C) <2013-> <Yulei Sui> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // //===----------------------------------------------------------------------===// /* * SymbolTableInfo.h * * Created on: Nov 11, 2013 * Author: Yulei Sui */ #ifndef INCLUDE_SVF_FE_SYMBOLTABLEINFO_H_ #define INCLUDE_SVF_FE_SYMBOLTABLEINFO_H_ #include "MemoryModel/MemModel.h" #include "SVF-FE/LLVMModule.h" /*! * Symbol table of the memory model for analysis */ class SymbolTableInfo { public: /// various maps defined //{@ /// llvm value to sym id map /// local (%) and global (@) identifiers are pointer types which have a value node id. typedef DenseMap<const Value *, SymID> ValueToIDMapTy; /// sym id to memory object map typedef DenseMap<SymID,MemObj*> IDToMemMapTy; /// function to sym id map typedef DenseMap<const Function *, SymID> FunToIDMapTy; /// sym id to sym type map typedef DenseMap<SymID,SYMTYPE> IDToSymTyMapTy; /// struct type to struct info map typedef DenseMap<const Type*, StInfo*> TypeToFieldInfoMap; typedef std::set<CallSite> CallSiteSet; typedef DenseMap<const Instruction*,CallSiteID> CallSiteToIDMapTy; typedef DenseMap<CallSiteID,const Instruction*> IDToCallSiteMapTy; //@} private: /// Data layout on a target machine static DataLayout *dl; ValueToIDMapTy valSymMap; ///< map a value to its sym id ValueToIDMapTy objSymMap; ///< map a obj reference to its sym id IDToMemMapTy objMap; ///< map a memory sym id to its obj IDToSymTyMapTy symTyMap; /// < map a sym id to its type FunToIDMapTy returnSymMap; ///< return map FunToIDMapTy varargSymMap; ///< vararg map CallSiteSet callSiteSet; // Singleton pattern here to enable instance of SymbolTableInfo can only be created once. static SymbolTableInfo* symlnfo; /// Module SVFModule* mod; /// Max field limit static u32_t maxFieldLimit; /// Invoke llvm passes to modify module void prePassSchedule(SVFModule* svfModule); /// Clean up memory void destroy(); /// Whether to model constants bool modelConstants; protected: /// Constructor SymbolTableInfo() : modelConstants(false), maxStruct(NULL), maxStSize(0) { } public: /// Statistics //@{ static SymID totalSymNum; //@} /// Singleton design here to make sure we only have one instance during any analysis //@{ static SymbolTableInfo* Symbolnfo(); static void releaseSymbolnfo() { delete symlnfo; symlnfo = NULL; } virtual ~SymbolTableInfo() { destroy(); } //@} /// Set / Get modelConstants //@{ void setModelConstants(bool _modelConstants) { modelConstants = _modelConstants; } bool getModelConstants() const { return modelConstants; } //@} /// Get callsite set //@{ inline const CallSiteSet& getCallSiteSet() const { return callSiteSet; } //@} /// Module inline SVFModule* getModule() { return mod; } /// Get target machine data layout inline static DataLayout* getDataLayout(Module* mod) { if(dl==NULL) return dl = new DataLayout(mod); return dl; } /// Helper method to get the size of the type from target data layout //@{ u32_t getTypeSizeInBytes(const Type* type); u32_t getTypeSizeInBytes(const StructType *sty, u32_t field_index); //@} /// Start building memory model void buildMemModel(SVFModule* svfModule); /// collect the syms //@{ void collectSym(const Value *val); void collectVal(const Value *val); void collectObj(const Value *val); void collectRet(const Function *val); void collectVararg(const Function *val); //@} /// special value // @{ static bool isNullPtrSym(const Value *val); static bool isBlackholeSym(const Value *val); bool isConstantObjSym(const Value *val); static inline bool isBlkPtr(NodeID id) { return (id == BlkPtr); } static inline bool isNullPtr(NodeID id) { return (id == NullPtr); } static inline bool isBlkObj(NodeID id) { return (id == BlackHole); } static inline bool isConstantObj(NodeID id) { return (id == ConstantObj); } static inline bool isBlkObjOrConstantObj(NodeID id) { return (isBlkObj(id) || isConstantObj(id)); } inline void createBlkOrConstantObj(SymID symId) { assert(isBlkObjOrConstantObj(symId)); assert(objMap.find(symId)==objMap.end()); objMap[symId] = new MemObj(symId);; } inline MemObj* getBlkObj() const { return getObj(blackholeSymID()); } inline MemObj* getConstantObj() const { return getObj(constantSymID()); } inline SymID blkPtrSymID() const { return BlkPtr; } inline SymID nullPtrSymID() const { return NullPtr; } inline SymID constantSymID() const { return ConstantObj; } inline SymID blackholeSymID() const { return BlackHole; } /// Can only be invoked by PAG::addDummyNode() when creaing PAG from file. inline const MemObj* createDummyObj(SymID symId, const Type* type) { assert(objMap.find(symId)==objMap.end() && "this dummy obj has been created before"); MemObj* memObj = new MemObj(symId, type); objMap[symId] = memObj; return memObj; } // @} /// Handle constant expression // @{ void handleGlobalCE(const GlobalVariable *G); void handleGlobalInitializerCE(const Constant *C, u32_t offset); void handleCE(const Value *val); // @} /// Get different kinds of syms //@{ SymID getValSym(const Value *val) { if(isNullPtrSym(val)) return nullPtrSymID(); else if(isBlackholeSym(val)) return blkPtrSymID(); else { ValueToIDMapTy::const_iterator iter = valSymMap.find(val); assert(iter!=valSymMap.end() &&"value sym not found"); return iter->second; } } inline bool hasValSym(const Value* val) { if (isNullPtrSym(val) || isBlackholeSym(val)) return true; else return (valSymMap.find(val) != valSymMap.end()); } /// find the unique defined global across multiple modules inline const Value* getGlobalRep(const Value* val) const { if(const GlobalVariable* gvar = SVFUtil::dyn_cast<GlobalVariable>(val)) { if (LLVMModuleSet::getLLVMModuleSet()->hasGlobalRep(gvar)) val = LLVMModuleSet::getLLVMModuleSet()->getGlobalRep(gvar); } return val; } inline SymID getObjSym(const Value *val) const { ValueToIDMapTy::const_iterator iter = objSymMap.find(getGlobalRep(val)); assert(iter!=objSymMap.end() && "obj sym not found"); return iter->second; } inline MemObj* getObj(SymID id) const { IDToMemMapTy::const_iterator iter = objMap.find(id); assert(iter!=objMap.end() && "obj not found"); return iter->second; } inline SymID getRetSym(const Function *val) const { FunToIDMapTy::const_iterator iter = returnSymMap.find(val); assert(iter!=returnSymMap.end() && "ret sym not found"); return iter->second; } inline SymID getVarargSym(const Function *val) const { FunToIDMapTy::const_iterator iter = varargSymMap.find(val); assert(iter!=varargSymMap.end() && "vararg sym not found"); return iter->second; } //@} /// Statistics //@{ inline Size_t getTotalSymNum() const { return totalSymNum; } inline u32_t getMaxStructSize() const { return maxStSize; } //@} /// Get different kinds of syms maps //@{ inline ValueToIDMapTy& valSyms() { return valSymMap; } inline ValueToIDMapTy& objSyms() { return objSymMap; } inline IDToMemMapTy& idToObjMap() { return objMap; } inline FunToIDMapTy& retSyms() { return returnSymMap; } inline FunToIDMapTy& varargSyms() { return varargSymMap; } //@} /// Get struct info //@{ ///Get an iterator for StructInfo, designed as internal methods TypeToFieldInfoMap::iterator getStructInfoIter(const Type *T) { assert(T); TypeToFieldInfoMap::iterator it = typeToFieldInfo.find(T); if (it != typeToFieldInfo.end()) return it; else { collectTypeInfo(T); return typeToFieldInfo.find(T); } } ///Get a reference to StructInfo. inline StInfo* getStructInfo(const Type *T) { return getStructInfoIter(T)->second; } ///Get a reference to the components of struct_info. const inline std::vector<u32_t>& getFattenFieldIdxVec(const Type *T) { return getStructInfoIter(T)->second->getFieldIdxVec(); } const inline std::vector<u32_t>& getFattenFieldOffsetVec(const Type *T) { return getStructInfoIter(T)->second->getFieldOffsetVec(); } const inline std::vector<FieldInfo>& getFlattenFieldInfoVec(const Type *T) { return getStructInfoIter(T)->second->getFlattenFieldInfoVec(); } const inline Type* getOrigSubTypeWithFldInx(const Type* baseType, u32_t field_idx) { return getStructInfoIter(baseType)->second->getFieldTypeWithFldIdx(field_idx); } const inline Type* getOrigSubTypeWithByteOffset(const Type* baseType, u32_t byteOffset) { return getStructInfoIter(baseType)->second->getFieldTypeWithByteOffset(byteOffset); } //@} /// Compute gep offset virtual bool computeGepOffset(const User *V, LocationSet& ls); /// Get the base type and max offset const Type *getBaseTypeAndFlattenedFields(const Value *V, std::vector<LocationSet> &fields); /// Replace fields with flatten fields of T if the number of its fields is larger than msz. u32_t getFields(std::vector<LocationSet>& fields, const Type* T, u32_t msz); /// Collect type info void collectTypeInfo(const Type* T); /// Given an offset from a Gep Instruction, return it modulus offset by considering memory layout virtual LocationSet getModulusOffset(const MemObj* obj, const LocationSet& ls); /// Debug method void printFlattenFields(const Type* type); protected: /// Collect the struct info virtual void collectStructInfo(const StructType *T); /// Collect the array info virtual void collectArrayInfo(const ArrayType* T); /// Collect simple type (non-aggregate) info virtual void collectSimpleTypeInfo(const Type* T); /// Every type T is mapped to StInfo /// which contains size (fsize) , offset(foffset) /// fsize[i] is the number of fields in the largest such struct, else fsize[i] = 1. /// fsize[0] is always the size of the expanded struct. TypeToFieldInfoMap typeToFieldInfo; ///The struct type with the most fields const Type* maxStruct; ///The number of fields in max_struct u32_t maxStSize; }; /*! * Bytes/bits-level modeling of memory locations to handle weakly type languages. * (declared with one type but accessed as another) * Abstract memory objects are created according to the static allocated size. */ class LocSymTableInfo : public SymbolTableInfo { public: /// Constructor LocSymTableInfo() { } /// Destructor virtual ~LocSymTableInfo() { } /// Compute gep offset virtual bool computeGepOffset(const User *V, LocationSet& ls); /// Given an offset from a Gep Instruction, return it modulus offset by considering memory layout virtual LocationSet getModulusOffset(const MemObj* obj, const LocationSet& ls); /// Verify struct size construction void verifyStructSize(StInfo *stInfo, u32_t structSize); protected: /// Collect the struct info virtual void collectStructInfo(const StructType *T); /// Collect the array info virtual void collectArrayInfo(const ArrayType *T); }; class LocObjTypeInfo : public ObjTypeInfo { public: /// Constructor LocObjTypeInfo(const Value* val, Type* t, Size_t max) : ObjTypeInfo(val,t,max) { } /// Destructor virtual ~LocObjTypeInfo() { } /// Get the size of this object u32_t getObjSize(const Value* val); }; #endif /* INCLUDE_SVF_FE_SYMBOLTABLEINFO_H_ */
bc8961b78db9bdcd67b798caae15e426e2e57054
b600c25c4e6108831e4e29a7f9c363681d69fa79
/include/cantera/thermo/Nasa9Poly1.h
85ee184c1b04ed6b8859589c76454defb0db1b6d
[]
no_license
MrKingKong/cantera
d19f87cd59e1005a2e185a91a506297dfbf64fbd
994c9d1afbe7089d7bfea78739ec4f5e7a907eb0
refs/heads/master
2021-01-20T17:07:07.407745
2016-04-17T03:55:51
2016-04-17T03:55:51
56,511,537
0
1
null
2016-04-18T13:49:13
2016-04-18T13:49:13
null
UTF-8
C++
false
false
4,978
h
Nasa9Poly1.h
/** * @file Nasa9Poly1.h Header for a single-species standard state object derived * from \link Cantera::SpeciesThermoInterpType * SpeciesThermoInterpType\endlink based on the NASA 9 coefficient * temperature polynomial form applied to one temperature region (see \ref * spthermo and class \link Cantera::Nasa9Poly1 Nasa9Poly1\endlink). * * This parameterization has one NASA temperature region. */ /* * Copyright (2006) Sandia Corporation. Under the terms of * Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. */ #ifndef CT_NASA9POLY1_H #define CT_NASA9POLY1_H #include "SpeciesThermoInterpType.h" namespace Cantera { //! The NASA 9 polynomial parameterization for one temperature range. /*! * This parameterization expresses the heat capacity via a 7 coefficient * polynomial. Note that this is the form used in the 2002 NASA equilibrium * program. A reference to the form is provided below: * * "NASA Glenn Coefficients for Calculating Thermodynamic Properties of * Individual Species," B. J. McBride, M. J. Zehe, S. Gordon * NASA/TP-2002-211556, Sept. 2002 * * Nine coefficients \f$(a_0,\dots,a_8)\f$ are used to represent * \f$ C_p^0(T)\f$, \f$ H^0(T)\f$, and \f$ S^0(T) \f$ as * polynomials in \f$ T \f$ : * \f[ * \frac{C_p^0(T)}{R} = a_0 T^{-2} + a_1 T^{-1} + a_2 + a_3 T * + a_4 T^2 + a_5 T^3 + a_6 T^4 * \f] * * \f[ * \frac{H^0(T)}{RT} = - a_0 T^{-2} + a_1 \frac{\ln T}{T} + a_2 * + \frac{a_3}{2} T + \frac{a_4}{3} T^2 + \frac{a_5}{4} T^3 + * \frac{a_6}{5} T^4 + \frac{a_7}{T} * \f] * * \f[ * \frac{s^0(T)}{R} = - \frac{a_0}{2} T^{-2} - a_1 T^{-1} + a_2 \ln T * + a_3 T + \frac{a_4}{2} T^2 + \frac{a_5}{3} T^3 + \frac{a_6}{4} T^4 + a_8 * \f] * * The standard state is assumed to be an ideal gas at the standard pressure of * 1 bar, for gases. For condensed species, the standard state is the pure * crystalline or liquid substance at the standard pressure of 1 atm. * * These NASA representations may have multiple temperature regions through the * use of the Nasa9PolyMultiTempRegion object, which uses multiple copies of * this Nasa9Poly1 object to handle multiple temperature regions. * * @ingroup spthermo * @see Nasa9PolyMultiTempRegion */ class Nasa9Poly1 : public SpeciesThermoInterpType { public: //! Empty constructor Nasa9Poly1(); //! Normal constructor /*! * @param tlow Minimum temperature * @param thigh Maximum temperature * @param pref reference pressure (Pa). * @param coeffs Vector of coefficients used to set the * parameters for the standard state. */ Nasa9Poly1(double tlow, double thigh, double pref, const double* coeffs); virtual SpeciesThermoInterpType* duplMyselfAsSpeciesThermoInterpType() const; virtual int reportType() const; virtual size_t temperaturePolySize() const { return 7; } virtual void updateTemperaturePoly(double T, double* T_poly) const; /*! * @copydoc SpeciesThermoInterpType::updateProperties * * Temperature Polynomial: * - tt[0] = t; * - tt[1] = t*t; * - tt[2] = t*t*t; * - tt[3] = t*t*t*t; * - tt[4] = 1.0/t; * - tt[5] = 1.0/(t*t); * - tt[6] = std::log(t); */ virtual void updateProperties(const doublereal* tt, doublereal* cp_R, doublereal* h_RT, doublereal* s_R) const; virtual void updatePropertiesTemp(const doublereal temp, doublereal* cp_R, doublereal* h_RT, doublereal* s_R) const; //! This utility function reports back the type of parameterization and all //! of the parameters for the species /*! * All parameters are output variables * * @param n Species index * @param type Integer type of the standard type * @param tlow output - Minimum temperature * @param thigh output - Maximum temperature * @param pref output - reference pressure (Pa). * @param coeffs Vector of coefficients used to set the parameters for * the standard state. There are 12 of them, designed to be compatible * with the multiple temperature formulation. * - coeffs[0] is equal to one. * - coeffs[1] is min temperature * - coeffs[2] is max temperature * - coeffs[3+i] from i =0,9 are the coefficients themselves */ virtual void reportParameters(size_t& n, int& type, doublereal& tlow, doublereal& thigh, doublereal& pref, doublereal* const coeffs) const; virtual void modifyParameters(doublereal* coeffs); protected: //! array of polynomial coefficients vector_fp m_coeff; }; } #endif
2fd55515552a328cb5378e852df47971527b76a6
dc521971da2b2984a276e3c6f946409c4b02ad1b
/four 4's/la5.h
cadf33c3e376538c5e56a00f67982d80f283cc91
[]
no_license
sjakson/Cplusplus
9146e362d06904564be61b3a3e8bc9749f171359
435a010e91907c269a7c8895ee133c5bc9490688
refs/heads/master
2021-06-15T02:00:26.361242
2021-02-19T08:32:09
2021-02-19T08:32:09
141,215,983
0
0
null
null
null
null
UTF-8
C++
false
false
2,437
h
la5.h
//Jackson, Scott 003092073 /*This is the header file that stores the expression tree node struct and the expression tree struct*/ #ifndef EXPRNODE_H #define EXPREODE_H const int NUMBER = 0, // Values representing two kinds of nodes. OPERATOR = 1; #include<string> #include<cmath> #include<sstream> #include<algorithm> #include<cstdlib> struct ExpNode { // A node in an expression tree. int kind; // Which type of node is this? // (Value is NUMBER or OPERATOR.) double number; // The value in a node of type NUMBER. int op, op1, op2, op3; // The operator in a node of type OPERATOR. ExpNode *left; // Pointers to subtrees, ExpNode *right; // in a node of type OPERATOR. ExpNode *GetLeftSubtree() const { return left; } ExpNode *GetRightSubtree() const { return right; } ExpNode(){} ExpNode( double val ) { // Constructor for making a node of type NUMBER. // The are only allowed to me leaves kind = NUMBER; number = val; this->left = NULL; this->right = NULL; } ExpNode( int op, ExpNode *left, ExpNode *right ) { // Constructor for making a node of type OPERATOR. kind = OPERATOR; this->op = op; this->left = left; this->right = right; } std::string ToString() const { //Converts the value in the node from an integer to a string if (kind == NUMBER) { std::stringstream s; s << int(number); return s.str(); } else { switch (op) { case 0: return "+"; case 1: return "-"; case 2: return "*"; case 3: return "/"; case 4: return "^"; } return "?"; } } double Evaluate() const { //computes the solution to the expression tree if (kind == NUMBER) { return number; } else { double lhs = GetLeftSubtree()->Evaluate(); double rhs = GetRightSubtree()->Evaluate(); switch (op) { case 0: return lhs + rhs; case 1: return lhs - rhs; case 2: return lhs * rhs; case 3: return lhs / rhs; case 4: return pow(lhs, rhs); } } } }; struct ExpTree{ //stores the infix form , postfix form and solution for each expression tree std::string infix; std::string postfix; double value; }; #endif
16811e93d715275a425ae6908e72cbcf16bd9efb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_3462_squid-3.3.14.cpp
c79ed0ee28e1599208da2249351f098514e8dca2
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
squid_repos_function_3462_squid-3.3.14.cpp
void * ClientSocketContext::operator new (size_t byteCount) { /* derived classes with different sizes must implement their own new */ assert (byteCount == sizeof (ClientSocketContext)); CBDATA_INIT_TYPE(ClientSocketContext); return cbdataAlloc(ClientSocketContext); }