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
76981e637f6976ee80601348bfb45110fc442203
cd3138b3a6cd90fef96c018eec907cee89c2acdb
/src/pattern/mixture/Component.h
8c098e012ca1c2a8dec0eb489c96292e62dfc067
[]
no_license
naxo100/PExKa
56fdc8e0852e9d4a9a0bf5788c921d26da2607dc
96605468f02e0b97baad50b7bc3310f23f56b1ca
refs/heads/master
2021-07-21T05:45:57.229379
2020-04-29T12:58:25
2020-04-29T12:58:25
48,058,530
2
0
null
null
null
null
UTF-8
C++
false
false
1,960
h
Component.h
/* * Component.h * * Created on: Jan 21, 2019 * Author: naxo100 */ #ifndef SRC_PATTERN_MIXTURE_COMPONENT_H_ #define SRC_PATTERN_MIXTURE_COMPONENT_H_ #include "Mixture.h" namespace pattern { /** \brief Defines a set of agents that are explicitly connected by sites. * Class Mixture is initialized empty and then filled with agents and links. * After that, setGraph() must be called to reorder agents and produce graph, * making the mixture comparable and ready to be declared in the environment. * */ class Mixture::Component : public Pattern { friend class Mixture; short_id id; vector<Agent*> agents; union { list<ag_st_id> *links; //(comp_ag_id,site_id) -> (comp_ag_id,site_id) map<ag_st_id,ag_st_id> *graph; }; list<pair<const simulation::Rule&,small_id>> deps; //map<big_id,ag_st_id> auxiliars; public: Component(); Component(const Component& comp); ~Component(); bool contains(const Mixture::Agent* a); short addAgent(Mixture::Agent* a); void addLink(const pair<ag_st_id,ag_st_id> &lnk,const map<short,short> &mask); size_t size() const override; void setId(short_id i); short_id getId() const; const vector<Agent*>::const_iterator begin() const; const vector<Agent*>::const_iterator end() const; vector<small_id> setGraph(); const map<ag_st_id,ag_st_id>& getGraph() const; string toString(const Environment& env) const; const Agent& getAgent(small_id ag_id ) const override; //void setAuxCoords(const std::map<std::string,std::tuple<int,small_id,small_id>>& aux_coords); /** \brief Returns agent and site ids of site-link * exception-safe * return ag_id,site on fail */ ag_st_id follow(small_id ag_id,small_id site) const; bool operator==(const Mixture::Component &m) const; void addRateDep(const simulation::Rule& dep,small_id cc); const list<pair<const simulation::Rule&,small_id>>& getRateDeps() const; }; } /* namespace pattern */ #endif /* SRC_PATTERN_MIXTURE_COMPONENT_H_ */
811944739ad5210bef19ae078520d83f7558d53a
1cfd20fa175e1751d1441f32f990ece5423c484a
/algorithms/0023_MergekSortedLists/0023_MergekSortedLists.cpp
ff7fab8867d4fdb28956e725b51f8d34b4a7677e
[ "MIT" ]
permissive
243468234/leetcode-question
9cdfc0db329d8b7b380674b1ebad8e05d624c6b8
35aad4065401018414de63d1a983ceacb51732a6
refs/heads/master
2022-11-25T13:30:42.650593
2020-08-02T07:43:48
2020-08-02T07:43:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
882
cpp
0023_MergekSortedLists.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* merge(vector <ListNode*> &lists, int l, int r) { if (l == r) return lists[l]; if (l > r) return nullptr; int mid = (l + r) >> 1; return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r)); } ListNode* mergeKLists(vector<ListNode*>& lists) { return merge(lists, 0, lists.size() - 1); } ListNode* mergeTwoLists (ListNode* l1, ListNode* l2){ if(!l1) return l2; if(!l2) return l1; if(l1->val <= l2->val){ l1->next = mergeTwoLists(l1->next,l2); return l1; } else{ l2->next = mergeTwoLists(l1,l2->next); return l2; } }; };
8b107716a96284c7f8f20b06fb455d815695a864
25d30e51b9dca92df293a54414bd3832d6c11409
/map.cpp
d92abd6d23739551d9e3270276c6b330900bd720
[]
no_license
ColinBin/minimal_SRPG
2f93916c2612e67aef4ce6ec2f772bc461563959
75ebd3a9482932315d17b11cbe0fbf983d2124a9
refs/heads/master
2020-04-06T07:56:10.354259
2016-09-10T12:55:14
2016-09-10T12:55:14
65,596,556
3
1
null
null
null
null
UTF-8
C++
false
false
3,567
cpp
map.cpp
#include <iostream> #include <iomanip> #include <cmath> #include "map.h" using namespace std; Map::Map(int length,int width){ this->length=length; this->width=width; SetMap(this->length,this->width); } Map::Map(){ length=20; width=20; SetMap(length,width); } Map::~Map(){ // free Position arrays first for(int i=0;i<length;i++){ delete [] atlas[i]; } // free Position pointer array delete [] atlas; atlas=NULL; } void Map::SetMap(int length,int width){ // space for position pointer array atlas=new Position*[length]; for(int i=0;i<length;i++){ // space for position arrays atlas[i]=new Position[width]; for(int j=0;j<width;j++){ atlas[i][j].SetXY(i,j); } } } void Map::PlaceCharacter(Character* character,int x,int y){ atlas[x][y].SetCharacter(character); character->SetPosition(&atlas[x][y]); } void Map::MoveCharacter(Character* character,int x,int y){ character->GetPosition()->UnsetCharacter(); PlaceCharacter(character,x,y); } void Map::Show(){ for(int i=0;i<length;i++){ for(int j=0;j<width;j++){ Character* temp=atlas[i][j].GetCharacter(); // set background color cout<<((i+j)%2?BG_BLACK:BG_WHITE); if(temp!=NULL){ string stamp=temp->GetCareerStamp(); cout<<((temp->GetCamp()==DEFENDER)?F_RED:F_BLUE)<<HIGHLIGHT; cout.width(2); cout<<stamp<<OFF; }else{ cout.width(2); cout<<" "; } } cout<<OFF<<endl; } } void Map::ShowMove(Character* character,int cursor_x,int cursor_y){ int x=character->GetPosition()->GetX(); int y=character->GetPosition()->GetY(); for(int i=0;i<length;i++){ for(int j=0;j<width;j++){ if(x==i&&y==j){ // twinkle effect on current character cout<<TWINKLE; } Character* temp=atlas[i][j].GetCharacter(); int difference_sum=abs(x-i)+abs(y-j); // set base background color if(i==cursor_x&&j==cursor_y){ // if current location is where the cursor is cout<<BG_PURPLE; }else if(character->CheckMoveRange(i,j)&&temp==NULL){ // if current location is accessible cout<<((difference_sum%2)?BG_D_GREEN:BG_GREEN); }else{ // inaccessible location cout<<((i+j)%2?BG_BLACK:BG_WHITE); } if(temp!=NULL){ string stamp=temp->GetCareerStamp(); cout<<((temp->GetCamp()==DEFENDER)?F_RED:F_BLUE)<<HIGHLIGHT; cout.width(2); cout<<stamp<<OFF; }else{ cout.width(2); cout<<" "; } } cout<<OFF<<endl; } } void Map::ShowAttack(Character* character,int cursor_x,int cursor_y){ int x=character->GetPosition()->GetX(); int y=character->GetPosition()->GetY(); for(int i=0;i<length;i++){ for(int j=0;j<width;j++){ if(x==i&&y==j){ // twinkle effect on current character cout<<TWINKLE; } Character* temp=atlas[i][j].GetCharacter(); int difference_sum=abs(x-i)+abs(y-j); // set base background color if(i==cursor_x&&j==cursor_y){ // if current location is where the cursor is cout<<BG_PURPLE; }else if(character->CheckAttackRange(i,j)){ // in attack range cout<<((difference_sum%2)?BG_RED:BG_YELLOW); }else{ // inaccessible location cout<<(((i+j)%2)?BG_BLACK:BG_WHITE); } if(temp!=NULL){ string stamp=temp->GetCareerStamp(); cout<<((temp->GetCamp()==DEFENDER)?F_RED:F_BLUE)<<HIGHLIGHT; cout.width(2); cout<<stamp<<OFF; }else{ cout.width(2); cout<<" "<<OFF; } } cout<<OFF<<endl; } } int Map::GetLength(){ return length; } int Map::GetWidth(){ return width; } Character* Map::IsOccupied(int x,int y){ return atlas[x][y].GetCharacter(); }
03a3311675e50e8b49f8ad8c16e9660a061122f6
59638c368c9020f03e32efbfbd4ec2d122ce71df
/src/helper/AKROSD.cc
0315503981ae67a9d7ce26f6081fe1c5104e9c29
[]
no_license
cheidegg/dileptons
845b504616dc74ed50124a64b2ff9b2365e2a8ab
da9f2a62a0e0d4e3ee3a94a3115f85c8264f5242
refs/heads/master
2020-05-18T22:24:22.003438
2014-10-06T13:59:36
2014-10-06T13:59:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,558
cc
AKROSD.cc
/***************************************************************************** ****************************************************************************** ****************************************************************************** ** ** ** The Dileptons Analysis Framework ** ** ** ** Constantin Heidegger, CERN, Summer 2014 ** ** ** ****************************************************************************** ****************************************************************************** *****************************************************************************/ #ifndef AKROSD_cc #define AKROSD_cc #include <TString.h> #include "src/helper/Tools.cc"; typedef TString AKROSD; namespace AKROSD { //____________________________________________________________________________ inline bool CheckStringForDefinedVariables(AKROSD string, std::vector<AKROSD> osdefinitions){ /* checks the AKROSD string according to the rules of defined event variables parameters: string (AKROSD string to be checked), osdefinitions (vector of AKROSD strings for object selection definitions) return: true (if everything is ok), false (else) */ } //____________________________________________________________________________ inline bool CheckStringForEventSelection(AKROSD string, std::vector<AKROSD> osdefinitions){ /* checks the AKROSD string according to the rules of event selection definitions parameters: string (AKROSD string to be checked), osdefinitions (vector of AKROSD strings for object selection definitions) return: true (if everything is ok), false (else) */ } //____________________________________________________________________________ inline bool CheckStringForObjectSelection(AKROSD string){ /* checks the AKROSD string according to the rules of object selection definitions parameters: string (AKROSD string to be checked) return: true (if everything is ok), false (else) */ } //____________________________________________________________________________ inline AKROSD RemoveStatements(AKROSD string, AKROSD needle){ /* removes statements containing needle from a AKROSD string parameters: string (AKROSD string to be edited), needle (AKROSD substring to identify statements that need to be removed) return: new_string (edited string) */ } //____________________________________________________________________________ inline AKROSD SortStatements(AKROSD string){ /* sorts the statements of the AKROSD string alphabetically parameters: string (AKROSD string to be edited) return: new_string (edited string) */ } //____________________________________________________________________________ inline AKROSD NegateStatement(AKROSD statement){ /* negates a single regular statement of the AKROSD string parameters: statement (single AKROSD statement) return: newstatement (negated statement) */ AKROSD newstatement = statement; TString searchfor[6] = {"++", "--", "=" , "!=", "+" , "-" }; // order of arguments is important! TString replaceby[6] = {"-" , "+" , "!=", "=" , "--", "++"}; // order of arguments is important! for(int i = 0; i<6; ++i){ newstatement = newstatement.ReplaceAll(searchfor[i], replaceby[i]); return newstatement; } //____________________________________________________________________________ inline AKROSD NegateStatements(AKROSD string, AKROSD needle){ /* negates statements containing needle in a AKROSD string parameters: string (AKROSD string to be edited), needle (AKROSD substring to identify statements that need to negated) return: new_string (edited string) */ } //____________________________________________________________________________ AKROSD InterpretRangeStatements(AKROSD string){ /* performs the interpretation of ALL range statements (e.g. NJ+2-3) used in an AKROSD string parameters: string (AKROSD string) return: newstring (interpreted AKROSD string) */ AKROSD newstring; AKROSD statement; AKROSD lastdelimiter; for(Ssiz_t position = 0; position < string.Length(); ++position){ // search through every char of the AKROSD string AKROSD delimiter = string(position,1); // if the char is no , or | we attach it to the statement if(delimiter != "," && delimiter != "|") { statement += delimiter; } // if the char is indeed , or | or if we have reached the end of the string // the statement is complete else if(delimiter == "," || delimiter == "|" || position + 1 == string.Length()) { // looking for a range statement which (1) is no if-th-el statement and (2) contains // + and - operators at the same time if(Tools::CountTStringOccurrence(statement, "%if") == 0 && Tools::CountTStringOccurrence(statement, "+") > 0 && Tools::CountTStringOccurrence(statement, "-") > 0) { // define which operator oomes first in the statement AKROSD first = "-"; AKDOSD second = "+"; if(statement.Index("+") > 0 && statement.Index("+") < statement.Index("-")){ first = "+"; second = "-"; } // we explode the statement twice at every operator in order to get the information between them // i.e. the statement looks like AAA+BBB-CCC (or AAA-CCC+BBB) and we want to interpret this as // AAA+BBB,AAA-CCC (or alternatively AAA-CCC,AAA+BBB) so we need to get AAA, BBB and CCC individually std::vector<AKROSD> explode1 = Tools::ExplodeTString(statement, first); std::vector<AKROSD> explode2 = Tools::ExplodeTString(explode1[1], second); statement = "(" + explode1[0] + first + explode2[0] + "," + explode1[0] + second + explode2[1] + ")"; } // add the interpreted statement to the new string newstring = newstring + lastdelimiter + statement; // reset everything and be prepared for the next statement lastdelimiter = delimiter; statement = ""; } } return newstring; } //____________________________________________________________________________ inline AKROSD InterpretIfThElStatements(AKROSD string){ /* performs the interpretation of ALL if-th-el statements used in an AKROSD string parameters: string (AKROSD string) return: newstring (interpreted AKROSD string) */ // we first add a whitespace because Index will return 0 if we find '%if' at the first // position in the string and 0 is interpreted as false in the subsequent if-clause string = " " + string; Ssiz_t first = string.Index("%if"); if(first > 0){ // if the next separator is | instead of an , we separate by |, otherwise we separate by , TString lookfor = ","; if(string.Index("|", first) > 0 && string.Index("|", first) < string.Index(",", first)) lookfor = "|"; if(string.Index(lookfor, first) > 0) Ssiz_t separate = string.Index(lookfor, first); else Ssiz_t separate = string.Length(); // we take out the first if-th-el statement from left AKROSD statement = string(first, separate - first); statement = statement.Strip(kBoth, " "); // we take out the three regular statements between the if, th and el keywords // i.e. the statement looks like ifAAAthBBBelCCC and we want to get AAA, BBB, CCC individually std::vector<AKROSD> explode1 = Tools::ExplodeTString(statement, "th"); std::vector<AKROSD> explode2 = Tools::ExplodeTString(explode1[1], "el"); AKROSD ifstatement = explode1[0](3, explode1[0].Length()-3); AKROSD thstatement = explode2[0]; AKROSD elstatement = explode2[1]; ifstatement.Strip(kBoth, " "); thstatement.Strip(kBoth, " "); elstatement.Strip(kBoth, " "); // interpreting the if-th-el statement statement = "((" + ifstatement + "," + thstatement + ")|(" + AKROSD::NegateStatement(ifstatement) + "," + elstatement + "))"; // remaining if-th-el statements are interpreted one after another recursively return string(0,first).Strip(kBoth, " ") + statement + AKROSD::InterpretIfThElStatements(string(separate, string.Length()-separate)); } else { return string; } } //____________________________________________________________________________ inline AKROSD InterpretAbbreviations(AKROSD string){ /* performs the interpretation of the abbreviations used in an AKROSD string parameters: string (AKROSD string) return: newstring (interpreted AKROSD string) */ AKROSD new_string; // $newstring=""; $searchforlist[0] = array('CH' , 'PT' , 'ETA' , 'PHI'); $replacebylist[0] = array('ElCharge', 'ElPt', 'ElEta', 'ElPhi'); $searchforlist[1] = array('LE' , 'VM'); $replacebylist[1] = array('Loose-Electron-', 'Veto-Muon-'); $searchforlist[2] = array('M', 'E'); $replacebylist[2] = array('Muon-', 'Electron-'); for($k=0;$k<3;$k++) { $done = false; echo "k: ". $k.", "; for($i=1;$i<=strlen($string);$i++){ echo "i: ". $i.", "; for($j=0;$j<sizeof($searchforlist[$k]);$j++) { echo "j: ". $j.", substr: ".substr($string,-$i).", searchfor: ".$searchforlist[$k][$j].", "; if(substr($string,-$i) == $searchforlist[$k][$j]) { $string=substr($string,0,strlen($string)-$i); $newstring=$replacebylist[$k][$j].$newstring; $done = true; } echo "replaceby: ".$replacebylist[$k][$j].", newstring: ".$newstring.", string: ".$string.", done: ".$done."<br />"; if($done) break 2; } } } for($i=0;$i<sizeof($searchfor);$i++) $string = str_replace($searchfor[$i], $replaceby[$i], $string); return $newstring; } //____________________________________________________________________________ inline AKROSD InterpretOperators(AKROSD string){ /* performs the interpretation of the operators used in an AKROSD string parameters: string (AKROSD string) return: newstring (interpreted AKROSD string) */ AKROSD newstring = string; TString searchfor[6] = {"++", "--", "=" , "!=", "+" , "-" }; // order of arguments is important! TString replaceby[6] = {">" , "<" , "==", "!=", ">=", "<="}; // order of arguments is important! for(int i = 0; i<6; ++i){ newstring = newstring.ReplaceAll(searchfor[i], replaceby[i]); return newstring; } //____________________________________________________________________________ inline AKROSD InterpretString(AKROSD string){ /* performs the interpretation of the AKROSD string parameters: string (AKROSD string) return: newstring (interpreted AKROSD string) */ AKROSD newstring; newstring = string.ReplaceAll(" ", ""); newstring = InterpretRangeStatements(newstring); newstring = InterpretIfThElStatements(newstring); newstring = newstring.ReplaceAll(",", " && "); newstring = newstring.ReplaceAll("|", " || "); newstring = InterpretAbbreviations(newstring); newstring = InterpretOperators(newstring); return $newstring; } } #endif
5f7f57840a0446f1c84898bd361e721f67b6fc5c
3030937abd11eff11b6fd84dc7108f229c459069
/test3d/Window.h
aa7ad08f3e45d3a520e8e98200cecb6eac82bfc7
[]
no_license
j4ra/test3d
09376275a354f90e979df719d4d244c12a3003a2
82ae4b31d5cfbfb1a12dae8c7af47077a9c1ac86
refs/heads/master
2021-06-25T06:52:33.150761
2021-03-23T12:39:45
2021-03-23T12:39:45
213,878,460
0
0
null
null
null
null
UTF-8
C++
false
false
2,512
h
Window.h
#pragma once #include "MiniWindows.h" #include "BaseException.h" #include "Keyboard.h" #include "Mouse.h" #include "Graphics.h" #include <string> #include <memory> #include <optional> #define WND_CLASS_NAME "test3d_window" namespace Application { class Window { public: class Exception : public BaseException { using BaseException::BaseException; public: static std::string TranslateMessage(HRESULT hr); }; class HrException : public Exception { using Exception::Exception; public: HrException(int line, const char* file, HRESULT hr) noexcept; std::string GetErrorString() const noexcept; HRESULT GetErrorCode() const noexcept; const char* GetType() const noexcept override; const char* what() const noexcept override; private: HRESULT hr; }; class NoGfxException : public Exception { using Exception::Exception; public: const char* GetType() const noexcept override; }; private: class WindowClass { public: const char* GetName() const noexcept; HINSTANCE GetInstance() const noexcept; WindowClass(const char* name); ~WindowClass(); WindowClass(const WindowClass&) = delete; WindowClass& operator=(const WindowClass&) = delete; private: std::string wndClassName; HINSTANCE hInst; }; public: Window(int width, int height, const char* name); ~Window(); Window(const Window&) = delete; Window& operator=(const Window&) = delete; Rendering::Graphics& Gfx(); inline const Mouse& GetMouse() { return mouse; } inline const Keyboard& GetKeyboard() { return kbd; } void SetTitle(const std::string& title); static std::optional<int> ProcessMessages(); private: static LRESULT CALLBACK HandleMsgSetup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK HandleMsgThunk(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT HandleMsg(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) noexcept; private: WindowClass wndClass; Keyboard kbd; Mouse mouse; int width; int height; HWND hWnd; std::unique_ptr<Rendering::Graphics> pGfx; }; }
26b81348208b74783297d81b0af019d17cb06b08
032f89675fb2d4a4ce68127e6d500477b6515afa
/C/quick sort.cpp
533008f1632203dff1f3d1cf627b890d08e8960c
[]
no_license
silent1993/c-language
996af660056d054acc10439116f02a89489aa83f
0a93cece80b8046362b6e01fdd696e1b5d1e8f6b
refs/heads/master
2016-09-08T02:33:17.653778
2015-07-29T14:22:39
2015-07-29T14:22:39
39,870,234
1
1
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
quick sort.cpp
int FindPivot(int i,int j) { int firstkey; int k; firstkey=A[i]; for(k=i+1;k<=j;k++) { if(A[k]>firstkey) return k; else if(A[k]<firstkey) return i; } return 0; } int Partition(int i,int j,int pivot) { int l,r; l=i; r=j; do{ while(A[l]<pivot) l=l+1; while(A[r]>=pivot) r=r-1; Swap(A[l],A[r]); }while(l<=r); return 1; } void QuickSortb(int i,int j) { int pivot; int pivotindex; int k; pivotindex=FindPivot(i,j); if(pivotindex) { pivot=A[pivotindex]; k=Partition(i,j,pivot); QuickSortb(i,k-1); } } void QuickSortf(int i,int j) { int pivot; int pivotindex; int k; pivotindex=FindPivot(i,j); if(pivotindex) { pivot=A[pivotindex]; k=Partition(i,j,pivot); QuickSortf(k,j); } } int main() { Partition(1,n,A[j]); if((n-j)>(j-1)) QuickSortf(1,j); else QuickSortb(j,n); printf("%d",A[j]); }
a7e1269b467f4950a1dbe4e2c7d820edbdf5da19
6f2866cfa3620d9fe27590df94287301eeb141ed
/FractalV2/fct/unittest/Pixel_UnitTest.h
d25adfeee51a1dc76be91c83837824f2965d6443
[]
no_license
highoffscience/Birthday_Program_Fractal
cf8ec869b191af5ea2cb5dc8090123387517c8ae
92fb07595511f42e307ee737542b80517be67212
refs/heads/master
2020-03-23T02:36:57.915718
2018-07-14T22:49:03
2018-07-14T22:49:03
140,982,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,507
h
Pixel_UnitTest.h
/** * @author Forrest Jablonski */ #ifndef _FCT_UNITTEST_PIXELUNITTEST_H_ #define _FCT_UNITTEST_PIXELUNITTEST_H_ // class under test // ---------------------- #include "Pixel.h" // - using namespace fct; // - // ---------------------- // place all #includes after CUT so we don't // pollute the header file #include "TestSuiteFramework.h" /** * */ class Pixel_UnitTest : public TestSuiteFramework { public: explicit Pixel_UnitTest() = default; virtual ~Pixel_UnitTest() = default; // --------------------------------------------------------------------- // ------------------------------ Helpers ------------------------------ // --------------------------------------------------------------------- bool confirmValuesFromGetters(const Pixel& pxl, const pxl_t r, const pxl_t g, const pxl_t b, const pxl_t a, const pxl_t tolerance = 0.0); // --------------------------------------------------------------------- // ----------------------------- Test List ----------------------------- // --------------------------------------------------------------------- void test_Constructor_001(); void test_Constructor_002(); void test_Setters_001(); void test_Arithmetic_001(); void test_Arithmetic_002(); void test_Arithmetic_003(); void test_Arithmetic_004(); }; // Pixel_UnitTest #endif // hdr guard
b8eb2988110e59f15d0c8e0529b1b7ebeccc6ff6
620dbd095008650a6e534e34906923f8b04c5d47
/cpp/rte/mo_optical_props.h
a91c0cf6df88a844ed60ff7c418dd173bc9e0e80
[ "BSD-3-Clause" ]
permissive
E3SM-Project/rte-rrtmgp
8bd993a4c7acbcb5df8722306e7f3223986e4cac
ddf82a25a3a59a8f0fe904b69181cb7bd99881fb
refs/heads/master
2023-02-05T08:21:23.973022
2023-01-31T19:44:18
2023-01-31T19:44:18
221,975,040
2
1
BSD-3-Clause
2023-01-31T19:44:20
2019-11-15T17:46:51
Fortran
UTF-8
C++
false
false
19,435
h
mo_optical_props.h
#pragma once #include "rrtmgp_const.h" #include "mo_optical_props_kernels.h" // Base class for optical properties // Describes the spectral discretization including the wavenumber limits // of each band (spectral region) and the mapping between g-points and bands class OpticalProps { public: int2d band2gpt; // (begin g-point, end g-point) = band2gpt(2,band) int1d gpt2band; // band = gpt2band(g-point) int ngpt; real2d band_lims_wvn; // (upper and lower wavenumber by band) = band_lims_wvn(2,band) std::string name; // Base class: Initialization // Values are assumed to be defined in bands a mapping between bands and g-points is provided void init( real2d const &band_lims_wvn , int2d const &band_lims_gpt=int2d() , std::string name="" ) { using yakl::intrinsics::size; using yakl::intrinsics::any; using yakl::intrinsics::allocated; using yakl::intrinsics::maxval; using yakl::componentwise::operator<; using yakl::fortran::parallel_for; using yakl::fortran::SimpleBounds; int2d band_lims_gpt_lcl("band_lims_gpt_lcl",2,size(band_lims_wvn,2)); if (size(band_lims_wvn,1) != 2) { stoprun("optical_props::init(): band_lims_wvn 1st dim should be 2"); } #ifdef RRTMGP_EXPENSIVE_CHECKS if (any(band_lims_wvn < 0.)) { stoprun("optical_props::init(): band_lims_wvn has values < 0."); } #endif if (allocated(band_lims_gpt)) { if (size(band_lims_gpt,2) != size(band_lims_wvn,2)) { stoprun("optical_props::init(): band_lims_gpt size inconsistent with band_lims_wvn"); } #ifdef RRTMGP_EXPENSIVE_CHECKS if (any(band_lims_gpt < 1) ) { stoprun("optical_props::init(): band_lims_gpt has values < 1"); } #endif // for (int j=1; j <= size(band_lims_gpt,2); j++) { // for (int i=1; i <= size(band_lims_gpt,1); i++) { parallel_for( YAKL_AUTO_LABEL() , SimpleBounds<2>(size(band_lims_gpt,2),size(band_lims_gpt,1)) , YAKL_LAMBDA (int j, int i) { band_lims_gpt_lcl(i,j) = band_lims_gpt(i,j); }); } else { // Assume that values are defined by band, one g-point per band // for (int iband = 1; iband <= size(band_lims_wvn, 2); iband++) { parallel_for( YAKL_AUTO_LABEL() , SimpleBounds<1>(size(band_lims_wvn, 2)) , YAKL_LAMBDA (int iband) { band_lims_gpt_lcl(2,iband) = iband; band_lims_gpt_lcl(1,iband) = iband; }); } // Assignment this->band2gpt = band_lims_gpt_lcl; this->band_lims_wvn = band_lims_wvn; this->name = name; this->ngpt = maxval(this->band2gpt); // Make a map between g-points and bands // Efficient only when g-point indexes start at 1 and are contiguous. this->gpt2band = int1d("gpt2band",maxval(band_lims_gpt_lcl)); // TODO: I didn't want to bother with race conditions at the moment, so it's an entirely serialized kernel for now YAKL_SCOPE( this_gpt2band , this->gpt2band ); parallel_for( YAKL_AUTO_LABEL() , SimpleBounds<1>(1) , YAKL_LAMBDA (int dummy) { for (int iband=1; iband <= size(band_lims_gpt_lcl,2); iband++) { for (int i=band_lims_gpt_lcl(1,iband); i <= band_lims_gpt_lcl(2,iband); i++) { this_gpt2band(i) = iband; } } }); } void init(OpticalProps const &in) { if ( ! in.is_initialized() ) { stoprun("optical_props::init(): can't initialize based on un-initialized input"); } else { this->init( in.get_band_lims_wavenumber() , in.get_band_lims_gpoint() ); } } bool is_initialized() const { return yakl::intrinsics::allocated(this->band2gpt); } // Base class: finalize (deallocate memory) void finalize() { this->band2gpt = int2d(); this->gpt2band = int1d(); this->band_lims_wvn = real2d(); this->name = ""; } // Number of bands int get_nband() const { using yakl::intrinsics::size; if (this->is_initialized()) { return yakl::intrinsics::size(this->band2gpt,2); } return 0; } // Number of g-points int get_ngpt() const { if (this->is_initialized()) { return this->ngpt; } return 0; } // Bands for all the g-points at once; dimension (ngpt) int1d get_gpoint_bands() const { return gpt2band; } // First and last g-point of a specific band int1d convert_band2gpt(int band) const { int1d ret("band2gpt",2); if (this->is_initialized()) { ret(1) = this->band2gpt(1,band); ret(2) = this->band2gpt(2,band); } else { ret(1) = 0; ret(2) = 0; } return ret; } // Band associated with a specific g-point int convert_gpt2band(int gpt) const { if (this->is_initialized()) { return this->gpt2band(gpt); } return 0; } // The first and last g-point of all bands at once; dimension (2, nbands) int2d get_band_lims_gpoint() const { return this->band2gpt; } // Lower and upper wavenumber of all bands // (upper and lower wavenumber by band) = band_lims_wvn(2,band) real2d get_band_lims_wavenumber() const { return this->band_lims_wvn; } // Lower and upper wavelength of all bands real2d get_band_lims_wavelength() const { using yakl::intrinsics::size; using yakl::fortran::parallel_for; using yakl::fortran::SimpleBounds; real2d ret("band_lim_wavelength",size(band_lims_wvn,1),size(band_lims_wvn,2)); // for (int j = 1; j <= size(band_lims_wvn,2); j++) { // for (int i = 1; i <= size(band_lims_wvn,1); i++) { YAKL_SCOPE( this_band_lims_wvn , this->band_lims_wvn ); if (this->is_initialized()) { parallel_for( YAKL_AUTO_LABEL() , SimpleBounds<2>( size(band_lims_wvn,2) , size(band_lims_wvn,1) ) , YAKL_LAMBDA (int j, int i) { ret(i,j) = 1. / this_band_lims_wvn(i,j); }); } else { parallel_for( YAKL_AUTO_LABEL() , SimpleBounds<2>( size(band_lims_wvn,2) , size(band_lims_wvn,1) ) , YAKL_LAMBDA (int j, int i) { ret(i,j) = 0.; }); } return ret; } // Are the bands of two objects the same? (same number, same wavelength limits) bool bands_are_equal(OpticalProps const &rhs) const { using yakl::intrinsics::size; using yakl::intrinsics::epsilon; using yakl::fortran::parallel_for; using yakl::fortran::SimpleBounds; // if ( this->get_nband() != rhs.get_nband() || this->get_nband() == 0) { return false; } // yakl::ScalarLiveOut<bool> ret(true); // // for (int j=1 ; j <= size(this->band_lims_wvn,2); j++) { // // for (int i=1 ; i <= size(this->band_lims_wvn,1); i++) { // auto &this_band_lims_wvn = this->band_lims_wvn; // auto &rhs_band_lims_wvn = rhs.band_lims_wvn; // parallel_for( YAKL_AUTO_LABEL() , Bounds<2>( size(this->band_lims_wvn,2) , size(this->band_lims_wvn,1) ) , YAKL_LAMBDA (int j, int i) { // if ( abs( this_band_lims_wvn(i,j) - rhs_band_lims_wvn(i,j) ) > 5*epsilon(this_band_lims_wvn) ) { // ret = false; // } // }); // return ret.hostRead(); // This is working around an issue that arises in E3SM's rrtmgpxx integration. // Previously the code failed in the creation of the ScalarLiveOut variable, but only for higher optimizations bool ret = true; auto this_band_lims_wvn = this->band_lims_wvn.createHostCopy(); auto rhs_band_lims_wvn = rhs.band_lims_wvn .createHostCopy(); for (int j=1 ; j <= size(this->band_lims_wvn,2); j++) { for (int i=1 ; i <= size(this->band_lims_wvn,1); i++) { if ( abs( this_band_lims_wvn(i,j) - rhs_band_lims_wvn(i,j) ) > 5*epsilon(this_band_lims_wvn) ) { ret = false; } } } return ret; } // Is the g-point structure of two objects the same? // (same bands, same number of g-points, same mapping between bands and g-points) bool gpoints_are_equal(OpticalProps const &rhs) const { using yakl::intrinsics::size; using yakl::fortran::parallel_for; using yakl::fortran::SimpleBounds; if ( ! this->bands_are_equal(rhs) || this->get_ngpt() != rhs.get_ngpt() ) { return false; } // yakl::ScalarLiveOut<bool> ret(true); // // for (int i=1; i <= size(this->gpt2bnd,1); i++) { // auto &this_gpt2band = this->gpt2band; // auto &rhs_gpt2band = rhs.gpt2band; // parallel_for( YAKL_AUTO_LABEL() , Bounds<1>(size(this->gpt2band,1)) , YAKL_LAMBDA (int i) { // if ( this_gpt2band(i) != rhs_gpt2band(i) ) { ret = false; } // }); // return ret.hostRead(); // This is working around an issue that arises in E3SM's rrtmgpxx integration. // Previously the code failed in the creation of the ScalarLiveOut variable, but only for higher optimizations bool ret = true; auto this_gpt2band = this->gpt2band.createHostCopy(); auto rhs_gpt2band = rhs.gpt2band .createHostCopy(); for (int i=1; i <= size(this->gpt2band,1); i++) { if ( this_gpt2band(i) != rhs_gpt2band(i) ) { ret = false; } } return ret; } // Expand an array of dimension arr_in(nband) to dimension arr_out(ngpt) // real1d expand(real1d const &arr_in) const { // real1d ret("arr_out",size(this->gpt2band,1)); // // do iband=1,this->get_nband() // // TODO: I don't know if this needs to be serialize or not at first glance. Need to look at it more. // auto &this_band2gpt = this->gpt2band; // int nband = get_nband(); // parallel_for( YAKL_AUTO_LABEL() , Bounds<1>(1) , YAKL_LAMBDA (int dummy) { // for (int iband = 1 ; iband <= nband ; iband++) { // for (int i=this_band2gpt(1,iband) ; i <= this_band2gpt(2,iband) ; i++) { // ret(i) = arr_in(iband); // } // } // }); // return ret; // } void set_name( std::string name ) { this->name = name; } std::string get_name() const { return this->name; } }; class OpticalPropsArry : public OpticalProps { public: real3d tau; // optical depth (ncol, nlay, ngpt) int get_ncol() const { if (yakl::intrinsics::allocated(tau)) { return yakl::intrinsics::size(this->tau,1); } else { return 0; } } int get_nlay() const { if (yakl::intrinsics::allocated(tau)) { return yakl::intrinsics::size(this->tau,2); } else { return 0; } } }; // We need to know about 2str's existence because it is referenced in 1scl class OpticalProps2str; // Not implementing get_subset because it isn't used class OpticalProps1scl : public OpticalPropsArry { public: void validate() const { using yakl::intrinsics::allocated; using yakl::intrinsics::any; using yakl::componentwise::operator<; if (! allocated(this->tau)) { stoprun("validate: tau not allocated/initialized"); } #ifdef RRTMGP_EXPENSIVE_CHECKS if (any(this->tau < 0)) { stoprun("validate: tau values out of range"); } #endif } void delta_scale(real3d const &dummy) const { } void alloc_1scl(int ncol, int nlay) { if (! this->is_initialized()) { stoprun("OpticalProps1scl::alloc_1scl: spectral discretization hasn't been provided"); } if (ncol <= 0 || nlay <= 0) { stoprun("OpticalProps1scl::alloc_1scl: must provide > 0 extents for ncol, nlay"); } this->tau = real3d("tau",ncol,nlay,this->get_ngpt()); tau = 0; } // Initialization by specifying band limits and possibly g-point/band mapping void alloc_1scl(int ncol, int nlay, real2d const &band_lims_wvn, int2d const &band_lims_gpt=int2d(), std::string name="") { this->init(band_lims_wvn, band_lims_gpt, name); this->alloc_1scl(ncol, nlay); } void alloc_1scl(int ncol, int nlay, OpticalProps const &opIn, std::string name="") { if (this->is_initialized()) { this->finalize(); } this->init(opIn.get_band_lims_wavenumber(), opIn.get_band_lims_gpoint(), name); this->alloc_1scl(ncol, nlay); } void increment(OpticalProps1scl &that) { if (! this->bands_are_equal(that)) { stoprun("OpticalProps::increment: optical properties objects have different band structures"); } int ncol = that.get_ncol(); int nlay = that.get_nlay(); int ngpt = that.get_ngpt(); if (this->gpoints_are_equal(that)) { increment_1scalar_by_1scalar(ncol, nlay, ngpt, that.tau, this->tau); } else { if (this->get_ngpt() != that.get_nband()) { stoprun("OpticalProps::increment: optical properties objects have incompatible g-point structures"); } inc_1scalar_by_1scalar_bybnd(ncol, nlay, ngpt, that.tau, this->tau, that.get_nband(), that.get_band_lims_gpoint()); } } // Implemented later because OpticalProps2str hasn't been created yet inline void increment(OpticalProps2str &that); void print_norms() const { using yakl::intrinsics::sum; using yakl::intrinsics::allocated; std::cout << "name : " << name << "\n"; if (allocated(band2gpt )) { std::cout << "band2gpt : " << sum(band2gpt ) << "\n"; } if (allocated(gpt2band )) { std::cout << "gpt2band : " << sum(gpt2band ) << "\n"; } if (allocated(band_lims_wvn)) { std::cout << "band_lims_wvn: " << sum(band_lims_wvn) << "\n"; } if (allocated(tau )) { std::cout << "tau : " << sum(tau ) << "\n"; } } }; // Not implementing get_subset because it isn't used class OpticalProps2str : public OpticalPropsArry { public: real3d ssa; // single-scattering albedo (ncol, nlay, ngpt) real3d g; // asymmetry parameter (ncol, nlay, ngpt) void validate() const { using yakl::intrinsics::size; using yakl::intrinsics::allocated; using yakl::intrinsics::any; using yakl::componentwise::operator<; using yakl::componentwise::operator>; if ( ! allocated(this->tau) || ! allocated(this->ssa) || ! allocated(this->g) ) { stoprun("validate: arrays not allocated/initialized"); } int d1 = size(this->tau,1); int d2 = size(this->tau,2); int d3 = size(this->tau,3); if ( d1 != size(this->ssa,1) || d2 != size(this->ssa,2) || d3 != size(this->ssa,3) || d1 != size(this->g ,1) || d2 != size(this->g ,2) || d3 != size(this->g ,3) ) { stoprun("validate: arrays not sized consistently"); } #ifdef RRTMGP_EXPENSIVE_CHECKS if (any(this->tau < 0) ) { stoprun("validate: tau values out of range"); } if (any(this->ssa < 0) || any(this->ssa > 1)) { stoprun("validate: ssa values out of range"); } if (any(this->g < -1) || any(this->g > 1)) { stoprun("validate: g values out of range"); } #endif } void delta_scale(real3d const &forward=real3d()) { using yakl::intrinsics::size; using yakl::intrinsics::allocated; using yakl::intrinsics::any; using yakl::componentwise::operator<; using yakl::componentwise::operator>; // Forward scattering fraction; g**2 if not provided int ncol = this->get_ncol(); int nlay = this->get_nlay(); int ngpt = this->get_ngpt(); if (allocated(forward)) { if (size(forward,1) != ncol || size(forward,2) != nlay || size(forward,3) != ngpt) { stoprun("delta_scale: dimension of 'forward' don't match optical properties arrays"); } #ifdef RRTMGP_EXPENSIVE_CHECKS if (any(forward < 0) || any(forward > 1)) { stoprun("delta_scale: values of 'forward' out of bounds [0,1]"); } #endif delta_scale_2str_kernel(ncol, nlay, ngpt, this->tau, this->ssa, this->g, forward); } else { delta_scale_2str_kernel(ncol, nlay, ngpt, this->tau, this->ssa, this->g); } } void alloc_2str(int ncol, int nlay) { if (! this->is_initialized()) { stoprun("optical_props::alloc: spectral discretization hasn't been provided"); } if (ncol <= 0 || nlay <= 0) { stoprun("optical_props::alloc: must provide positive extents for ncol, nlay"); } this->tau = real3d("tau",ncol,nlay,this->get_ngpt()); this->ssa = real3d("ssa",ncol,nlay,this->get_ngpt()); this->g = real3d("g ",ncol,nlay,this->get_ngpt()); tau = 0; ssa = 0; g = 0; } void alloc_2str(int ncol, int nlay, real2d const &band_lims_wvn, int2d const &band_lims_gpt=int2d(), std::string name="") { this->init(band_lims_wvn, band_lims_gpt, name); this->alloc_2str(ncol, nlay); } void alloc_2str(int ncol, int nlay, OpticalProps const &opIn, std::string name="") { if (this->is_initialized()) { this->finalize(); } this->init(opIn.get_band_lims_wavenumber(), opIn.get_band_lims_gpoint(), name); this->alloc_2str(ncol, nlay); } void increment(OpticalProps1scl &that) { if (! this->bands_are_equal(that)) { stoprun("OpticalProps::increment: optical properties objects have different band structures"); } int ncol = that.get_ncol(); int nlay = that.get_nlay(); int ngpt = that.get_ngpt(); if (this->gpoints_are_equal(that)) { increment_1scalar_by_2stream(ncol, nlay, ngpt, that.tau, this->tau, this->ssa); } else { if (this->get_ngpt() != that.get_nband()) { stoprun("OpticalProps::increment: optical properties objects have incompatible g-point structures"); } inc_1scalar_by_2stream_bybnd(ncol, nlay, ngpt, that.tau, this->tau, this->ssa, that.get_nband(), that.get_band_lims_gpoint()); } } void increment(OpticalProps2str &that) { if (! this->bands_are_equal(that)) { stoprun("OpticalProps::increment: optical properties objects have different band structures"); } int ncol = that.get_ncol(); int nlay = that.get_nlay(); int ngpt = that.get_ngpt(); if (this->gpoints_are_equal(that)) { increment_2stream_by_2stream(ncol, nlay, ngpt, that.tau, that.ssa, that.g, this->tau, this->ssa, this->g); } else { if (this->get_ngpt() != that.get_nband()) { stoprun("OpticalProps::increment: optical properties objects have incompatible g-point structures"); } inc_2stream_by_2stream_bybnd(ncol, nlay, ngpt, that.tau, that.ssa, that.g, this->tau, this->ssa, this->g, that.get_nband(), that.get_band_lims_gpoint()); } } void print_norms() const { using yakl::intrinsics::sum; using yakl::intrinsics::allocated; std::cout << "name : " << name << "\n"; if (allocated(band2gpt )) { std::cout << "band2gpt : " << sum(band2gpt ) << "\n"; } if (allocated(gpt2band )) { std::cout << "gpt2band : " << sum(gpt2band ) << "\n"; } if (allocated(band_lims_wvn)) { std::cout << "band_lims_wvn: " << sum(band_lims_wvn) << "\n"; } if (allocated(tau )) { std::cout << "tau : " << sum(tau ) << "\n"; } if (allocated(ssa )) { std::cout << "ssa : " << sum(ssa ) << "\n"; } if (allocated(g )) { std::cout << "g : " << sum(g ) << "\n"; } } }; inline void OpticalProps1scl::increment(OpticalProps2str &that) { if (! this->bands_are_equal(that)) { stoprun("OpticalProps::increment: optical properties objects have different band structures"); } int ncol = that.get_ncol(); int nlay = that.get_nlay(); int ngpt = that.get_ngpt(); if (this->gpoints_are_equal(that)) { increment_2stream_by_1scalar(ncol, nlay, ngpt, that.tau, that.ssa, this->tau); } else { if (this->get_ngpt() != that.get_nband()) { stoprun("OpticalProps::increment: optical properties objects have incompatible g-point structures"); } inc_2stream_by_1scalar_bybnd(ncol, nlay, ngpt, that.tau, that.ssa, this->tau, that.get_nband(), that.get_band_lims_gpoint()); } }
94b21cd6efe39fc2f2201cac3421746d82826c2c
90c3f3bc5d0dea8de15e9d07aa55f010f1cd773d
/minimum-window-substring/main_optimize.cpp
a5b9f3f1ac0be11b8e3eb227c4e5d3cb330f9bdc
[]
no_license
kmiku7/leetcode
d3ad4251b199f672e8f7d3377ed2db075f7ca216
3e56d2be80be01ff64d0ff2bb2efdd87c3dcefb1
refs/heads/master
2021-01-18T15:06:11.706879
2015-10-04T15:48:57
2015-10-04T15:48:57
26,670,616
0
0
null
null
null
null
UTF-8
C++
false
false
1,973
cpp
main_optimize.cpp
#include <iostream> #include <string> #include <unordered_map> #include <climits> using namespace std; class Solution { public: string minWindow(string S, string T) { int unique_count = 0; int unique_expect = 0; int alpha_count[256] = {0}; int alpha_expect[256] = {0}; for(auto c : T){ alpha_expect[c] += 1; unique_expect += (alpha_expect[c]==1); } const char *s_begin = S.c_str(); const char *s_guard = s_begin + S.size(); const char *s_end = NULL; const char *min_start = NULL; int min_len = INT_MAX; while(s_begin<s_guard && alpha_expect[*s_begin]==0) ++s_begin; s_end = s_begin - 1; while(s_begin<s_guard && s_end<s_guard) { if(unique_expect == unique_count) { if(s_end-s_begin+1<min_len) { min_start = s_begin; min_len = s_end-s_begin+1; } if(alpha_count[*s_begin] == alpha_expect[*s_begin]) --unique_count; alpha_count[*s_begin] -= 1; ++s_begin; while(s_begin<s_guard && alpha_expect[*s_begin]==0) ++s_begin; } else { ++s_end; while(s_end<s_guard && alpha_expect[*s_end]==0) ++s_end; if(s_end>=s_guard) continue; alpha_count[*s_end] += 1; if(alpha_expect[*s_end] == alpha_count[*s_end]) unique_count += 1; } } if(min_start==NULL) return ""; return string(min_start, min_start+min_len); } }; int main(int argc, char** argv) { string S = "ADOBECODEBANC"; string T = "ABC"; string SA = "AAAAAAAAAAABB"; string TA = "AAAAB"; string SB = "abc"; string TB = "b"; Solution s; cout << s.minWindow(S, T) << endl; cout << s.minWindow(SA, TA) << endl; cout << s.minWindow(SB, TB) << endl; return 0; }
fe57b09eb0ebb6073f2a68a82bbbae8d94fcb26d
259bd4b12bef8f6c3e5150195efbd9533c7d67a5
/3684.cpp
6a7630ce569c62c310350e105f7b36b89f2ed5cc
[]
no_license
hank08tw/poj
daf7e579a81ba62bbfc76308f244dc7b6c86135d
4959b782e32ee22981b8cdaed4fefefe382ea60c
refs/heads/master
2020-03-07T18:53:55.538374
2018-09-22T01:20:48
2018-09-22T01:20:48
127,655,791
2
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
3684.cpp
#include <iostream> #include <algorithm> #include <stdio.h> #include <math.h> //r>0時不會 WA using namespace std; double y[105]; int N,H,R,T; const double g=10.0; double calc(int TT){ double t=sqrt(2*H/g); int k=(int)(TT/t); if(k%2==0){ double d=TT-k*t; return H-g*d*d/2; }else{ double d=k*k+t-TT; return H-g*d*d/2; } } int main(){ int c; cin >> c; while(c--){ cin >> N >> H >> R >> T; for(int i=0;i<N;i++){ y[i]=calc(T-i); } sort(y,y+N); for(int i=0;i<N;i++)printf("%.2f%c",y[i]+2*R*i/100.0,i+1==N ? '\n':' '); } }
486a41637bb3f651e748d666d4029928704775f0
e2e11d342899f7f2627337c55a1c7ed78694e31e
/TrabalhoPratico_14840/texture.cpp
2fbb33d45a7f9f27fd8cd02f34d1c06c0e82b85c
[]
no_license
jfaps09/P3D_TP_2019
f5221e39d91dd70eed9a862a7950fe7a54a7547b
3aaf000cf21d8cfc0582689804fc6d858809e791
refs/heads/master
2020-05-23T05:05:26.192990
2019-06-05T19:46:56
2019-06-05T19:46:56
186,645,597
1
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
texture.cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" GLuint loadFileTGA(const char * imagepath) { GLuint texture; glGenTextures(1, &texture); //Bind the newly created texture glBindTexture(GL_TEXTURE_2D, texture); //Flip texture image on load, since texture coordinates are loaded inverted vertically stbi_set_flip_vertically_on_load(true); //Read the file using stb_image header, call glTexImage2D with the right parameters int width, height, channels; unsigned char* imageData = stbi_load(imagepath, &width, &height, &channels, 4); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); //Pretty decent trilinear filtering, change anything(???) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); return texture; }
d668d44036dc90c6b8d6f8c66bf3350b10cc4a22
be396f735b69793dd155ccab4aacedba1b11a8cd
/jagjeets/ps4/ps4_2/main.cpp
4bc8376d20b24df273c544c25f47893e9a0c33e7
[]
no_license
jagjeet-singh/Advanced-Engineering-Computation
3d9267dde53a6e90516078e206709fc9f10ac789
0cfe6554274a45c48b16999c546b385e73b9a2d4
refs/heads/master
2020-03-23T17:35:39.210809
2018-07-22T14:19:34
2018-07-22T14:19:34
141,866,504
0
1
null
null
null
null
UTF-8
C++
false
false
4,994
cpp
main.cpp
/* //////////////////////////////////////////////////////////// File Name: main.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include <fslazywindow.h> #include <stdio.h> #include "hashtable.h" #include "simplebitmap.h" #include <string> #include <iostream> using namespace std; template <> HashCommon::CodeType HashBase<SimpleBitmap>::HashCode (const SimpleBitmap &key) const { HashTable <SimpleBitmap,int>::CodeType sum=0; const unsigned int m[]={5,7,11,13,17,19}; int counter=0; for(int iy=0;iy<key.GetHeight();++iy) for(int ix=0; ix<key.GetWidth(); ++ix) { auto pixelPtr = key.GetPixelPointer(ix,iy); for(int p=0; p<6; p++) { sum+=(pixelPtr[p])*m[counter%6]; counter++; } } return sum; } class FsLazyWindowApplication : public FsLazyWindowApplicationBase { protected: bool needRedraw; HashTable <SimpleBitmap,int> table; SimpleBitmap sbp; int CutWid = 40; int CutHei = 40; public: FsLazyWindowApplication(); virtual void BeforeEverything(int argc,char *argv[]); virtual void GetOpenWindowOption(FsOpenWindowOption &OPT) const; virtual void Initialize(int argc,char *argv[]); virtual void Interval(void); virtual void BeforeTerminate(void); virtual void Draw(void); virtual bool UserWantToCloseProgram(void); virtual bool MustTerminate(void) const; virtual long long int GetMinimumSleepPerInterval(void) const; virtual bool NeedRedraw(void) const; }; FsLazyWindowApplication::FsLazyWindowApplication() { needRedraw=false; } /* virtual */ void FsLazyWindowApplication::BeforeEverything(int argc,char *argv[]) { } /* virtual */ void FsLazyWindowApplication::GetOpenWindowOption(FsOpenWindowOption &opt) const { opt.x0=0; opt.y0=0; opt.wid=1200; opt.hei=800; } /* virtual */ void FsLazyWindowApplication::Initialize(int argc,char *argv[]) { sbp.LoadPng(argv[1]); auto key=FsInkey(); if(FSKEY_ESC==key) { SetMustTerminate(true); } int fileCounter = 0; for (int iy=0; iy<sbp.GetHeight(); iy+=CutHei) { for (int ix=0; ix<sbp.GetWidth(); ix+=CutWid) { auto cut = sbp.CutOut(ix, iy, CutWid, CutHei); cut.Invert(); table.Update(cut,fileCounter); fileCounter++; } } printf("Table Size: %lld\n",table.GetN() ); } /* virtual */ void FsLazyWindowApplication::Interval(void) { needRedraw=true; } /* virtual */ void FsLazyWindowApplication::Draw(void) { int wid,hei; FsGetWindowSize(wid,hei); glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); int x = 0; int y = CutWid; int fileCounter = 0; for(auto hd=table.First(); true==hd.IsNotNull(); hd=table.Next(hd)) { auto keyPtr=table[hd]; if(nullptr!=keyPtr) { glRasterPos2i(x,y); glDrawPixels(CutWid,CutHei,GL_RGBA,GL_UNSIGNED_BYTE,keyPtr->GetBitmapPointer()); if (x>(wid-CutWid)) { y+=CutHei; x=0; } else { x+=CutWid; } } } FsSwapBuffers(); needRedraw=false; } /* virtual */ bool FsLazyWindowApplication::UserWantToCloseProgram(void) { return true; // Returning true will just close the program. } /* virtual */ bool FsLazyWindowApplication::MustTerminate(void) const { return FsLazyWindowApplicationBase::MustTerminate(); } /* virtual */ long long int FsLazyWindowApplication::GetMinimumSleepPerInterval(void) const { return 10; } /* virtual */ void FsLazyWindowApplication::BeforeTerminate(void) { } /* virtual */ bool FsLazyWindowApplication::NeedRedraw(void) const { return needRedraw; } static FsLazyWindowApplication *appPtr=nullptr; /* static */ FsLazyWindowApplicationBase *FsLazyWindowApplicationBase::GetApplication(void) { if(nullptr==appPtr) { appPtr=new FsLazyWindowApplication; } return appPtr; }
80ef6ece1863dc625e4dd94262ac666888102fd6
f1a2325795dcd90f940e45a3535ac3a0cb765616
/development/TelecomServices/EPM/src/PM_RulesRmonCounter.cpp
f18e6357ba19317fc62579eb14c833a54ba5d490
[]
no_license
MoonStart/Frame
45c15d1e6febd7eb390b74b891bc5c40646db5de
e3a3574e5c243d9282778382509858514585ae03
refs/heads/master
2021-01-01T19:09:58.670794
2015-12-02T07:52:55
2015-12-02T07:52:55
31,520,344
0
0
null
null
null
null
UTF-8
C++
false
false
7,275
cpp
PM_RulesRmonCounter.cpp
/*-------------------------------------------------------------------------- Copyright(c) Tellabs Transport Group. All rights reserved SUBSYSTEM: Performance Monitoring. TARGET : TRN. AUTHOR : December 21, 2005 Larry Wolfrum. DESCRIPTION: The class to update RMON layer counter parameters. --------------------------------------------------------------------------*/ #include <TelCommon/TEL_BbRegionBaseImp.h> #include <PM/PM_GenericApplication.h> #include <EPM/PM_BbCountRmon.h> #include <PM/PM_RegionImp.h> #include <PM/PM_MainBaseSubApplication.h> #include <PM/PM_RmonCounterSubApplication.h> #include <PM/src/PM_Rules.h> #include <EPM/src/PM_AccPeriodRmonCounter.h> #include <EPM/src/PM_RulesRmonCounter.h> #include <Alarm/ALM_AppIf.h> #include <Alarm/ALM_FailureRegionImp.h> #include <Alarm/ALM_FailureBase.h> #include <Monitoring/MON_OptSubApplication.h> #include <Configuration/CFG_AppIf.h> #include <Configuration/CFG_Rs.h> //----------------------------------------------------------------- // Class default constructor. PM_RulesRmonCounter::PM_RulesRmonCounter (PM_GenericApplication& theGenericApplication, uint16 theIndex): PM_Rules(theGenericApplication, theIndex, PM_TypeRmonCounter::GetMaxNbParamsNoHighOrder64Bits()), myCounterRmon ( (*myGenericApplication.GetRegionCountRmon())[theIndex]), mySignalType ( CT_TEL_SIGNAL_UNKNOWN ) { Init(); } //----------------------------------------------------------------- // Class default destructor. PM_RulesRmonCounter::~PM_RulesRmonCounter () { // Nothing to do for now. } //----------------------------------------------------------------- void PM_RulesRmonCounter::Init() { myFirstTime = true; // Call base class method. PM_Rules::Init(); } //----------------------------------------------------------------- void PM_RulesRmonCounter::UpdateRules(bool* thefilteringStateFirstStage, bool* thefilteringStateSecondStage) { // Parameter index. uint32 param; // Computed state for first stage filtering (2.5 seconds failures). bool filteringStateFirstStage[PM_TypeRmonCounter::PM_PARAM_NUM]; // Computed state for second stage filtering (90 seconds failures). bool filteringStateSecondStage[PM_TypeRmonCounter::PM_PARAM_NUM]; // Group of failures (ored). bool failuresGroup; // Iteraror of Accumulation Period vector<PM_AccumulationPeriod*>::iterator i; PM_RmonCounterSubApplication& rmonApp = dynamic_cast<PM_RmonCounterSubApplication&>(myGenericApplication); MON_OptSubApplication* aMonOptApp = NULL; MON_AppIf* aMonAppIf; if( (aMonAppIf = rmonApp.GetCardContext().GetOptIf().GetMonPortSideAppPtr( myAutoRateLock.ConvertPmSideToCtIfId( rmonApp.GetSide() ) )) != NULL ) { aMonOptApp = dynamic_cast<MON_OptSubApplication*>(aMonAppIf); } CT_TEL_SignalType signalType = CT_TEL_SIGNAL_UNKNOWN; CFG_Rs& aCfgRsObj = (CFG_Rs &)(*(rmonApp.GetCardContext().GetRsIf().GetCfgPortSideApp(myAutoRateLock.ConvertPmSideToCtIfId(rmonApp.GetSide())).GetCfgRegion()))[0]; // Retrieve card signal type configuration. signalType = aCfgRsObj.GetSignalType(); // Verify signal type change. if (signalType != mySignalType) { // Reset PM data for all Accumulation period for (i = myVectorOfAccumulationPeriod.begin(); i != myVectorOfAccumulationPeriod.end(); i++) { (*i)->ResetAll(); } // Update my signal type. mySignalType = signalType; } // At first iteration only. if (myFirstTime) { // For all parameters. for (param = 0; param < PM_TypeRmonCounter::GetMaxNbParamsNoHighOrder64Bits(); param++) { // Set availability for all Accumulation periods. // IDF is available if monitoring status is valid, otherwise it is not available. for (i = myVectorOfAccumulationPeriod.begin(); i != myVectorOfAccumulationPeriod.end(); i++) { (*i)->SetAvailability(param, myValidityState[param]); } } // Update first time flag. myFirstTime = false; } // // Apply rules and determine TCA filtering state: // // Filter parameters and TCA when LOS is detected on the OPT layer. ALM_FailureBase &almOptRef = (ALM_FailureBase &)(*(myGenericApplication.GetAlmOptApplication().GetFilteredRegionPtr()))[0]; failuresGroup = almOptRef.GetStatus(CT_TelAlarmCondition::ALM_LOS_OPT); if( !failuresGroup ) { // No LOS detected myCurrentValueParam[PM_TypeRmonCounter::PM_DROP].UnsignedValue = myCounterRmon.GetDroppedEvents(); myCurrentValueParam[PM_TypeRmonCounter::PM_PKT].UnsignedValue = myCounterRmon.GetPackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_BCPKT].UnsignedValue = myCounterRmon.GetBroadcastPackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_MCPKT].UnsignedValue = myCounterRmon.GetMulticastPackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_CRCAE].UnsignedValue = myCounterRmon.GetCrcAlignErrors(); myCurrentValueParam[PM_TypeRmonCounter::PM_USPKT].UnsignedValue = myCounterRmon.GetUndersizePackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_OSPKT].UnsignedValue = myCounterRmon.GetOversizePackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_FRAG].UnsignedValue = myCounterRmon.GetFragmentedPackets(); myCurrentValueParam[PM_TypeRmonCounter::PM_JABR].UnsignedValue = myCounterRmon.GetJabbers(); for (param = 0; param < PM_TypeRmonCounter::PM_PARAM_NUM; param++) { filteringStateFirstStage[param] = failuresGroup; filteringStateSecondStage[param] = failuresGroup; } } else { for (param = 0; param < PM_TypeRmonCounter::PM_PARAM_NUM; param++) { filteringStateFirstStage[param] = failuresGroup; filteringStateSecondStage[param] = failuresGroup; } for (param = 0; param < PM_TypeRmonCounter::GetMaxNbParamsNoHighOrder64Bits(); param++) { myCurrentValueParam[param].UnsignedValue = 0; } } //------------------------------------------------------------------ // Apply Auto Rate Lock rules GOPT/MRTME AutoRateLock features. //------------------------------------------------------------------ //CFG_Rs& aCfgRsObj = (CFG_Rs &)(*(rmonApp.GetCardContext().GetRsIf().GetCfgPortSideApp(myAutoRateLock.ConvertPmSideToCtIfId(rmonApp.GetSide())).GetCfgRegion()))[0]; if ( ((aMonOptApp != NULL) && (aMonOptApp->GetAutoRateLockSupported()) && (aCfgRsObj.GetSignalType() == CT_TEL_SIGNAL_GOPT)) ) { myAutoRateLock.AdjustForAutoRateLock( rmonApp.GetCardContext(), myNumberOfParam, myCurrentValueParam, filteringStateFirstStage, filteringStateSecondStage, rmonApp.GetSide() ); } else { myAutoRateLock.ResetAutoRateLockStates(); } //Call the method of the base class. PM_Rules::UpdateRules( filteringStateFirstStage, filteringStateSecondStage ); } bool* PM_RulesRmonCounter::GetAutoRateInhibitProfile() { return myAutoRateLock.GetAutoRateInhibitProfile(); } bool PM_RulesRmonCounter::IsAutoRateStateRefreshed() { return myAutoRateLock.IsAutoRateStateRefreshed(); }
c8a9694d30bbc873d49c235efd7ac768b3bff2c0
0d82d405f5dffc68d30ddb0d42830740cb5df069
/src/apps/sent2vec/sent2vec.cpp
294903302c6696f73e65480cea52288c65b4b71a
[ "Apache-2.0" ]
permissive
nathinal/SwiftMPI
7fe6780561a3272d61fc6aa0e574f7f54811e7f8
1792e85ab674b6e0d2bd46223f1f1b6631c50e80
refs/heads/master
2020-05-30T20:35:17.191675
2016-04-25T09:56:56
2016-04-25T09:56:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,154
cpp
sent2vec.cpp
#include <functional> #include "../../swiftmpi.h" #include "../word2vec/word2vec.h" using namespace swift_snails; class WordMiniBatch : public MiniBatch { public: WordMiniBatch() {} void push() = delete; // size_t gather_keys (FILE* file, int &line_id, int minibatch, int // nthreads=0) = delete; }; class Sent2Vec { public: Sent2Vec(const std::string &path, const std::string &out_path, int niters) : _batchsize(global_config().get("worker", "minibatch").to_int32()), _nthreads(global_config().get("worker", "nthreads").to_int32()), _window(global_config().get("word2vec", "window").to_int32()), _negative(global_config().get("word2vec", "negative").to_int32()), _alpha(global_config().get("word2vec", "learning_rate").to_float()), _niters(niters) { _path = path; _out_path = out_path; CHECK_GT(_path.size(), 0); CHECK_GT(_batchsize, 0); CHECK_GT(_nthreads, 0); CHECK_GT(_niters, 0); //_word_minibatch.init_param(&_word_param_cache); } void load_word_vector(const std::string &path) { global_server<server_t>().load(path); global_mpi().barrier(); } void train() { // TODO begin to learn sentence vector std::mutex file_mut; std::mutex out_file_mut; std::atomic<int> line_count{0}; int line_id{0}, _line_id; SpinLock spinlock; Instance ins; FILE *file = fopen(_path.c_str(), "rb"); std::ofstream ofile(_out_path.c_str()); AsynExec::task_t handler = [this, &file, &file_mut, &ofile, &out_file_mut, &line_id, &line_count, &spinlock] { std::string line; char *cline; Instance ins; bool parse_res; LineFileReader line_reader(file); Vec neu1(len_vec()), neu1e(len_vec()); Vec sent_vec(len_vec()); float error; while (true) { if (line_count > _batchsize) break; if (feof(file)) break; { std::lock_guard<std::mutex> lk(file_mut); cline = line_reader.getline(); if (!cline) continue; } line_count++; line = std::move(std::string(cline)); parse_res = parse_instance(line, ins); if (!parse_res) continue; w2v_key_t sent_id = hash_fn(line.c_str()); sent_vec.random(); // init for (int i = 0; i < _niters; i++) error = learn_instance(ins, neu1, neu1e, sent_vec); _error.accu(error); { std::lock_guard<std::mutex> lk(out_file_mut); ofile << sent_id << "\t" << sent_vec << std::endl; } if (++line_id % _batchsize == 0) RAW_LOG_INFO("training process: %d", line_id); if (line_count > _batchsize) break; if (feof(file)) break; } }; while (true) { line_count = 0; if (_word_minibatch.gather_keys(file, _line_id, _batchsize) < 5) break; _word_minibatch.pull(); _word_minibatch.param().grads().clear(); async_exec(_nthreads, handler, global_channel()); _word_minibatch.clear(); } fclose(file); LOG(WARNING) << "error:\t" << _error.norm(); } protected: float learn_instance(Instance &ins, Vec &neu1, Vec &neu1e, Vec &sent_vec) noexcept { // neu1.clear(); neu1e.clear(); int a, c, b = global_random()() % _window; int sent_length = ins.words.size(); int pos = 0; int label; float g, f; w2v_key_t word, target, last_word; for (pos = 0; pos < sent_length; pos++) { word = ins.words[pos]; neu1.clear(); neu1e.clear(); b = global_random()() % _window; neu1 = sent_vec; for (a = b; a < _window * 2 + 1 - b; a++) { if (a != _window) { c = pos - _window + a; if (c < 0 || c >= sent_length) continue; last_word = ins.words[c]; Vec &syn0_lastword = _word_minibatch.param().params()[last_word].v; neu1 += syn0_lastword; } } for (int d = 0; d < _negative + 1; d++) { if (d == 0) { target = word; label = 1; // generate negative samples } else { target = _word_minibatch.table()[(global_random()() >> 16) % table_size]; if (target == 0) target = _word_minibatch.table()[(global_random()() >> 16) % table_size]; if (target == word) continue; label = 0; } Vec &syn1neg_target = _word_minibatch.param().params()[target].h; f = 0; f += neu1.dot(syn1neg_target); if (f > MAX_EXP) g = (label - 1) * _alpha; else if (f < -MAX_EXP) g = (label - 0) * _alpha; else g = (label - exptable(f)) * _alpha; //_error.accu(10000 * g * g); neu1e += g * syn1neg_target; //_word_minibatch.param().grads()[target].accu_h(g * neu1); } sent_vec += _alpha * neu1e; /* // hidden -> in for (a = b; a < _window * 2 + 1 - b; a++) { if (a != _window) { c = pos - _window + a; if (c < 0 || c >= sent_length) continue; last_word = ins.words[c]; Vec &syn0_lastword = _word_minibatch.param().params()[last_word].v; //_word_minibatch.param().grads()[last_word].accu_v( neu1e); sent_vec += _alpha * neu1e; } } */ } return g * g; } // dataset path std::string _path, _out_path; int _batchsize; int _nthreads; int _niters; int _window; int _negative; int nlines = 0; std::unordered_set<w2v_key_t> _local_keys; float _alpha; // learning rate WordMiniBatch _word_minibatch; Error _error; }; // end class Word2Vec using namespace std; int main(int argc, char *argv[]) { GlobalMPI::initialize(argc, argv); // init config fms::CMDLine cmdline(argc, argv); std::string param_help = cmdline.registerParameter("help", "this screen"); std::string param_config_path = cmdline.registerParameter( "config", "path of config file \t[string]"); std::string param_word_vec = cmdline.registerParameter( "wordvec", "path of word vector \t[string]"); std::string param_data_path = cmdline.registerParameter( "data", "path of dataset, text only! \t[string]"); std::string param_niters = cmdline.registerParameter( "niters", "number of iterations \t[int]"); std::string param_param_output = cmdline.registerParameter( "output", "path to output paragraph vectors\t[string]"); if (cmdline.hasParameter(param_help) || argc == 1) { cout << endl; cout << "===================================================================" << endl; cout << " Doc2Vec (Distributed Paragraph Vector)" << endl; cout << " Author: Suprjom <yanchunwei@outlook.com>" << endl; cout << "===================================================================" << endl; cmdline.print_help(); cout << endl; cout << endl; return 0; } if (!cmdline.hasParameter(param_config_path) || !cmdline.hasParameter(param_data_path) || !cmdline.hasParameter(param_word_vec) || !cmdline.hasParameter(param_niters)) { LOG(ERROR) << "missing parameter"; cmdline.print_help(); return 0; } std::string config_path = cmdline.getValue(param_config_path); std::string data_path = cmdline.getValue(param_data_path); std::string output_path = cmdline.getValue(param_param_output); std::string word_vec_path = cmdline.getValue(param_word_vec); int niters = stoi(cmdline.getValue(param_niters)); global_config().load_conf(config_path); global_config().parse(); // init cluster Cluster<ClusterWorker, server_t, w2v_key_t> cluster; cluster.initialize(); Sent2Vec sent2vec(data_path, output_path, niters); LOG(WARNING) << "... loading word vectors"; sent2vec.load_word_vector(word_vec_path); LOG(WARNING) << "... to train"; sent2vec.train(); LOG(WARNING) << "cluster exit."; return 0; }
75d016dd917bb3c45908c4676e6a2687837229fa
4bce8f0ee794ce069855465a39223da2f677ddbe
/training/lab_4/Ford.h
5a5e3705063caea9402b950574432c7d9e6e2fe4
[]
no_license
MichalLeszczynski-WFiIS/WFiIS_PO_2019
eb8d29e105e33b16c9f4e3355d6ce27b2ecf6e38
3a81dec25c214143c727fee53ef5ebccbd686703
refs/heads/master
2022-01-10T20:00:10.853485
2019-05-30T08:00:02
2019-05-30T08:00:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
530
h
Ford.h
#pragma once #include <iostream> #include "Car.h" class Ford : public Car { public: Ford() {} virtual std::string TypeInfo() const override{return "Ford Fiesta";} virtual std::string ColorInfo() const override{return "Red";} virtual std::string EngineFuelInfo() const override{return "Pb98";} virtual std::string EngineCapInfo() const override{return "1398 [cm^3]";} virtual std::string EnginePowInfo() const override{return "45 [kW]";} virtual std::string GpsInfo() const override {return "F/Google/No.000.000\n";} };
d34ee29dabd299265025639caa4a6cc6ccca10d2
99ba97988fc131ff33547d53b1a97f541b5ed8ba
/WallChess.cpp
e6f37550f202ec6dac3bd40354c44597af19e550
[]
no_license
codewasp942/WallChess
dd229480d162b4b339e117eef82fa6e30d6313eb
87287023ac876410d74318d5fad450a6100d97bf
refs/heads/master
2023-02-24T14:17:35.087172
2021-01-30T10:23:52
2021-01-30T10:23:52
334,317,160
1
1
null
null
null
null
GB18030
C++
false
false
5,642
cpp
WallChess.cpp
/* https://github.com/codewasp942/WallChess Visual Studio 2019 on windows */ #include <iostream> #include <windows.h> #include <cstdio> #include <cmath> #include <conio.h> #include "position.h" #include "ioex.h" #include "dfs.h" #include "qipan.h" #define elif(tiaojian) else if(tiaojian) using namespace std; bool mp[3][maxxw][maxyw]; //某位置是否有墙 bool cmove[maxxw][maxyw]; //是否可达 char outm[2*maxxw][2 * maxyw]; //地图输出 const int xw = 7, yw = 7; //棋盘宽度、高度 int piy = 2; //棋盘前空开列数 pos p1, p2; //棋子位置 HANDLE hout; //标准输出句柄 FILE* fp; //C风格的文件输入输出 int s1, s2; //记录领地面积 int wins = 0; //记录赢家,3表示平局 inline void outto(pos ps, char(*outm)[218], char ch); void drawqi(int x,int y); void draw(); void printhelp(); bool judge(); int main(){ if ((fp = fopen("help.txt", "r")) == NULL) { MessageBox(HWND_DESKTOP, TEXT("无法打开帮助文件,请确认help.txt在程序目录下"), TEXT("运行错误"), MB_OK | MB_ICONERROR); return 5201314; } if (!hinit(hout)) { MessageBox(HWND_DESKTOP, TEXT("无法获取标准输出句柄"), TEXT("运行错误"),MB_OK | MB_ICONERROR); return 5201314; } while (1) { memset(mp, 0, sizeof(mp)); for (int j = 1;j <= yw;j++) { mp[0][1][j] = mp[0][xw + 1][j] = 1; } for (int i = 1;i <= xw;i++) { mp[1][i][1] = mp[1][i][yw + 1] = 1; } p1.x = p1.y = 1; p2.x = xw;p2.y = yw; int akey; while (1) { scan(0, cmove, mp, xw, yw, p1, p2, 3); draw(); akey = getk(); while (akey != 32) { if (0 <= akey && akey <= 3) { outto(p1, outm, ' '); pos tmp = p1[akey]; if (!(tmp.x<1 || tmp.x>xw || tmp.y<1 || tmp.y>yw || tmp == p2 || !cmove[tmp.x][tmp.y] || mp[akey % 2][max(tmp.x, p1.x)][max(tmp.y, p1.y)])) { p1 = tmp; } draw(); Sleep(100); }elif(akey == 'i') { printhelp(); } akey = getk(); } panduan_p1: do { akey = getk(); } while (0 > akey || akey > 3); if (akey == 0) { if (mp[0][p1.x][p1.y])goto panduan_p1; mp[0][p1.x][p1.y] = 1; }elif(akey == 1) { if (mp[1][p1.x][p1.y])goto panduan_p1; mp[1][p1.x][p1.y] = 1; }elif(akey == 2) { if (mp[0][p1.x + 1][p1.y])goto panduan_p1; mp[0][p1.x + 1][p1.y] = 1; }elif(akey == 3) { if (mp[1][p1.x][p1.y + 1])goto panduan_p1; mp[1][p1.x][p1.y + 1] = 1; } scan(0, cmove, mp, xw, yw, p2, p1, 3); draw(); if (!judge()) { break; } scan(0, cmove, mp, xw, yw, p2, p1, 3); draw(); akey = getk(); while (akey != 32) { if (0 <= akey && akey <= 3) { outto(p1, outm, ' '); pos tmp = p2[akey]; if (!(tmp.x<1 || tmp.x>xw || tmp.y<1 || tmp.y>yw || tmp == p1 || !cmove[tmp.x][tmp.y] || mp[akey % 2][max(tmp.x, p2.x)][max(tmp.y, p2.y)])) { p2 = tmp; } draw(); Sleep(100); }elif(akey == 'i') { printhelp(); } akey = getk(); } panduan_p2: do { akey = getk(); } while (0 > akey || akey > 3); if (akey == 0) { if (mp[0][p2.x][p2.y])goto panduan_p2; mp[0][p2.x][p2.y] = 1; }elif(akey == 1) { if (mp[1][p2.x][p2.y])goto panduan_p2; mp[1][p2.x][p2.y] = 1; }elif(akey == 2) { if (mp[0][p2.x + 1][p2.y])goto panduan_p2; mp[0][p2.x + 1][p2.y] = 1; }elif(akey == 3) { if (mp[1][p2.x][p2.y + 1])goto panduan_p2; mp[1][p2.x][p2.y + 1] = 1; } scan(0, cmove, mp, xw, yw, p2, p1, 3); draw(); if (!judge()) { break; } } system("cls"); if (s1 > s2) { puts(">>> >>> Red wins !!! <<< <<<"); }elif(s1 < s2) { puts(">>> >>> Blue wins !!! <<< <<<"); }elif(s1 == s2) { puts(">>> >>> -+-+ Tie +-+- <<< <<<"); } printf("\n\n"); printf(" %2d ",s1); outch(':', COL_RED, COL_BLACK); printf(" %2d\n\n\n\n",s2); system("pause"); } CloseHandle(hout); return 0; } inline void outto(pos ps, char(*outm)[218], char ch) { outm[calx(ps.x) + 1][caly(ps.y) + 1] = ch; outm[calx(ps.x) + 1][caly(ps.y) + 2] = ch; } void drawqi() { for (int i = 1;i <= xw + 1;i++) { for (int j = 1;j <= yw + 1;j++) { outm[calx(i)][caly(j)] = '#'; } } for (int i = 1;i <= xw; i++){ for (int j = 1;j <= yw; j++) { if (cmove[i][j]) { outto(pos(i, j), outm, '-'); } } } for (int i = 1;i <= xw + 1; i++) { for (int j = 1;j <= yw + 1; j++) { if (mp[0][i][j]) { outm[calx(i)][caly(j) + 1] = '='; outm[calx(i)][caly(j) + 2] = '='; } if (mp[1][i][j]) { outm[calx(i) + 1][caly(j)] = '='; } } } outto(p1, outm, '1'); outto(p2, outm, '2'); } void draw() { system("cls"); puts(">->-> The WallChess <-<-<"); puts("$ press i to find help..."); for (int i = 1;i <= calx(xw + 1);i++) { for (int j = 1;j <= caly(yw + 1);j++) { outm[i][j] = ' '; } } drawqi(); for (int i = 1;i <= calx(xw+1);i++){ for (int j = 1;j <= piy;j++) { printf(" "); } for (int j = 1;j <= caly(yw+1);j++) { if (outm[i][j] == ' ') putchar(' '); elif(outm[i][j] == '1') outch(' ', COL_RED, COL_RED); elif(outm[i][j] == '2') outch(' ', COL_BLUE, COL_BLUE); elif(outm[i][j] == '#') outch('#', COL_WHITE, COL_PURPLE); elif(outm[i][j] == '-') outch('.', COL_CYAN, COL_BLACK); elif(outm[i][j] == '=') outch('+', COL_PURPLE, COL_PURPLE); else putchar(' '); } printf("\n"); } } void printhelp() { system("cls"); char buffer[509]; while (fgets(buffer,509,fp) != NULL) { puts(buffer); } while (_getch() != 'i') {}; draw(); } bool judge() { s1 = scan(1, cmove, mp, xw, yw, p1, p2, 0); s2 = scan(1, cmove, mp, xw, yw, p2, p1, 0); return cmove[p1.x][p1.y]; }
104cf86933100e309d32587ec036a69b51944cdd
e8ac5270951b8eafd947e869c2b6b901c9a7b754
/log_server.cpp
d77e84535959a4bcfea26162b761020440eac1e9
[]
no_license
Sweetkubuni/UDP_Server
b60c9d17778657e82470bb97ed254764584d7c14
c415e946d18fa075e02b856f8799a29e5a2d033e
refs/heads/master
2020-06-19T00:27:58.784741
2016-11-28T05:56:30
2016-11-28T05:56:30
74,931,452
0
0
null
null
null
null
UTF-8
C++
false
false
2,377
cpp
log_server.cpp
#include <iostream> #include <fstream> #include <cstring> #include <ctime> #include <cstdlib> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> using namespace std; #define PORT 8767 #define BUFSIZE 512 #define FOREVER 1 int main(int argc, char* argv[]) { pid_t process_id = 0; pid_t sid = 0; // Create child process process_id = fork(); // Indication of fork() failure if (process_id < 0) { cerr << "fork failed!\n"; // Return failure in exit status exit(1); } // PARENT PROCESS. Need to kill it. if (process_id > 0) { cout << "process_id of child process" << process_id << endl; // return success in exit status exit(0); } //unmask the file mode umask(0); //set new session sid = setsid(); if (sid < 0) { // Return failure exit(1); } // Change the current working directory to root. chdir("/"); // Close stdin. stdout and stderr close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* CHILD PROCESS PROCEDURE ONLY! */ //logging file ofstream log; log.open("server_log.txt", ios::out | ios::app); struct sockaddr_in myaddr; // our address struct sockaddr_in remaddr; // remote address socklen_t addrlen = sizeof(remaddr); int recvlen; int fd; // server socket char buf[BUFSIZE]; // receive buffer memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(PORT); if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { std::time_t result = std::time(nullptr); log << "Error: cannot create socket! " << "TIMESTAMP: " << std::asctime(std::localtime(&result)) << endl; log.close(); return 0; } if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { std::time_t result = std::time(nullptr); log << "Error: bind failed " << "TIMESTAMP: " << std::asctime(std::localtime(&result)) << endl; log.close(); return 0; } while (FOREVER) { recvlen = recvfrom(fd, (void *)&buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen); if (recvlen > 0) { string data(buf, recvlen); log << inet_ntoa(remaddr.sin_addr) << " : " << data << '\n'; if (data.compare("STOP") == 0) break; } }// end of FOREVER loop close(fd); log.close(); return (0); }
2e2372ecfc70ccea958350ab2a545ae1ea93218b
e3873080bbdc845c047869bc394914e55957b090
/main.cpp
b6dfdf6449fdecf18180e3172ff5c529a2bec14d
[]
no_license
aashreya/JSONDB-Lite
2d4d2cd7a0c5639ce66974780e2e09fafc00b2bb
6d248af91706775c79360ff5e8b6b77894ce7b56
refs/heads/master
2021-09-09T23:08:22.661675
2018-03-20T06:14:55
2018-03-20T06:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,800
cpp
main.cpp
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; class Query{ string key; string value; bool hasSubQuery; public: Query(string k,string v,bool isList=false){ if(isList){ key=key; value=v; } else{ key=k; value=v; if(value.find(':')!=string::npos) hasSubQuery=true; else hasSubQuery=false; } } const string &getKey(){ return key; } const string &getValue(){ return value; } const bool &getHasSubQuery(){ return hasSubQuery; } }; class stackNode{ public: int index; char brackets; stackNode(int index, char brackets) : index(index), brackets(brackets) {} }; class jsonDB{ vector<string> dataStore; public: void addToDS(string inp){ dataStore.push_back(inp); } vector<string> getAll(){ return dataStore; } void print(vector<string> dataStore){ for (auto line:dataStore) cout<<line<<endl; } void clearAll(){ dataStore.clear(); } string findValue(string input){ //cout<<"\nRecived string to find input:"<<input<<endl; if(input.size()==0) return ""; if(input.find('"')==string::npos){ return input.substr(0,input.size()-1); } if(input.find('{')==string::npos){ int start=input.find_first_not_of(":\""); int last; for(int i=start;i<input.size();i++){ char c=input[i]; if(input[i] == '"') { last=i; break;} } string val=input.substr(start,last-start); return val; } else{ int countStart=0; int stopIndex=input.size(); for(int i=0;i<input.size();i++){ if(input[i]=='}'){ --countStart; if(countStart==0){ stopIndex=i; break; } } if(input[i]=='{') ++countStart; } string value=input.substr(1,stopIndex-1); //cout<<"\n Parssed Value is: "<<value<<endl; return value; } } map<string,bool> parseListValue(string input){ map<string,bool> values; if(input=="[]" || input=="" || input=="[" || input=="]"){ cerr<<"Invalid List numbers"; return values; } string charecter=""; for(int i=0;i<input.size();i++){ if(input[i]=='[' || input[i]==']') continue; if(input[i]==','){ values[charecter]= true; charecter=""; } else{ charecter=charecter+input[i]; } } values[charecter]= true; return values; } string getKey(string keyString){ int startIndex,stopIndex=-1; for(int i=0;i<keyString.size();i++){ if(keyString[i]!='{'){ startIndex=i; break; } } string key=keyString.substr(startIndex,keyString.size()-startIndex); return key; } string getObjectValue(string str){ string value; int startIndex,stopIndex; stack<stackNode*> s1; stackNode* s; bool breakLoop= false; if(!str.size()) return ""; else{ for(int i=0;i<str.size();i++){ switch (str[i]){ case '{': s=new stackNode(i,'{'); s1.push(s); break; case '[': s=new stackNode(i,'['); s1.push(s); break; case '}': s=s1.top(); s1.pop(); if(s1.empty()){ breakLoop = true; stopIndex=i; startIndex=s->index; } break; case ']': s=s1.top(); s1.pop(); if(s1.empty()){ breakLoop = true; stopIndex=i; startIndex=s->index; } break; } if(breakLoop){ value=str.substr(startIndex,stopIndex-startIndex+1); break; } } } return value; } string getValue(string str){ if(!str.size()) return ""; else{ string value; int stopIndex; int startIndex=str.find(':'); if(str[startIndex+1]=='{' || str[startIndex+1]=='[' ) value=getObjectValue(str); else{ startIndex=startIndex+1; for(int i=startIndex;i<str.size();i++){ if(str[i]==',' || str[i]==']' || str[i]=='}'){ stopIndex=i; break; } } value=str.substr(startIndex,stopIndex-startIndex); } return value; } } string getValue(string key,string str){ if(!str.size()) return ""; int startIndex=str.find(key)+key.size(); if(startIndex!=string::npos){ str=str.substr(startIndex,str.size()-startIndex); } string value=getValue(str); return value; } string removeString(string key,string input){ int start=input.find(key); input=input.substr(start+key.size(),input.size()-(start+key.size())); //cout<<"\nRemaining string: "<<input; return input; } void getFilters(string filter,queue<Query*>& queryQueue){ Query* q = nullptr; if(filter=="") return; int splitter=-1; splitter=filter.find(':'); //no keys found if(splitter==string::npos) return; string possibleKey=filter.substr(0,splitter); //cout<<endl<<"Possible Key"<<possibleKey<<endl; string key=getKey(possibleKey); //cout<<"\nKey: "<<key; string removeStr=removeString(key,filter); string value=getValue(removeStr); //cout<<"\nValue:"<<value; q=new Query(key,value); queryQueue.push(q); removeStr=removeString(value+',',removeStr); getFilters(removeStr,queryQueue); return; } vector<pair<string,string>> containsInList(vector<pair<string,string>>& dataStore,string searchValues){ cout<<"\n\nRecieved datastore:\n"; for(auto x:dataStore){ cout<<endl<<x.first<<"\t"<<x.second; } for(int i=0;i<dataStore.size();i++){ string entryList=dataStore[i].first; if(entryList=="false" || dataStore[i].second=="false"){ dataStore[i].second="false"; dataStore[i].first="false"; continue; } dataStore[i].second="true"; string listValue=getValue("\"list\"",dataStore[i].first); map<string,bool> hmapEntry=parseListValue(listValue); map<string,bool> hmapSearch=parseListValue(searchValues); for(map<string,bool>::iterator it=hmapSearch.begin();it!=hmapSearch.end();*it++){ if(hmapEntry.count(it->first)==0){ dataStore[i].second="false"; break; } } } return dataStore; }; vector<pair<string,string>> performQuery(vector<pair<string,string>>& dataStore,queue<Query*> queryQueue){ vector<pair<string,string>> queryResult; vector<pair<string,string>> newValueDataStore; Query* currentQuery; //if its empty, then to the data store, add true or false to the end query if(queryQueue.empty()){ if(dataStore.size()==0) cerr<<"\n Datastore is empty!"; for(int i=0;i<dataStore.size();i++){ //if the key is false, result will be false if(dataStore[i].second=="false") dataStore[i].second="false"; else dataStore[i].second="true"; } return dataStore; } currentQuery=queryQueue.front(); queryQueue.pop(); //case 1: Where there is no subQuery if(!currentQuery->getHasSubQuery()) { if(currentQuery->getKey() == "\"list\""){ dataStore=containsInList(dataStore,currentQuery->getValue()); } else { //Geeting the results back. for (int i = 0; i < dataStore.size(); i++) { if (dataStore[i].first.size() == 0 || dataStore[i].second == "false" || dataStore[i].first == "false") dataStore[i].second = "false"; else { string filterMatch = currentQuery->getKey() + ':' + currentQuery->getValue(); string value = getValue(currentQuery->getKey(), dataStore[i].first); string keyValue = currentQuery->getKey() + ':' + value; if (keyValue.find(filterMatch) != string::npos) dataStore[i].second = "true"; else dataStore[i].second = "false"; } } } queryResult = performQuery(dataStore,queryQueue); //cout<<"Need to map these results to datastore"; //MAPING ORIGINAL DATASTORE TO THESE RESULTS for(int i=0;i<dataStore.size();i++){ dataStore[i].second="false"; if(queryResult[i].second=="true") dataStore[i].second="true"; } return dataStore; } //create a new dataStore from the existing dataStore which has the values of the key. //pass it to filterwrapper function //you will get the table with two columns else if(currentQuery->getHasSubQuery()) { //creating new datastore values for (int i = 0; i < dataStore.size(); i++) { pair<string, string> record; record.first = dataStore[i].first; //checking if the datastore's first is false, then add seciind as false; if (dataStore[i].first == "" || dataStore[i].first == "false"||dataStore[i].second == "false") { record.second = "false"; } else { string value = getValue(currentQuery->getKey(), dataStore[i].first); //get value from the front record.first = value; } newValueDataStore.push_back(record); } queryResult = filterWrapper(currentQuery->getValue(), newValueDataStore); //teh data store wil be of size 1 //MAPING ORIGINAL DATASTORE TO THESE RESULTS for (int i = 0; i < dataStore.size(); i++) { dataStore[i].second = "false"; if (queryResult[i].second == "true") dataStore[i].second = "true"; } queryResult.clear(); queryResult = performQuery(dataStore, queryQueue); //MAPING ORIGINAL DATASTORE TO THESE RESULTS for (int i = 0; i < dataStore.size(); i++) { dataStore[i].second = "false"; if (queryResult[i].second == "true") dataStore[i].second = "true"; } } return dataStore; } vector<pair<string,string>> filterWrapper(string input,vector<pair<string,string>>& dataStore){ queue<Query*> queryQueue; vector<pair<string,string>> queryAnswer; getFilters(input,queryQueue); if(!queryQueue.empty()){ queryAnswer=performQuery(dataStore,queryQueue); } return queryAnswer; } void deleteFromDB(vector<string> queryResult){ map<string,bool> hmap; for(int i=0;i<queryResult.size();i++){ hmap[queryResult[i]]=true; } vector<string> newDataStore; for(int i=0;i<dataStore.size();i++){ if(hmap.count(dataStore[i])==0) newDataStore.push_back(dataStore[i]); } dataStore.clear(); dataStore=newDataStore; } }; int main() { jsonDB db; fstream file; file.open("/Users/anushavijay/CLionProjects/HackerRanker/input.txt"); while(!file.eof()){ string line; getline (file,line); cout<<line<<endl; string command=line.substr(0,line.find(' ')); string input=line.substr(line.find(' ')+1,(line.size()-command.size()-1)); if(command == "add") db.addToDS(input); else if(command == "delete"){ if(input=="{}"){ db.clearAll(); } else{ //cout<<"\nDeleting line with Filter:"<<line; cout<<"\n----------------\n"; vector<pair<string,string>> dataStore; vector<string> data=db.getAll(); for(int i=0;i<data.size();i++){ pair<string,string> dataRecord; dataRecord.first=data[i]; dataStore.push_back(dataRecord); } vector<pair<string,string>> queryResult = db.filterWrapper(input,dataStore); vector<string>querys; for (auto x:queryResult) { if(x.second=="true") querys.push_back(x.first); } db.deleteFromDB(querys); } } else{ if (input == "{}"){ db.print(db.getAll()); } else{ //cout<<"\n Getting with filters:"<<input; cout<<"\n----------------\n"; vector<pair<string,string>> dataStore; vector<string> data=db.getAll(); for(int i=0;i<data.size();i++){ pair<string,string> dataRecord; dataRecord.first=data[i]; dataStore.push_back(dataRecord); } vector<pair<string,string>> queryResult = db.filterWrapper(input,dataStore); vector<string>querys; for (auto x:queryResult) { if(x.second=="true") querys.push_back(x.first); } db.print(querys); // for (auto x:queryResult) { // if(x.second=="true") // cout << endl << x.first; // } } } } /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
aca2f42a48cab40121e7d17b256f6272290f5cd6
27c1cd4c44a67cbb1e94b408d3603fe5fce5b042
/src/example/CustomFilm.cpp
0257271ae5093eed6ec057ac7a1a151c1a0b7bc6
[ "BSD-2-Clause" ]
permissive
LeksiDor/LFRayTracerPBRT
09711ea93c89be264b51499ab71703ab1f4d4b23
bccb488fda7c3666845409db1575b91c39040f8d
refs/heads/master
2022-11-15T15:41:26.957285
2020-07-07T14:19:07
2020-07-07T14:19:07
264,190,056
3
0
null
null
null
null
UTF-8
C++
false
false
3,489
cpp
CustomFilm.cpp
#include "CustomFilm.h" using namespace lfrt; CustomFilm::CustomFilm( const Int width, const Int height ) { SetSize( width, height ); } bool CustomFilm::SetSize(const Int& width, const Int& height) { if ( width <= 0 || height <= 0 ) return false; weighted.Resize( width, height ); weights.Resize( width, height ); unweighted.Resize( width, height ); return true; } bool CustomFilm::GetRenderBounds( Int& startX, Int& startY, Int& endX, Int& endY) const { startX = 0; startY = 0; endX = Width(); endY = Height(); return true; } bool CustomFilm::GetSamplingBounds( Int& startX, Int& startY, Int& endX, Int& endY) const { startX = 0; startY = 0; endX = Width(); endY = Height(); return true; } SampleTile* CustomFilm::CreateSampleTile( const Int& startX, const Int& startY, const Int& endX, const Int& endY ) { return new CustomFilmTile( startX, startY, endX, endY ); } bool CustomFilm::MergeSampleTile( SampleTile* tile ) { CustomFilmTile* filmTile = dynamic_cast<CustomFilmTile*>(tile); if ( filmTile == nullptr ) return false; const Int startX = filmTile->startX; const Int startY = filmTile->startY; for ( Int localX = 0; localX < filmTile->width; ++localX ) { for ( Int localY = 0; localY < filmTile->height; ++localY ) { weighted(startX+localX,startY+localY) = filmTile->weighted(localX,localY); weights(startX+localX,startY+localY) = filmTile->weights(localX,localY); unweighted(startX+localX,startY+localY) = filmTile->unweighted(localX,localY); } } return true; } bool CustomFilm::DestroySampleTile( SampleTile* tile ) { CustomFilmTile* filmTile = dynamic_cast<CustomFilmTile*>(tile); if ( filmTile == nullptr ) return false; delete filmTile; return true; } bool CustomFilm::GetColor( const Int& x, const Int& y, Real& r, Real& g, Real& b) const { if ( x < 0 || y < 0 || x >= Width() || y >= Height() ) return false; const RGB& sum = weighted(x,y); const Real& w = weights(x,y); const RGB& flat = unweighted(x,y); r = flat.r; g = flat.g; b = flat.b; if ( w > 0 ) { r += sum.r / w; g += sum.g / w; b += sum.b / w; } return true; } CustomFilmTile::CustomFilmTile(const Int& startX, const Int& startY, const Int& endX, const Int& endY ) :startX(startX) ,startY(startY) ,width(endX-startX) ,height(endY-startY) { weighted.Resize(width,height); weights.Resize(width,height); unweighted.Resize(width,height); } bool CustomFilmTile::AddSample(const VEC2& raster, const VEC2& secondary, const Real& sampleWeight, const Real& rayWeight, const Real& r, const Real& g, const Real& b, const bool isWeighted ) { const Int x = Int(raster.x) - startX; const Int y = Int(raster.y) - startY; if ( x < 0 || y < 0 || x >= width || y >= width ) return false; if ( isWeighted ) { const Real w = sampleWeight * rayWeight; RGB& rgb = weighted(x,y); rgb.r += w*r; rgb.g += w*g; rgb.b += w*b; weights(x,y) = weights(x,y) + w; } else { RGB& rgb = unweighted(x,y); rgb.r += r; rgb.g += g; rgb.b += b; } return true; }
ac7e70937b2cae45cedfc9f89d83bf7d50272faf
2f68c2a4a28d2d92edeb6e619e32420716e1ce39
/sum_arr.cpp
ad87b08b96c53af768b3bb09880d6994ffdbfc50
[]
no_license
Ashish0o7/cpp-codes2
77c94245bc7ae228a5aed5d7b8461139a6e8638b
30fcc56938d1a22ce0c55e1952cd7fdc776b498f
refs/heads/main
2023-04-22T00:25:25.210915
2021-05-09T10:58:14
2021-05-09T10:58:14
347,954,566
2
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
sum_arr.cpp
#include <iostream> using namespace std; int main() { int arr[5]; int sum = 0 , prd = 1; cout<<"Enter elements for array : "<<endl; for(int i = 0 ; i <= 4 ; i++) { cin>>arr[i]; } for(int i = 0 ; i <= 4 ; i++) { sum = sum + arr[i]; } for(int i = 0 ; i <= 4 ; i++) { prd = prd * arr[i]; } cout<<"Sum of all elements is : "<<sum<<endl; cout<<"Product of all elements is : "<<prd<<endl; }
ebff4e05afb559e3622e012ec43b8a1b6013c110
69dd81f7fd0097e4448f13aeb271405b7f53d298
/src/renderer/VertexArray.cpp
b3173bae7f969c1d2138521285d1612a4bc521dc
[ "MIT" ]
permissive
wdaughtridge/GraviT
a42dc62973f5134ba642109415c4c1b47d424498
110abb61a99c7844ee3477b72d72e97d12d1ccb0
refs/heads/master
2023-06-22T14:54:14.378024
2020-06-21T05:47:52
2020-06-21T05:47:52
269,491,553
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
VertexArray.cpp
// // VertexArray.cpp // GraviT // // Created by William Daughtridge on 6/13/20. // Copyright © 2020 William Daughtridge. All rights reserved. // #include "VertexArray.h" void GraviT::VertexArray::Bind() const { glBindVertexArray(m_arrayID); } void GraviT::VertexArray::Delete() { glDeleteVertexArrays(1, &m_arrayID); }
849f1008836e01a352ba7ab1179f3b5ace58bb11
11d335b447ea5389f93165dd21e7514737259ced
/transport/Includes/CAtomTable.h
09332bb41336602eed2cd80e0530febc9c04e395
[]
no_license
bennbollay/Transport
bcac9dbd1449561f2a7126b354efc29ba3857d20
5585baa68fc1f56310bcd79a09bbfdccfaa61ed7
refs/heads/master
2021-05-27T03:30:57.746841
2012-04-12T04:31:22
2012-04-12T04:31:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
498
h
CAtomTable.h
#ifndef INCL_CATOMTABLE #define INCL_CATOMTABLE #include "CSymbolTable.h" // CAtomTable. Implementation of a string hash table class CAtomTable : public CObject { public: CAtomTable (void); CAtomTable (int iHashSize); virtual ~CAtomTable (void); ALERROR AppendAtom (const CString &sString, int *retiAtom); int Atomize (const CString &sString); private: CSymbolTable *Hash (const CString &sString); int m_iHashSize; int m_iNextAtom; CSymbolTable *m_pBackbone; }; #endif
041324597bd9749145f0dc2e56687f0a02dbee5c
7894893e65ed143bbc6216ba2d9cee167bb53941
/Tree/pathSumII/pathSumII.cpp
c0b17146bb602c0e44f6040b6c3f4f8acf6c71c1
[]
no_license
kevinrwx/LeetCode
681f4c2388eff6d3466d1091577585fa4926db73
7073b60d2c3ddc1e0f66be21f01f6a4277b85992
refs/heads/master
2016-12-13T02:48:22.383331
2016-04-05T12:23:32
2016-04-05T12:23:32
27,356,935
0
0
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
pathSumII.cpp
//Path Sum II #include <iostream> #include <vector> #include <stack> #include <algorithm> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; vector<int> nodeToval(stack<TreeNode*> st) { vector<int> results; stack<TreeNode*> wa; while(!st.empty()) { TreeNode* tmp = st.top(); st.pop(); wa.push(tmp); } while(!wa.empty()) { TreeNode* tmp = wa.top(); wa.pop(); results.push_back(tmp->val); } return results; } void backtrack(vector<vector<int> > &results, stack<TreeNode*> st, TreeNode* root, int sum) { if(sum == 0 && root->left == NULL && root->right == NULL) { vector<int> tmp = nodeToval(st); results.push_back(tmp); } else { if(root->left != NULL) { st.push(root->left); backtrack(results, st, root->left, sum-root->left->val); } if(st.size() > 1 && root->left != NULL) st.pop(); if(root->right != NULL) { st.push(root->right); backtrack(results, st, root->right, sum-root->right->val); } } } vector<vector<int> > pathSum(TreeNode* root, int sum) { vector<vector<int> > results; if(root == NULL) return results; stack<TreeNode*> st; st.push(root); backtrack(results, st, root, sum-root->val); return results; } void printVector(vector<vector<int> > &results) { int len = results.size(); if(len == 0) cout<<"empty vector"; else { for(int i = 0; i < len; i++) { for(int j = 0; j < results[i].size(); j++) cout<<results[i][j]<<" "; cout<<endl; } } cout<<endl; } int main() { TreeNode* root = new TreeNode(5); //root->left = new TreeNode(4); root->right = new TreeNode(8); //root->left->left = new TreeNode(11); //root->right->left = new TreeNode(13); root->right->right = new TreeNode(4); // root->left->left->left = new TreeNode(7); // root->left->left->right = new TreeNode(2); // root->right->right->left = new TreeNode(5); root->right->right->right = new TreeNode(2); int sum = 19; vector<vector<int> > results = pathSum(root, sum); printVector(results); return 0; }
6100cc347e7a087a5ede6f7a841bf934495f0c0e
96d79d09797cab9e93681d1c0d92f5127488d792
/src/civilized/buildings/Residential.cpp
48f263ed227f8886a0253a7ebb0f1aa6aed4fd8c
[]
no_license
Truttle1/BlockstersGame
5bd4af166ea5abc540c4de7cf64eb95ca078d4c8
2f9918e1f646909c285497a8dff0d2de085a385f
refs/heads/master
2020-04-20T23:56:53.097683
2019-08-11T04:29:02
2019-08-11T04:29:02
169,181,826
0
0
null
null
null
null
UTF-8
C++
false
false
3,882
cpp
Residential.cpp
/* * Residential.cpp * * Created on: Jun 27, 2019 * Author: truttle1 */ #include "Residential.h" Texture2D Residential::house; Texture2D Residential::teepee; bool Residential::loadedImages = false; Residential::Residential(int ix, int iy) : Building(ix,iy) { landValue = 1; population = 0; buildingType = RES; populationDifference = 0; hasRoad = false; hasFarm = false; myFarm = nullptr; myRoad = nullptr; farmDistance = 0; starving = false; trafficJam = false; } Residential::~Residential() { } void Residential::nextEat() { } void Residential::nextGeneration() { for(unsigned i = 0; i < objects.size(); i++) { if(objects[i]->getBuilding() == ROAD) { if(adjacent(objects[i]) && !hasRoad && population > 0) { hasRoad = true; landValue += 1; myRoad = static_cast<Road*>(objects[i]); trafficAddition = (population/20)+1; myRoad->moreTraffic(1); } } } if(hasRoad && rand()%10 < 5 && population > 0) { myRoad->lessenTraffic(trafficAddition); std::vector<GameObject*> roads = getAdjacent(ROAD); myRoad = static_cast<Road*>(roads[rand()%roads.size()]); trafficAddition = (population/20)+1; myRoad->moreTraffic(trafficAddition); } if(hasRoad && !adjacent(myRoad)) { hasRoad = false; landValue -= 1; } if(hasRoad && myRoad->getTraffic() >= 1 && !trafficJam) { landValue -= 1; trafficJam = true; } if(hasRoad && myRoad->getTraffic() < 1 && trafficJam) { landValue += 1; trafficJam = false; } if(hasFarm && distanceToBuilding(FARM) > farmDistance) { landValue -= 1; hasFarm = false; myFarm = nullptr; } if(!starving && hasFarm && myFarm->almostEmpty()) { landValue -= 1; starving = true; } if(starving && hasFarm && !myFarm->almostEmpty()) { landValue += 1; starving = false; } if(distanceToBuilding(FARM) < 24) { Farm* f = static_cast<Farm*>(nearestBuilding(FARM)); if((!hasFarm && !f->isEmpty()) || (!f->isEmpty() && hasFarm && myFarm->isEmpty())) { landValue += 1; hasFarm = true; myFarm = f; myFarm->lowerCapacity(1); } } farmDistance = distanceToBuilding(FARM); if(rand()%15 <= landValue) { populationDifference += 3; } else if(rand()%10 <= 2) { populationDifference -= 2; } while(population+populationDifference < 0) { populationDifference++; } while(population+populationDifference > maxPop) { populationDifference--; } if(true) { if(populationDifference > 0) { if(myFarm != nullptr) { myFarm->lowerCapacity(2); } } else if(populationDifference < 0 && myFarm != nullptr) { myFarm->raiseCapacity(1); } CivHandler::addPopulation(populationDifference); population += populationDifference; } populationDifference = 0; CivHandler::payTaxes(population); } void Residential::setPopulation(int pop) { population = pop; CivHandler::addPopulation(pop); } int Residential::getPopulation() { return population; } void Residential::nextMove() { } void Residential::tick() { if(!loadedImages) { setImages( LoadTexture("src/img/city/teepee.png"), LoadTexture("src/img/city/house.png")); loadedImages = true; } if(getClicking() && isPlayer()) { demolish(); } } void Residential::render() { /* if(landValue == 0) { DrawRectangle(x,y,8,8,BLACK); } if(landValue == 1) { DrawRectangle(x,y,8,8,RED); } if(landValue == 2) { DrawRectangle(x,y,8,8,BLUE); } if(landValue == 3) { DrawRectangle(x,y,8,8,YELLOW); } if(landValue == 4) { DrawRectangle(x,y,8,8,GREEN); } if(landValue == 5) { DrawRectangle(x,y,8,8,MAGENTA); }*/ if(population <= 0) { DrawRectangle(x,y,8,8,{0,192,0,255}); } else { DrawTexture(teepee,x,y,WHITE); } } void Residential::setImages(Texture2D iTeepee, Texture2D iHouse) { teepee = iTeepee; house = iHouse; } void Residential::finalize() { if(hasFarm) { myFarm->lowerCapacity(-1); } }
8031b01374a55bf77bc69c8ead4dd827314d356f
ffb5d0ead0ba1beee4e7413d1b76f8971330be97
/UVa_vertex.cpp
5f8f64100851bc6e4c711b5b58c0aa0ac8a443da
[]
no_license
tajul-saajan/Uva-Solved
6267479d944980053a30fc45d01891be7063c3f1
ae0f7c3857ae95658f53f7afedd32369cded765a
refs/heads/master
2021-07-11T03:12:05.250232
2020-12-26T07:30:19
2020-12-26T07:30:19
220,164,497
0
0
null
null
null
null
UTF-8
C++
false
false
1,865
cpp
UVa_vertex.cpp
#include<bits/stdc++.h> using namespace std; #define SET(a) memset(a,-1,sizeof(a)) #define ALL(a) a.begin(),a.end() #define CLR(a) memset(a,0,sizeof(a)) #define PB push_back #define PIE acos(-1.0) #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define READ freopen("input.txt", "r", stdin) #define WRITE freopen("output.txt", "w", stdout) #define ll long long #define sc(a) scanf("%d",&a) #define scc(a,b) scanf("%d%d",&a,&b) #define KS printf("Case %d: ",kk++) #define pf() printf() #define loop(i,num) for(int i=0;i<num;i++) #define MOD 1000000007 #define MX 100010 int n; vector< vector<int> > L; bool visited[100]; void unreachable(int v) { fill(visited,visited+n,false); queue<int> Q; Q.push(v); int aux; while(!Q.empty()) { aux=Q.front(); Q.pop(); int z=L[aux].size(); for(int i=0; i<z; i++) { if(visited[L[aux][i]]) continue; visited[L[aux][i]]=true; Q.push(L[aux][i]); } } int cont=0; for(int i=0; i<n; i++) if(!visited[i]) cont++; printf("%d",cont); for(int i=0; i<n; i++) if(!visited[i]) printf(" %d",i+1); printf("\n"); } int main() { int a,b,m; //READ; while(1) { scanf("%d",&n); if(n==0) break; L.clear(); L.resize(n); while(1) { scanf("%d",&a); if(a==0) break; while(1) { scanf("%d",&b); if(b==0) break; L[a-1].push_back(b-1); } } scanf("%d",&m); for(int i=0; i<m; i++) { scanf("%d",&a); unreachable(a-1); } } return 0; }
151312fd0dfd47dbdd2b39eb0342fdfe0831d701
954d216e92924a84fbd64452680bc58517ae53e8
/source/apps/demos/nckDemo_Metaballs.h
b4fc7fbb722466463bb090ec18b06f5e6666c984
[ "MIT" ]
permissive
nczeroshift/nctoolkit
e18948691844a8657f8937d2d490eba1b522d548
c9f0be533843d52036ec45200512ac54c1faeb11
refs/heads/master
2021-01-17T07:25:02.626447
2020-06-10T14:07:03
2020-06-10T14:07:03
47,587,062
3
2
null
null
null
null
UTF-8
C++
false
false
875
h
nckDemo_Metaballs.h
/** * NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license. * https://github.com/nczeroshift/nctoolkit */ #ifndef _NCK_DEMO_METABALLS_H_ #define _NCK_DEMO_METABALLS_H_ #include "../nckDemo.h" class Demo_Metaballs : public Demo{ public: Demo_Metaballs(Core::Window * wnd, Graph::Device * dev); ~Demo_Metaballs(); void Load(); void Render(float dt); void UpdateWndEvents(); std::vector<std::string> GetKeywords(); std::string GetDescription(); private: Core::Chronometer * chron; Gui::FontMap * fontMap; Graph::Texture * fontTexture; Graph::Program * shader; Scene::MCRenderer * processor; std::vector<Scene::MCSphereShape> spheres; float dimensions; int currentLod; int maxLod; float zRotation; float time; }; Demo * CreateDemo_Metaballs(Core::Window * wnd, Graph::Device * dev); #endif
78a697159d5047b5cb4e5501ed7d73c2f49fb1f4
7892ed4b9aa38d34f0d84d9c3aa9419e30d894e0
/elunebot.bootstrap/nativehost.h
2d5ac2e872a36b27dd6324c939f18dcfb6825bf1
[]
no_license
Gofrettin/EluneBot
90ba1138a6aee0dd61dc2caa7fc55345ee2cd299
31627838ebb2736214789c3e1aca6ac5fe9a2f3e
refs/heads/master
2022-08-31T08:26:41.513524
2022-04-25T15:15:41
2022-04-25T15:15:41
417,240,848
0
0
null
null
null
null
UTF-8
C++
false
false
102
h
nativehost.h
#pragma once class nativehost { public: int main(LPCWSTR dir); typedef void entrypoint(); };
96676561caec68a9d33ec3d0a5ebfb3af19d99d9
772d932a0e5f6849227a38cf4b154fdc21741c6b
/CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/rpg3D/gw/view/mainui/MIGUIVAT_Base.cpp
8b5ed842153eccb12c3f302e65ba270fcaf787b5
[]
no_license
AdrianNostromo/CodeSamples
1a7b30fb6874f2059b7d03951dfe529f2464a3c0
a0307a4b896ba722dd520f49d74c0f08c0e0042c
refs/heads/main
2023-02-16T04:18:32.176006
2021-01-11T17:47:45
2021-01-11T17:47:45
328,739,437
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
MIGUIVAT_Base.cpp
#include "MIGUIVAT_Base.h" #include <rpg3D/gw/entity/template/ToolsHandlerTemplate.h> #include <rpg3D/gw/entity/module/toolsHandler/IToolsHandlerModule.h> #include <worldGame3D/gw/entity/IWorldEntity.h> using namespace rpg3D; MIGUIVAT_Base::MIGUIVAT_Base(IApp* app, ArrayList<MenuItemConfig*>* viewItemConfigs, ArrayList<StateChangeDurations*>* viewEaseDurationsSList, base::IGameWorld* gw) : super(app, viewItemConfigs, viewEaseDurationsSList, gw) { //void } void MIGUIVAT_Base::setListenerToolExtraActivation(IListenerToolExtraActivation* listenerToolExtraActivation) { this->listenerToolExtraActivation = listenerToolExtraActivation; } void MIGUIVAT_Base::onSelectedFocusEntityChange_pre() { super::onSelectedFocusEntityChange_pre(); if (selectedFocusEntity_toolsHandler != nullptr) { selectedFocusEntity_toolsHandler = nullptr; } } void MIGUIVAT_Base::onSelectedFocusEntityChanged(IWorldEntity* selectedFocusEntity, ArrayList<std::shared_ptr<IEventListener>>& selectedFocusEntity_autoListenersList) { super::onSelectedFocusEntityChanged(selectedFocusEntity, selectedFocusEntity_autoListenersList); if (selectedFocusEntity != nullptr) { selectedFocusEntity_toolsHandler = selectedFocusEntity->getComponentAs<IToolsHandlerModule*>(false/*mustExist*/); } } MIGUIVAT_Base::~MIGUIVAT_Base() { //void }
d00139f1362bb7f8cfbf1c7503e3255bbd9bfcda
df7366b9d1e195458e2df676543248e7dddcbdb4
/uva 10004 bicoloring.cpp
c7d88ff2d5cfa5adc24ab8813b06d49cbde594e5
[]
no_license
FahimSifnatul/problem_solving_with_FahimSifnatul_cpp_version
b30e76a19b3ec95e298fe1ed60533e51344d090b
639071ed1b00be6ab1a648fc995c7a5044f58c2a
refs/heads/master
2022-07-14T05:09:32.098498
2020-05-20T09:42:30
2020-05-20T09:42:30
265,513,170
1
0
null
null
null
null
UTF-8
C++
false
false
1,506
cpp
uva 10004 bicoloring.cpp
#include<bits/stdc++.h> using namespace std; vector<int>node[200]; deque<int>q; int level[200]; /*int bfs(int n) { int u,v,flg=0; memset(level,-1,sizeof level); q.push_back(0); level[0]=0; while(!q.empty()) { u=q.front(); q.pop_front(); v=node[u].size(); for(int i=0;i<v;i++) { if(level[node[u][i]]==-1) { level[node[u][i]]=level[u]+1; q.push_back(node[u][i]); } } } return 0; }*/ int main() { int n,l; while(scanf("%d",&n)==1 and n!=0) { scanf("%d",&l); int x,y,flg=0,len[n]; for(int i=0;i<l;i++) { scanf("%d%d",&x,&y); node[x].push_back(y); node[y].push_back(x); } //bfs(n); for(int i=0;i<n;i++) { int le=node[i].size(); len[i]=le; //cout<<len<<endl; } //sort(len,len+n); int one=0,two=0,three=0,dif1,dif2; for(int i=0;i<n;i++) { if(len[i]>2) ++three; else if(len[i]==2) ++two; else ++one; } if((three==1 and one==n-1) or (n%2==0 and two==n) or (n-two==2 and three==0) or n==1) printf("BICOLORABLE.\n"); else printf("NOT BICOLORABLE.\n"); for(int i=0;i<n;i++) node[i].clear(); } return 0; }
b635300fc6c71e47c05d3d051380f1d5871e759d
97bb7da626def8ad206be815c64348778f550d38
/1306.jump-game-iii/JumpGame3.cpp
e7ca948ccf66f82a32a0fc6194e14051331b761a
[]
no_license
songkey7/leetcode
c242daafe33cc6035461fc2f3e751489d8b2551e
2f72c821bd0551313813c9b745ddf5207e1cb71c
refs/heads/master
2021-05-14T09:50:35.570822
2020-04-10T01:20:11
2020-04-10T01:20:11
116,336,985
0
0
null
null
null
null
UTF-8
C++
false
false
584
cpp
JumpGame3.cpp
// // Created by songkey on 2020/2/28. // #include "JumpGame3.h" bool JumpGame3::canReach(vector<int> &arr, int start) { if(start < 0 || start >= arr.size() || arr[start] < 0) return false; if(arr[start] == 0) return true; int t = arr[start]; arr[start] = -1; return canReach(arr, start + t) || canReach(arr, start - t); } void JumpGame3::run() { vector<int> arr1 = {4,2,3,0,3,1,2}; assert(canReach(arr1, 5)); vector<int> arr2 = {4,2,3,0,3,1,2}; assert(canReach(arr2, 0)); vector<int> arr3 = {3,0,2,1,2}; assert(!canReach(arr3, 2)); }
2f0bf5f68fc6059705b2c536dfdcbb8a0227e4a1
1118fa1d6b40d1cd33476e896a423a7e4c9e8880
/XeytanCuteServer/services/ClientContext.h
28bf945f5d929e456f5e43d473513c4ac5a31417
[]
no_license
melardev/XeytanQpp-RAT
464995e6afc771bb7920d6a751f80392c84cd69e
09097826b1bf9cfb45fad7552ea8c2738fdd93b7
refs/heads/master
2020-07-24T11:04:00.171848
2019-09-11T20:37:11
2019-09-11T20:37:11
207,902,443
8
2
null
null
null
null
UTF-8
C++
false
false
692
h
ClientContext.h
#pragma once #include "NetClientService.h" class NetServerService; class ClientContext { public: ClientContext(); ClientContext(const QSharedPointer<NetServerService>& net_server_service, const QSharedPointer<NetClientService>& client); ~ClientContext(); QSharedPointer<NetClientService> getNetClientService(); const QSharedPointer<NetServerService> getNetServerService(); void set_net_client_service(const QSharedPointer<NetClientService>& client); private: // The owner const QSharedPointer<NetServerService> netServerService; // The handler for any successive connections: desktop, camera, keylog, etc. QSharedPointer<NetClientService> netClientService; };
5ffc54f5f9e297b76f2d3ad4f9b49214438f8306
54a91ac41ef6fd5a80df98c8f4c87080a593c9c7
/Non-Photorealistic Rendering/Element3D.cpp
ab8ec564abc228ba1ffb8fd3d23762b03301aaa2
[]
no_license
sergiocalahorro/Non-Photorealistic-Rendering
c9fcb2d885b14692504f14a6d3ef7b65ad5839e2
d8f43d4d0b574b14ec270e20a658642732c3589c
refs/heads/master
2021-03-01T21:29:56.287931
2021-02-25T11:34:08
2021-02-25T11:34:08
245,814,986
4
0
null
null
null
null
ISO-8859-1
C++
false
false
4,066
cpp
Element3D.cpp
#include "Element3D.h" // - Constructor por defecto Element3D::Element3D() { modelMatrix = glm::mat4(1.0f); } // - Destructor Element3D::~Element3D() { } // - Obtener matriz de modelado del elemento 3D glm::mat4 Element3D::getModelMatrix() { return modelMatrix; } // - Asignar matriz de modelado del elemento 3D void Element3D::setModelMatrix(glm::mat4 modelMatrix) { this->modelMatrix = modelMatrix; } // - Transformación geométrica: traslación void Element3D::translate(glm::vec3 translation) { this->modelMatrix = glm::translate(this->modelMatrix, translation); } // - Transformación geométrica: escalado void Element3D::scale(glm::vec3 scale) { this->modelMatrix = glm::scale(this->modelMatrix, scale); } // - Transformación geométrica: rotación void Element3D::rotate(glm::vec3 rotation, float angle) { this->modelMatrix = glm::rotate(this->modelMatrix, angle, rotation); } // - Saber si es o no un plano bool Element3D::elementIsPlane() { return isPlane; } // - Asignar parámetros del contorno básico void Element3D::setBasicOutline(BasicOutline basic) { this->basicOutline = basic; initialBasicOutline = this->basicOutline; } // - Asignar parámetros del contorno básico BasicOutline& Element3D::getBasicOutline() { return this->basicOutline; } // - Restaurar contorno avanzado a su estado por defecto void Element3D::resetBasicOutline() { this->basicOutline.color = initialBasicOutline.color; this->basicOutline.thickness = initialBasicOutline.thickness; } // - Asignar parámetros del contorno avanzado void Element3D::setAdvancedOutline(AdvancedOutline advanced) { this->advancedOutline = advanced; initialAdvancedOutline = this->advancedOutline; } // - Asignar parámetros del contorno avanzado AdvancedOutline& Element3D::getAdvancedOutline() { return this->advancedOutline; } // - Restaurar contorno avanzado a su estado por defecto void Element3D::resetAdvancedOutline() { this->advancedOutline.color = initialAdvancedOutline.color; this->advancedOutline.thickness = initialAdvancedOutline.thickness; this->advancedOutline.extension = initialAdvancedOutline.extension; } // - Asignar parámetros de la técnica Monochrome void Element3D::setMonochromeTechnique(MonochromeTechnique monochrome) { this->monochrome = monochrome; initialMonochrome = this->monochrome; } // - Obtener parámetros de la técnica Monochrome MonochromeTechnique& Element3D::getMonochromeTechnique() { return this->monochrome; } // - Restaurar técnica Monochrome a su estado por defecto void Element3D::resetMonochromeTechnique() { this->monochrome = initialMonochrome; } // - Asignar parámetros de la técnica Cel-Shading void Element3D::setCelShadingTechnique(CelShadingTechnique celShading) { this->celShading = celShading; initialCelShading = this->celShading; } // - Obtener parámetros de la técnica Cel-Shading CelShadingTechnique& Element3D::getCelShadingTechnique() { return this->celShading; } // - Restaurar técnica Cel-Shading a su estado por defecto void Element3D::resetCelShadingTechnique() { this->celShading = initialCelShading; } // - Asignar parámetros de la técnica Hatching void Element3D::setHatchingTechnique(HatchingTechnique hatching) { this->hatching = hatching; initialHatching = this->hatching; } // - Obtener parámetros de la técnica Hatching HatchingTechnique& Element3D::getHatchingTechnique() { return this->hatching; } // - Restaurar técnica Hatching a su estado por defecto void Element3D::resetHatchingTechnique() { this->hatching = initialHatching; } // - Asignar parámetros de la técnica Gooch Shading void Element3D::setGoochShadingTechnique(GoochShadingTechnique goochShading) { this->goochShading = goochShading; initialGoochShading = this->goochShading; } // - Obtener parámetros de la técnica Gooch Shading GoochShadingTechnique& Element3D::getGoochShadingTechnique() { return this->goochShading; } // - Restaurar técnica Gooch Shading a su estado por defecto void Element3D::resetGoochShadingTechnique() { this->goochShading = initialGoochShading; }
0bb3a83454103d350db8a8558c2103d3627f2520
fa7f442ef185c00b55d3edeeac83b96be7c7acb3
/Papilio_DUO_Verification/src/Papilio_DUO_Test_Plan_Stimulus_Board/Papilio_DUO_Test_Plan_Stimulus_Board.ino
1084347f230bcd3d7e7248f9e2fe356afae0859a
[]
no_license
Mafei/Test-Plans
0cad3155c9be1c0329991c3d40a4c0f7c12e8258
0e894e689915a9140b6e6163dc198e4509047fec
refs/heads/master
2021-01-16T22:39:37.935171
2014-12-18T00:26:10
2014-12-18T00:26:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
958
ino
Papilio_DUO_Test_Plan_Stimulus_Board.ino
/* Gadget Factory Papilio One Stimulus Sketch for Verification Used to test the I/O of new Papilio One boards. This is the sketch that runs on the board built into the Pogo Pin tester. created 2010 by Jack Gassett from existing Arduino code snippets http://www.gadgetfactory.net This example code is in the public domain. */ int pinCount=54; void setup() { for (int thisPin = 1; thisPin < pinCount; thisPin++) { pinMode(thisPin, OUTPUT); } pinMode(0,INPUT); //Disable the ISP pins pinMode(11,INPUT); pinMode(12,INPUT); pinMode(13,INPUT); } void loop(){ if (digitalRead(0)) { for (int thisPin = 1; thisPin < pinCount; thisPin=thisPin+2) { digitalWrite(thisPin, HIGH); digitalWrite(thisPin-1, LOW); } } else { for (int thisPin = 1; thisPin < pinCount; thisPin=thisPin+2) { digitalWrite(thisPin, LOW); digitalWrite(thisPin-1, HIGH); } } }
0f75d42ccea112d3f8a00f99391d5e767a2d2462
e7e497b20442a4220296dea1550091a457df5a38
/main_project/talkn/function/TalkFunIM/src/FunIMOther.cpp
026fcee4a4ab871e07a081e813d4b7168b71d2aa
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
FunIMOther.cpp
#include "FunIMOther.h" #include "TalkProxyAdapter.h" #include "TalkCommon.h" #include "XmppTools.h" using namespace com::xiaonei::talk::function::im::other; using namespace com::xiaonei::talk; using namespace com::xiaonei::talk::util; using namespace com::xiaonei::talk::adapter; using namespace com::xiaonei::talk::common; void FunIMOther::ProcessPingRequest(const Str2StrMap& paras) { const string FuncName = "ProcessPingRequest::Handle"; TimeStatN ts; string jid_string, id; JidPtr jid; ParasGetValue("actor_jid", jid_string, paras); ParasGetValue("iq:id", id, paras); try { jid = stringToJid(jid_string); if(!jid) return; } catch(...) { MCE_WARN(FuncName << "stringToJid error"); } string reply = "<iq type=\"result\" to=\"" + jid_string + "\" from=\"talk.renren.com\" id=\"" + id + "\" />"; try { TalkProxyAdapter::instance().express(jid, reply); } catch(Ice::Exception& e) { MCE_WARN(FuncName << "-->TalkProxyAdapter::express error" << e); } FunStatManager::instance().Stat(FuncName, ts.getTime(), (ts.getTime() > 50.0)); }
2088d950fff4443b5776f467f755fc7e71581db2
2155b0d6ed0b40ff491b9a5669d77e932d039013
/deffem_postprocessor/src/Color.cpp
d0b1983eb008e62de42087c57e2cd4bd6378821f
[ "Apache-2.0" ]
permissive
mmaikel/DEFFEM_Postprocessor
7bf2b076cdd87975e4e3bac919fcac21cdcf8fc1
c4412a93a873e480f8a44196b54038cec1e6172b
refs/heads/master
2021-07-14T03:22:57.386591
2020-06-02T14:16:22
2020-06-02T14:16:22
156,970,671
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
cpp
Color.cpp
#include "../headers/Color.h" using namespace deffem; Color::Color() { this->red = 0.0; this->green = 0.0; this->blue = 0.0; this->alpha = 1.0; } Color::Color(GLfloat red, GLfloat green, GLfloat blue) { this->red = red; this->green = green; this->blue = blue; this->alpha = 1.0; } Color::Color(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) { this->red = red; this->green = green; this->blue = blue; this->alpha = alpha; } Color::Color(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha, std::string name) { this->red = red; this->green = green; this->blue = blue; this->alpha = 1.0; this->colorName = name; } Color::Color(GLfloat red, GLfloat green, GLfloat blue, std::string name) { this->red = red; this->green = green; this->blue = blue; this->alpha = alpha; this->colorName = name; } Color Color::fromString(std::string colorName) { return Colors::colors[colorName]; } Color Colors::red(1.0f, 0.0f, 0.0f, "red"); Color Colors::green(0.0f, 1.0f, 0.0f, "green"); Color Colors::blue(0.0f, 0.0f, 1.0f, "blue"); Color Colors::black(0.0f, 0.0f, 0.0f, "black"); Color Colors::darkGray(0.15f, 0.15f, 0.17f, "dark-gray"); Color Colors::gray(0.3f, 0.3f, 0.32f, "gray"); Color Colors::lightGray(0.55f, 0.55f, 0.57f, "light-gray"); Color Colors::lightBlue(0.53f, 0.8f, 0.98f, "light-blue"); Color Colors::white(1.0f, 1.0f, 1.0f, "white"); Color Colors::yellow(1.0f, 1.0f, 0.4f, "yellow"); Color Colors::orange(1.0f, 0.65f, 0.0f, "orange"); Color Colors::magenta(1.0f, 0.0f, 0.564f, "magenta"); Color Colors::purple(0.5f, 0.0f, 0.5f, "purple"); std::map<std::string, Color> Colors::colors = std::map<std::string, Color>{ std::pair<std::string, Color>(red.colorName, red), std::pair<std::string, Color>(green.colorName, green), std::pair<std::string, Color>(blue.colorName, blue), std::pair<std::string, Color>(black.colorName, black), std::pair<std::string, Color>(darkGray.colorName, darkGray), std::pair<std::string, Color>(gray.colorName, gray), std::pair<std::string, Color>(lightGray.colorName, lightGray), std::pair<std::string, Color>(lightBlue.colorName, lightBlue), std::pair<std::string, Color>(white.colorName, white), std::pair<std::string, Color>(yellow.colorName, yellow), std::pair<std::string, Color>(orange.colorName, orange), std::pair<std::string, Color>(magenta.colorName, magenta), std::pair<std::string, Color>(purple.colorName, purple), };
ac61555ce61c870f0eae132463f78bdd71f78240
7a67db68dbaa9d696b4af914c14b949c14da51d8
/70_recursion_iteration.cpp
837a818d1747b86eefde6c3dfba85590c0506c36
[]
no_license
igoingdown/leetcode
9b556ed6fe5107f6fb9aab639efaad49bebf57b9
875d522c0c10cd3bb872fa118ff229e7a659f791
refs/heads/main
2021-12-03T17:19:16.348784
2021-11-18T10:38:25
2021-11-18T10:38:27
69,318,899
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
70_recursion_iteration.cpp
class Solution { public: int climbStairs(int n) { if (n == 0) return 0; if (n == 1) return 1; int pre1 = 1, pre2 = 2, cur = 2; for (int i = 3; i <= n; i++) { cur = pre1 + pre2; pre1 = pre2; pre2 = cur; } return cur; } };
ac94ac7a98e0724a829930a017c6400e26debf8a
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-redshift/include/aws/redshift/model/ScheduledActionType.h
ceae79222d9e7be3acabb9bf868eec758718f028
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
5,503
h
ScheduledActionType.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/redshift/Redshift_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/redshift/model/ResizeClusterMessage.h> #include <aws/redshift/model/PauseClusterMessage.h> #include <aws/redshift/model/ResumeClusterMessage.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace Redshift { namespace Model { /** * <p>The action type that specifies an Amazon Redshift API operation that is * supported by the Amazon Redshift scheduler. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ScheduledActionType">AWS * API Reference</a></p> */ class ScheduledActionType { public: AWS_REDSHIFT_API ScheduledActionType(); AWS_REDSHIFT_API ScheduledActionType(const Aws::Utils::Xml::XmlNode& xmlNode); AWS_REDSHIFT_API ScheduledActionType& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); AWS_REDSHIFT_API void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; AWS_REDSHIFT_API void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline const ResizeClusterMessage& GetResizeCluster() const{ return m_resizeCluster; } /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline bool ResizeClusterHasBeenSet() const { return m_resizeClusterHasBeenSet; } /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline void SetResizeCluster(const ResizeClusterMessage& value) { m_resizeClusterHasBeenSet = true; m_resizeCluster = value; } /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline void SetResizeCluster(ResizeClusterMessage&& value) { m_resizeClusterHasBeenSet = true; m_resizeCluster = std::move(value); } /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline ScheduledActionType& WithResizeCluster(const ResizeClusterMessage& value) { SetResizeCluster(value); return *this;} /** * <p>An action that runs a <code>ResizeCluster</code> API operation. </p> */ inline ScheduledActionType& WithResizeCluster(ResizeClusterMessage&& value) { SetResizeCluster(std::move(value)); return *this;} /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline const PauseClusterMessage& GetPauseCluster() const{ return m_pauseCluster; } /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline bool PauseClusterHasBeenSet() const { return m_pauseClusterHasBeenSet; } /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline void SetPauseCluster(const PauseClusterMessage& value) { m_pauseClusterHasBeenSet = true; m_pauseCluster = value; } /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline void SetPauseCluster(PauseClusterMessage&& value) { m_pauseClusterHasBeenSet = true; m_pauseCluster = std::move(value); } /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline ScheduledActionType& WithPauseCluster(const PauseClusterMessage& value) { SetPauseCluster(value); return *this;} /** * <p>An action that runs a <code>PauseCluster</code> API operation. </p> */ inline ScheduledActionType& WithPauseCluster(PauseClusterMessage&& value) { SetPauseCluster(std::move(value)); return *this;} /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline const ResumeClusterMessage& GetResumeCluster() const{ return m_resumeCluster; } /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline bool ResumeClusterHasBeenSet() const { return m_resumeClusterHasBeenSet; } /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline void SetResumeCluster(const ResumeClusterMessage& value) { m_resumeClusterHasBeenSet = true; m_resumeCluster = value; } /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline void SetResumeCluster(ResumeClusterMessage&& value) { m_resumeClusterHasBeenSet = true; m_resumeCluster = std::move(value); } /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline ScheduledActionType& WithResumeCluster(const ResumeClusterMessage& value) { SetResumeCluster(value); return *this;} /** * <p>An action that runs a <code>ResumeCluster</code> API operation. </p> */ inline ScheduledActionType& WithResumeCluster(ResumeClusterMessage&& value) { SetResumeCluster(std::move(value)); return *this;} private: ResizeClusterMessage m_resizeCluster; bool m_resizeClusterHasBeenSet = false; PauseClusterMessage m_pauseCluster; bool m_pauseClusterHasBeenSet = false; ResumeClusterMessage m_resumeCluster; bool m_resumeClusterHasBeenSet = false; }; } // namespace Model } // namespace Redshift } // namespace Aws
212066b53de3d5cb7594f0bb1597440424201330
e83e76c6b232075e0f71f78b42d0cd98aff6d541
/Week1 Pointer2 q2.cpp
e4a184f52b1543419bd16d2baf68ea11dc0cbd15
[]
no_license
TheCYBORGIANpulkit/CS142-Week-1
4991b2c9d3f9d5f5ad5b41753ad4467ca940f709
4c14e6a16c114596d4041959c96780649d9dba60
refs/heads/master
2020-04-14T22:58:08.953796
2019-01-10T14:09:08
2019-01-10T14:09:08
164,185,189
0
0
null
null
null
null
UTF-8
C++
false
false
575
cpp
Week1 Pointer2 q2.cpp
#include<iostream> using namespace std; /* Find out (add code to print out) the address of the variable x in foo1, and the variable y in foo2. What do you notice? Can you explain this? */ void foo1(int xval) { int x; x = xval; /* print the address and value of x here */ int *p = &x; cout<< *p<<endl; cout<< p <<endl; } void foo2(int dummy) { int y; y = dummy; int *q = &y; cout<< *q <<endl; cout<< q <<endl; /* print the address and value of y here */ } int main() { foo1(7); foo2(11); return 0; }
5a18539f17f56ceeeea4730c6c53976150ce6bef
8c5f16b6e5616f7e823a502d7235d1e7bd1c8825
/homework/9-5.cpp
4a578dad4acc3fa847006fc5a5d754e9ca5ff2de
[]
no_license
TouwaErioH/VHDL-files
4c437bb7a060fb16f2dda38c7abfcd36b1d5af15
09032ac75250b279937299779a521e087d5c7cb0
refs/heads/master
2020-03-14T16:44:36.604261
2019-06-26T08:15:31
2019-06-26T08:15:31
131,704,035
1
2
null
null
null
null
GB18030
C++
false
false
1,139
cpp
9-5.cpp
#include <stdio.h> #include <stdlib.h> struct Date{ int year; int month; int date; }; int main() { int years,days; int month=1; int n=0; struct Date thedate; int normal[12]={31,28,31,30,31,30,31,31,30,31,30,31}; int abnormal[12]={31,29,31,30,31,30,31,31,30,31,30,31}; printf("按顺序先后输入年份和第几天:\n"); scanf("%d%d",&years,&days); thedate.year=years; if(years%4!=0||years%400!=0) { if(days<=31) {thedate.month=1; thedate.date=days; } else {while(days-normal[n]>normal[n+1]) { days=days-normal[n]; n++; } thedate.month=n+2; thedate.date=days-normal[n];} } else { if(days<=31) {thedate.month=1; thedate.date=days; } else {while(days-abnormal[n]>abnormal[n+1]) { days=days-abnormal[n]; n++; } thedate.month=n+2; thedate.date=days-abnormal[n];} } printf("%d.%d.%d",thedate.year,thedate.month,thedate.date); system("pause"); return 0; }
166889e9c833556ee724911c196d296e40d9320f
62d991fdb7b796012ae19bb9deb4847b42d884df
/tensorflow/lite/micro/kernels/arc_mli/mli_interface.h
b4087f3b87ba465a48a2d7e2bc53ca9491835ec4
[ "Apache-2.0" ]
permissive
xmos/tflite-micro
27483372b233a53c4884c55e654fc44d19433bd6
0b02e2e8e9da516afeebafb6e936d5311b33111e
refs/heads/main
2023-08-18T21:08:10.649833
2021-09-23T14:50:47
2021-09-23T14:50:47
386,217,339
1
1
Apache-2.0
2021-09-23T14:50:48
2021-07-15T08:22:41
C++
UTF-8
C++
false
false
2,460
h
mli_interface.h
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_LITE_MICRO_KERNELS_ARC_MLI_INTERFACE_H_ #define TENSORFLOW_LITE_MICRO_KERNELS_ARC_MLI_INTERFACE_H_ #include "mli_api.h" // NOLINT #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" namespace tflite { namespace ops { namespace micro { // Abstracts access to mli_tensor fields to use different versions of MLI // Library (1.x and 2.x) // Example: // ops::micro::MliTensorInterface mli_in = // ops::micro::MliTensorInterface(static_cast<mli_tensor*>( // context->AllocatePersistentBuffer(context, sizeof(mli_tensor)))); class MliTensorInterface { public: // Make sure that lifetime of MliTensorInterface instance isn't bigger than // related mli_tensor. MliTensorInterface(mli_tensor* tensor) : tensor_(tensor){}; MliTensorInterface() = default; ~MliTensorInterface() = default; template <typename T> T* Data(); template <typename T> T Scale(); template <typename T> T ZeroPoint(); template <typename T> T ScaleFracBits(); mli_tensor* MliTensor(); const mli_tensor* MliTensor() const; int32_t* Dim(); uint32_t* Rank(); uint32_t* Shape(); const uint32_t* Shape() const; const uint32_t* DataCapacity() const; uint32_t* ScaleCapacity(); mli_element_type* ElType(); uint32_t* ScaleFracBitsCapacity(); int32_t* MemStride(); uint32_t* ZeroPointCapacity(); template <typename T> void SetData(T* data, uint32_t capacity) const; void SetScale(float fscale); void SetScalePerChannel(float* fscale, const int num_channels); void SetElType(TfLiteType type); private: mli_tensor* tensor_; }; } // namespace micro } // namespace ops } // namespace tflite #endif // TENSORFLOW_LITE_MICRO_KERNELS_ARC_MLI_SLICERS_H_
228978dcd96398f0528798b9547ac4d7a7194b31
487c4ec822da71b9b393d8089caa477b8d4f69f7
/3Daxis.cpp
c61bbbef3401fc37dc963ded26ebb0eac0eae916
[]
no_license
nm666code/3Daxis
dc46c485afff383ab12bf968bf673ef223727c75
2c77ebe9c2d383d4b9629a550e18fe7055b5d882
refs/heads/main
2023-08-28T17:10:02.250876
2021-11-01T14:42:26
2021-11-01T14:42:26
423,500,873
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
cpp
3Daxis.cpp
#include <GL/glut.h> #include<iostream> using namespace std; void myinit(void) { glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); } void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.2, 0.2, 0.2, 1.0); glMatrixMode(GL_MODELVIEW); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(3.8, 0.0, 0.0); glEnd(); glColor3f(0.0, 1.0, 0.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 3.8, 0.0); glEnd(); glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 3.8); glEnd(); glLoadIdentity(); gluLookAt(5.0, 5.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glutSwapBuffers(); glFlush(); } void reshape(int width, int height) { int aspect = width * 1.0f / height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, width, height); gluPerspective(60.0f, aspect, 0.1f, 10.0f); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(640, 480); glutInitWindowPosition(10, 10); glutCreateWindow("U10916025"); myinit(); glutDisplayFunc(display); glutReshapeFunc(reshape); display(); glutMainLoop(); return 0; }
fb9069c3ba8186342fcb81dbcf4b5dd947f0bec5
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/generator/internal/metadata_decorator_generator.cc
1ad34ca8c5faa05acc6050f43ef2b64d44e129f8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
14,168
cc
metadata_decorator_generator.cc
// Copyright 2020 Google 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 // // https://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 "generator/internal/metadata_decorator_generator.h" #include "generator/internal/codegen_utils.h" #include "generator/internal/http_option_utils.h" #include "generator/internal/longrunning.h" #include "generator/internal/predicate_utils.h" #include "generator/internal/printer.h" #include "generator/internal/routing.h" #include "google/cloud/internal/absl_str_cat_quiet.h" #include "google/cloud/internal/url_encode.h" #include "absl/strings/str_split.h" #include <google/protobuf/descriptor.h> #include <algorithm> namespace google { namespace cloud { namespace generator_internal { namespace { enum ContextType { kPointer, kReference }; std::string SetMetadataText(google::protobuf::MethodDescriptor const& method, ContextType context_type) { std::string const context = context_type == kPointer ? "*context" : "context"; auto info = ParseExplicitRoutingHeader(method); // If there are no explicit routing headers, we fall back to the routing as // defined by the google.api.http annotation if (info.empty()) { if (HasHttpRoutingHeader(method)) { return " SetMetadata(" + context + ", absl::StrCat($method_request_params$));"; } // If the method does not have a `google.api.routing` or `google.api.http` // annotation, we do not send the "x-goog-request-params" header. return " SetMetadata(" + context + ");"; } // clang-format off std::string text; text += " std::vector<std::string> params;\n"; text += " params.reserve(" + std::to_string(info.size()) + ");\n\n"; for (auto const& kv : info) { // In the simplest (and probably most common) cases where no regular // expression matching is needed for a given routing parameter key, we skip // the static loading of `RoutingMatcher`s and simply use if statements. if (std::all_of( kv.second.begin(), kv.second.end(), [](RoutingParameter const& rp) { return rp.pattern == "(.*)"; })) { auto const* sep = " "; for (auto const& rp : kv.second){ text += sep; text += "if (!request." + rp.field_name + "().empty()) {\n"; text += " params.push_back(absl::StrCat(\"" + kv.first + "=\", internal::UrlEncode(request." + rp.field_name + "())));\n"; text += " }"; sep = " else "; } text += "\n\n"; continue; } text += " static auto* " + kv.first + "_matcher = []{\n"; text += " return new google::cloud::internal::RoutingMatcher<$request_type$>{\n"; text += " \"" + internal::UrlEncode(kv.first) + "=\", {\n"; for (auto const& rp : kv.second) { text += " {[]($request_type$ const& request) -> std::string const& {\n"; text += " return request." + rp.field_name + "();\n"; text += " },\n"; // In the special match-all case, we do not bother to set a regex. if (rp.pattern == "(.*)") { text += " absl::nullopt},\n"; } else { text += " std::regex{\"" + rp.pattern + "\", std::regex::optimize}},\n"; } } text += " }};\n"; text += " }();\n"; text += " " + kv.first + "_matcher->AppendParam(request, params);\n\n"; } text += " if (params.empty()) {\n"; text += " SetMetadata(" + context + ");\n"; text += " } else {\n"; text += " SetMetadata(" + context + ", absl::StrJoin(params, \"&\"));\n"; text += " }"; return text; // clang-format on } } // namespace MetadataDecoratorGenerator::MetadataDecoratorGenerator( google::protobuf::ServiceDescriptor const* service_descriptor, VarsDictionary service_vars, std::map<std::string, VarsDictionary> service_method_vars, google::protobuf::compiler::GeneratorContext* context) : StubGeneratorBase("metadata_header_path", "metadata_cc_path", service_descriptor, std::move(service_vars), std::move(service_method_vars), context) {} Status MetadataDecoratorGenerator::GenerateHeader() { HeaderPrint(CopyrightLicenseFileHeader()); HeaderPrint( // clang-format off "\n" "// Generated by the Codegen C++ plugin.\n" "// If you make any local changes, they will be lost.\n" "// source: $proto_file_name$\n" "\n" "#ifndef $header_include_guard$\n" "#define $header_include_guard$\n"); // clang-format on // includes HeaderPrint("\n"); HeaderLocalIncludes({vars("stub_header_path"), "google/cloud/version.h"}); HeaderSystemIncludes( {HasLongrunningMethod() ? "google/longrunning/operations.grpc.pb.h" : "", "map", "memory", "string"}); auto result = HeaderOpenNamespaces(NamespaceType::kInternal); if (!result.ok()) return result; // metadata decorator class HeaderPrint(R"""( class $metadata_class_name$ : public $stub_class_name$ { public: ~$metadata_class_name$() override = default; $metadata_class_name$( std::shared_ptr<$stub_class_name$> child, std::multimap<std::string, std::string> fixed_metadata); )"""); HeaderPrintPublicMethods(); HeaderPrint(R"""( private: void SetMetadata(grpc::ClientContext& context, std::string const& request_params); void SetMetadata(grpc::ClientContext& context); std::shared_ptr<$stub_class_name$> child_; std::multimap<std::string, std::string> fixed_metadata_; std::string api_client_header_; }; )"""); HeaderCloseNamespaces(); // close header guard HeaderPrint("\n#endif // $header_include_guard$\n"); return {}; } Status MetadataDecoratorGenerator::GenerateCc() { CcPrint(CopyrightLicenseFileHeader()); CcPrint( // clang-format off "\n" "// Generated by the Codegen C++ plugin.\n" "// If you make any local changes, they will be lost.\n" "// source: $proto_file_name$\n"); // clang-format on // includes CcPrint("\n"); CcLocalIncludes( {vars("metadata_header_path"), "google/cloud/internal/absl_str_cat_quiet.h", HasExplicitRoutingMethod() ? "google/cloud/internal/absl_str_join_quiet.h" : "", "google/cloud/internal/api_client_header.h", HasExplicitRoutingMethod() ? "google/cloud/internal/routing_matcher.h" : "", "google/cloud/common_options.h", "google/cloud/status_or.h"}); CcSystemIncludes({vars("proto_grpc_header_path"), "memory"}); auto result = CcOpenNamespaces(NamespaceType::kInternal); if (!result.ok()) return result; // constructor CcPrint(R"""( $metadata_class_name$::$metadata_class_name$( std::shared_ptr<$stub_class_name$> child, std::multimap<std::string, std::string> fixed_metadata) : child_(std::move(child)), fixed_metadata_(std::move(fixed_metadata)), api_client_header_(google::cloud::internal::ApiClientHeader("generator")) {} )"""); // metadata decorator class member methods for (auto const& method : methods()) { if (IsStreamingWrite(method)) { CcPrintMethod(method, __FILE__, __LINE__, R"""( std::unique_ptr<::google::cloud::internal::StreamingWriteRpc< $request_type$, $response_type$>> $metadata_class_name$::$method_name$( std::shared_ptr<grpc::ClientContext> context) { SetMetadata(*context); return child_->$method_name$(std::move(context)); } )"""); continue; } if (IsBidirStreaming(method)) { // Asynchronous streaming writes do not consume a request. Typically, the // first `Write()` call contains any relevant data to "start" the stream. // Thus, the decorator cannot add any routing instructions. The caller // should initialize `context` with any such instructions. CcPrintMethod(method, __FILE__, __LINE__, R"""( std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc< $request_type$, $response_type$>> $metadata_class_name$::Async$method_name$( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context) { SetMetadata(*context); return child_->Async$method_name$(cq, std::move(context)); } )"""); continue; } CcPrintMethod( method, {MethodPattern( { {IsResponseTypeEmpty, // clang-format off "\nStatus\n", "\nStatusOr<$response_type$>\n"}, {"$metadata_class_name$::$method_name$(\n" " grpc::ClientContext& context,\n" " $request_type$ const& request) {\n"}, {SetMetadataText(method, kReference)}, {"\n return child_->$method_name$(context, request);\n" "}\n",} // clang-format on }, And(IsNonStreaming, Not(IsLongrunningOperation))), MethodPattern({{R"""( future<StatusOr<google::longrunning::Operation>> $metadata_class_name$::Async$method_name$( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, $request_type$ const& request) { )"""}, {SetMetadataText(method, kPointer)}, {R"""( return child_->Async$method_name$(cq, std::move(context), request); } )"""}}, IsLongrunningOperation), MethodPattern( { // clang-format off {"\n" "std::unique_ptr<google::cloud::internal::StreamingReadRpc<$response_type$>>\n" "$metadata_class_name$::$method_name$(\n" " std::shared_ptr<grpc::ClientContext> context,\n" " $request_type$ const& request) {\n"}, {SetMetadataText(method, kPointer)}, {"\n return child_->$method_name$(std::move(context), request);\n" "}\n",} // clang-format on }, IsStreamingRead)}, __FILE__, __LINE__); } for (auto const& method : async_methods()) { if (IsStreamingRead(method)) { auto const definition = absl::StrCat( R"""( std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc< $response_type$>> $metadata_class_name$::Async$method_name$( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context, $request_type$ const& request) { )""", SetMetadataText(method, kPointer), R"""( return child_->Async$method_name$(cq, std::move(context), request); } )"""); CcPrintMethod(method, __FILE__, __LINE__, definition); continue; } if (IsStreamingWrite(method)) { // Asynchronous streaming writes do not consume a request. Typically, the // first `Write()` call contains any relevant data to "start" the stream. // Thus, the decorator cannot add any routing instructions. The caller // should initialize `context` with any such instructions. auto const definition = absl::StrCat( R"""( std::unique_ptr<::google::cloud::internal::AsyncStreamingWriteRpc< $request_type$, $response_type$>> $metadata_class_name$::Async$method_name$( google::cloud::CompletionQueue const& cq, std::shared_ptr<grpc::ClientContext> context) { SetMetadata(*context); return child_->Async$method_name$(cq, std::move(context)); } )"""); CcPrintMethod(method, __FILE__, __LINE__, definition); continue; } CcPrintMethod( method, {MethodPattern( {{IsResponseTypeEmpty, // clang-format off "\nfuture<Status>\n", "\nfuture<StatusOr<$response_type$>>\n"}, {R"""($metadata_class_name$::Async$method_name$( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, $request_type$ const& request) { )"""}, {SetMetadataText(method, kPointer)}, {R"""( return child_->Async$method_name$(cq, std::move(context), request); } )"""}}, // clang-format on And(IsNonStreaming, Not(IsLongrunningOperation)))}, __FILE__, __LINE__); } // long running operation support methods if (HasLongrunningMethod()) { CcPrint(R"""( future<StatusOr<google::longrunning::Operation>> $metadata_class_name$::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { SetMetadata(*context, "name=" + request.name()); return child_->AsyncGetOperation(cq, std::move(context), request); } future<Status> $metadata_class_name$::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { SetMetadata(*context, "name=" + request.name()); return child_->AsyncCancelOperation(cq, std::move(context), request); } )"""); } CcPrint(R"""( void $metadata_class_name$::SetMetadata(grpc::ClientContext& context, std::string const& request_params) { context.AddMetadata("x-goog-request-params", request_params); SetMetadata(context); } void $metadata_class_name$::SetMetadata(grpc::ClientContext& context) { for (auto const& kv : fixed_metadata_) { context.AddMetadata(kv.first, kv.second); } context.AddMetadata("x-goog-api-client", api_client_header_); auto const& options = internal::CurrentOptions(); if (options.has<UserProjectOption>()) { context.AddMetadata( "x-goog-user-project", options.get<UserProjectOption>()); } auto const& authority = options.get<AuthorityOption>(); if (!authority.empty()) context.set_authority(authority); } )"""); CcCloseNamespaces(); return {}; } } // namespace generator_internal } // namespace cloud } // namespace google
79b84cb47604302d969fd77d5ac74857180b47a4
8198656013927dcf07c081b4ecd2a06873b86ac5
/frameworks/C++/cutelyst/src/databaseupdatestest.h
3ddd556e832a5b0fe7504838d4c26eb490437f32
[ "LicenseRef-scancode-warranty-disclaimer" ]
permissive
oci-pronghorn/FrameworkBenchmarks
a4dd888c7f0740f635acd1e3f0b40094dae9ecc5
f9cad2bce5e4ef6d9a42585e3bf23476b6d95c68
refs/heads/master
2020-04-02T01:42:54.539998
2019-05-06T03:16:24
2019-05-06T03:16:24
153,871,128
4
0
BSD-3-Clause
2019-05-06T02:25:33
2018-10-20T04:57:24
Java
UTF-8
C++
false
false
579
h
databaseupdatestest.h
#ifndef DATABASEUPDATESTEST_H #define DATABASEUPDATESTEST_H #include <Cutelyst/Controller> using namespace Cutelyst; class QSqlQuery; class DatabaseUpdatesTest : public Controller { Q_OBJECT C_NAMESPACE("") public: explicit DatabaseUpdatesTest(QObject *parent = 0); C_ATTR(updates_postgres, :Local :AutoArgs) void updates_postgres(Context *c); C_ATTR(updates_mysql, :Local :AutoArgs) void updates_mysql(Context *c); private: inline void processQuery(Context *c, QSqlQuery &query, QSqlQuery &updateQuery); }; #endif // DATABASEUPDATESTEST_H
4e013cad337a3fff69683322899241eb159f7a93
0f6df4510ccacdc39491154ecac6e7a316f03229
/Conditionals and loops/lec3_2.cpp
659e537955afe3d21e1baea1570298f2df3fddcd
[]
no_license
cyril1999/codenin
4c30b15f0502ef7238f7230ed5ab50e0955e0584
29979db2aec034efea4d54330cdb9a44de1291b8
refs/heads/master
2022-06-21T06:49:18.252383
2020-05-14T08:52:56
2020-05-14T08:52:56
261,735,087
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
lec3_2.cpp
#include <iostream> using namespace std; int main() { /* This piece of code is pretty important as it covers the concept of '!' here, b=20 inside the 'if' parentheses, would've been considered as true if not for the '!'sign which flips any non-zero value to zero thus not allowing the control to enter into the if statement. i.e. !b==0 which is false. '!' plays the perfect role of flipping th truth value of a statement. e.g. a=0; !a== non-zero value which allows the code inside the if statement to get executed */ /* int a = 10, b = 20, c = 30; if(a <= b && !b) { cout << "hello"; } else if(c >= a && c >= b) { cout << "hi"; } else { cout << "hey"; } */ }
0e3ae5ea75344f8a6791774b7faa7a0e0723dd54
c973979d4270168dbdd9de408bbc288413d2bd1e
/include/file_wrappers.hpp
408689ff9d654e7b49be1e5371d16ef31d6864ea
[]
no_license
alshai/pfbwt-f
e86adb62d9df238a78a436cc3a4e6a87ff8eb69e
663eebf1848f86e1dd09f03b4e72d1a53c093d9e
refs/heads/master
2022-02-07T08:29:50.840442
2022-01-18T15:23:55
2022-01-18T15:23:55
234,143,279
4
2
null
2022-01-27T19:04:43
2020-01-15T18:14:56
C++
UTF-8
C++
false
false
6,566
hpp
file_wrappers.hpp
#ifndef FILEW_HPP #define FILEW_HPP #include <vector> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include "mio.hpp" void die_(const char* string) { fprintf(stderr, "%s\n", string); exit(1); } size_t get_file_size_(const char* path) { if (!strcmp(path, "-")) { die_("cannot get file size from stdin"); } FILE* fp = fopen(path, "rb"); if (fp == NULL) { fprintf(stderr, "%s: ", path); die_("error opening file"); } fseek(fp, 0, SEEK_END); size_t size = ftell(fp); fclose(fp); return size; } /* load file using mmap and treat it as an STL container (mio) * TODO: create a MAP_PRIVATE version */ template<typename T, mio::access_mode AccessMode> class MMapFile { public: using value_type = T; using size_type = size_t; using reference = value_type&; using const_reference = const value_type&; using iterator = value_type*; using const_iterator = const value_type*; MMapFile() = default; MMapFile(std::string path) : mm(path) { if (!mm.size()) { die_("MMapFile: file empty!"); } if (mm.size() % sizeof(T) != 0) { die_("error: file is not evenly divided into size(T)-sized words"); } } /* start fresh from a file, given a size * size is number of elements, not number of bytes */ void init_file(std::string path, size_t size) { // make sure that file is 'cleared' and set to the appropriate size FILE* fp = fopen(path.data(), "wb"); if (fp) { fclose(fp); } else { fprintf(stderr, "%s: ", path.data()); die_("error opening file"); } if (truncate(path.data(), size * sizeof(T))) { die_("error setting file size"); } // map file std::error_code e; mm.map(path, 0, size * sizeof(T), e); } template<mio::access_mode A = AccessMode, typename = typename std::enable_if<A == mio::access_mode::write>::type> reference operator[](const size_type i) noexcept { return reinterpret_cast<T*>(mm.data())[i]; } const_reference operator[](const size_type i) const noexcept { return reinterpret_cast<const T*>(mm.data())[i]; } size_t size() const noexcept { return mm.size() / sizeof(T); } template<mio::access_mode A = AccessMode, typename = typename std::enable_if<A == mio::access_mode::write>::type> T* data() noexcept { return reinterpret_cast<T*>(mm.data()); } const T* data() const noexcept { return reinterpret_cast<const T*>(mm.data()); } template<mio::access_mode A = AccessMode, typename = typename std::enable_if<A == mio::access_mode::write>::type> iterator begin() noexcept { return data(); } const_iterator begin() const noexcept { return data(); } const_iterator cbegin() const noexcept { return data(); } template<mio::access_mode A = AccessMode, typename = typename std::enable_if<A == mio::access_mode::write>::type> iterator end() noexcept { return data() + size(); } const_iterator end() const noexcept { return data() + size(); } const_iterator cend() const noexcept { return data() + size(); } private: mio::basic_mmap<AccessMode, unsigned char> mm; T* data_; // this is derived from mm }; template<typename T> using MMapFileSource = MMapFile<T, mio::access_mode::read>; /* NOTE: I think this is MAP_SHARED by default. * TODO: add option for MAP_PRIVATE */ template<typename T> using MMapFileSink = MMapFile<T, mio::access_mode::write>; /* loads a file into a read-only vector. neither the data nor the underlying * file are allowed to be changed */ template<typename T> class VecFileSource : private std::vector<T> { public: VecFileSource() = default; VecFileSource(std::string path) { size_t size = get_file_size_(path.data()); size_t nelems = size / sizeof(T); FILE* fp = fopen(path.data(), "rb"); if (fp == NULL) { fprintf(stderr, "VecFileSource: error opening %s\n", path.data()); exit(1); } this->resize(nelems); if (fread(&(this->data())[0], sizeof(T), this->size(), fp) != nelems) { fprintf(stderr, "VecFileSource: error reading from %s\n", path.data()); exit(1); } fclose(fp); } typename std::vector<T>::const_reference operator[](typename std::vector<T>::size_type i) const { return std::vector<T>::operator[](i); } typename std::vector<T>::size_type size() const { return std::vector<T>::size(); } }; template<typename T> class VecFileSink : public std::vector<T> { public: VecFileSink() = default; /* load data from whole file */ VecFileSink(std::string path) : fname(path) { size_t size = get_file_size_(path.data()); size_t nelems = size / sizeof(T); FILE* fp = fopen(path.data(), "rb"); if (fp == NULL) { fprintf(stderr, "VecFileSink: error opening %s\n", path.data()); exit(1); } this->resize(nelems); if (fread(&(*this)[0], sizeof(T), this->size(), fp) != nelems) { fprintf(stderr, "VecFileSink: error reading from %s\n", path.data()); exit(1); } fclose(fp); } /* use when initialized with default constructor in order to reserve heap space * for an empty vector and store the file name to which the vector will be written * upon destruction */ void init_file(std::string path, size_t s) { fname = path; this->resize(s); } protected: std::string fname; }; /* use this when you want allow the underlying file to reflect * any changes made to its data */ template<typename T> class VecFileSinkShared : public VecFileSink<T> { public: VecFileSinkShared() = default; VecFileSinkShared(std::string s) : VecFileSink<T>(s) {}; /* writes data to file before exiting */ ~VecFileSinkShared() { if (this->fname == "") { fprintf(stderr, "no file specified. Data will not be saved to disk\n"); } else { FILE* fp = fopen(this->fname.data(), "wb"); if (fwrite(&(this->data())[0], sizeof(T), this->size(), fp) != this->size()) { die_("unable to write data"); } fclose(fp); } } }; template<typename T> using VecFileSinkPrivate = VecFileSink<T>; #endif
067c16187fe7c8aa6627833577a27f222fe3e7f1
375d8de06b741495f4504ec3d7f52e59e93ad387
/PacMan/include/Application.h
191466b72ced2c459b200334257861734f3bd2ce
[]
no_license
Victor01Avalos/Graficacion-6o-trimestre-
88ca5c39c1f02f7dbef915dba015b8ca78e92db7
c76096c6de26038b9d6856025d802ed7f1e031c5
refs/heads/master
2021-01-21T22:01:41.454231
2017-06-22T23:08:16
2017-06-22T23:08:16
95,148,580
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
h
Application.h
#pragma once #include <iostream> #include "Object3D.h" #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "glm/vec4.hpp" #include "glm/vec3.hpp" #include "GLFW\glfw3.h" #define MapaX 20 #define MapaY 15 class Application { public: Application(); ~Application(); void update(); void setup(); void Display2(); void display(); void collisionWall(); void keyboard(int key, int scancode, int action, int mods); void rotatePlayer(float angle); void mouseButtonX(int button, int action, int mods); void mousePos(int x, int y); bool editor; glm::vec2 screen; private: Object3D triangle; float angle; bool walkW, walkS, Left, Right, movePlayer; int mouseX, mouseY; //para tener el Id de la variable time de los shaders GLuint timeId, transformationId; glm::mat4 rotationX; glm::mat4 rotationY; glm::mat4 rotationZ; glm::mat4 transform; glm::vec3 eye, Eye2; glm::vec3 target, Target2; glm::vec3 up; glm::vec3 movmnt; glm::mat4 lookAt; glm::mat4 perspective; glm::mat4 ortho; glm::mat4 newPos; int mapa[MapaX][MapaY] = { }; };
298b0e8f4a15401967640b1007d5c6937d664d87
95e1371c84994d12c5c82a2741ee30d707f39573
/tutor/HtmlPageWidget.cpp
d3e7b7268cc935fc030f8f1309b8b4826bc95505
[]
no_license
dkuzminov/flashback_fork
790774a95b24926094926630d1f9fd57b19e0dc7
64b01858a668cde7c97ae63a6942d939bb3883cd
refs/heads/master
2021-01-18T03:10:10.037515
2017-07-31T06:27:12
2017-07-31T06:27:12
84,269,588
0
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
HtmlPageWidget.cpp
#include <QtWebKit> #include <QtWebKitWidgets> #include <QtWidgets> #include "HtmlPageWidget.h" HtmlPageWidget::HtmlPageWidget(guimodel::IStep &step, QWidget *parent) : QWidget(parent), m_step(step) { setupUi(this); step.GetPageController().MasterWebControl(*webView); buttonsGroupWidget->setVisible(false); } void HtmlPageWidget::Invalidate() { m_step.GetPageController().MasterWebControl(*webView); }
950377853371924202c2b4f5ad93a823b47de3f7
4d14eacf69f9f43b106ac6acc4968cf86c1447ed
/C++ Ess/Chapter 1/Lab 1.3/lab 1.3.1.cpp
85bfb7c7646dc43371fc50758c1d295e4eb46f7e
[]
no_license
lizakrishen/Practice-2017-2018
9baf77ffee4dd3b6880fdb41ce3c21cfe1d4087c
4e25ea817f800f4c72f867e35398e7326676b549
refs/heads/master
2021-08-31T00:22:03.162679
2017-12-20T00:17:33
2017-12-20T00:17:33
111,195,992
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
lab 1.3.1.cpp
#include <iostream>//we included iostream #include <iomanip>//we included iomanip #include <string>//we included string int main() { int v=10800; // 3*60*60 int zzz=3*60;// This is a variable to hold the value of 3 minutes in seconds int zz=5*60; float siii=3.141526; //This is the value of pi return 0; }
8fa7e1ce1eb607e002b59127d6b463dd6a90e26b
7e95dc3b89a87931cd762973b25b352d42cdcf27
/1.ino
57c0fb539571c694caef48b74a5dfea63a336ed2
[]
no_license
farahnabilatt3b/ModemRF
fcdfb4ad7db1a9f2d554e0a8ee466c127ef4f841
ece1c84afb39d9e562ceb93b94c9c9bfccdd66a8
refs/heads/main
2023-01-30T02:09:07.927672
2020-12-13T15:31:54
2020-12-13T15:31:54
321,096,842
0
0
null
null
null
null
UTF-8
C++
false
false
604
ino
1.ino
#include <LiquidCrystal.h> LiquidCrystal lcd(13, 12, 11, 10, 9,8); int TEMP_SENSOR=A0; void setup () { lcd.begin (20,4); Serial.begin(9600); lcd.setCursor(0,0); lcd.print("wireless Serial"); lcd.setCursor(0,1); lcd.print("Comunnication via 2.4 GHz"); lcd.setCursor(0,2); lcd.print("modem at PNJ....."); } void loop () { int TEMP_SENSOR_ADC_VALUE = analogRead (TEMP_SENSOR); int TEMP_VAL = TEMP_SENSOR_ADC_VALUE/2; lcd.setCursor (0,3); lcd.print ("temp. in 0C:"); lcd.setCursor (13,3); lcd.print (TEMP_VAL); Serial.write (TEMP_VAL); delay (100); }
2cbdc26bcf097179aa9a4290788dd76d4af1854a
819f46d38d0d68381c6ec051aea430be9c65e0f7
/mainwindow.cpp
cc818a1e7dabb4aeda53cc4fccab4e9b6f0ec047
[]
no_license
evovch/LMD_processor
f2a745df49c12bd967c7b32377f0c6968038c403
72941ee96412c87dc856b4cf5759b849b1d1d8ec
refs/heads/master
2021-01-10T23:33:36.199981
2018-04-06T11:12:08
2018-04-06T11:12:08
70,593,528
0
0
null
null
null
null
UTF-8
C++
false
false
9,961
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QString> #include <QFileDialog> #include "cls_LmdFile.h" #include <fstream> #include <iostream> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); std::string readString; std::ifstream inputFile("/tmp/LMD_processor.txt"); if (!inputFile.is_open()) return; // ------------------------------------------------------------------- getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_2->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_7->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_4->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_5->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_3->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_6->setText(QString::fromStdString(readString.substr(4))); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } ui->lineEdit_8->setText(QString::fromStdString(readString.substr(4))); // ------------------------------------------------------------------- getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fInputFolderPath = readString.substr(4); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fPedestalsFolderPath = readString.substr(4); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fPixelMapFolderPath = readString.substr(4); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fEffCalFolderPath = readString.substr(4); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fGraphsFolderPath = readString.substr(4); getline(inputFile, readString); if (inputFile.eof() || readString.length()<4) { return; } this->fOutputFolderPath = readString.substr(4); } MainWindow::~MainWindow() { QString inputFilename = ui->lineEdit->text(); QString pedestalFilename = ui->lineEdit_2->text(); QString pixelMapFilename = ui->lineEdit_7->text(); QString effCalibFilename = ui->lineEdit_4->text(); QString graphsFilename = ui->lineEdit_5->text(); QString outputFilename = ui->lineEdit_3->text(); QString outTreeFilename = ui->lineEdit_6->text(); QString outCrossTalkFilename = ui->lineEdit_8->text(); std::ofstream outputFile("/tmp/LMD_processor.txt"); outputFile << "IN: " << inputFilename.toStdString() << std::endl; outputFile << "PED:" << pedestalFilename.toStdString() << std::endl; outputFile << "PXM:" << pixelMapFilename.toStdString() << std::endl; outputFile << "EFF:" << effCalibFilename.toStdString() << std::endl; outputFile << "GRA:" << graphsFilename.toStdString() << std::endl; outputFile << "OUT:" << outputFilename.toStdString() << std::endl; outputFile << "OTR:" << outTreeFilename.toStdString() << std::endl; outputFile << "OCT:" << outCrossTalkFilename.toStdString() << std::endl; std::string tmpStr; size_t lastSlashPos; tmpStr = inputFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fInputFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "INP:" << fInputFolderPath << std::endl; tmpStr = pedestalFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fPedestalsFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "PDP:" << fPedestalsFolderPath << std::endl; tmpStr = pedestalFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fPedestalsFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "PMP:" << fPixelMapFolderPath << std::endl; tmpStr = effCalibFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fEffCalFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "EFP:" << fEffCalFolderPath << std::endl; tmpStr = graphsFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fGraphsFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "GRP:" << fGraphsFolderPath << std::endl; tmpStr = outputFilename.toStdString(); lastSlashPos = tmpStr.rfind("/"); fOutputFolderPath = tmpStr.substr(0, lastSlashPos+1); outputFile << "OUP:" << fOutputFolderPath << std::endl; outputFile.close(); delete ui; } void MainWindow::ImportFile(void) { //TODO check ui->label->setText("Importing..."); ui->label->update(); QString v_filename = ui->lineEdit->text(); QString v_pedFilename = ui->lineEdit_2->text(); QString v_pixelMapFilename = ui->lineEdit_7->text(); QString v_effCalibFilename = ui->lineEdit_4->text(); QString v_graphsFilename = ui->lineEdit_5->text(); cls_LmdFile* v_inputFile = new cls_LmdFile(); v_inputFile->SetOutputHistoFile(ui->lineEdit_3->text()); v_inputFile->SetOutputTreeFile(ui->lineEdit_6->text()); v_inputFile->SetOutputCrossTalkFile(ui->lineEdit_8->text()); v_inputFile->ImportPedestals(v_pedFilename); v_inputFile->ImportPixelMap(v_pixelMapFilename); //v_inputFile->ImportEffCalib(v_effCalibFilename); //v_inputFile->ImportGraphsFile(v_graphsFilename); if (ui->checkBox->isChecked()) v_inputFile->SetShowHistograms(kTRUE); else v_inputFile->SetShowHistograms(kFALSE); if (ui->checkBox->isChecked()) v_inputFile->SetShowHistograms(kTRUE); else v_inputFile->SetShowHistograms(kFALSE); v_inputFile->StartProcessing(v_filename); delete v_inputFile; ui->label->setText("Finished analysis."); } // ======================================================================================== // Input // ======================================================================================== void MainWindow::SelectDataFile(void) { QFileDialog v_dial; v_dial.setFileMode(QFileDialog::ExistingFile); v_dial.setNameFilter(tr("Data files (*.lmd)")); v_dial.setDirectory(QString::fromStdString(fInputFolderPath)); QStringList v_fileNames; if (v_dial.exec()) { v_fileNames = v_dial.selectedFiles(); ui->lineEdit->setText(v_fileNames.at(0)); } } void MainWindow::SelectPedestalsFile(void) { QFileDialog v_dial; v_dial.setFileMode(QFileDialog::ExistingFile); v_dial.setNameFilter(tr("Pedestal files (*.dat)")); v_dial.setDirectory(QString::fromStdString(fPedestalsFolderPath)); QStringList v_fileNames; if (v_dial.exec()) { v_fileNames = v_dial.selectedFiles(); ui->lineEdit_2->setText(v_fileNames.at(0)); } } void MainWindow::SelectPixelMapFile(void) { QFileDialog v_dial; v_dial.setFileMode(QFileDialog::ExistingFile); v_dial.setNameFilter(tr("Pixel map files (*.txt)")); v_dial.setDirectory(QString::fromStdString(fPixelMapFolderPath)); QStringList v_fileNames; if (v_dial.exec()) { v_fileNames = v_dial.selectedFiles(); ui->lineEdit_7->setText(v_fileNames.at(0)); } } void MainWindow::SelectEffCalibFile(void) { QFileDialog v_dial; v_dial.setFileMode(QFileDialog::ExistingFile); v_dial.setNameFilter(tr("Calibration files (*.par)")); v_dial.setDirectory("~"); QStringList v_fileNames; if (v_dial.exec()) { v_fileNames = v_dial.selectedFiles(); ui->lineEdit_4->setText(v_fileNames.at(0)); } } void MainWindow::SelectGraphsFile(void) { QFileDialog v_dial; v_dial.setFileMode(QFileDialog::ExistingFile); v_dial.setNameFilter(tr("Graphs files (*.root)")); v_dial.setDirectory("~"); QStringList v_fileNames; if (v_dial.exec()) { v_fileNames = v_dial.selectedFiles(); ui->lineEdit_5->setText(v_fileNames.at(0)); } } // ======================================================================================== // Output // ======================================================================================== void MainWindow::SelectOutputFile(void) { std::string generatedFilename = this->fOutputFolderPath + "analysis.root"; QString v_fileName = QFileDialog::getSaveFileName(this, tr("Save analysis file"), QString::fromStdString(generatedFilename), tr("Root files (*.root)")); ui->lineEdit_3->setText(v_fileName); } void MainWindow::SelectTreeFile(void) { std::string generatedFilename = this->fOutputFolderPath + "tree.root"; QString v_fileName = QFileDialog::getSaveFileName(this, tr("Save tree file"), QString::fromStdString(generatedFilename), tr("Root files (*.root)")); ui->lineEdit_6->setText(v_fileName); } void MainWindow::SelectCrossTalkFile(void) { std::string generatedFilename = this->fOutputFolderPath + "crosstalk.root"; QString v_fileName = QFileDialog::getSaveFileName(this, tr("Save cross-talk analysis file"), QString::fromStdString(generatedFilename), tr("Root files (*.root)")); ui->lineEdit_8->setText(v_fileName); }
63e399544048027cb127927df1dc6e2b6d7d5c84
e4acfc74af19f692dd3e12220e6fab951a199b64
/components/uxvcos_interface/src/EthernetSensor.h
6ea83a9b1696c518f3097973940fc0118ee03fd5
[]
no_license
tu-darmstadt-ros-pkg/uxvcos
222b1d4c84966a04cb9862e7055a612f151c6109
ac57278f57dc8060950b86a1ab188ff35acdb3cd
refs/heads/master
2021-01-23T08:39:30.890385
2013-08-01T17:37:37
2013-08-01T17:37:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,819
h
EthernetSensor.h
//================================================================================================= // Copyright (c) 2013, Johannes Meyer and contributors, Technische Universitat Darmstadt // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Flight Systems and Automatic Control group, // TU Darmstadt, nor the names of its contributors may be used to // endorse or promote products derived from this software without // specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //================================================================================================= #ifndef INTERFACE_ETHERNETSENSOR_H #define INTERFACE_ETHERNETSENSOR_H #include "EthernetSensorBase.h" #include <uxvcos/data/Key.h> #include <uxvcos/Module.h> namespace uxvcos { namespace Interface { template <typename SensorClass> class EthernetSensor : public SensorClass, public EthernetSensorBase { public: EthernetSensor(Interface::EthernetInterface* owner, const std::string& name = "", const std::string& port_name = "", const std::string& description = "", MessageId messageId = 0, Data::Key key = Data::Key()) : SensorClass(owner, name, port_name, description) , EthernetSensorBase(owner) , messageId(messageId), key(key) { construct(); } EthernetSensor(Interface::EthernetInterface* owner, MessageId messageId = 0, Data::Key key = Data::Key()) : SensorClass(owner) , EthernetSensorBase(owner) , messageId(messageId), key(key) { construct(); } virtual ~EthernetSensor() {} // EthernetSensorPtr sensor() { // return boost::dynamic_pointer_cast<EthernetSensorBase>(this->shared_from_this()); // } virtual bool initialize() { return SensorClass::initialize(); } virtual void cleanup() { SensorClass::cleanup(); } virtual bool decode(void *payload, size_t length, MessageId id); virtual const std::string &getName() const { return this->SensorClass::getName(); } virtual MessageId getMessageId() const { return messageId; } virtual Data::Key getKey() const { return key; } virtual void request(Request &request) const { SET_REQUEST(getMessageId(), request); } virtual std::ostream& operator>>(std::ostream& os) const { return os << *((SensorClass *)this); } virtual RTT::Logger& log() const { return SensorClass::log(); } virtual const typename SensorClass::ValueType& get() const { return SensorClass::get(); } protected: const MessageId messageId; Data::Key key; }; } // namespace Interface } // namespace uxvcos #endif // INTERFACE_ETHERNETSENSOR_H
a1ee450eeb6966a68c6dd8aea81ddbb3efeba1e1
381f12ea221339d585476b9fbadeae9a93a65981
/Game/GameChange.h
981d91312637fbd070b471e0e4ac51c6a7f7e720
[]
no_license
yandongdabin/PlaneGame
7fc6ae517c507530c68b0e11cdbaee20c969c9a2
b58894afa86b5c722eadbb444287583cd6fe61ca
refs/heads/master
2020-12-24T09:52:55.027783
2016-11-09T08:35:23
2016-11-09T08:35:23
73,264,543
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
GameChange.h
#pragma once #include "gameobject.h" #include "Resource.h" class CGameChange : public CGameObject { public: CGameChange(void); ~CGameChange(void); BOOL Draw(CDC* pDC,BOOL bPause); static BOOL LoadImage(); CRect GetRect() { return CRect(m_ptPos,CPoint(m_ptPos.x+CHANGE_WIDTH,m_ptPos.y+CHANGE_HEIGHT)); } void SetPos() { m_ptPos.y += 3; } int GetIndex() { return index; } private: static const int CHANGE_HEIGHT = 29; static const int CHANGE_WIDTH = 43; static CImageList m_Images[4]; int index; };
6db3453231e8ccb181eaf10ba6a3c1d65473213b
10ce753566eb0d524153cb7a596c96e03284d426
/Manager/UserManager.h
7b5b54edc61fa6f3e6ffac84f208a45055145ad8
[]
no_license
JLUCProject2020/cproject2020-group-7
3b715659115b960358b3ab6b16d2fc551ce1faf8
b6fb4844c6ca86ed34d5e25eb6f1f8076e49789b
refs/heads/master
2022-12-14T20:31:10.252132
2020-09-09T15:02:08
2020-09-09T15:05:17
293,831,315
0
0
null
null
null
null
GB18030
C++
false
false
1,032
h
UserManager.h
#pragma once #include "UserAdd.h" #include "UserEdit.h" #include "UserDel.h" #include "UserStatusAdd.h" #include "UserStatusEdit.h" #include "UserStatusDel.h" #include "afxcmn.h" // CUserManager 对话框 class CUserManager : public CDialogEx { DECLARE_DYNAMIC(CUserManager) public: CUserManager(CWnd* pParent = NULL); // 标准构造函数 virtual ~CUserManager(); // 对话框数据 enum { IDD = IDD_MANAGER }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CUserAdd m_UserAddDlg; CUserEdit m_UserEditDlg; CUserDel m_UserDelDlg; CUserStatusAdd m_UserStatusDlg; CUserStatusEdit m_UserStatusEditDlg; CUserStatusDel m_UserStatusDelDlg; afx_msg void OnBnClickedAdd(); afx_msg void OnBnClickedEdit(); afx_msg void OnBnClickedDel(); virtual BOOL OnInitDialog(); CListCtrl m_UserList; CListCtrl m_UserStatusList; afx_msg void OnBnClickedUserStatusAdd(); afx_msg void OnBnClickedUserStatusEdit(); afx_msg void OnBnClickedUserStatusDel(); };
e78882e3ab67d8f89f46df2ad124173b57cdc0d9
4d839f73c42ac060733c7ef44c7e6951ef8a14bf
/Source/Main/ImageConversion.cpp
d293e23d7ed379e639b1b53ccd1eb50d95ff856c
[]
no_license
ZacWalk/ImageWalker
8252aa6d39bde8d04bb00560082f296619168e98
5b7a61a4961054c4a61f9e04e10dc18161b608f4
refs/heads/master
2021-01-21T21:42:37.209350
2018-06-05T15:59:24
2018-06-05T15:59:24
3,126,103
4
1
null
null
null
null
MacCentralEurope
C++
false
false
19,810
cpp
ImageConversion.cpp
/////////////////////////////////////////////////////////////////////// // // This file is part of the ImageWalker code base. // For more information on ImageWalker see www.ImageWalker.com // // Copyright (C) 1998-2001 Zac Walker. All rights reserved. // /////////////////////////////////////////////////////////////////////// // // IW::Image : implementation file // // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" extern DWORD masks1[]; extern int masks2[]; extern int shift2[]; void IW::IndexesToRGBA(LPCOLORREF pBitsOut, const int nSize, IW::LPCCOLORREF pPalette) { for(int x = 0; x < nSize; x++) { pBitsOut[x] = pPalette[pBitsOut[x]] | 0xFF000000; } } void IW::SumLineTo32(LPBYTE pLine, const IW::RGBSUM *ps, int cx) { int denom, r; for(int i = 0; i < cx; i++) { // blend with white denom = ps->c; if (denom > 1) { r = denom >> 1; pLine[0] = (r + ps->r) / denom; pLine[1] = (r + ps->g) / denom; pLine[2] = (r + ps->b) / denom; pLine[3] = (r + ps->a) / (ps->ac ? ps->ac : 1); } else { pLine[0] = ps->r; pLine[1] = ps->g; pLine[2] = ps->b; pLine[3] = ps->a / (ps->ac ? ps->ac : 1); } ++ps; pLine += 4; } } void IW::SumLineTo16(LPBYTE pLine, const IW::RGBSUM *ps, int cx) { assert(((int)pLine & 0x03) == 0); // Should be aligned to align?? int cx2 = cx & 0xfffffffe; int denom, denom2; const IW::RGBSUM *ps2; LPBYTE pLineEnd = pLine + (cx * 2); while(pLine < (pLineEnd - 2)) { // blend with white denom = IW::Max(ps->c, 1u); ps2 = ps + 1; denom2 = IW::Max(ps2->c, 1u); *((int*)pLine) = (((ps->r / denom) >> 3) & 0x0000001F) | (((ps->g / denom) << 2) & 0x000003E0) | (((ps->b / denom) << 7) & 0x00007C00) | (((ps2->r / denom2) << 13) & 0x001F0000) | (((ps2->g / denom2) << 18) & 0x03E00000) | (((ps2->b / denom2) << 23) & 0x7C000000); ps += 2; pLine += 4; } // May be a last one!! while(pLine < pLineEnd) { denom = IW::Max(ps->c, 1u); *((short*)pLine) = (((ps->r / denom) >> (3)) & 0x0000001F) | (((ps->g / denom) << (2)) & 0x000003E0) | (((ps->b / denom) << (7)) & 0x00007C00); ps++; pLine += 2; } } void IW::ToSums(IW::LPRGBSUM pSum, LPDWORD pLineIn, int cxOut, int cxIn, bool isHighQuality, bool bFirstY) { int x = (cxOut >> 1) + cxIn; IW::LPCRGBSUM pSumEnd = pSum + cxOut; IW::LPCDWORD pLineEnd = pLineIn + cxIn; DWORD c, a; if (isHighQuality) { while(pLineIn < pLineEnd) { assert(pSum < pSumEnd); // Check for out buffer overflow c = *pLineIn++; a = IW::GetA(c); if (a) { pSum->r += IW::GetR(c); pSum->g += IW::GetG(c); pSum->b += IW::GetB(c); pSum->c++; pSum->a += a; } pSum->ac++; x -= cxOut; if (x < cxOut) { pSum++; x += cxIn; } } } else { if (bFirstY) { while(pLineIn < pLineEnd) { assert(pSum < pSumEnd); // Check for out buffer overflow c = *pLineIn++; pSum->r += IW::GetR(c); pSum->g += IW::GetG(c); pSum->b += IW::GetB(c); pSum->c++; x -= cxOut; if (x < cxOut) { pSum++; x += cxIn; } } } else { for(int i = 0; i < cxOut; i++) { int xx = (i * cxIn) / cxOut; assert(xx < cxIn); c = pLineIn[xx]; pSum->r += IW::GetR(c); pSum->g += IW::GetG(c); pSum->b += IW::GetB(c); pSum->c++; pSum++; } } } } void IW::Convert1to32(LPCOLORREF pBitsOut, LPCBYTE pBitsInIn, const int nStart, const int nSize) { const int nSizeWithStart = nSize + nStart; IW::LPCDWORD pBitsIn = (IW::LPCDWORD)pBitsInIn; DWORD c = pBitsIn[nStart >> 5]; int xn; for(int xx = nStart; xx < nSizeWithStart; xx++) { xn = xx & 31; if (xn == 0) { c = pBitsIn[xx >> 5]; } *pBitsOut++ = (c & masks1[xn]) ? 1 : 0; } } void IW::Convert1to32(LPCOLORREF pBitsOut, LPCBYTE pBitsInIn, const int nStart, const int nSize, IW::LPCCOLORREF pPalette) { IW::Convert1to32(pBitsOut, pBitsInIn, nStart, nSize); IW::IndexesToRGBA(pBitsOut, nSize, pPalette); } void IW::Convert2to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize) { const int nSizeWithStart = nSize + nStart; for(int xx = nStart; xx < nSizeWithStart; xx++) { BYTE b = (pBitsIn[xx >> 2] & masks2[xx & 2]) >> shift2[xx & 2]; *pBitsOut++ = b; } } void IW::Convert2to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize, IW::LPCCOLORREF pPalette) { IW::Convert2to32(pBitsOut, pBitsIn, nStart, nSize); IW::IndexesToRGBA(pBitsOut, nSize, pPalette); } void IW::Convert4to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize) { const int nSizeWithStart = nSize + nStart; int c; for(int xx = nStart; xx < nSizeWithStart; xx++) { c = (xx & 1) ? pBitsIn[xx >> 1] & 0x0f : pBitsIn[xx >> 1] >> 4; *pBitsOut++ = c; } } void IW::Convert4to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize, IW::LPCCOLORREF pPalette) { IW::Convert4to32(pBitsOut, pBitsIn, nStart, nSize); IW::IndexesToRGBA(pBitsOut, nSize, pPalette); } void IW::Convert8to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize) { const int nSizeWithStart = nSize + nStart; pBitsIn += nStart; for(int n = nStart; n < nSizeWithStart; n++) { *pBitsOut++ = *pBitsIn++; } } void IW::Convert8to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize, IW::LPCCOLORREF pPalette) { IW::Convert8to32(pBitsOut, pBitsIn, nStart, nSize); IW::IndexesToRGBA(pBitsOut, nSize, pPalette); } void IW::Convert8Alphato32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize, IW::LPCCOLORREF pPalette) { const int nSizeWithStart = nSize + nStart; pBitsIn += nStart; for(int n = nStart; n < nSizeWithStart; n++) { *pBitsOut++ = pPalette[*pBitsIn++]; } } void IW::Convert8GrayScaleto32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize) { int c; const int nSizeWithStart = nSize + nStart; pBitsIn += nStart; for(int n = nStart; n < nSizeWithStart; n++) { c = *pBitsIn++; *pBitsOut++ = RGB(c,c,c); } } void IW::Convert555to32(LPCOLORREF pBitsOut, LPCBYTE pBitsInIn, const int nStart, const int nSize) { // Get a pointer to the end const COLORREF *pBitsOutEnd = pBitsOut + nSize; LPDWORD pBitsIn = (LPDWORD)(pBitsInIn + (nStart*2)); DWORD c; while(pBitsOut < pBitsOutEnd) { c = *pBitsIn++; *pBitsOut++ = IW::RGB555to888(c) | 0xFF000000; if (pBitsOut >= pBitsOutEnd) return; c >>= 16; *pBitsOut++ = IW::RGB555to888(c) | 0xFF000000; } } void IW::Convert565to32(LPCOLORREF pBitsOut, LPCBYTE pBitsInIn, const int nStart, const int nSize) { // Get a pointer to the end const COLORREF *pBitsOutEnd = pBitsOut + nSize; LPCBYTE pBitsIn = pBitsInIn + nStart*2; DWORD c; // Move to an alligned bit part of memory while((0 != ((int)pBitsOut & 3)) && (pBitsOut < pBitsOutEnd)) { c = *reinterpret_cast<const unsigned short*>(pBitsIn); *pBitsOut++ = IW::RGB565to888(c) | 0xFF000000; pBitsIn += 2; } while(pBitsOut < pBitsOutEnd) { c = *((LPDWORD)pBitsIn); *pBitsOut++ = IW::RGB565to888(c) | 0xFF000000; if (pBitsOut >= pBitsOutEnd) return; c >>= 16; *pBitsOut++ = IW::RGB565to888(c) | 0xFF000000; pBitsIn += 4; } } void IW::Convert24to32(LPCOLORREF pBitsOut, LPCBYTE pBitsIn, const int nStart, const int nSize) { // Get a pointer to the end const COLORREF *pBitsOutEnd = pBitsOut + nSize; // Find start location if (nStart) pBitsIn += 3 * nStart; // Move to an aligned bit part of memory LPBYTE pOut = (LPBYTE)pBitsOut; // Align to 8 byte boundry while((0 != ((int)pBitsIn & 3)) && (pOut < (LPCBYTE)pBitsOutEnd)) { *pOut++ = *pBitsIn++; *pOut++ = *pBitsIn++; *pOut++ = *pBitsIn++; *pOut++ = (BYTE)0xff; } pBitsOut = (LPDWORD)pOut; if (IW::HasMMX() && pBitsOut < (pBitsOutEnd - 8)) { // MMX Version // // The theory here is use the 64 bit MMX registers // to suck in 24 bit pixels; I can then use a series // of rotations masks and re-packing to push out // 32 bit pixels. // // I donít really understand how to optimize this for // pairing but my plan is to try not to use the same // registers next to each other, I am interested if // anyone has some opinions on this? __int64 mask0=0x0ff000000ff000000; __int64 mask1=0x00000ffffffff0000; _asm { mov edx, pBitsOutEnd sub edx, 32 mov edi, pOut mov esi, pBitsIn movq mm7, mask0 movq mm6, mask1 TheLoop: movq mm0, [esi] // Pixel 1 movq mm1, mm0 PSRLQ mm1, 24 // Pixel 2 movq mm2, [esi + 8] movq mm3, mm2 PSRLQ mm3, 8 // Pixel 4 PSLLQ mm2, 16 PAND mm2, mm6 movq mm4, mm0 PSRLQ mm4, 48 POR mm2, mm4 // Pixel 3 punpckldq mm0, mm1 punpckldq mm2, mm3 POR mm0, mm7 POR mm2, mm7 movq [edi], mm0 // Write pixels 1 and 2 movq [edi + 8], mm2 // Write pixels 3 and 4 movq mm0, mm3 PSRLQ mm0, 24 // Pixel 5 PSRLQ mm3, 48 // Pixel 6 movq mm1, [esi + 16] movq mm2, mm1 PSLLQ mm1, 8 por mm1, mm3 movq mm2, [esi + 16] PSRLQ mm2, 16 // Pixel 7 movq mm3, mm2 PSRLQ mm3, 24 // Pixel 8 punpckldq mm0, mm1 punpckldq mm2, mm3 POR mm0, mm7 POR mm2, mm7 movq [edi + 16], mm0 // Write pixels 5 and 6 movq [edi + 24], mm2 // Write pixels 7 and 8 add esi, 24 // Increment source pointer add edi, 32 // Increment destination pointer cmp edi, edx jl TheLoop mov pOut, edi mov pBitsIn, esi EMMS } } else { // Continue processing UINT nPixel1, nPixel2; IW::LPCDWORD pIn = (IW::LPCDWORD)pBitsIn; const COLORREF *pBitsOutEnd2 = pBitsOutEnd - 4; while(pBitsOut < pBitsOutEnd2) { // DWORD 1 nPixel1 = *pIn++; // pixel 1 *pBitsOut++ = (nPixel1 & 0x00ffffff) | 0xff000000; // pixel 2 nPixel2 = (nPixel1 >> 24) & 0xff; // DWORD 2 nPixel1 = *pIn++; nPixel2 |= (nPixel1 << 8) & 0x00ffff00; *pBitsOut++ = nPixel2 | 0xff000000; // pixel 3 nPixel2 = (nPixel1 >> 16) & 0x0000ffff; // DWORD 3 nPixel1 = *pIn++; nPixel2 |= (nPixel1 << 16) & 0x00ff0000; *pBitsOut++ = nPixel2 | 0xff000000; // pixel 4 *pBitsOut++ = (nPixel1 >> 8) | 0xff000000; } pBitsIn = (LPCBYTE)pIn; pOut = (LPBYTE)pBitsOut; } // Complete any incomplete work while(pOut < (LPCBYTE)pBitsOutEnd) { *pOut++ = *pBitsIn++; *pOut++ = *pBitsIn++; *pOut++ = *pBitsIn++; *pOut++ = (BYTE)0xff; } } //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// void IW::ConvertARGBtoABGR(LPBYTE pBitsOutX, LPCBYTE pBitsInX, const int nSize) { LPDWORD pBitsIn = (LPDWORD)pBitsInX; LPDWORD pBitsOut = (LPDWORD)pBitsOutX; const LPDWORD pBitsOutEnd = pBitsOut + nSize; while(pBitsOut< pBitsOutEnd) { *pBitsOut++ = SwapRB(*pBitsIn++); } } void IW::ConvertRGBtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { const LPBYTE pBitsOutEnd = pBitsOut + (nSize * 3); BYTE r,g,b; while(pBitsOut< pBitsOutEnd) { r = *pBitsIn++; g = *pBitsIn++; b = *pBitsIn++; *pBitsOut++ = b; *pBitsOut++ = g; *pBitsOut++ = r; } } void IW::ConvertYCbCrtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { } void IW::ConvertCMYKtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { int xIn = 0; int xOut = 0; int C, M, Y, K; for(int i = 0; i < nSize; i++) { C = pBitsIn[xIn + 0]; M = pBitsIn[xIn + 1]; Y = pBitsIn[xIn + 2]; K = pBitsIn[xIn + 3]; pBitsOut[xOut + 0] = IW::ByteClamp(255 - (Y + K)); pBitsOut[xOut + 1] = IW::ByteClamp(255 - (M + K)); pBitsOut[xOut + 2] = IW::ByteClamp(255 - (C + K)); xIn += 4; xOut += 3; } } void IW::ConvertYCCKtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { } void IW::ConvertCIELABtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { int x = 0; int R, G, B; int L, a, b; for(int i = 0; i < nSize; i++) { L = pBitsIn[x + 2]; a = pBitsIn[x + 1]; b = pBitsIn[x + 0]; IW::LABtoRGB(L, a, b, R, G, B); pBitsOut[x + 0] = R; pBitsOut[x + 1] = G; pBitsOut[x + 2] = B; x += 3; } } void IW::ConvertICCLABtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { IW::ConvertCIELABtoBGR(pBitsOut, pBitsIn, nSize); } void IW::ConvertITULABtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { IW::ConvertCIELABtoBGR(pBitsOut, pBitsIn, nSize); } void IW::ConvertLOGLtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { } void IW::ConvertLOGLUVtoBGR(LPBYTE pBitsOut, LPCBYTE pBitsIn, const int nSize) { } //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// void IW::RGBtoHSL(int R, int G, int B, int &H, int &S, int &L) { const int HSLMAX = 255; /* H,L, and S vary over 0-HSLMAX */ const int RGBMAX = 255; /* R,G, and B vary over 0-RGBMAX */ /* HSLMAX BEST IF DIVISIBLE BY 6 */ /* RGBMAX, HSLMAX must each fit in a BYTE. */ /* Hue is undefined if Saturation is 0 (grey-scale) */ /* This value determines where the Hue scrollbar is */ /* initially set for achromatic colors */ const int UNDEFINED = (HSLMAX*2/3); WORD Rdelta,Gdelta,Bdelta; /* intermediate value: % of spread from max*/ const BYTE cMax = IW::Max( IW::Max(R,G), B); /* calculate lightness */ const BYTE cMin = IW::Min( IW::Min(R,G), B); L = (BYTE)((((cMax+cMin)*HSLMAX)+RGBMAX)/(2*RGBMAX)); if (cMax==cMin) /* r=g=b --> achromatic case */ { S = 0; /* saturation */ H = UNDEFINED; /* hue */ } else { /* chromatic case */ if (L <= (HSLMAX/2)) /* saturation */ S = (BYTE)((((cMax-cMin)*HSLMAX)+((cMax+cMin)/2))/(cMax+cMin)); else S = (BYTE)((((cMax-cMin)*HSLMAX)+((2*RGBMAX-cMax-cMin)/2))/(2*RGBMAX-cMax-cMin)); /* hue */ Rdelta = (WORD)((((cMax-R)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); Gdelta = (WORD)((((cMax-G)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); Bdelta = (WORD)((((cMax-B)*(HSLMAX/6)) + ((cMax-cMin)/2) ) / (cMax-cMin)); if (R == cMax) H = (BYTE)(Bdelta - Gdelta); else if (G == cMax) H = (BYTE)((HSLMAX/3) + Rdelta - Bdelta); else /* B == cMax */ H = (BYTE)(((2*HSLMAX)/3) + Gdelta - Rdelta); if (H < 0) H += HSLMAX; if (H > HSLMAX) H -= HSLMAX; } return; } //////////////////////////////////////////////////////////////////////////////// static float HueToRGB(float n1,float n2, float hue) { //<F. Livraghi> fixed implementation for HSL2RGB routine float rValue; if (hue > 360) hue = hue - 360; else if (hue < 0) hue = hue + 360; if (hue < 60) rValue = n1 + (n2-n1)*hue/60.0f; else if (hue < 180) rValue = n2; else if (hue < 240) rValue = n1+(n2-n1)*(240-hue)/60; else rValue = n1; return rValue; } //////////////////////////////////////////////////////////////////////////////// void IW::HSLtoRGB(int H, int S, int L, int &r, int &g, int &b) { //<F. Livraghi> fixed implementation for HSL2RGB routine const float h = (float)H * 360.0f/255.0f; const float s = (float)S/255.0f; const float l = (float)L/255.0f; const float m2 = (l <= 0.5) ? l * (1+s) : l + s - l*s; const float m1 = 2 * l - m2; if (s == 0) { r=g=b=(BYTE)(l*255.0f); } else { r = (int)(HueToRGB(m1,m2,h+120) * 255.0f); g = (int)(HueToRGB(m1,m2,h) * 255.0f); b = (int)(HueToRGB(m1,m2,h-120) * 255.0f); } return; } void IW::RGBtoLAB(int R, int G, int B, int &L, int &a, int &b) { // Convert between RGB and CIE-Lab color spaces // Uses ITU-R recommendation BT.709 with D65 as reference white. // algorithm contributed by "Mark A. Ruzon" <ruzon@CS.Stanford.EDU> double fX, fY, fZ; double X = 0.412453*R + 0.357580*G + 0.180423*B; double Y = 0.212671*R + 0.715160*G + 0.072169*B; double Z = 0.019334*R + 0.119193*G + 0.950227*B; X /= (255 * 0.950456); Y /= 255; Z /= (255 * 1.088754); if (Y > 0.008856) { fY = pow(Y, 1.0/3.0); L = static_cast<int>(116.0*fY - 16.0 + 0.5); } else { fY = 7.787*Y + 16.0/116.0; L = static_cast<int>(903.3*Y + 0.5); } if (X > 0.008856) fX = pow(X, 1.0/3.0); else fX = 7.787*X + 16.0/116.0; if (Z > 0.008856) fZ = pow(Z, 1.0/3.0); else fZ = 7.787*Z + 16.0/116.0; a = static_cast<int>(500.0*(fX - fY) + 0.5); b = static_cast<int>(200.0*(fY - fZ) + 0.5); } void IW::LABtoRGB(int L, int a, int b, int &R, int &G, int &B) { // Convert between RGB and CIE-Lab color spaces // Uses ITU-R recommendation BT.709 with D65 as reference white. // algorithm contributed by "Mark A. Ruzon" <ruzon@CS.Stanford.EDU> double X, Y, Z; double fY = pow((L + 16.0) / 116.0, 3.0); if (fY < 0.008856) fY = L / 903.3; Y = fY; if (fY > 0.008856) fY = pow(fY, 1.0/3.0); else fY = 7.787 * fY + 16.0/116.0; double fX = a / 500.0 + fY; if (fX > 0.206893) X = pow(fX, 3.0); else X = (fX - 16.0/116.0) / 7.787; double fZ = fY - b /200.0; if (fZ > 0.206893) Z = pow(fZ, 3.0); else Z = (fZ - 16.0/116.0) / 7.787; X *= (0.950456 * 255); Y *= 255; Z *= (1.088754 * 255); int RR = static_cast<int>(3.240479*X - 1.537150*Y - 0.498535*Z + 0.5); int GG = static_cast<int>(-0.969256*X + 1.875992*Y + 0.041556*Z + 0.5); int BB = static_cast<int>(0.055648*X - 0.204043*Y + 1.057311*Z + 0.5); R = RR < 0 ? 0 : RR > 255 ? 255 : RR; G = GG < 0 ? 0 : GG > 255 ? 255 : GG; B = BB < 0 ? 0 : BB > 255 ? 255 : BB; }
448cda3e6474bc2e195a16d6238c0ea43e10b118
3188d2b4e8e9869c80819e8a3d99ebace8adfd06
/(July)30_Days_Challenge/BestTimetoBuyandSellStockwithCooldown.cpp
1afd1ed997c618ab77582e1ac2abb4eeae91326f
[]
no_license
Divyalok123/LeetCode_Practice
78ce9ba0deb8719b71111e17ae65422d76d2a306
2ac1dd229e7154e5ddddb0c72b9bfbb9c897d825
refs/heads/master
2023-06-30T08:55:33.369349
2021-08-01T06:17:06
2021-08-01T06:17:06
256,864,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
BestTimetoBuyandSellStockwithCooldown.cpp
/* Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) */ #include <iostream> #include <vector> #include <algorithm> using namespace std; static int x = []() { ios_base::sync_with_stdio(false); cin.tie(0); return 0; }(); class Solution { public: int maxProfit(vector<int> &prices) { int n = prices.size(); int hold = INT_MIN, sell = 0, cool = 0; for (int i = 0; i < n; i++) { hold = max(hold, cool - prices[i]); cool = sell; sell = max(sell, hold + prices[i]); } return max(cool, sell); } };
35aacc2010e2f7ebf606d634ea22a6dae74744b5
e542522d4bcddbe88a66879a7183a73c1bbdbb17
/Others/Google_competition/Codejam/2021/Round/2/C/solve.cpp
d70964ee1c9cc39a566c9860313078dc869f10c4
[]
no_license
ishank-katiyar/Competitive-programming
1103792f0196284cf24ef3f24bd243d18536f2f6
5240227828d5e94e2587d5d2fd69fa242d9d44ef
refs/heads/master
2023-06-21T17:30:48.855410
2021-08-13T14:51:53
2021-08-13T14:51:53
367,391,580
0
0
null
null
null
null
UTF-8
C++
false
false
8,240
cpp
solve.cpp
#include <bits/stdc++.h> using namespace std; template <typename T> T inverse(T a, T m) { T u = 0, v = 1; while (a != 0) { T t = m / a; m -= t * a; swap(a, m); u -= t * v; swap(u, v); } assert(m == 1); return u; } template <typename T> class Modular { public: using Type = typename decay<decltype(T::value)>::type; constexpr Modular() : value() {} template <typename U> Modular(const U& x) { value = normalize(x); } template <typename U> static Type normalize(const U& x) { Type v; if (-mod() <= x && x < mod()) v = static_cast<Type>(x); else v = static_cast<Type>(x % mod()); if (v < 0) v += mod(); return v; } const Type& operator()() const { return value; } template <typename U> explicit operator U() const { return static_cast<U>(value); } constexpr static Type mod() { return T::value; } Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; } Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; } template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); } template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); } Modular& operator++() { return *this += 1; } Modular& operator--() { return *this -= 1; } Modular operator++(int) { Modular result(*this); *this += 1; return result; } Modular operator--(int) { Modular result(*this); *this -= 1; return result; } Modular operator-() const { return Modular(-value); } template <typename U = T> typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) { #ifdef _WIN32 uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value); uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m; asm( "divl %4; \n\t" : "=a" (d), "=d" (m) : "d" (xh), "a" (xl), "r" (mod()) ); value = m; #else value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value)); #endif return *this; } template <typename U = T> typename enable_if<is_same<typename Modular<U>::Type, int64_t>::value, Modular>::type& operator*=(const Modular& rhs) { int64_t q = static_cast<int64_t>(static_cast<long double>(value) * rhs.value / mod()); value = normalize(value * rhs.value - q * mod()); return *this; } template <typename U = T> typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) { value = normalize(value * rhs.value); return *this; } Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); } template <typename U> friend const Modular<U>& abs(const Modular<U>& v) { return v; } template <typename U> friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs); template <typename U> friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs); template <typename U> friend std::istream& operator>>(std::istream& stream, Modular<U>& number); private: Type value; }; template <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; } template <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); } template <typename T, typename U> bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; } template <typename T> bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); } template <typename T, typename U> bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); } template <typename T, typename U> bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); } template <typename T> bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; } template <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; } template <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; } template <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; } template <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; } template <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; } template <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; } template <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; } template <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; } template <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; } template <typename T> Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; } template <typename T, typename U> Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; } template <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; } template<typename T, typename U> Modular<T> power(const Modular<T>& a, const U& b) { assert(b >= 0); Modular<T> x = a, res = 1; U p = b; while (p > 0) { if (p & 1) res *= x; x *= x; p >>= 1; } return res; } template <typename T> bool IsZero(const Modular<T>& number) { return number() == 0; } template <typename T> string to_string(const Modular<T>& number) { return to_string(number()); } template <typename T> std::ostream& operator<<(std::ostream& stream, const Modular<T>& number) { return stream << number(); } template <typename T> std::istream& operator>>(std::istream& stream, Modular<T>& number) { typename common_type<typename Modular<T>::Type, int64_t>::type x; stream >> x; number.value = Modular<T>::normalize(x); return stream; } /* using ModType = int; struct VarMod { static ModType value; }; ModType VarMod::value; ModType& md = VarMod::value; using Mint = Modular<VarMod>; */ constexpr int md = (int) 1e9 + 7; using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>; int main() { ios_base::sync_with_stdio(0); cin.tie(0); const int maxn = 1e6 + 1; vector<Mint> fact (maxn, 1); for (int i = 2; i < maxn; i++) fact[i] = fact[i - 1] * i; auto ncr = [&] (int n, int r) -> Mint { if (r > n) return 0; return fact[n] / (fact[r] * fact[n - r]); }; int TT; cin >> TT; for (int ttt = 1; ttt <= TT; ttt++) { int n; cin >> n; vector<int> A (n); map <int, vector<int>> mp; for (int i = 0; i < n; i++) { cin >> A[i]; mp[A[i]].push_back (i); } auto ff = [&] (int l, int r, int x) -> int { auto it = upper_bound(mp[x].begin(), mp[x].end(), r); if (it == mp[x].begin()) return -1; it--; if (*it >= l) return *it; return -1; }; function<Mint(int, int, int)> f = [&] (int l, int r, int x) -> Mint { if (l > r) return 1; if (l == r) return A[l] == x; int last = ff (l, r, x); if (last == -1) return 0; Mint ans = 1; ans *= ncr (r - l, last - l); ans *= f (l, last - 1, x); ans *= f (last + 1, r, x + 1); return ans; // int n = a.size(); // if (n == 1) { // return a.front() == 1; // } // int idx = -1; // for (int i = 0; i < n; i++) { // if (a[i] == 1) idx = i; // if (a[i] <= 0 || a[i] > i + 1) return 0; // } // if (idx == -1) { // return 0; // } // Mint ans = 1; // ans *= ncr (n - 1, idx); // vector<int> a1, a2; // for (int i = 0; i < idx; i++) { // a1.push_back(a[i]); // } // for (int i = idx + 1; i < n; i++) { // a2.push_back(a[i] - 1); // } // if (a1.empty() == false) { // ans *= f (a1); // } // if (a2.empty() == false) { // ans *= f (a2); // } // return ans; }; cout << "Case #" << ttt << ": "; cout << f (0, n - 1, 1) << '\n'; } return 0; }
b0d61eb02224829ff756f5f437726b38ee293c9a
ad85d7f9f6e203ab12da9a64b34cb4f19187a202
/trash_codes/Cpp/static/main.cpp
8c457c0794abf0a1828b60d42dbf8794efe95197
[]
no_license
dheeraj-2000/dsalgo
daeb1219c1f902d9a28f0993b191527d7a257c93
2b71317fb372ceefdaaa4310217872abc48c5007
refs/heads/master
2022-11-08T09:42:24.106938
2022-10-31T14:23:03
2022-10-31T14:23:03
212,872,334
94
435
null
2022-12-03T11:18:05
2019-10-04T17:49:40
C++
UTF-8
C++
false
false
176
cpp
main.cpp
#include<iostream> using namespace std; // extern int s_variable; static int s; void dunct(){ } int main(){ // cout<<s_variable<<endl; cin>>s; cout<<s; }
c97ec2a15b6ae96b27c7397ae73507bde3f64afd
3b95023ca6a40060f5ab5520e569c0708a51e409
/list.cpp
529e944d1001ea11eb2376c1c78657cfa1810cd6
[]
no_license
kkubkko/paralelko2
4c19157d3f8e6b170292777b3321946ac1a64941
97fd448f8314960435c90312b42efd6e2a61cc79
refs/heads/master
2021-03-12T22:08:29.471109
2015-06-16T21:52:29
2015-06-16T21:52:29
35,576,542
0
0
null
null
null
null
UTF-8
C++
false
false
4,967
cpp
list.cpp
/* * File: list.cpp * Author: Lukáš Junek * * Created on 8. březen 2014, 22:11 */ #include "list.h" /* * Dokument obsahuje triviální funkce pro obsluhu seznamu vláken, * které nejsou potřeba zvášť komentovat. */ List::List() { m_poc_polozkek = 0; m_first = 0; m_last = 0; m_akt = 0; m_act_pozice = -1; } List::~List() { polozka *pom; while (m_first != 0) { pom = m_first; m_first = m_first->left; delete pom; } } void List::smazVse() { while (!isEmpty()){ smazFirst(); } m_poc_polozkek = 0; m_act_pozice = -1; } void List::pridejNaZacatek(Vlakno* p_vlakno){ polozka *pom = new polozka; pom->vlakno = p_vlakno; pom->left = 0; pom->right = m_first; if (m_first != 0) { m_first->left = pom; } m_first = pom; if (m_last == 0) { m_last = m_first; } m_poc_polozkek++; if (this->akt()) { m_act_pozice++; } } void List::pridejNaKonec(Vlakno* p_vlakno){ polozka *pom = new polozka; if (m_last == 0) { pridejNaZacatek(p_vlakno); } else { pom->vlakno = p_vlakno; pom->left = m_last; pom->right = 0; m_last->right = pom; m_last = pom; m_poc_polozkek++; } } Vlakno* List::vratPosledni(){ if (m_last != 0) { return m_last->vlakno; } else { return 0; } } Vlakno* List::vratPrvni() { if (m_first != 0) { return m_first->vlakno; } else { return 0; } } Vlakno* List::vratAkt() { if (m_akt != 0) { return m_akt->vlakno; } else { return 0; } } polozka* List::vratAktPrv(){ if (m_akt != 0) { return m_akt; } else { return 0; } } void List::nastavAktNaFirst() { m_akt = m_first; m_act_pozice = 0; } void List::aktLeft() { if (m_akt != 0) { m_akt = m_akt->left; m_act_pozice--; } } void List::aktRight() { if (m_akt != 0) { m_akt = m_akt->right; m_act_pozice++; } } bool List::aktFirst() { if (m_akt == m_first) { return true; } else { return false; } } bool List::aktLast() { if (m_akt == m_last) { return true; } else { return false; } } bool List::akt() { if (m_akt != 0) { return true; } else { return false; } } void List::smazAkt() { polozka *pom; if (m_akt != 0) { if (m_akt == m_first) { m_first = m_akt->right; } if (m_akt == m_last) { m_last = m_akt->left; } pom = m_akt; m_akt = pom->right; if (!pom->right == 0) { pom->right->left = pom->left; } if (!pom->left == 0) { pom->left->right = pom->right; } delete pom; m_poc_polozkek--; } } void List::smazPrv(polozka* prv){ polozka *pom; if (prv != 0) { if (prv == m_first) { m_first = prv->right; } if (prv == m_last) { m_last = prv->left; } pom = prv; if (!pom->right == 0) { pom->right->left = pom->left; } if (!pom->left == 0) { pom->left->right = pom->right; } delete pom; m_poc_polozkek--; } } void List::smazFirst() { polozka *pom; if (m_first != 0) { pom = m_first; m_first = pom->right; if (m_first != 0) m_first->left = 0; delete pom; m_poc_polozkek--; if (this->akt()){ m_act_pozice--; } } } void List::smazLast() { polozka *pom; if (m_last != 0) { if (this->aktLast()){ m_act_pozice = -1; } pom = m_last; m_last = pom->left; if (m_last != 0) m_last->right = 0; delete pom; m_poc_polozkek--; } } int List::vratPocPolozek(){ return m_poc_polozkek; } int List::vratAktualniPozici(){ return m_act_pozice; } bool List::isEmpty() { if (m_first == 0) { return true; } else { return false; } } void List::aktVstupVlakna(int p_vstup) { polozka *pom; if (m_akt != 0) { pom = m_akt; pom->vlakno->m_akt_vstup = p_vstup; } } int List::vratVstupVlakna() { if (m_akt != 0) { return m_akt->vlakno->m_akt_vstup; } else { return vs_end; } } void List::aktStavVlakna(int p_stav){ if (m_akt != 0) { m_akt->vlakno->m_err_stav = p_stav; } } int List::vratStavVlakna() { if (m_akt != 0) { return m_akt->vlakno->m_err_stav; } else { return OK; } }
eb8223503064e344ef6ecb0de7a4d7419e3ebd46
cb7d0de772b4cb805707823d42cecff3d9d2fe2b
/student.h
cbc131b306519636b54c40beae9f1ccd1bf1683e
[]
no_license
sam-mcanelly/homecoming_timer
4ca05b454b1a91e84acbe7be0d35065b69a73ac6
bd6abf17aceffed0d25059a52f03f27cc6738b20
refs/heads/master
2021-05-29T18:09:23.123015
2015-09-21T22:41:55
2015-09-21T22:41:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,108
h
student.h
#ifndef STUDENT_H #define STUDENT_H /* importing QString for use with name and card number */ #include <QString> #include <QTime> #include <sstream> /*---------------------------------------------- * * ===========student.h========== * * * Student class definition with member variables * and function definitions * * Author: Sam McAnelly * Last Revised: 5/21/2015 * * * ---------------------------------------------*/ class Student { private: std::string name; std::string first_name; std::string last_name; QString card_number; float hours_required; float hours_deducted; float hours_complete; float hours_day_total; bool status; bool names_computed; QTime timer; void compute_names(); public: Student(); Student(std::string _name); Student(std::string _name, QString _card_num, float _hours_req); ~Student(); Student& operator=(const Student &old_stud); float get_hours_required() const; void set_hours_required(float new_hours_complete); float get_base_hours() const; float get_deductions() const; void set_deductions(float deductions); void set_hours_day_total(float total); bool get_status() const; void set_status(bool new_status); void toggle_status(); float get_hours_deducted() const; float get_hours_day_total() const; float get_hours_complete(); float get_base_hours_complete() const; float get_hours_incomplete() const; void set_hours_complete(float hrs); void increment_hours_complete(float addition); std::string get_name() const; const std::string get_last_name() const; const std::string get_first_name() const; void set_name(std::string new_name); std::string get_card_number() const; void set_card_number(QString new_card_number); QTime get_timer() const; void clock_in(); void clock_out(); float get_current_complete_time(); void output_debug_info(); }; #endif // STUDENT_H
0d42bc0c23608d1b385131f4c00b05a7c9bff15b
9b3affbcebf4c3f481f4b01d9737ee67dc7d54b0
/Plot/Source/PlotEditor/Private/Hierarchy/SPlotHierarchyView.h
27972f5bb931138b39bd8b885275a99508c293fe
[]
no_license
977908569/Plot
d9e7e6118b32735a7637f71df89b8c9cfe33ddbf
940b5d19246c1f8346a86584214d57f5f1b68e81
refs/heads/main
2023-02-08T16:24:52.844132
2020-12-31T06:20:20
2020-12-31T06:20:20
325,729,532
1
0
null
null
null
null
UTF-8
C++
false
false
3,280
h
SPlotHierarchyView.h
#pragma once #include "Input/Reply.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/SCompoundWidget.h" #include "Misc/TextFilter.h" #include "Framework/Views/TreeFilterHandler.h" #include "PlotEditor.h" #include "Components/Widget.h" #include "SPlotHierarchyViewItem.h" class SPlotHierarchyView : public SCompoundWidget { public: typedef TTextFilter< TSharedPtr<FPlotHierarchyModel> > PlotTextFilter; public: SLATE_BEGIN_ARGS( SPlotHierarchyView ){} SLATE_END_ARGS() void Construct(const FArguments& InArgs, TSharedPtr<FPlotEditor> InEditor, UPlot* InPlot); virtual ~SPlotHierarchyView(); virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) override; virtual void OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) override; virtual void OnMouseLeave(const FPointerEvent& MouseEvent) override; virtual FReply OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent) override; private: TSharedPtr<SWidget> PlotHierarchy_OnContextMenuOpening(); void PlotHierarchy_OnGetChildren(TSharedPtr<FPlotHierarchyModel> InParent, TArray< TSharedPtr<FPlotHierarchyModel> >& OutChildren); TSharedRef< ITableRow > PlotHierarchy_OnGenerateRow(TSharedPtr<FPlotHierarchyModel> InItem, const TSharedRef<STableViewBase>& OwnerTable); void PlotHierarchy_OnSelectionChanged(TSharedPtr<FPlotHierarchyModel> SelectedItem, ESelectInfo::Type SelectInfo); void PlotHierarchy_OnExpansionChanged(TSharedPtr<FPlotHierarchyModel> Item, bool bExpanded); void PlotHierarchy_OnMouseClick(TSharedPtr<FPlotHierarchyModel> InItem); void PlotHierarchy_OnMouseDoubleClick(TSharedPtr<FPlotHierarchyModel> InItem); private: void BeginRename(); bool CanRename() const; UPlot* GetPlot() const; void OnPlotChanged(UPlot* InPlot); void OnEditorSelectionChanged(); void RefreshTree(); void RebuildTreeView(); FReply HandleDeleteSelected(); void OnSearchChanged(const FText& InFilterText); FText GetSearchText() const; void GetPlotFilterStrings(TSharedPtr<FPlotHierarchyModel> Plot, TArray<FString>& OutStrings); void OnObjectsReplaced(const TMap<UObject*, UObject*>& ReplacementMap); void UpdateItemsExpansionFromModel(); void SaveItemsExpansion(); void RestoreItemsExpansion(); enum class EExpandBehavior : uint8 { NeverExpand, AlwaysExpand, RestoreFromPrevious, FromModel }; void RecursiveExpand(TSharedPtr<FPlotHierarchyModel>& Model, EExpandBehavior ExpandBehavior); void RestoreSelectedItems(); void RecursiveSelection(TSharedPtr<FPlotHierarchyModel>& Model); void SetItemExpansionRecursive(TSharedPtr<FPlotHierarchyModel> Model, bool bInExpansionState); private: TWeakPtr<class FPlotEditor> PlotEditor; TSharedPtr<FUICommandList> CommandList; TSharedPtr< TreeFilterHandler< TSharedPtr<FPlotHierarchyModel> > > FilterHandler; TArray< TSharedPtr<FPlotHierarchyModel> > RootPlots; TArray< TSharedPtr<FPlotHierarchyModel> > TreeRootPlots; TSharedPtr<SBorder> TreeViewArea; TSharedPtr< STreeView< TSharedPtr<FPlotHierarchyModel> > > PlotTreeView; TSet< FName > ExpandedItemNames; TSharedPtr<class SSearchBox> SearchBoxPtr; TSharedPtr<PlotTextFilter> SearchBoxPlotFilter; bool bRefreshRequested; bool bRebuildTreeRequested; bool bIsUpdatingSelection; };
892fc70d306a4fd13e3cd47d41488c269eb6eb5b
4406a56319b2e63302977ca92ef0ad2fb115eab7
/LeetCode_Monthly_Challenge/April/C++/Week_2/Partition List.cpp
1da2883796b91d562a7a7af6eda55cf9e31251bf
[]
no_license
rohan-khurana/Algorithms
1796fdbad987e1c8ac9ff4a15f146eba1aadf750
aed6b572aba88672912b6932da85b192dfb84732
refs/heads/master
2023-05-13T02:45:14.338722
2021-06-08T17:25:46
2021-06-08T17:25:46
262,344,996
1
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
Partition List.cpp
/*Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example 1: Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5] Example 2: Input: head = [2,1], x = 2 Output: [1,2] Constraints: The number of nodes in the list is in the range [0, 200]. -100 <= Node.val <= 100 -200 <= x <= 200 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode* ptr1 = new ListNode(0); ListNode* ptr2 = new ListNode(0); ListNode* ptr11 = ptr1; ListNode* ptr22 = ptr2; while(head){ if(head->val<x){ ptr11->next=new ListNode(head->val); ptr11=ptr11->next; } else{ ptr22->next=new ListNode(head->val); ptr22=ptr22->next; } head=head->next; } ptr11->next=ptr2->next; return ptr1->next; } };
063fd80dae5563d947b01ade99687bf72bca7969
4cb86b79b4631cf84a44ede6f11d514776d10db1
/3rdparty/grapevine-foundation/include/Grapevine/Material/CubemapResource.hpp
f9f8b02b12caf50e6359e97471bde79dd44ffa52
[]
no_license
vladimir-stepanov/facemask
efb37aad4601f2de9a1ddb53b47b8c1ce0faddc1
92bdf29410f9136b0a66a328aceafa1f0cd9fbf5
refs/heads/master
2020-06-27T06:23:30.825477
2017-07-18T08:39:53
2017-07-18T08:39:53
94,244,670
2
1
null
null
null
null
UTF-8
C++
false
false
1,028
hpp
CubemapResource.hpp
/** * Copyright (C) 2013-2014 Huawei Technologies Finland Oy. * * This is unpublished work. See README file for more information. */ #ifndef GRAPEVINE_MATERIAL_CUBEMAPRESOURCE #define GRAPEVINE_MATERIAL_CUBEMAPRESOURCE #include <string> #include <vector> #include "Grapevine/Resource/Resource.hpp" #include <Grapevine/Image/Bitmap.hpp> #include "Grapevine/Material/CubemapAsset.hpp" namespace Grapevine { class ImageResource; class CubemapResource: public Resource { public: CubemapResource(std::string const& filename, CubemapAsset::Type::Enum type); CubemapResource(Bitmap& filename, CubemapAsset::Type::Enum type); ~CubemapResource(); unsigned int textureId(); static void purgeStaleCubemaps(); private: static std::vector<unsigned int> staleTextureIds_; ImageResource* imageResource_; void initialize(); unsigned int textureId_; CubemapAsset::Type::Enum type_; friend class TextureFactory; }; } #endif
a5ac1f3a44cd7a74115b4e02e39af988a7ce034f
eec122d20ba720420c648de7fe068954b7e9db85
/cprogram/reversestring.cpp
db31a494ccce9e53c22d68fe529052aa21eb8cf3
[]
no_license
lydiawilson25/JProject
6a5276716e4883a0af7b4bbe3e5e9190b2cecea8
4a0177df8125f1794b3e2aabbf41548a2ad4887d
refs/heads/master
2021-01-10T18:31:59.065354
2015-08-29T01:44:47
2015-08-29T01:44:47
41,561,897
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
reversestring.cpp
#include<iostream> int main() { char *str="lydia"; //char *rev = reverse(str); } char reverse(char *str){ char *end =str; char tmp; if(str){ while(*end){ ++end; print("value of end %c" end); } --end; } return end; }
7ca586ee2a4a30e0def1f81413fc95cad6a37b49
5505658019e2057d56bc754410b3ad6cd69df391
/source/tsflie.cpp
bd2fd910082d040cf4bc4267f2d5b17fb09bcc5c
[]
no_license
liuchuxiong/TsAnalysor
7401bba2fa33e6912d4ca6d6b78894db9e2da08b
439527d5762e72f7099ed3fa68c611a06952bdc0
refs/heads/master
2023-08-16T22:59:30.758152
2016-07-04T06:47:10
2016-07-04T06:47:10
null
0
0
null
null
null
null
GB18030
C++
false
false
2,084
cpp
tsflie.cpp
//作者 蔡砚刚 20160622 xiaoc@pku.edu.cn #include <stdlib.h> #include "tsfile.h" #pragma warning(disable: 4996) // POSIX setmode and fileno deprecated FILE *g_ts_file = NULL; //ts 原始文件 FILE *g_ts_ts = NULL; //打印每个ts的详细信息 FILE *g_ts_video = NULL; //输出视频流信息 FILE *g_ts_audio = NULL; //输出音频流信息 FILE *g_ts_out = NULL; //输出修改后的ts流 char *ts_file_name = NULL; //ts 原始文件 -i 配置 如:-i brazil-bq.ts char *ts_ts_name = NULL; //打印每个ts的详细信息 -t 配置 如:-t brazil-bq.log char *ts_video_name = NULL; //输出视频流信息 -v 配置 如:-v brazil-bq.264 char *ts_audio_name = NULL; //输出音频流信息 -a 配置 如:-a brazil-bq.aac char *ts_out_name = NULL; //输出修改后的ts流 -o 配置 如:-o brazil-new.ts int g_errors = 0; //统计错误个数 //打开ts相关文件 void openFlvFiles() { if(ts_file_name) { g_ts_file = fopen(ts_file_name,"rb"); if(!g_ts_file) { printf("打开文件失败: %s\n",ts_file_name); system("pause"); exit(0); } } if(ts_ts_name) { g_ts_ts = fopen(ts_ts_name,"w"); if(!g_ts_ts) { printf("打开文件失败: %s\n",ts_ts_name); system("pause"); exit(0); } } if(ts_video_name) { g_ts_video = fopen(ts_video_name,"wb"); if(!g_ts_video) { printf("打开文件失败: %s\n",ts_video_name); system("pause"); exit(0); } } if(ts_audio_name) { g_ts_audio = fopen(ts_audio_name,"wb"); if(!g_ts_audio) { printf("打开文件失败: %s\n",ts_audio_name); system("pause"); exit(0); } } if(ts_out_name) { g_ts_out = fopen(ts_out_name,"wb"); if(!g_ts_out) { printf("打开文件失败: %s\n",ts_out_name); system("pause"); exit(0); } } } //关闭ts相关文件 void closeFlvFiles() { if(g_ts_file) fclose(g_ts_file); if(g_ts_ts) fclose(g_ts_ts); if(g_ts_video) fclose(g_ts_video); if(g_ts_audio) fclose(g_ts_audio); if(g_ts_out) fclose(g_ts_out); }
97068640ff858b926c8c17f66f9cf025dc7c95be
1985d0b696cd7e6a3c66f0c7fcb8522e732eee12
/appseed/audio_alsa/audio_alsa_wave_in.h
e8cd60ba37ded70fef9be951908a6647c9491f39
[]
no_license
ca2/nodeapp-linux
effe36935623cd820647c7738b66d0bfc026d0b2
9fb4c8093afa846ea526aa06354f05c5b34949c7
refs/heads/main
2022-12-21T10:05:47.101457
2018-11-10T22:11:47
2018-11-10T22:11:47
98,114,367
14
0
null
null
null
null
UTF-8
C++
false
false
1,458
h
audio_alsa_wave_in.h
#pragma once namespace multimedia { namespace audio_alsa { class CLASS_DECL_AUDIO_MMSYSTEM wave_in : virtual public snd_pcm, virtual public ::multimedia::audio::wave_in { public: wave_in(::aura::application * papp); virtual ~wave_in(); virtual bool wave_in_initialize_encoder(); //virtual ::multimedia::e_result wave_in_add_buffer(int32_t iBuffer); //virtual ::multimedia::e_result wave_in_add_buffer(LPWAVEHDR lpwavehdr); snd_pcm_t * wave_in_get_safe_PCM(); virtual void * get_os_data(); ::multimedia::e_result wave_in_open(int32_t iBufferCount, int32_t iBufferSampleCount); ::multimedia::e_result wave_in_close(); ::multimedia::e_result wave_in_stop(); ::multimedia::e_result wave_in_start(); ::multimedia::e_result wave_in_reset(); //virtual void translate_wave_in_message(::signal_details * pobj); virtual bool init_thread() override; virtual void term_thread() override; //virtual void pre_translate_message(::signal_details * pobj); void CALLBACK wave_in_proc(snd_pcm_t * hwi, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2); virtual void run() override; //WAVEFORMATEX * wave_format(); //LPWAVEHDR wave_hdr(int iBuffer); }; } // namespace audio_alsa } // namespace multimedia
277bc153d1712d4c3b717212c44bcf76a1686f29
23f75340ae3b4f03ad3dba55e7a722dc0ef68ccf
/49-Camera/wwEmailWithAttachment.hpp
372da2a1932c4540edd2c367eb6139f5baf98eb3
[]
no_license
FMXExpress/CPP-Cross-Platform-Samples
5f0283a5c73f621e32e6bf3f641c9c2dfd85024b
bb9a9807a3baf663c91bd8ff1b95cd4188bbc8ad
refs/heads/master
2022-10-05T20:35:39.004542
2022-09-22T00:10:55
2022-09-22T00:10:55
219,104,851
8
9
null
null
null
null
UTF-8
C++
false
false
2,494
hpp
wwEmailWithAttachment.hpp
// CodeGear C++Builder // Copyright (c) 1995, 2018 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'wwEmailWithAttachment.pas' rev: 33.00 (Windows) #ifndef WwemailwithattachmentHPP #define WwemailwithattachmentHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> #include <SysInit.hpp> #include <System.SysUtils.hpp> #include <System.Classes.hpp> #include <System.Types.hpp> #include <System.Math.hpp> #include <System.Generics.Collections.hpp> #include <System.IOUtils.hpp> #include <System.StrUtils.hpp> #include <System.Win.ComObj.hpp> #include <Winapi.ShellAPI.hpp> #include <Winapi.Windows.hpp> #include <Winapi.ActiveX.hpp> #include <System.Win.Registry.hpp> #include <System.TypInfo.hpp> //-- user supplied ----------------------------------------------------------- namespace Wwemailwithattachment { //-- forward type declarations ----------------------------------------------- //-- type declarations ------------------------------------------------------- enum class DECLSPEC_DENUM TwwEmailAttachmentLocation : unsigned char { Default, Cache, Files, ExternalDrive, ExternalCache }; //-- var, const, procedure --------------------------------------------------- extern DELPHI_PACKAGE void __fastcall wwEmail(System::UnicodeString *Recipients, const int Recipients_High, System::UnicodeString *ccRecipients, const int ccRecipients_High, System::UnicodeString *bccRecipients, const int bccRecipients_High, System::UnicodeString Subject, System::UnicodeString Content, System::UnicodeString AttachmentPath, System::UnicodeString mimeTypeStr = System::UnicodeString())/* overload */; extern DELPHI_PACKAGE void __fastcall wwEmail(System::UnicodeString Recipients, System::UnicodeString ccRecipients, System::UnicodeString bccRecipients, System::UnicodeString Subject, System::UnicodeString Content, System::UnicodeString AttachmentPath, System::UnicodeString mimeTypeStr = System::UnicodeString())/* overload */; } /* namespace Wwemailwithattachment */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_WWEMAILWITHATTACHMENT) using namespace Wwemailwithattachment; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // WwemailwithattachmentHPP
9bc6a81b4cde8b778c3e23731d853e209e307186
534ed34a71d11e6eb6c91857ce3ab331ebfa6373
/Qbert/RedBall.cpp
68af60b169358c7f648ff93fac6e70f97779400a
[]
no_license
JaakkoKaikkonen/Qbert
f9b3d39f2e1a5b16b105c43fa45bfc0719e8c342
a938d81e83308b1faace7a6ca76bc26a55227051
refs/heads/master
2020-04-15T14:24:55.925088
2019-07-26T02:51:41
2019-07-26T02:51:41
164,754,788
0
0
null
null
null
null
UTF-8
C++
false
false
2,171
cpp
RedBall.cpp
#include "RedBall.hpp" namespace Game { RedBall::RedBall(gameDataRef data, int spawnDelay) : Enemy(data, spawnDelay) { enemy.setTexture(this->data->assets.getTexture("Enemy")); enemy.setTextureRect(RED_BALL_JUMP); enemy.setOrigin(enemy.getGlobalBounds().width / 2, enemy.getGlobalBounds().height / 2); enemy.setScale(2.0f, 2.0f); enemy.setPosition(RED_BALL_START_POS); } void RedBall::update(std::array<Box*, 28>& boxes, sf::Vector2f qbertPos) { //std::cout << _spawnCounter << std::endl; if (spawnCounter > 0) { spawnCounter--; } else { if (fell) { this->fall(); } else { if (drop) { enemy.move(0.0f, 5.0f); if (boxes[2]->contains(enemy.getPosition() + sf::Vector2f(0.0f, -5.0f))) { drop = false; moveTimer = 25; } } else { moveTimer++; if (moveTimer > 40) { jumpStartPos = enemy.getPosition(); x = 0; y = 0; dir = (Dir)(rand() % 2); jumpCounter = 28; moveTimer = 0; } } if (jumpCounter > 0) { switch (dir) { case Dir::Down: x -= 32.0f/28.0f; y = ((4.0f + sqrt(7.0f)) / 64.0f) * pow(-x - ((16.0f*((sqrt(7.0f) - 1.0f)) / 3.0f)), 2) - 8.0f; enemy.setPosition(jumpStartPos.x + x, jumpStartPos.y + y); break; case Dir::Right: x += 32.0f / 28.0f; y = ((4.0f + sqrt(7.0f)) / 64.0f) * pow(x - ((16.0f*((sqrt(7.0f) - 1.0f)) / 3.0f)), 2) - 8.0f; enemy.setPosition(jumpStartPos.x + x, jumpStartPos.y + y); } jumpCounter--; //y = ((3.0f*(21.0f + 8.0f*sqrt(5.0f))) / 1024.0f) * pow(x - ((32.0f*(4.0f*sqrt(5.0f) - 5.0f)) / 11.0f), 2) - 15.0f; //y = (3.0f * (13.0f + sqrt(105.0f))) / 512.0f * pow(x - (2.0f * (sqrt(105.0f) - 5.0f)), 2) - 15.0f; } } } } void RedBall::reset(bool gameOver) { if (gameOver) { spawnCounter = spawnDelay; } else { spawnCounter = 100; } enemy.setPosition(RED_BALL_START_POS); drop = true; fell = false; jumpCounter = 0; } void RedBall::animate() { if (jumpCounter > 0 || drop) { enemy.setTextureRect(RED_BALL_JUMP); } else { enemy.setTextureRect(RED_BALL); } } }
ab24f550d289d594e723de7b869f85f9c1b485fe
acc532b234aef1b473ea9dcb62d1416cfb939e58
/Calculator/C++ Files/Integer.cpp
73c95a6183362c502e33accc3b261c062b2a9b86
[]
no_license
BanerjeeVikrant/CalculatorV2
7ceaea7b880020e19e6a76ac4af63ba8eb879a2a
b4fc1642de11f8b87782114b8b1cca00d136229b
refs/heads/master
2022-11-13T21:16:46.239581
2020-07-08T09:13:04
2020-07-08T09:13:04
278,043,615
0
0
null
null
null
null
UTF-8
C++
false
false
1,835
cpp
Integer.cpp
// // Integer.cpp // Calculator // // Created by Vikrant Banerjee on 2/1/20. // Copyright © 2020 Vikrant Banerjee. All rights reserved. // #include "Integer.hpp" #include "Fraction.hpp" Value* Integer::add(const Value* other){ const Integer *intOther = dynamic_cast<const Integer*>(other); if (intOther) { return (new Integer(i + intOther->i)); } const Fraction *fracOther = dynamic_cast<const Fraction*>(other); if (fracOther) { return (new Fraction(fracOther->n + fracOther->d * i, fracOther->d)); } return nullptr; } Value* Integer::subtract(const Value* other){ const Integer *intOther = dynamic_cast<const Integer*>(other); if (intOther) { return (new Integer(i - intOther->i)); } const Fraction *fracOther = dynamic_cast<const Fraction*>(other); if (fracOther) { return (new Fraction(fracOther->n + fracOther->d * i, fracOther->d)); } return nullptr; } Value* Integer::multiply(const Value* other){ const Integer *intOther = dynamic_cast<const Integer*>(other); if (intOther) { return (new Integer(i * intOther->i)); } const Fraction *fracOther = dynamic_cast<const Fraction*>(other); if (fracOther) { return (new Fraction(fracOther->n * i, fracOther->d)); } return nullptr; } Value* Integer::divide(const Value* other){ const Integer *intOther = dynamic_cast<const Integer*>(other); if (intOther) { if ((i % intOther->i) == 0) { return (new Integer(i / intOther->i)); } else { return new Fraction(i, intOther->i); } } const Fraction *fracOther = dynamic_cast<const Fraction*>(other); if (fracOther) { return (new Fraction(fracOther->n, fracOther->d * i)); } return nullptr; }
10a756fb2f30cc11f57b98c3f3bbaf4d74b84eb4
ea89955e343ced5e705b4a338039e658a4ba67cb
/Source/Behavior/Behavior.h
64daf40edab6f7f840b103d05aef5bfa8c9dfa70
[]
no_license
kennethdmiller3/videoventure
775ce24ee4aebe3dfc65876a3fc9abb93f29b51d
7182b78fde61421c48abc679ef6f2992e740d678
refs/heads/master
2021-06-03T19:26:26.704306
2020-07-25T05:37:02
2020-07-25T05:37:02
32,195,803
2
0
null
null
null
null
UTF-8
C++
false
false
1,550
h
Behavior.h
#pragma once #include "Task.h" // forward declaration class Controller; class Brain; class Behavior : public Task { protected: unsigned int mId; Controller *mController; public: Behavior(unsigned int aId, Controller *aController) : mId(aId) , mController(aController) { } virtual ~Behavior() { } }; namespace BehaviorDatabase { namespace Loader { typedef unsigned int (* Entry)(unsigned int, const tinyxml2::XMLElement *); class GAME_API Configure { private: unsigned int mTagId; // tag hash id for the configure Entry mPrev; // entry that this replaced public: static Database::Typed<Entry> &GetDB(); Configure(unsigned int aTagId, Entry aEntry); ~Configure(); static const Entry &Get(unsigned int aTagId); }; } namespace Initializer { class GAME_API Activate { public: typedef Behavior * (* Entry)(unsigned int, Controller *); private: unsigned int mDatabaseId; Entry mPrev; public: static Database::Typed<Entry> &GetDB(); Activate(unsigned int aDatabaseId, Entry aEntry); ~Activate(); static const Entry &Get(unsigned int aDatabaseId); }; class GAME_API Deactivate { public: typedef void (* Entry)(unsigned int); private: unsigned int mDatabaseId; Entry mPrev; public: static Database::Typed<Entry> &GetDB(); Deactivate(unsigned int aDatabaseId, Entry aEntry); ~Deactivate(); static const Entry &Get(unsigned int aDatabaseId); }; } }
a91beede95579a5cb0e16f4395bf7ec30f1e4c4b
e84d0dcbd2e5b73f300c9a570843c01b3a26173f
/SLY MOTOR/ModulePlayer.cpp
0ba927d0708f1556fee3686342e393d9591465f7
[]
no_license
MoyaSly/SLY-MOTOR
c5206fe5a1f84239d22640d392c5e6b168f61ef0
337a136e4f5cc64e7db8b65cb3f8aded6531176c
refs/heads/master
2020-04-11T03:01:25.730121
2016-10-14T16:25:47
2016-10-14T16:25:47
68,018,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,288
cpp
ModulePlayer.cpp
#include "Globals.h" #include "Application.h" #include "ModulePlayer.h" #include "Primitive.h" #include "PhysVehicle3D.h" #include "PhysBody3D.h" ModulePlayer::ModulePlayer(Application* app, bool start_enabled) : Module(app, start_enabled), vehicle(NULL) { turn = acceleration = brake = 0.0f; } ModulePlayer::~ModulePlayer() {} // Load assets bool ModulePlayer::Start() { LOG("Loading player"); return true; } // Unload assets bool ModulePlayer::CleanUp() { LOG("Unloading player"); return true; } // Update: draw background update_status ModulePlayer::Update(float dt) { return UPDATE_CONTINUE; } bool ModulePlayer::Reset() { LOG("Player Reset Successfully!"); ResetVehicle(0, 0, 0, 0); return true; } float ModulePlayer::GetSpeed() { return vehicle->GetKmh(); } btVector3 ModulePlayer::GetForwardVec3() { return vehicle->vehicle->getForwardVector();; } vec3 ModulePlayer::GetPosition() { vec3 position; btTransform a = vehicle->body->getWorldTransform(); position.Set(a.getOrigin().getX(), a.getOrigin().getY(), a.getOrigin().getZ()); return position; } void ModulePlayer::ResetVehicle(float x, float y, float z, float angle) { vehicle->SetPos(x, y, z); vehicle->StopMotion(); vehicle->Orient(angle); elevators->SetPos(x + 0.0f, y + 3.0f, z + 10.0f); }
92ffd4abc2a064974f5109af89ffa1b46aa23480
08e2d7d0b3ffc78d3fee8633f02583b94e756262
/include/DataStructure/HeaderInfo.hpp
8f2c28ea1dae239d9c0b9fa95eb5d7993afd634f
[]
no_license
Alexej/Cpp2020
582b4909d36ad04b5a01353a1af8cafad2037012
facd9b3fed0ec3a29276fb8bd18b2d9fe4561cce
refs/heads/master
2022-11-21T09:38:05.388007
2020-07-18T18:03:22
2020-07-18T18:03:22
279,686,054
0
0
null
null
null
null
UTF-8
C++
false
false
336
hpp
HeaderInfo.hpp
#ifndef H_HEADERINFO #define H_HEADERINFO #include <stdint.h> namespace Cpp2020::DataStructure { class HeaderInfo { public: HeaderInfo() = default; HeaderInfo(int32_t gho, int32_t cdlib); int32_t globalHeaderOffset_; int32_t compressedDataLengthInBits_; }; } #endif
c59028e61ba0ce2514fb7735107edac291d8a882
191460258090bcabe392785948025887696ccd1b
/src/xenia/kernel/fs/stfs.h
505d7dfd691475089213d2dfa4ada30d1f70ac04
[]
no_license
DrChat/xenia
1b81ab13298229cb568c1385774f47792a802767
0dc06a7e6fedaa4dd7bbe4e3c34bc288a58f6c49
refs/heads/master
2020-04-05T18:29:57.710202
2015-05-20T05:31:37
2015-05-20T05:31:37
34,922,300
5
5
null
2015-05-01T20:21:14
2015-05-01T20:21:14
null
UTF-8
C++
false
false
5,341
h
stfs.h
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2014 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef XENIA_KERNEL_FS_STFS_H_ #define XENIA_KERNEL_FS_STFS_H_ #include <memory> #include <vector> #include "xenia/base/fs.h" #include "xenia/base/mapped_memory.h" #include "xenia/kernel/fs/entry.h" #include "xenia/xbox.h" namespace xe { namespace kernel { namespace fs { class STFS; // http://www.free60.org/STFS enum STFSPackageType { STFS_PACKAGE_CON, STFS_PACKAGE_PIRS, STFS_PACKAGE_LIVE, }; enum STFSContentType : uint32_t { STFS_CONTENT_ARCADE_TITLE = 0x000D0000, STFS_CONTENT_AVATAR_ITEM = 0x00009000, STFS_CONTENT_CACHE_FILE = 0x00040000, STFS_CONTENT_COMMUNITY_GAME = 0x02000000, STFS_CONTENT_GAME_DEMO = 0x00080000, STFS_CONTENT_GAMER_PICTURE = 0x00020000, STFS_CONTENT_GAME_TITLE = 0x000A0000, STFS_CONTENT_GAME_TRAILER = 0x000C0000, STFS_CONTENT_GAME_VIDEO = 0x00400000, STFS_CONTENT_INSTALLED_GAME = 0x00004000, STFS_CONTENT_INSTALLER = 0x000B0000, STFS_CONTENT_IPTV_PAUSE_BUFFER = 0x00002000, STFS_CONTENT_LICENSE_STORE = 0x000F0000, STFS_CONTENT_MARKETPLACE_CONTENT = 0x00000002, STFS_CONTENT_MOVIE = 0x00100000, STFS_CONTENT_MUSIC_VIDEO = 0x00300000, STFS_CONTENT_PODCAST_VIDEO = 0x00500000, STFS_CONTENT_PROFILE = 0x00010000, STFS_CONTENT_PUBLISHER = 0x00000003, STFS_CONTENT_SAVED_GAME = 0x00000001, STFS_CONTENT_STORAGE_DOWNLOAD = 0x00050000, STFS_CONTENT_THEME = 0x00030000, STFS_CONTENT_TV = 0x00200000, STFS_CONTENT_VIDEO = 0x00090000, STFS_CONTENT_VIRAL_VIDEO = 0x00600000, STFS_CONTENT_XBOX_DOWNLOAD = 0x00070000, STFS_CONTENT_XBOX_ORIGINAL_GAME = 0x00005000, STFS_CONTENT_XBOX_SAVED_GAME = 0x00060000, STFS_CONTENT_XBOX_360_TITLE = 0x00001000, STFS_CONTENT_XBOX_TITLE = 0x00005000, STFS_CONTENT_XNA = 0x000E0000, }; enum STFSPlatform : uint8_t { STFS_PLATFORM_XBOX_360 = 0x02, STFS_PLATFORM_PC = 0x04, }; enum STFSDescriptorType : uint32_t { STFS_DESCRIPTOR_STFS = 0, STFS_DESCRIPTOR_SVOD = 1, }; class STFSVolumeDescriptor { public: bool Read(const uint8_t* p); uint8_t descriptor_size; uint8_t reserved; uint8_t block_separation; uint16_t file_table_block_count; uint32_t file_table_block_number; uint8_t top_hash_table_hash[0x14]; uint32_t total_allocated_block_count; uint32_t total_unallocated_block_count; }; class STFSHeader { public: bool Read(const uint8_t* p); uint8_t license_entries[0x100]; uint8_t header_hash[0x14]; uint32_t header_size; STFSContentType content_type; uint32_t metadata_version; uint64_t content_size; uint32_t media_id; uint32_t version; uint32_t base_version; uint32_t title_id; STFSPlatform platform; uint8_t executable_type; uint8_t disc_number; uint8_t disc_in_set; uint32_t save_game_id; uint8_t console_id[0x5]; uint8_t profile_id[0x8]; STFSVolumeDescriptor volume_descriptor; uint32_t data_file_count; uint64_t data_file_combined_size; STFSDescriptorType descriptor_type; uint8_t device_id[0x14]; wchar_t display_names[0x900 / 2]; wchar_t display_descs[0x900 / 2]; wchar_t publisher_name[0x80 / 2]; wchar_t title_name[0x80 / 2]; uint8_t transfer_flags; uint32_t thumbnail_image_size; uint32_t title_thumbnail_image_size; uint8_t thumbnail_image[0x4000]; uint8_t title_thumbnail_image[0x4000]; }; class STFSEntry { public: STFSEntry(); typedef std::vector<std::unique_ptr<STFSEntry>> child_t; typedef child_t::iterator child_it_t; STFSEntry* GetChild(const xe::fs::WildcardEngine& engine, child_it_t& ref_it); STFSEntry* GetChild(const char* name); void Dump(int indent); std::string name; X_FILE_ATTRIBUTES attributes; size_t offset; size_t size; uint32_t update_timestamp; uint32_t access_timestamp; child_t children; typedef struct { size_t offset; size_t length; } BlockRecord_t; std::vector<BlockRecord_t> block_list; }; class STFS { public: enum Error { kSuccess = 0, kErrorOutOfMemory = -1, kErrorReadError = -10, kErrorFileMismatch = -30, kErrorDamagedFile = -31, }; STFS(MappedMemory* mmap); virtual ~STFS(); const STFSHeader* header() const { return &header_; } STFSEntry* root_entry() const { return root_entry_.get(); } Error Load(); void Dump(); private: Error ReadHeaderAndVerify(const uint8_t* map_ptr); Error ReadAllEntries(const uint8_t* map_ptr); size_t BlockToOffset(uint32_t block); uint32_t ComputeBlockNumber(uint32_t block_index); typedef struct { uint32_t next_block_index; uint32_t info; } BlockHash_t; BlockHash_t GetBlockHash(const uint8_t* map_ptr, uint32_t block_index, uint32_t table_offset); MappedMemory* mmap_; STFSPackageType package_type_; STFSHeader header_; uint32_t table_size_shift_; std::unique_ptr<STFSEntry> root_entry_; }; } // namespace fs } // namespace kernel } // namespace xe #endif // XENIA_KERNEL_FS_STFS_H_
06429636f41565bad1b9e04f55c0e9557d77d99d
cef24f812db46468c1468b2f14bcd171ff3338eb
/Main.cpp
118050added9e4982e6b1321c60c80b8a5b8a6fe
[]
no_license
henriquedavid/project_search
b47551e09fcb231757e049c695d1e6acf276db02
a5ff35e1bfc431e29fe6988f07f6c07b2c569706
refs/heads/master
2021-04-06T09:40:30.221315
2018-03-20T21:15:58
2018-03-20T21:15:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,165
cpp
Main.cpp
/* * Programa que possibilita testar 7 algoritmos * de busca (linear, binaria interativa * e recursiva, ternária interativa e * recursiva, jump search e fibonacci search). * */ #include <iostream> // std::cout, std::endl, std::cerr, std::cin #include <chrono> // std::chrono, std::chrono::system_clock, std::chrono::duration_cast #include <algorithm> // .count(), #include <iterator> // std::ostream_iterator<int> #include <cmath> // std::sqrt #include <string> // std::string #include <sstream> // std::istringstream #include <fstream> // .open(), .close(), .fail() #include <vector> // std::vector<std::string> #include <iomanip> // std::setw(), std::setprecision() // Transforma uma string em um inteiro. /* * \param recebe valor em string. * \return retorna valor em inteiro. */ int getInteger(std::string value){ int ver = 0; int valor; while(ver == 0){ std::istringstream iss(value); iss >> valor >> std::ws; if(iss.fail() or !iss.eof()){ std::cerr << "Erro ao converter!\nInsira novamente: \n" << std::endl; std::cin >> value; } else ver = 1; } return valor; } /* * Padrão para as buscas Linear, Binária Interativa, Binária Recursiva, Ternária Interativa, * Jump Search e Fibonacci Search. * * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * linearSearch( long int *first , long int *last , int value , long int *default_last){ // Percorre o vetor. for( auto i( first ); i < last ; i++ ){ // Verifica se é o valor desejado. if( value == *i ) return i; } // Retorna o último elemento. return default_last; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * binarySearch( long int *first , long int *last , int value , long int *default_last){ // Atribui a back o ponteiro last para não perder o ponteiro final auto back( last ); //Percorre o vetor de forma que haja divisões e seus valores de inicio e fim ficam variando. while( first <= last ){ int middle = ( last - first ) / 2; // Verifica se o valor do meio no intervalo é o valor escolhido if( *( first + middle ) == value ){ return first + middle; } // Se o valor não é o do meio, verifica se o valor é menor que a metade, se sim, a metade é o novo começo // caso contrário é o novo final do intervalo. if( *( first + middle ) < value ){ first = first + middle + 1; } else{ last = last - middle - 1; } } // Caso não tenha encontrado o valor, retorne o final do intervalo. return back; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * binary_rec( long int *first , long int *last , int value , long int *default_last){ // Condição para garantir que não haja procura fora do intervalo informado do número if( first <= last ){ // Descobre o valor da metade do intervalo int middle = ( last - first ) / 2; // Verifica se a metade é o valor procurado, caso contrário verifica se é maior, se sim, // a metade é o inicio, senão, a metade é o final e chama novamente a função. if( *( first + middle ) == value ){ return first + middle; } else if( *( first + middle ) < value ){ // Retira o valor já consultado auto new_first = first + middle + 1; return binary_rec( new_first , last , value , default_last ); } else{ // Retira o valor já consultado auto new_last = last - middle - 1; return binary_rec( first , new_last , value , default_last ); } } // Caso não encontre o valor retornar o final do vetor. return default_last; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * ternSearch( long int *first , long int *last , int value , long int *default_last ){ // Percorre o vetor while( first <= last ){ // Divide o vetor em 3 partes int middle1 = ( last - first) / 3; int middle2 = 2 * middle1; // Verifica se o valor desejado está em uma das duas partes encontras if( *( first + middle1 ) == value ) return first + middle1; if( *( first + middle2 ) == value ) return first + middle2; // Se o valor for menor que o primeiro valor, o final é o primeiro valor da divisão, // caso contrário verificar se está entre o primeiro e o segundo valor, se sim, então // o inicio é o primeiro valor e o final é o segundo valor, caso contrário o segundo valor // é o final. if( value < *( first + middle1 ) ){ last = first + middle1 - 1; } else if( *( first + middle1 ) < value && value < *( first + middle2 ) ){ first = first + middle1 + 1; last = first + middle2 - 1; } else if (value > *( first + middle2 ) ){ first = first + middle2 + 1; } else{ return default_last; } } // Se não encontrado retornar o final do intervalo. return default_last; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * tern_rec( long int *first , long int *last , int value , long int *default_last ){ // Verifica se o ponteiro first está dentro do intervalo. if( first <= last ){ // Descobre os dois pontos médios quando dividido em 3 partes. int middle1 = ( last - first ) / 3; int middle2 = 2 * middle1; // Verifica se o valor em algum dos pontos médios das partes do vetor. if( *( first + middle1 ) == value ) return first + middle1; if( *( first + middle2 ) == value ) return first + middle2; // Verifica em qual intervalo está o valor, quando definido chama novamente a função até encontrar o valor. if( value < *( first + middle1 ) ){ return tern_rec( first , first + middle1 - 1 , value , default_last ); } else if( *( first + middle1 ) < value && value < *( first + middle2 ) ){ return tern_rec( first + middle1 + 1 , first + middle2 - 1 , value , default_last ); } else if ( value > *( first + middle2 ) ){ return tern_rec( first + middle2 + 1 , last , value , default_last ); } else{ return default_last; } } // Se o valor não foi encontrado então retornar o inicio do intervalo original. return default_last; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * jump_search(long int *first, long int *last, int value, long int *default_last){ // Define a raiz quadrada da distância o intervalo. int aux = std::sqrt( ( last - first ) ); // Variaveis para não modificar o inicio e o final originais. long int* new_first = first; long int* new_last = first+aux; // Procura por todo o vetor em partes while( first <= last && new_last <= default_last ){ // Verifica se o valor está no inicio (modificado), ou no final (modificado) do intervalo. if( value == *new_first ) return new_first; if( value == *new_last ) return new_last; // Verifica se o valor está no intervalo do inicio e o final // Caso o valor não esteja é estabelecido novos valores para o inicio e o final do intervalo if( value > *new_first && value < *new_last ) return linearSearch( new_first , new_last , value , default_last ); else{ new_first += aux; new_last += aux; } } // Caso o valor não seja encontrado retorna o final original do intervalo completo. return default_last; } // Retorna o menor valor entre dois números, função para auxiliar a função fibonacci_search. /* * \param recebe inteiro. * \param recebe inteiro. * \return retorna qual é o menor valor entre dois. */ int menorValor( int x , int y ){ if( x < y ) return x; return y; } /* * \param ponteiro first aponta para o primeiro elemento do vetor. * \param ponteiro last aponta para após o último elemento do array. * \param value - valor desejado que deseja buscar. * \param ponteiro default_last aponta para após o último elemento do array. * \return ponteiro para o valor desejado; ou para após o último elemento do array. */ long int * fibonacci_search( long int *first , long int *last , int value , long int *default_last ){ // Estabelece a condição básica dos números de fibonacci. int fib_m2 = 0; int fib_m1 = 1; // Realiza a condição inicial para os números de fibonacci. int fib = fib_m2 + fib_m1; // Define variaveis auxiliares. int menor = 0 , aux = -1; // Verifica os números de fibonacci em todo o vetor até encontrar qual se aproxima do valor, // sendo sempre menor ou igual, não podendo ser um número maior. while( fib <= *( last - 1 ) ){ fib_m2 = fib_m1; fib_m1 = fib; fib = fib_m2 + fib_m1; } // Condição de início para a busca a partir da sequência. while( fib > 1 ){ // Verifica qual o menor valor entre o fibonacci + menor ou o final do vetor. menor = menorValor( fib_m2 + aux , *( last - 2 ) ); /* Se o valor encontrado for igual ao vetor então é o valor procurado, caso contrário * verifica se o menor é menor que o valor, se sim então atualiza os números de fibonacci * e permite a nome do menor com o valor encontrado, caso contrário apenas * atualiza os números de fibonacci. */ if( *( first + menor ) < value ){ fib = fib_m1; fib_m1 = fib_m2; fib_m2 = fib - fib_m1; aux = menor; } else if( *( first + menor ) > value ){ fib = fib_m2; fib_m1 = fib_m1 - fib_m2; fib_m2 = fib - fib_m1; } else{ return first + menor; } } // Caso o valor não seja encontrado, então retornar a posição do ultimo valor no intervalo original. return default_last; } int main(int argc, char* argv[]){ long int quant_Element = 0; // acompanha a variação da quantidade de elementos. /* * tipo_busca informa qual o tipo de busca desejada e o padrão * caso não seja informado o tipo de busca. */ std::string tipo_busca = "LN"; int valor; /* * quant_max é a quantidade máxima de um vetor (varia de computador em computador). */ long int quant_max_Element = 1026991; int amostras = 0; // Verifica a quantidade de amostras desejadas. std::ofstream FILE; std::vector<std::string> cabecalho = {"Quantidade de Elementos","TEMPO(ns)"}; if(argc < 3){ // Apresenta erro caso o usuário não tenha executado corretamente o executável. std::cout << "Há informações faltando\n ./EXECUTAVEL QUANTIDADE_AMOSTRAS REPRESENTACAO_DA_BUSCA" << std::endl << "Opção de Buscas:\nLN - Linear\nBI - Binária Interativa\nBR - Binária Recursiva\n" << "TI - Ternária Interativa\nTR - Ternária Recursiva\nJS - Jump Search\nFB - Fibonacci Search\n"; } else{ // Transforma o valor da quantidade de amostras. amostras = getInteger(argv[1]); // Recebe o tipo de busca. tipo_busca = argv[2]; // Cria arquivo com o nome do tipo de busca em formato csv para gerar os gráficos. FILE.open("results_" + tipo_busca + ".csv"); // Verifica se foi possível abrir o arquivo, caso contrário apresenta erro e encerra o programa. if(FILE.fail()){ std::cout << "Erro ao abrir o arquivo!" << std::endl; return -1; } // Insere o padrão do cabeçalho no arquivo de saída. FILE << "TIPO DE BUSCA: " << tipo_busca << ", Quantidade de amostras analisadas:" << amostras << std::endl << std::endl; FILE << cabecalho[0] << " "; FILE << ", " << cabecalho[1] << " "; FILE << std::endl; // Inicia a quantidade de elementos no vetor. int media_inicial = quant_max_Element / amostras; quant_Element = media_inicial; // Executa séries de repetições de amostras. for( auto rep(1); rep <= amostras; rep++){ // Reinicia a média em cada repetição. int media = 0; // Previne caso a quantidade de elementos for maior do que suportado. if(quant_Element > quant_max_Element) quant_Element = quant_max_Element; // Cria um vetor para armazenar elementos. long int A[quant_Element]; // Insere elementos no vetor. for( auto i(0); i < quant_Element; i++){ A[i] = i; } // Torna a variável valor não seja um elemento do vetor. valor = quant_max_Element+1; // Realiza séries de testes dos tempos da busca escolhida. for( auto t(0); t < 100; t++){ auto start = std::chrono::system_clock::now(); // Realiza a busca desejada. if(tipo_busca == "FS") auto result = fibonacci_search( A, A+quant_Element, valor, A+quant_Element ); else if(tipo_busca == "BI") auto result = binarySearch( A, A+quant_Element, valor, A+quant_Element ); else if(tipo_busca == "BR") auto result = binary_rec( A, A+quant_Element, valor, A+quant_Element ); else if(tipo_busca == "TI") auto result = ternSearch( A, A+quant_Element, valor, A+quant_Element ); else if(tipo_busca == "TR") auto result = tern_rec( A, A+quant_Element, valor, A+quant_Element ); else if(tipo_busca == "JS") auto result = jump_search( A, A+quant_Element, valor, A+quant_Element ); else auto result = linearSearch( A, A+quant_Element, valor, A+quant_Element ); auto end = std::chrono::system_clock::now(); int waste_time = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); media += (waste_time - media) / rep; } //Insere os dados no arquivo. FILE << std::fixed << std::setprecision(cabecalho[0].size()) << std::setw(cabecalho[0].size()) << quant_Element << ", "; FILE << " " << std::fixed << std::setprecision(cabecalho[1].size()) << std::setw(cabecalho[1].size()) << media << " "; FILE << std::endl; // Adiciona mais elementos no vetor. quant_Element += media_inicial; } FILE.close(); } return 0; }
c0175c2727010d83a634a2123fbe7c086854c7c3
b5a59d30d57ae5530c16c3d09e1141e1a72e6f82
/ir_tst/ir_tst.ino
b50dd3fb036507fbbea785919b66fb45ecc872d2
[]
no_license
ammanvedi/Autonomous-Bot
eb3dda1af724aaaa2e4f396eea63dcd7a4f64697
1ce2867e6eb71f4e725882bc054f0e045114b7ca
refs/heads/master
2016-09-06T12:49:30.904355
2014-02-13T16:04:29
2014-02-13T16:04:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,577
ino
ir_tst.ino
#include <DistanceGP2Y0A21YK.h> DistanceGP2Y0A21YK Dist; int distance; int led1 = A0; int led2 = A3; int led3 = A5; void setup() { Serial.begin(9600); Dist.begin(A4); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); //Setup Channel A pinMode(12, OUTPUT); //Initiates Motor Channel A pin pinMode(9, OUTPUT); //Initiates Brake Channel A pin //Setup Channel B pinMode(13, OUTPUT); //Initiates Motor Channel A pin pinMode(8, OUTPUT); //Initiates Brake Channel A pin } void loop() { //Motor A forward @ full speed digitalWrite(12, HIGH); //Establishes forward direction of Channel A digitalWrite(9, LOW); //Disengage the Brake for Channel A analogWrite(3, 255); //Spins the motor on Channel A at full speed //Motor B backward @ half speed digitalWrite(13, HIGH); //Establishes backward direction of Channel B digitalWrite(8, LOW); //Disengage the Brake for Channel B analogWrite(11, 255); //Spins the motor on Channel B at half speed distance = Dist.getDistanceCentimeter(); Serial.print("\nDistance in centimers: "); Serial.print(distance); if(distance > 10){ digitalWrite(led1, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); } else{ if(distance > 5 && distance < 10) { digitalWrite(led2, LOW); digitalWrite(led1, LOW); digitalWrite(led3, HIGH); }else{ digitalWrite(led2, HIGH); digitalWrite(led1, LOW); digitalWrite(led3, LOW); } } delay(500); //make it readable }
e2dd1dcbf32357b89c95561736f74b7310073107
d28d31a687f653bf033892e8c84b55d61882741a
/workshops/valdiviezod/unit1/WS01ProgramingFundamentals/ProgrammingFundamentals.cpp
83fd9f47750f69d3444970e216536529df070d43
[]
no_license
elascano/ESPE202105-OOP-SW-3682
02debcbd73540438ac39e04eb5ed2c4c99c72eb0
6198fb3b90faeee6ea502f3eb80532a67cf5739f
refs/heads/main
2023-08-29T12:30:09.487090
2021-09-20T14:40:03
2021-09-20T14:40:03
369,223,490
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
ProgrammingFundamentals.cpp
#include<iostream> #include<conio.h> using namespace std; void data(); int sum(int h[5],int); int h[5],len; int average(int h[5],int); int sear(); int main(){ system ("color F0"); cout<<"-----Welcome to my program-----"<<endl<<endl; data(); cout<<"The sum of the numbers is: "<<sum(h,len)<<endl<<endl; cout<<"The average of the numbers is: "<<average(h,len)<<endl<<endl; sear(); cout<<" "<<endl; cout<<"Thanks for using the program..."<<endl; getch(); return 0; } void data(){ cout<<"Choose 5 or 3 depending on the number of elements you want: "; cin>>len; for(int i=0;i<len;i++){ cout<<i+1<<". Enter a number: "; cin>>h[i]; } } int sum(int h[],int len){ int sum=0; int i; for(i=0;i<len;i++){ sum+=h[i]; } return sum; } int average(int h[],int len){ int average=0; int sum=0; int i; for(i=0;i<len;i++){ sum+=h[i]; average=sum/len; } return average; } int sear(){ int a[]={12,23,34,65,87,98,0}; int i,dat; char band = 'F'; dat=h[i]; i=0; while((band =='F')&&(i<len)){ if(a[i]==dat){ band='V'; } i++; } if(band=='F'){ cout<<"The number that was searched does not exist"<<endl; } else if (band == 'V'){ cout<<"The number was found"<<endl; } }
2dc08c4ce0f168004d8cc2cd0f7a7e9ffef72bfc
be2a632b4c514318742ec6a2cbb40bbfa0a98aa6
/questao1-teobaldo-master/include/roupa.h
fb8d4046b5da45fbcafa99c5567a6fc89487082b
[]
no_license
joicyoliv/LP-Laboratorio3
cc45183f4df6ff807658ed4a1396ef4b40f649c2
19c13b46bd0fc6bcb32c00f0cf5ca71009881461
refs/heads/master
2020-03-17T10:40:21.265742
2018-05-15T16:33:05
2018-05-15T16:33:05
133,514,926
0
0
null
null
null
null
UTF-8
C++
false
false
1,736
h
roupa.h
/** * @file roupa.h * @brief Arquivo cabecalho com as definições dos métodos da classe roupa derivada da classe produto * * @author Joicy Oliveira * @since 11/05/2018 * @date 13/05/2018 */ #ifndef ROUPA_H #define ROUPA_H #include "produto.h" /** * @class Roupa derivada de Produto */ class Roupa : public Produto { public: /** * @brief Construtor padrão */ Roupa(); /** * @brief Construtor paramatrizado * @param _codigo Código de barras da Roupa * @param _descricao Descrição da Roupa * @param _preco Preço da Roupa * @param _marca Marca da Roupa * @param _sexo Sexo da Roupa * @param _tamanho Tamanho da Roupa */ Roupa(std::string _codigo, std::string _descricao, short _preco, std::string _marca, char _sexo, std::string _tamanho); /** * @brief Destrutor padrão */ ~Roupa(); private: std::string m_marca; char m_sexo; std::string m_tamanho; public: /** * @brief Função que extrai a marca da Roupa * @return Marca da Roupa */ std::string getMarca(); /** * @brief Função que extrai o sexo da Roupa * @return Sexo da Roupa */ char getSexo(); /** * @brief Função que extrai o tamanho da Roupa * @return Tamanho da Roupa */ std::string getTamanho(); /** * @brief Altera a marca da Roupa * @param _marca Marca da Roupa * @return Não retorna valor */ void setMarca(std::string _marca); /** * @brief Altera o sexo da Roupa * @param _sexo Sexo da Roupa * @return Não retorna valor */ void setSexo(char _sexo); /** * @brief Altera o tamanho da Roupa * @param _tamanho Tamanho da Roupa * @return Não retorna valor */ void setTamanho(std::string _tamanho); private: std::ostream& print(std::ostream &o) const; }; #endif
16cc803d8ac00175f95b0c6f821b9629290d5455
964c99be141f47493862ee9a3b2ea63da7e138a0
/third-party/loki-lib/loki/Allocator.h
02ece5ea63ae3e2247fc1172a2eb73c3c76f6b74
[ "BSL-1.0" ]
permissive
rpavlik/util-headers
a9b66f8114849a07dce6bf168d781f07ef86020b
1a8444782d15cb9458052e3d8251c4f5b8e808d5
refs/heads/main
2022-03-13T07:13:49.607510
2022-03-11T18:11:32
2022-03-11T18:11:32
26,022,592
3
1
null
null
null
null
UTF-8
C++
false
false
5,104
h
Allocator.h
//////////////////////////////////////////////////////////////////////////////// // The Loki Library // Copyright (c) 2008 by Rich Sposato // // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // The author makes no representations about the // suitability of this software for any purpose. It is provided "as is" // without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// #ifndef LOKI_ALLOCATOR_HPP_INCLUDED #define LOKI_ALLOCATOR_HPP_INCLUDED // $Id$ // Requires project to be compiled with loki/src/SmallObj.cpp and loki/src/Singleton.cpp #include <loki/SmallObj.h> namespace Loki { //----------------------------------------------------------------------------- /** @class LokiAllocator Adapts Loki's Small-Object Allocator for STL container classes. This class provides all the functionality required for STL allocators, but uses Loki's Small-Object Allocator to perform actual memory operations. Implementation comes from a post in Loki forums (by Rasmus Ekman?). */ template < typename Type, typename AllocT = Loki::AllocatorSingleton<> > class LokiAllocator { public: typedef ::std::size_t size_type; typedef ::std::ptrdiff_t difference_type; typedef Type * pointer; typedef const Type * const_pointer; typedef Type & reference; typedef const Type & const_reference; typedef Type value_type; /// Default constructor does nothing. inline LokiAllocator( void ) throw() { } /// Copy constructor does nothing. inline LokiAllocator( const LokiAllocator & ) throw() { } /// Type converting allocator constructor does nothing. template < typename Type1 > inline LokiAllocator( const LokiAllocator< Type1 > & ) throw() { } /// Destructor does nothing. inline ~LokiAllocator() throw() { } /// Convert an allocator<Type> to an allocator <Type1>. template < typename Type1 > struct rebind { typedef LokiAllocator< Type1 > other; }; /// Return address of reference to mutable element. pointer address( reference elem ) const { return &elem; } /// Return address of reference to const element. const_pointer address( const_reference elem ) const { return &elem; } /** Allocate an array of count elements. Warning! The true parameter in the call to Allocate means this function can throw exceptions. This is better than not throwing, and returning a null pointer in case the caller assumes the return value is not null. @param count # of elements in array. @param hint Place where caller thinks allocation should occur. @return Pointer to block of memory. */ pointer allocate( size_type count, const void * hint = 0 ) { (void)hint; // Ignore the hint. void * p = AllocT::Instance().Allocate( count * sizeof( Type ), true ); return reinterpret_cast< pointer >( p ); } /// Ask allocator to release memory at pointer with size bytes. void deallocate( pointer p, size_type size ) { AllocT::Instance().Deallocate( p, size * sizeof( Type ) ); } /// Calculate max # of elements allocator can handle. size_type max_size( void ) const throw() { // A good optimizer will see these calculations always produce the same // value and optimize this function away completely. const size_type max_bytes = size_type( -1 ); const size_type bytes = max_bytes / sizeof( Type ); return bytes; } /// Construct an element at the pointer. void construct( pointer p, const Type & value ) { // A call to global placement new forces a call to copy constructor. ::new( p ) Type( value ); } /// Destruct the object at pointer. void destroy( pointer p ) { // If the Type has no destructor, then some compilers complain about // an unreferenced parameter, so use the void cast trick to prevent // spurious warnings. (void)p; p->~Type(); } }; //----------------------------------------------------------------------------- /** All equality operators return true since LokiAllocator is basically a monostate design pattern, so all instances of it are identical. */ template < typename Type > inline bool operator == ( const LokiAllocator< Type > &, const LokiAllocator< Type > & ) { return true; } /** All inequality operators return false since LokiAllocator is basically a monostate design pattern, so all instances of it are identical. */ template < typename Type > inline bool operator != ( const LokiAllocator< Type > & , const LokiAllocator< Type > & ) { return false; } //----------------------------------------------------------------------------- } // namespace Loki #endif // LOKI_ALLOCATOR_INCLUDED
7ef2c380adba81d141665e6fa070d76440c8f28e
ea8cccb7e8b88d4050db16463c971c8df0380a3e
/Color.cpp
5d87aa11b6b9e4352d765ce4bf96eace7c3ed7fc
[ "MIT" ]
permissive
FourChar/Ando
9bcbe9dbf99fc6dbb1b1d0ed233859b7112a3640
e391f547bd0d0d0dc71f5fccb6ed7287bfc6d92e
refs/heads/master
2021-01-17T12:56:01.199566
2017-06-30T06:05:30
2017-06-30T06:05:30
84,074,930
2
2
null
null
null
null
UTF-8
C++
false
false
4,221
cpp
Color.cpp
#include "Color.hpp" namespace ando { Color::Color() { this->uColor[0] = this->uColor[1] = this->uColor[2] = this->uColor[3] = 0; } Color::Color(const Color &col) { for (int i = 0; i < 4; i++) this->uColor[i] = col.uColor[i]; } Color::Color(uint8_t uColor[4]) { for(int i = 0; i < 4; i++) this->uColor[i] = uColor[i]; } Color::Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { this->setR(r); this->setG(g); this->setB(b); this->setA(a); } Color::Color(unsigned long hex) { this->set(hex); } int Color::operator [](int index) { if((index < 0) || (index > 3)) { return -1; } return this->uColor[index]; } Color Color::operator =(const Color &rhs) { for (int i = 0; i < 4; i++) { this->uColor[i] = rhs.uColor[i]; } return (*this); } bool Color::operator ==(const Color &rhs) { return ( (this->r() == rhs.r()) && (this->g() == rhs.g()) && (this->b() == rhs.b()) && (this->a() == rhs.a()) ); } bool Color::operator !=(const Color &rhs) { return ( (this->r() != rhs.r()) || (this->g() != rhs.g()) || (this->b() != rhs.b()) || (this->a() != rhs.a()) ); } uint8_t Color::r() const { return this->uColor[0]; } uint8_t Color::g() const { return this->uColor[1]; } uint8_t Color::b() const { return this->uColor[2]; } uint8_t Color::a() const { return this->uColor[3]; } unsigned long Color::rgba() const { unsigned long hexColor = ((unsigned long)this->uColor[3] << 24); hexColor |= ((unsigned long)this->uColor[0] << 16); hexColor |= ((unsigned long)this->uColor[1] << 8); hexColor |= ((unsigned long)this->uColor[2]); return hexColor; } unsigned long Color::rgb() const { unsigned long hexColor = ((unsigned long)this->uColor[0] << 16); hexColor |= ((unsigned long)this->uColor[1] << 8); hexColor |= ((unsigned long)this->uColor[2]); return hexColor; } Color &Color::setR(uint8_t r) { this->uColor[0] = r; return (*this); } Color &Color::setG(uint8_t g) { this->uColor[1] = g; return (*this); } Color &Color::setB(uint8_t b) { this->uColor[2] = b; return (*this); } Color &Color::setA(uint8_t a) { this->uColor[3] = a; return (*this); } Color &Color::set(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { this->setR(r); this->setG(g); this->setB(b); this->setA(a); return (*this); } Color &Color::set(unsigned long hex) { this->uColor[0] = (uint8_t)((hex >> 16) & 0xFF); this->uColor[1] = (uint8_t)((hex >> 8) & 0xFF); this->uColor[3] = (uint8_t)((hex >> 24) & 0xFF); this->uColor[2] = (uint8_t)(hex & 0xFF); return (*this); } namespace colors { Color invisible(0, 0, 0, 0); Color black(0, 0, 0); Color white(255, 255, 255); Color red(255, 0, 0); Color green(0, 255, 0); Color blue(0, 0, 255); namespace reds { Color vanillaIce(242, 215, 213); Color shilo(230, 176, 170); Color newYorkPink(217, 136, 128); Color chestnutRose(205, 97, 85); Color tallPoppy(192, 57, 43); Color mexicanRed(169, 50, 38); Color oldBrick(146, 43, 33); Color mocha(123, 36, 28); Color cherrywood(100, 30, 22); Color azalea(250, 219, 216); Color mandysPink(245, 183, 177); Color apricot(241, 148, 138); Color burntSienna(236, 112, 99); Color cinnabar(231, 76, 60); Color flushMahogany(203, 67, 53); Color burntUmber(148, 49, 38); Color metalicCopper(120, 40, 31); } namespace purples { Color prelude(215, 189, 226); Color lightWisteria(195, 155, 211); Color eastSide(175, 122, 197); Color wisteria(155, 89, 182); Color affair(136, 78, 160); Color bossanova(81, 46, 95); } namespace blues { Color regentStBlue(169, 204, 227); Color halfBaked(127, 179, 213); Color danube(84, 153, 199); Color mariner(41, 128, 185); Color jellyBean(36, 113, 163); Color matisse(31, 97, 141); Color blumine(26, 82, 118); Color biscay(21, 67, 96); Color blizzardBlue(174, 214, 241); Color seagull(133, 193, 233); Color pictonBlue(93, 173, 226); Color curiousBlue(52, 152, 219); } } }
17f3cc8fe3dcd88161115f843c4bea1abab3d0b0
4eafb81121efac1ee76d03e01d19bf0b6ad0378f
/ooSockets/src/OProperties.hpp
190b34414183e0774c5c88c79dd75efb6763b815
[ "MIT" ]
permissive
yuckify/uav_vision
c14c760a9e2681aeffe7afee9fa31041e506b1f0
dce7f096b82c5295aa97c911238501f184c4940e
refs/heads/master
2020-05-18T15:40:07.141407
2011-06-07T19:26:54
2011-06-07T19:26:54
1,391,221
3
0
null
null
null
null
UTF-8
C++
false
false
5,599
hpp
OProperties.hpp
/* Copyright (c) 2010 Michael F. Varga * Email: michael@engineerutopia.com * Website: engineerutopia.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef PROPERTIES_H #define PROPERTIES_H #include<map> #include<fstream> #include<algorithm> #include<typeinfo> #include<string> #include<stdint.h> #include<OString.hpp> using namespace std; /** This is a simple relational configuration file parser. It parses files of * the format <key>=<value>. * \code * some.key=123 * another.key=test * \endcode * This class contains functions to perform automatic lexical casting for ease * of converting between integers and text. * \code * OProperties prop; * prop.open("test.config"); * int num = prop.get<int>("some.key"); * OString str = prop.get<OString>("another.key"); * \endcode */ class OProperties { public: /// Make an empty relational map. OProperties(); /// Initialize the relational map with some text contained in a file. OProperties(OString fn); /// Returns true if the relational map does not contain any values. bool isEmpty() const; /** Open a configuration file containing the sime relational text format. * @param fn The name of the file to be opened. * @return false is returned if the file is not found. */ bool open(OString fn); /** Save the configuration file using the simple relational text file format. * @param fn The name of the file to be saved. */ void save(OString fn); OString filename() const; /// Pass the configuration file to OProperties through a OString. void setText(OString text); /// Get the value for the specified 'key' as a OString. OString get(OString key) const; /// Get the value for the specified 'key' as a OString. OString getOString(OString key) const; /// Get the value for the specified 'key' as an int. int getInt(OString key) const; /// Get the value for the specified 'key' as a float. float getFloat(OString key) const; /// Get the value for the specified 'key' as a double. double getDouble(OString key) const; /// Get the value for the specified 'key' as a desired datatype. /// Valid datatypes for T are int, unsigned int, long, unsigned long and double. template<class T> T get(OString key) const { map<OString, OString>::const_iterator it = values.find(key); T block; if(it == values.end()) return nullType(block); return it->second.as<T>(); } /** Insert a key pair, if key does not already exist. Otherwise the value * for the key will be overwritten. * @param key The reference key value to be * @param val The value to assign the key. */ template<class T> void set(OString key, T val) { values[key] = val; } /** Return a reference to the value for the key in the relational map. */ OString& operator[](OString key); /// Get the associate map containing the properties. map<OString, OString> getMap() const; /// Set the associative map containing the properties. void setMap(map<OString, OString> vals); protected: std::map<OString, OString> values; OString v_fn; #ifdef __windows__ int8_t nullType(int8_t select) const { return 0; } uint8_t nullType(uint8_t select) const { return 0; } int16_t nullType(int16_t select) const { return 0; } uint16_t nullType(uint16_t select) const { return 0; } int32_t nullType(int32_t select) const { return 0; } uint32_t nullType(uint32_t select) const { return 0; } int64_t nullType(int64_t select) const { return 0; } uint64_t nullType(uint64_t select) const { return 0; } float nullType(float select) const { return 0; } double nullType(double select) const { return 0; } OString nullType(OString select) const { return ""; } #else int8_t nullType(int8_t select __attribute__((unused))) const { return 0; } uint8_t nullType(uint8_t select __attribute__((unused))) const { return 0; } int16_t nullType(int16_t select __attribute__((unused))) const { return 0; } uint16_t nullType(uint16_t select __attribute__((unused))) const { return 0; } int32_t nullType(int32_t select __attribute__((unused))) const { return 0; } uint32_t nullType(uint32_t select __attribute__((unused))) const { return 0; } int64_t nullType(int64_t select __attribute__((unused))) const { return 0; } uint64_t nullType(uint64_t select __attribute__((unused))) const { return 0; } float nullType(float select __attribute__((unused))) const { return 0; } double nullType(double select __attribute__((unused))) const { return 0; } OString nullType(OString select __attribute__((unused))) const { return ""; } #endif }; #endif // OProperties_H
5db08111d2b0aba662fb5a4f1206ab0a75bebd45
d04a93f31f9567b21872df686349ace0beb8c871
/rpuk-master/RPUK.Altis/config_files/CfgAtms.hpp
20eea8b83006bc85d26b16b327569cb9b1cc52d2
[]
no_license
SYNCO-ArmA3/rpuk-master
3e1bbcec27c910d10bf5374fe0635e718b542fe9
e2c47374cb4d68d074a4d1892dba2a2daf39e538
refs/heads/master
2021-06-10T20:22:56.515205
2016-12-31T01:13:11
2016-12-31T01:13:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
hpp
CfgAtms.hpp
/* * @File: CfgAtms.hpp * @Author: Ciaran "Ciaran" Langton <email@ciaranlangton.com> * * Copyright (C) Ciaran Langton 2016 - All Rights Reserved - https://www.roleplay.co.uk * Unauthorized copying of this file, via any medium is strictly prohibited * without the express permission of Ciaran "Ciaran" Langton <email@ciaranlangton.com> */ class CfgAtms { Altis[] = { { 10655.9, 12201.3, 2.88205 }, { 11008.4, 13474.7, 2.66546 }, { 11726.2, 13756.5, 2.85373 }, { 9018.87, 12029.3, 2.85653 }, { 12662.9, 14265.5, 2.80613 }, { 12589.4, 14374.4, 2.86208 }, { 14901.8, 11061, 2.67068 }, { 12415.7, 15561.3, 2.90657 }, { 9297.11, 15871, 2.66547 }, { 16702.7, 12511.1, 2.90164 }, { 16774.8, 12594.6, 2.65998 }, { 16816.7, 12579.4, 2.85289 }, { 7406.35, 15411, 2.66528 }, { 16889.7, 12670.5, 2.83506 }, { 16886.1, 12808, 2.89816 }, { 6800.42, 15588.9, 2.66545 }, { 14610.1, 16819.7, 2.81153 }, { 5077.96, 11264.2, 2.71861 }, { 17431.6, 13948.1, 2.87235 }, { 7081.58, 16402.5, 2.66444 }, { 15881.5, 16294.8, 2.30835 }, { 16660, 16099.6, 2.90162 }, { 14913.1, 17619.6, 2.8061 }, { 4181.9, 11785.4, 2.88862 }, { 4533.39, 14037.3, 2.66576 }, { 8626.68, 18265.1, 2.89558 }, { 3799.2, 11093.6, 2.69454 }, { 13980.5, 18634.7, 2.82122 }, { 16453.4, 17221.1, 2.87343 }, { 3701.12, 11801.5, 2.8855 }, { 10304.8, 19075.9, 2.79991 }, { 18102.5, 15263.6, 2.79621 }, { 3697.72, 12254.6, 2.87035 }, { 14007, 18780, 2.8167 }, { 3715.01, 13030.8, 2.87786 }, { 3925.02, 13854.2, 2.85503 }, { 3698.84, 13199.2, 2.81741 }, { 3777.4, 13517.8, 2.66583 }, { 3574.93, 12800.7, 2.84913 }, { 4920.61, 16156.4, 2.67682 }, { 3497.09, 13000.5, 2.86744 }, { 19306.5, 13232.1, 2.64901 }, { 3416.05, 13279.2, 2.66927 }, { 3593.64, 13994.7, 2.67751 }, { 3282, 12963.6, 2.93144 }, { 20191.7, 11732.4, 2.91162 }, { 20303.8, 11698.2, 2.98509 }, { 18779.9, 16633.7, 2.81273 }, { 9434.56, 20286.3, 2.87016 }, { 20475.7, 8886.04, 2.82895 }, { 3739.72, 17656.5, 2.6513 }, { 14616.6, 20810.3, 2.66513 }, { 20778.6, 6802.16, 2.86446 }, { 20936.4, 16846.1, 2.78828 }, { 21263.6, 16314.5, 2.76996 }, { 20937.5, 16964.4, 2.79526 }, { 25618.6, 21353.5, 2.9203 }, { 27030.1, 23282.8, 2.78083 } }; };
6b2f8412987286bc0b8ce329f011056c677c861a
47267247675fb109e262a8497ad8cdb880628eb3
/leetcode/alibaba.cpp
f9416fdaf09d3f54a274ceb7a1ce66555d8e6e16
[]
no_license
bkyileo/algorithm-practice
2aa461f6142fe92b2619f31643ee470f901e320a
616e4db3f4f0004288441805572c186ef64541d8
refs/heads/master
2021-01-21T21:00:44.011317
2017-11-02T02:20:12
2017-11-02T02:20:12
92,297,914
1
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
alibaba.cpp
#include<bits/stdc++.h> using namespace std; int main() { return 0; } vector<int> target; bool dfs(BinTree* root,int i) { if(!root)return false; if(i==target.size()&&!root->l&&!root->r)return true; if(root->v==target[i]) { if(dfs(root->l,i+1))return true; if(dfs(root->r,i+1))return true; return false; } else { return false; } } bool IsBranch(BinTree* root, int nodeList[],int nodeListSize) { target.clear(); for(int i=0;i<nodeListSize;++i)target.push_back(nodeList[i]); return dfs(root,0); }
892980741aa9f14dc286b5ba2560d2261bd8aa86
2cae54fe441ad0e84b8df6917153bbe3c81ae986
/4thought/4thought.cpp
92eb615fc460fa6cb9569e328605aef14b77bdce
[ "MIT" ]
permissive
omarchehab98/open.kattis.com-problems
3cb08a475ca4fb156462904a221362b98c2813c9
0523e2e641151dad719ef05cc9811a8ef5c6a278
refs/heads/master
2020-03-31T04:23:06.415280
2019-10-29T00:50:08
2019-10-29T00:50:08
151,903,075
1
0
null
null
null
null
UTF-8
C++
false
false
1,405
cpp
4thought.cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int eval(int o, int a, int b) { switch (o) { case 0: return a * b; case 1: return a / b; case 2: return a + b; case 3: return a - b; } return 0; } void solve(int n) { vector<char> operators = {'*','/','+','-'}; for (int c = 0; c < 4; c++) { for (int b = 0; b < 4; b++) { for (int a = 0; a < 4; a++) { vector<int> ops = {a,b,c}; vector<int> nums = {4,4,4,4}; int ans = 0; for (int i = 0; i < ops.size(); i++) { if (ops[i] >= 2) { continue; } nums[i] = eval(ops[i],nums[i],nums[i + 1]); ops.erase(ops.begin() + i); nums.erase(nums.begin() + i + 1); i--; } for (int i = 0; i < ops.size(); i++) { nums[i] = eval(ops[i],nums[i],nums[i + 1]); ops.erase(ops.begin() + i); nums.erase(nums.begin() + i + 1); i--; } if (nums[0] == n) { cout << "4 " << operators[a] << " 4 " << operators[b] << " 4 " << operators[c] << " 4 = " << nums[0] << endl; return; } } } } cout << "no solution" << endl; return; } int main() { int numberOfTests, m; cin >> numberOfTests; for (m = 0; m < numberOfTests; m++) { int n; cin >> n; solve(n); } }
212911779210ca7a7addb5be98316fcb13fda45d
c7c73566784a7896100e993606e1bd8fdd0ea94e
/pandatool/src/lwo/iffInputFile.cxx
f00dbf546935e30cac5cdd4179f29db1f3dacbdd
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
panda3d/panda3d
c3f94df2206ff7cfe4a3b370777a56fb11a07926
160ba090a5e80068f61f34fc3d6f49dbb6ad52c5
refs/heads/master
2023-08-21T13:23:16.904756
2021-04-11T22:55:33
2023-08-06T06:09:32
13,212,165
4,417
1,072
NOASSERTION
2023-09-09T19:26:14
2013-09-30T10:20:25
C++
UTF-8
C++
false
false
7,789
cxx
iffInputFile.cxx
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file iffInputFile.cxx * @author drose * @date 2001-04-24 */ #include "iffInputFile.h" #include "iffGenericChunk.h" #include "datagram.h" #include "datagramIterator.h" #include "virtualFileSystem.h" TypeHandle IffInputFile::_type_handle; /** * */ IffInputFile:: IffInputFile() { _input = nullptr; _owns_istream = false; _eof = true; _unexpected_eof = false; _bytes_read = 0; } /** * */ IffInputFile:: ~IffInputFile() { if (_owns_istream) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_input); } } /** * Attempts to open the indicated filename for reading. Returns true if * successful, false otherwise. */ bool IffInputFile:: open_read(Filename filename) { filename.set_binary(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); std::istream *in = vfs->open_read_file(filename, true); if (in == nullptr) { return false; } set_input(in, true); set_filename(filename); return true; } /** * Sets up the input to use an arbitrary istream. If owns_istream is true, * the istream will be deleted (via vfs->close_read_file()) when the * IffInputFile destructs. */ void IffInputFile:: set_input(std::istream *input, bool owns_istream) { if (_owns_istream) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_input); } _input = input; _owns_istream = owns_istream; _eof = false; _unexpected_eof = false; _bytes_read = 0; } /** * Extracts a signed 8-bit integer. */ int8_t IffInputFile:: get_int8() { Datagram dg; if (!read_bytes(dg, 1)) { return 0; } DatagramIterator dgi(dg); return dgi.get_int8(); } /** * Extracts an unsigned 8-bit integer. */ uint8_t IffInputFile:: get_uint8() { Datagram dg; if (!read_bytes(dg, 1)) { return 0; } DatagramIterator dgi(dg); return dgi.get_int8(); } /** * Extracts a signed 16-bit big-endian integer. */ int16_t IffInputFile:: get_be_int16() { Datagram dg; if (!read_bytes(dg, 2)) { return 0; } DatagramIterator dgi(dg); return dgi.get_be_int16(); } /** * Extracts a signed 32-bit big-endian integer. */ int32_t IffInputFile:: get_be_int32() { Datagram dg; if (!read_bytes(dg, 4)) { return 0; } DatagramIterator dgi(dg); return dgi.get_be_int32(); } /** * Extracts an unsigned 16-bit big-endian integer. */ uint16_t IffInputFile:: get_be_uint16() { Datagram dg; if (!read_bytes(dg, 2)) { return 0; } DatagramIterator dgi(dg); return dgi.get_be_uint16(); } /** * Extracts an unsigned 32-bit big-endian integer. */ uint32_t IffInputFile:: get_be_uint32() { Datagram dg; if (!read_bytes(dg, 4)) { return 0; } DatagramIterator dgi(dg); return dgi.get_be_uint32(); } /** * Extracts a 32-bit big-endian single-precision floating-point number. */ PN_stdfloat IffInputFile:: get_be_float32() { Datagram dg; if (!read_bytes(dg, 4)) { return 0; } DatagramIterator dgi(dg); return dgi.get_be_float32(); } /** * Extracts a null-terminated string. */ std::string IffInputFile:: get_string() { std::string result; char byte; while (read_byte(byte)) { if (byte == 0) { break; } result += byte; } align(); return result; } /** * Extracts a 4-character IFF ID. */ IffId IffInputFile:: get_id() { Datagram dg; if (!read_bytes(dg, 4)) { return IffId(); } const char *id = (const char *)dg.get_data(); return IffId(id); } /** * Reads a single IffChunk, determining its type based on its ID. Allocates * and returns a new IffChunk object of the appropriate type. Returns NULL if * EOF is reached before the chunk can be read completely, or if there is some * other error in reading the chunk. */ PT(IffChunk) IffInputFile:: get_chunk() { if (is_eof()) { return nullptr; } IffId id = get_id(); uint32_t length = get_be_uint32(); if (!is_eof()) { PT(IffChunk) chunk = make_new_chunk(id); chunk->set_id(id); size_t start_point = get_bytes_read(); size_t end_point = start_point + length; if (chunk->read_iff(this, end_point)) { if (is_eof()) { if (!_unexpected_eof) { nout << "Unexpected EOF on file reading " << *chunk << "\n"; _unexpected_eof = true; } return nullptr; } size_t num_bytes_read = get_bytes_read() - start_point; if (num_bytes_read > length) { nout << *chunk << " read " << num_bytes_read << " instead of " << length << " bytes.\n"; return nullptr; } else if (num_bytes_read < length) { size_t skip_count = length - num_bytes_read; nout << "Ignoring " << skip_count << " bytes at the end of " << *chunk << "\n"; skip_bytes(skip_count); } return chunk; } } return nullptr; } /** * Similar to get_chunk(), except the chunk size is only a 16-bit number * instead of 32-bit, and it takes a context, which is the chunk in which this * chunk is encountered. The parent chunk may (or may not) decide what kind * of chunk is meant by the various id's encountered. */ PT(IffChunk) IffInputFile:: get_subchunk(IffChunk *context) { if (is_eof()) { return nullptr; } IffId id = get_id(); uint16_t length = get_be_uint16(); if (!is_eof()) { PT(IffChunk) chunk = context->make_new_chunk(this, id); chunk->set_id(id); size_t start_point = get_bytes_read(); size_t end_point = start_point + length; if (chunk->read_iff(this, end_point)) { if (is_eof()) { if (!_unexpected_eof) { nout << "Unexpected EOF on file reading " << *chunk << "\n"; _unexpected_eof = true; } return nullptr; } size_t num_bytes_read = get_bytes_read() - start_point; if (num_bytes_read > length) { nout << *chunk << " read " << num_bytes_read << " instead of " << length << " bytes.\n"; return nullptr; } else if (num_bytes_read < length) { size_t skip_count = length - num_bytes_read; nout << "Ignoring " << skip_count << " bytes at the end of " << *chunk << "\n"; skip_bytes(skip_count); } return chunk; } } return nullptr; } /** * Reads a single byte. Returns true if successful, false otherwise. */ bool IffInputFile:: read_byte(char &byte) { if (is_eof()) { return false; } _input->get(byte); _bytes_read++; _eof = _input->eof() || _input->fail(); return !is_eof(); } /** * Reads a series of bytes, and stores them in the indicated Datagram. * Returns true if successful, false otherwise. */ bool IffInputFile:: read_bytes(Datagram &datagram, int length) { if (is_eof()) { return false; } char *buffer = new char[length]; _input->read(buffer, length); _eof = (_input->gcount() != length); if (is_eof()) { return false; } _bytes_read += length; datagram = Datagram(buffer, length); delete[] buffer; return true; } /** * Reads a series of bytes, but does not store them. Returns true if * successful, false otherwise. */ bool IffInputFile:: skip_bytes(int length) { if (is_eof()) { return false; } char byte; while (length > 0 && !is_eof()) { read_byte(byte); length--; } return !is_eof(); } /** * Allocates and returns a new chunk of the appropriate type based on the * given ID. */ IffChunk *IffInputFile:: make_new_chunk(IffId) { return new IffGenericChunk; }
ce12d7a076583eb4b8cfbc823e8ec4260963c28a
182cd131f236d25fcc3fad4bbd95464e33c8b270
/primo.cc
7018a11a32e2b70634adb37d59cbf0cf61fd0d9d
[]
no_license
FisicaComputacionalI/20171024-clase-fegala
e648c48813b2df34b8662536d9da28b8826b8a6a
4db2a119582785b0d36b8e29cfec74ac44fab75f
refs/heads/master
2021-07-17T16:05:47.502000
2017-10-24T19:02:00
2017-10-24T19:02:00
108,166,935
0
0
null
null
null
null
UTF-8
C++
false
false
448
cc
primo.cc
//Programa para comprobar si un nùmero es primo #include <iostream> using namespace std; int main() { long N=12; long Flag=0; long divisor=0; cout<<"Inserte un nùmero "<<endl; cin>>N; for(long i=2; i<=N/2; i++) { if (N%i==0){ Flag=1; divisor=i; break;} } if(Flag==1){ cout<<"Tu nùmero no es primo " <<endl; cout<<"porque se divide entre " <<divisor <<endl; } else cout<<"Tu nùmero es primo " <<endl; return 0; }
80208c9a62b5e5046bfddd8918a303b853acef59
8239562e9d1620ae942db148f7a5775874fa1b55
/1953.cpp
c5568a2ac827d18cf39eece0e3c7e6fb3c2b8e09
[]
no_license
Higumabear/POJ
1510d3dde88c3595d869cbd88fb12e138411c0c2
e5d0823f00e5e1a0cc16b8652abb37ea823cb23a
refs/heads/master
2020-04-01T19:25:04.098270
2017-11-22T02:18:56
2017-11-22T02:18:56
16,761,319
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
1953.cpp
/* * 1953.cpp * * Last update: <05/16/2013 23:36:00> */ #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> #include <cstring> #define ALL(c) (c).begin(), (c).end() using namespace std; static const double EPS = 1e-8; static const int INF = 1 << 29; typedef long long ll; ll dp[300][2]; int main(){ int n; cin >> n; for(int k = 1; k <= n; k++){ memset(dp, 0, sizeof(dp)); dp[1][0] = 1, dp[1][1] = 1; int m; cin >> m; for(int i = 1; i < m; i++){ dp[i + 1][0] += (dp[i][1] + dp[i][0]); dp[i + 1][1] += dp[i][0]; } cout << "Scenario #" << k << ":" << endl; cout << dp[m][1] + dp[m][0] << endl; cout << endl; } return 0; }
f93b2db2f6d4b90998af5d25a7f89ccf8292afb5
acc3f19bd25c01b1e8c861ed6f0af09d1861caa6
/dialogs/FindDlg.h
a8bb0a4a18149ea22e73f5d1709df1fc80cb4d08
[]
no_license
nickgammon/mushclient
7da44c02f2ebaedd38273e0c1f67a8a155a1f137
5f1ca253cf6f44b65caeafd9f2ad7a4b87817c8e
refs/heads/master
2022-11-11T14:57:20.924735
2022-10-30T00:32:03
2022-10-30T00:32:03
481,654
152
94
null
2023-09-06T03:35:59
2010-01-21T03:28:51
C
UTF-8
C++
false
false
1,346
h
FindDlg.h
#if !defined(AFX_FINDDLG_H__84E45A73_B390_11D0_8EBA_00A0247B3BFD__INCLUDED_) #define AFX_FINDDLG_H__84E45A73_B390_11D0_8EBA_00A0247B3BFD__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // FindDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CFindDlg dialog class CFindDlg : public CDialog { // Construction public: CFindDlg(CStringList & strFindStringList, CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CFindDlg) enum { IDD = IDD_FIND }; CComboBox m_ctlFindText; BOOL m_bMatchCase; int m_bForwards; BOOL m_bRegexp; CString m_strFindText; //}}AFX_DATA CString m_strTitle; CStringList & m_strFindStringList; // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFindDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CFindDlg) virtual BOOL OnInitDialog(); afx_msg void OnRegexpHelp(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FINDDLG_H__84E45A73_B390_11D0_8EBA_00A0247B3BFD__INCLUDED_)
89687f0803387a98aebdd96b3ce5b3bd248a5844
71a86fcbfe4e10f7fcf7cd4537d5fd45b39a2146
/Solovev_Platonic_Solids/Solovev_Platonic_Solids/MatrixMethods.cpp
91026805b5c87253c282a973fa7a4617b2540556
[]
no_license
fr0ga/Platonic_solids
5e99893dc763cf3c86cc7fe66682116fc8419dbc
08ae85419701dc6983e82a02f0c8c67fc14cc035
refs/heads/master
2021-01-11T16:58:36.402153
2017-01-22T10:26:17
2017-01-22T10:26:17
79,710,492
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,586
cpp
MatrixMethods.cpp
using namespace System::Drawing; #include "math.h" // cos, sin // Студент: Соловьев Андрей // Группа: БПИ122(2) // Семинар 5: 3D моделирование тел вращения и платоновых тел // Дата: 23.10.2015 // Среда разработки: Visual Studio 2013 // Реализованы алгоритмы вращения, сдвига, масштабирования // и проецирования тел вращения и платоновых тел. class MatrixMethods { public: static void move(cli::array<array<double>^>^ a, cli::array<array<double>^>^ Pd, int dx, int dy, int dz, int col, int row) { Pd[3][0] = dx; Pd[3][1] = dy; Pd[3][2] = dz; MatrixMult(a, Pd, col, row); } public: static void scale(cli::array<array<double>^>^ a, cli::array<array<double>^>^ Ps, double p, double q, double r, double s, int col, int row) { Ps[0][0] = p; Ps[1][1] = q; Ps[2][2] = r; Ps[3][3] = s; MatrixMult(a, Ps, col, row); } public: static void rotateOX(cli::array<array<double>^>^ a, cli::array<array<double>^>^ R, double Phi, int col, int row) { R[0][0] = 1; R[1][1] = cos(Phi); R[1][2] = sin(Phi); R[2][1] = -sin(Phi); R[2][2] = cos(Phi); R[3][3] = 1; MatrixMult(a, R, col, row); } public: static void rotateOY(cli::array<array<double>^>^ a, cli::array<array<double>^>^ R, double Phi, int col, int row) { R[0][0] = cos(Phi); R[0][2] = -sin(Phi); R[1][1] = 1; R[2][0] = sin(Phi); R[2][2] = cos(Phi); R[3][3] = 1; MatrixMult(a, R, col, row); } public: static void rotateOZ(cli::array<array<double>^>^ a, cli::array<array<double>^>^ R, double Phi, int col, int row) { R[0][0] = cos(Phi); R[0][1] = sin(Phi); R[1][0] = -sin(Phi); R[1][1] = cos(Phi); R[2][2] = 1; R[3][3] = 1; MatrixMult(a, R, col, row); } public: static void centralProjection(cli::array<array<double>^>^ a, cli::array<array<double>^>^ Pz, double z0, int col, int row) { Pz[0][0] = 1.0; Pz[1][1] = 1.0; Pz[2][3] = -1.0 / z0; Pz[3][3] = 1.0; MatrixMult(a, Pz, col, row); } public: static void orthogonalProjection(cli::array<array<double>^>^ a, cli::array<array<double>^>^ Pz, int col, int row) { Pz[0][0] = 1.0; Pz[1][1] = 1.0; Pz[2][3] = 0.0; Pz[3][3] = 1.0; MatrixMult(a, Pz, col, row); } public: static void MatrixMult(cli::array<array<double>^>^ a, cli::array<array<double>^>^ b, int numCol, int numRow) { cli::array<array<double>^>^ R = gcnew cli::array<array<double>^>(numRow); for (int i = 0; i < numRow; i++) R[i] = gcnew cli::array<double>(4); for (int i = 0; i < numRow; i++) { for (int j = 0; j < 4; j++) { R[i][j] = 0.0; for (int k = 0; k < numCol; k++) { R[i][j] += a[i][k] * b[k][j]; } } } for (int i = 0; i < numRow; i++) { for (int j = 0; j < 4; j++) { a[i][j] = R[i][j]; } } } public: static void localRotateOX(cli::array<array<double>^>^ a, cli::array<array<double>^>^ R, double l, double m, double n, int col, int row) { double d = sqrt(m*m + n*n); R[0][0] = 1; R[1][1] = n*1.0/d; R[1][2] = m*1.0 / d; R[2][1] = -m*1.0 / d; R[2][2] = n*1.0 / d; R[3][3] = 1; MatrixMult(a, R, col, row); } public: static void localRotateOY(cli::array<array<double>^>^ a, cli::array<array<double>^>^ R, double l, double m, double n, int col, int row) { double d = sqrt(m*m + n*n); R[0][0] = l*1.0; R[0][2] = d*1.0; R[1][1] = 1; R[2][0] = -d*1.0; R[2][2] = l*1.0; R[3][3] = 1; MatrixMult(a, R, col, row); } };
a40bfeb63c169b0391ab19fb06a43a9a13bfe550
32f2e4051d32c2217f805036ab3ef7ac7cbe4625
/OpenGL/Helper.cpp
8f307e53a1e1d5761c16483ddc2b9b69b86bfe1b
[]
no_license
Haoasakura/PGTR_OpenGl_Bullet
f84879921681a544986f7cf4743f75c3e3f32d1c
a7a39f6ab70263f298a8718f71747c100d16d903
refs/heads/master
2020-03-23T07:16:56.473444
2018-07-17T09:23:36
2018-07-17T09:23:36
141,260,762
0
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
Helper.cpp
#include "Helper.h" glm::mat4 getSphereModelMatrix(btRigidBody* sphere) { float r = ((btSphereShape*)sphere->getCollisionShape())->getRadius(); btTransform t; sphere->getMotionState()->getWorldTransform(t); float mat[16]; glm::mat4 ret(1.0); t.getOpenGLMatrix(mat); ret = glm::scale(ret, glm::vec3(r, r, r)); ret = glm::make_mat4(mat) * ret; return ret; } glm::mat4 getPlaneModelMatrix(btRigidBody* plane) { btTransform t; plane->getMotionState()->getWorldTransform(t); float mat[16]; glm::mat4 ret(1.0); t.getOpenGLMatrix(mat); ret = glm::make_mat4(mat); return ret; } glm::mat4 getBoxModelMatrix(btRigidBody* box) { btVector3 extent = ((btBoxShape*)box->getCollisionShape())->getHalfExtentsWithMargin(); btTransform t; box->getMotionState()->getWorldTransform(t); float mat[16]; glm::mat4 ret(1.0); t.getOpenGLMatrix(mat); ret = glm::scale(ret, glm::vec3(extent.x(), extent.y(), extent.z())); ret = glm::make_mat4(mat) * ret; return ret; }
2cd4b1783b9e8ba733f067d8790bc3329f0d3ad9
eea72893d7360d41901705ee4237d7d2af33c492
/src/geoutil/g3read/testG3CallFile.cc
e824c3d02e4261c5d1c92e8fa7b8c982dfa52b8d
[]
no_license
lsilvamiguel/Coral.Efficiencies.r14327
5488fca306a55a7688d11b1979be528ac39fc433
37be8cc4e3e5869680af35b45f3d9a749f01e50a
refs/heads/master
2021-01-19T07:22:59.525828
2017-04-07T11:56:42
2017-04-07T11:56:42
87,541,002
0
0
null
null
null
null
UTF-8
C++
false
false
629
cc
testG3CallFile.cc
#if __GNUG__ >= 2 # pragma implementation #endif #include "CsInit.h" #include "CsG3CallFile.h" int main(int argc, char *argv[]){ CsInit* init = CsInit::Instance(argc, argv); CsRegistrySing *reg_ = CsRegistrySing::Instance(); std::cout << "Test program for G3call List file reader." << std::endl; CsG3CallFile* pG3callList = CsG3CallFile::Instance(); std::cout << (*pG3callList) << std::endl; std::cout << "DUMP DETECTOR STRUCUTUR" << std::endl; (*pG3callList).HALL().dumpDetectors( std::cout ); std::cout << std::endl; std::cout << "END TEST PROGRAM" << std::endl; reg_->callEndMethods(); exit(0); }
5d71a5841b4f4e41078c41939c5433cc3cc6c720
52f1bf1b1abf672227d71d6b96f24f3d66085259
/chapter06/is_palindrome_test.cc
cc95624cb280cf5b0106b7a94f8f9cd1b08a148f
[]
no_license
loganstone/accelerated-cpp
e7e4bf7830c3212af0ff6c4ee28f86a3568d6919
65d98fe909aceefce72e8c047d37a52b2125893b
refs/heads/master
2020-04-08T14:40:44.403175
2019-01-14T09:13:51
2019-01-14T09:13:51
159,447,169
0
0
null
null
null
null
UTF-8
C++
false
false
461
cc
is_palindrome_test.cc
// Copyright 2018, loganstone #include <iostream> #include <string> #include <vector> #include "is_palindrome.h" int main() { std::vector<std::string> v; v.push_back("civic"); v.push_back("eye"); v.push_back("level"); v.push_back("madam"); v.push_back("rotor"); v.push_back("loganstone"); // false for (std::vector<std::string>::iterator i = v.begin(); i != v.end(); ++i) { std::cout << IsPalindrome(*i) << std::endl; } return 0; }
5ebf7bd03809b3ef333e2a75897f02a1cb08f0e1
2609137765a5fb9a7646361e47d1c5f68440faa3
/src/CTA.convert_hessio_to_VDST.cpp
c50873e451fb1013e1ce4db52cc3863b970159a0
[ "BSD-3-Clause" ]
permissive
Eventdisplay/Eventdisplay
6133a1fcac44efb37baf25f6d91d337c1965fcd2
50e297561ddac0ca2db39e0391a672f2f275994b
refs/heads/main
2023-06-24T03:58:48.287734
2023-06-14T06:29:25
2023-06-14T06:29:25
221,222,023
15
3
BSD-3-Clause
2023-08-23T15:17:56
2019-11-12T13:17:01
C++
UTF-8
C++
false
false
107,687
cpp
CTA.convert_hessio_to_VDST.cpp
/** CTA.convert_hessio_to_VDST * short a program to convert sim_telarray files (hessio) to EVNDISP DST format * * * Author of skeleton (as part of the hessio distribution): Konrad Bernloehr * * Author of modifications for eventdisplay: Gernot Maier (DESY) */ #include "initial.h" #include "io_basic.h" #include "history.h" #include "io_hess.h" #include "fileopen.h" #ifdef CTA_PROD2_TRGMASK #include "io_trgmask.h" #endif #include <bitset> #include <iostream> #include <map> #include <set> #include <stdlib.h> #include <string> #include <vector> #include <TFile.h> #include <TList.h> #include <TMath.h> #include <TTree.h> #include <TStopwatch.h> #include "VGlobalRunParameter.h" #include "VEvndispRunParameter.h" #include "VDSTTree.h" #include "VMonteCarloRunHeader.h" #include "VAstronometry.h" /////////////////////////////////////////////////////// // global variables /////////////////////////////////////////////////////// // number of telescopes (checked) unsigned int fNTel_checked = 0; // maximum number of pixels for the current array configuration unsigned int fGlobalMaxNumberofPixels = 0; // maximum number of FADC samples for the current array configuration unsigned int fGlobalMaxNumberofSamples = 0; // maximum number of telescopes in previous event unsigned int fGlobalNTelPreviousEvent = 0; // set if this event does not pass the minimum number of telescope condition bool fGlobalTriggerReset = false; // map with telescope types (length of map is total number of telescopes) map< int, ULong64_t > fTelescopeType; // set with telescope types (length of map is total number of telescope types) set< ULong64_t > fTelescopeTypeList; // map wit simtel telescope IDs (ID, counter) map< unsigned int, unsigned int > fTelescopeSimTelList; #ifdef CTA_PROD2_TRGMASK // trigger mask hash set struct trgmask_hash_set* fTriggerMask_hash_set = 0; #endif // minimum number of photo electrons needed for trigger type 4 int fMinNumber_pe_per_telescope = 30; // fill leaf with photoelectrons bool fFillPELeaf = false; // fill leaf with peak ADC values bool fFillPeakADC = false; // additional pedestal shift (e.g. for ASTRI analysis) float fPedestalShift = 0.; // Minimum energy cut float fMinEnergy = 0.; // Maximum energy cut float fMaxEnergy = 1.e20; // use this for writing of telconfig tree only bool fWriteTelConfigTreeOnly = false; /////////////////////////////////////////////////////// /*! hard wired timing configuration for pulse characterization (time of 100%, 20%, 50%.. of max pulse height) Changes must also be made to getTimingLevelIndex() 1 1 0.2 2 0.5 2 0.8 2 0.5 4 0.2 4 -40 5 */ vector< float > getPulseTimingLevels() { vector< float > t; t.push_back( 0.2 ); t.push_back( 0.5 ); t.push_back( 1.0 ); t.push_back( 0.5 ); t.push_back( 0.2 ); return t; } unsigned int getTimingLevelIndex( unsigned int i ) { if( i == 0 ) { return 2; // 100% } else if( i == 1 ) { return 0; // 20% } else if( i == 2 ) { return 1; // 50% } else if( i == 4 ) { return 3; // 50% } else if( i == 5 ) { return 4; // 20% } return 9999; } /* * read plate scale stretching factor from external file * * given per telescope type * * usually a file called $CTA_EVNDISP_AUX_DIR//DetectorGeometry/...EffectiveFocalLength* * */ map< ULong64_t, float > readCameraScalingMap( string iFile ) { map< ULong64_t, float > iCameraScalingMap; ifstream is; is.open( iFile.c_str(), ifstream::in ); if( !is ) { cout << "readCameraScalingMap error: file not found, " << iFile << endl; return iCameraScalingMap; } string iLine; string iT1; cout << "reading camera scaling configuration from " << iFile << endl; while( getline( is, iLine ) ) { if( iLine.size() > 0 && iLine.substr( 0, 1 ) == "*" ) { istringstream is_stream( iLine ); is_stream >> iT1; if( !( is_stream >> std::ws ).eof() ) { is_stream >> iT1; ULong64_t teltype = atoi( iT1.c_str() ); if( !( is_stream >> std::ws ).eof() ) { is_stream >> iT1; iCameraScalingMap[teltype] = atof( iT1.c_str() ); cout << "\t camera scaling for telescope type " << teltype << " :\t"; cout << 1. + iCameraScalingMap[teltype] << endl; } } } } is.close(); return iCameraScalingMap; } /** The factor needed to transform from mean p.e. units to units of the single-p.e. peak: Depends on the collection efficiency, the asymmetry of the single p.e. amplitude distribution and the electronic noise added to the signals. */ #define CALIB_SCALE 0.92 /* * FLAG_AMP_TMP 0: Use normal integrated amplitude. * 1: Use integration around global peak position from * pulse shape analysis. May include all pixels or only selected. * 2: Use integration around local peak position from * pulse shape analysis. Return 0 for pixels without * a fairly significant peak. */ #define FLAG_AMP_TMP 0 /* ---------------------- calibrate_pixel_amplitude ----------------------- */ /** Calibrate a single pixel amplitude, for cameras with two gains per pixel. * * @return Pixel amplitude in peak p.e. units. */ float calibrate_pixel_amplitude( AllHessData* hsdata, int itel, int ipix, int dummy, unsigned int& iLowGain ); float calibrate_pixel_amplitude( AllHessData* hsdata, int itel, int ipix, int dummy, unsigned int& iLowGain ) { int i = ipix, npix, significant, hg_known, lg_known; double npe, sig_hg, npe_hg, sig_lg, npe_lg; AdcData* raw; if( hsdata == NULL || itel < 0 || itel >= H_MAX_TEL ) { return 0.; } npix = hsdata->camera_set[itel].num_pixels; if( ipix < 0 || ipix >= npix ) { return 0.; } raw = hsdata->event.teldata[itel].raw; if( raw == NULL ) { return 0.; } if( ! raw->known ) { return 0.; } significant = hsdata->event.teldata[itel].raw->significant[i]; hg_known = hsdata->event.teldata[itel].raw->adc_known[HI_GAIN][i]; sig_hg = hg_known ? ( hsdata->event.teldata[itel].raw->adc_sum[HI_GAIN][i] - hsdata->tel_moni[itel].pedestal[HI_GAIN][i] ) : 0.; npe_hg = sig_hg * hsdata->tel_lascal[itel].calib[HI_GAIN][i]; lg_known = hsdata->event.teldata[itel].raw->adc_known[LO_GAIN][i]; sig_lg = lg_known ? ( hsdata->event.teldata[itel].raw->adc_sum[LO_GAIN][i] - hsdata->tel_moni[itel].pedestal[LO_GAIN][i] ) : 0.; npe_lg = sig_lg * hsdata->tel_lascal[itel].calib[LO_GAIN][i]; iLowGain = false; if( !significant ) { npe = 0.; } else if( hg_known && sig_hg < 1000000 && sig_hg > -1000 ) { npe = npe_hg; } else { npe = npe_lg; iLowGain = true; } /* npe is in units of 'mean photo-electrons'. */ /* We convert to experimentalist's */ /* 'peak photo-electrons' now. */ return ( float )( TMath::Nint( CALIB_SCALE * npe ) * 100. ) / 100.; } #include <signal.h> void stop_signal_function( int isig ); static int interrupted; /* ---------------------- stop_signal_function -------------------- */ /** * Stop the program gracefully when it catches an INT or TERM signal. * * @param isig Signal number. * * @return (none) */ void stop_signal_function( int isig ) { if( isig >= 0 ) { fprintf( stderr, "Received signal %d\n", isig ); } if( !interrupted ) fprintf( stderr, "Program stop signal. Stand by until current data block is finished.\n" ); interrupted = 1; signal( SIGINT, SIG_DFL ); signal( SIGTERM, SIG_DFL ); } /** Show program syntax */ static void syntax( char* program ); static void syntax( char* program ) { printf( "Syntax: %s [ options ] [ - | input_fname ... ]\n", program ); printf( "Options:\n" ); printf( " -v (More verbose output)\n" ); printf( " -q (Much more quiet output)\n" ); printf( " -s (Show data explained)\n" ); printf( " -S (Show data explained, including raw data)\n" ); printf( " --history (-h) (Show contents of history data block)\n" ); printf( " -i (Ignore unknown data block types)\n" ); printf( " --max-events n (Skip remaining data after so many triggered events.)\n" ); printf( " -a subarray file (list of telescopes to read with FOV.)\n" ); printf( " -o dst filename (name of dst output file)\n" ); printf( " -f 0(QADC), 1(FADC), 2(MIXED) (write FADC samples to DST file;default=2)\n" ); printf( " -c pedfile.root (file with pedestals and pedestal variances)\n" ); printf( " -t <trgmask directory> (directory with trigger mask files (corrections for Spring 2013 prod2 production)\n" ); printf( " -r on=1/off=0 (apply camera plate scaling for DC telescopes; default=1)\n" ); printf( " -rfile camera scaling file (read camera place scales from a file; default=none)\n" ); printf( " -NSB <float> (scale pedvars by sqrt(...) of this value\n" ); printf( " -pe (fill leaf with photoelectrons into DST tree (default: off)\n" ); printf( " -peakadc (fill leaf with peakadc values into DST tree (default: off)\n" ); printf( " -pedshift float(dc) (apply additional pedestal shift to sum values (default: 0.; good value for ASTRI: 150.)\n" ); printf( " -minenergy float(TeV) (apply a minimum energy cut in TeV on events in sim_telarray file.)\n" ); printf( " -maxenergy float(TeV) (apply a maximum energy cut in TeV on events in sim_telarray file.)\n" ); printf( " -pedshift float(dc) (apply additional pedestal shift to sum values (default: 0.; good value for ASTRI: 150.)\n" ); exit( EXIT_SUCCESS ); } using namespace std; /* read trigger mask from on external file this is the correction for the Spring 2013 prod2 production with wrong trigger settings */ bool read_trigger_mask( string trg_mask_file ) { #ifdef CTA_PROD2_TRGMASK struct trgmask_set* tms = ( trgmask_set* )calloc( 1, sizeof( struct trgmask_set ) ); if( fTriggerMask_hash_set ) { free( fTriggerMask_hash_set ); } fTriggerMask_hash_set = ( trgmask_hash_set* )calloc( 1, sizeof( struct trgmask_hash_set ) ); IO_BUFFER* iobuf = allocate_io_buffer( 1000000L ); if( iobuf == NULL ) { cout << "read_trigger_mask(): error, cannot allocate I/O buffer" << endl; exit( EXIT_FAILURE ); } iobuf->max_length = 200000000L; IO_ITEM_HEADER item_header; iobuf->input_file = fileopen( trg_mask_file.c_str(), "r" ); if( iobuf->input_file != NULL ) { cout << endl << "reading trigger masks from " << trg_mask_file << endl; unsigned int z = 0; for( ;; ) { if( find_io_block( iobuf, &item_header ) != 0 ) { break; } printf( "Found I/O block of type %ld\n", item_header.type ); if( read_io_block( iobuf, &item_header ) != 0 ) { break; } read_trgmask( iobuf, tms ); trgmask_fill_hashed( tms, fTriggerMask_hash_set ); z++; } if( z > 1 ) { cout << "read_trigger_mask(): error, more than one iobuf - code cannot handle this yet" << endl; exit( EXIT_FAILURE ); } fileclose( iobuf->input_file ); } else { cout << "read_trigger_mask(): error, cannot open trigger mask file: " << endl; cout << "\t" << trg_mask_file << endl; free( tms ); return false; } #endif return true; } /* * fill MC run headr (mainly with CORSIKA parameters, e.g. the scatter radius for the core positions) * */ bool DST_fillMCRunheader( VMonteCarloRunHeader* f, AllHessData* hsdata, bool iAddToFirstFile ) { // values from CORSIKA (from first file) if( !iAddToFirstFile ) { f->runnumber = hsdata->run_header.run; f->shower_prog_id = hsdata->mc_run_header.shower_prog_id; f->shower_prog_vers = hsdata->mc_run_header.shower_prog_vers; f->detector_prog_id = hsdata->mc_run_header.detector_prog_id; f->detector_prog_vers = ( unsigned int )hsdata->mc_run_header.detector_prog_vers; f->obsheight = hsdata->mc_run_header.obsheight; } // TODO: add simulation dates from shower and detector simulation // (need a compiler flag for backwards compatibility) if( iAddToFirstFile ) { f->num_showers += hsdata->mc_run_header.num_showers; } else { f->num_showers = hsdata->mc_run_header.num_showers; } f->num_use = hsdata->mc_run_header.num_use; f->core_pos_mode = hsdata->mc_run_header.core_pos_mode; f->core_range[0] = hsdata->mc_run_header.core_range[0]; f->core_range[1] = hsdata->mc_run_header.core_range[1]; f->az_range[0] = hsdata->mc_run_header.az_range[0]; f->az_range[1] = hsdata->mc_run_header.az_range[1]; f->alt_range[0] = hsdata->mc_run_header.alt_range[0]; f->alt_range[1] = hsdata->mc_run_header.alt_range[1]; f->diffuse = hsdata->mc_run_header.diffuse; f->viewcone[0] = hsdata->mc_run_header.viewcone[0]; f->viewcone[1] = hsdata->mc_run_header.viewcone[1]; if( iAddToFirstFile && f->E_range[0] != hsdata->mc_run_header.E_range[0] ) { cout << "DST_fillMCRunheader(): warning, energy range differ, " << f->E_range[0] << ", " << hsdata->mc_run_header.E_range[0] << endl; } f->E_range[0] = hsdata->mc_run_header.E_range[0]; if( iAddToFirstFile && f->E_range[1] != hsdata->mc_run_header.E_range[1] ) { cout << "DST_fillMCRunheader(): warning, energy range differ, " << f->E_range[1] << ", " << hsdata->mc_run_header.E_range[1] << endl; } f->E_range[1] = hsdata->mc_run_header.E_range[1]; if( iAddToFirstFile && f->spectral_index != hsdata->mc_run_header.spectral_index ) { cout << "DST_fillMCRunheader(): warning, energy range differ, " << f->spectral_index << ", " << hsdata->mc_run_header.spectral_index << endl; } f->spectral_index = hsdata->mc_run_header.spectral_index; f->B_total = hsdata->mc_run_header.B_total; f->B_inclination = hsdata->mc_run_header.B_inclination; f->B_declination = hsdata->mc_run_header.B_declination; f->injection_height = hsdata->mc_run_header.injection_height; f->fixed_int_depth = hsdata->mc_run_header.fixed_int_depth; f->atmosphere = hsdata->mc_run_header.atmosphere; f->corsika_iact_options = hsdata->mc_run_header.corsika_iact_options; f->corsika_low_E_model = hsdata->mc_run_header.corsika_low_E_model; f->corsika_high_E_model = hsdata->mc_run_header.corsika_high_E_model; f->corsika_bunchsize = hsdata->mc_run_header.corsika_bunchsize; f->corsika_wlen_min = hsdata->mc_run_header.corsika_wlen_min; f->corsika_wlen_max = hsdata->mc_run_header.corsika_wlen_max; f->corsika_low_E_detail = hsdata->mc_run_header.corsika_low_E_detail; f->corsika_high_E_detail = hsdata->mc_run_header.corsika_high_E_detail; if( iAddToFirstFile ) { f->combined_runHeader = true; } return true; } /* * fill MC event data (e.g. primary type, MC energy, etc) * * transform into VERITAS coordinate system */ bool DST_fillMCEvent( VDSTTree* fData, AllHessData* hsdata ) { // MC fData->fDSTeventnumber = hsdata->mc_event.event; fData->fDSTrunnumber = hsdata->run_header.run; fData->fDSTprimary = hsdata->mc_shower.primary_id; fData->fDSTenergy = hsdata->mc_shower.energy; fData->fDSTaz = hsdata->mc_shower.azimuth * TMath::RadToDeg(); fData->fDSTze = 90. - hsdata->mc_shower.altitude * TMath::RadToDeg(); // Observe: transform to VERITAS coordinate system // x: East, y: North fData->fDSTxcore = -1.* hsdata->mc_event.ycore; fData->fDSTycore = hsdata->mc_event.xcore; ///////////////////////////////////////////////////////////////////////////// // calculate offset in camera coordinates from telescope and MC direction // (Note: assume that all telescope point into the same direction) double i_tel_el = hsdata->run_header.direction[1] * TMath::RadToDeg(); double i_tel_az = hsdata->run_header.direction[0] * TMath::RadToDeg(); double j_x, j_y = 0.; int j_j = 0; VAstronometry::vlaDs2tp( fData->fDSTaz * TMath::DegToRad(), ( 90. - fData->fDSTze )*TMath::DegToRad(), i_tel_az * TMath::DegToRad(), i_tel_el * TMath::DegToRad(), &j_x, &j_y, &j_j ); fData->fDSTTel_xoff = j_x * TMath::RadToDeg(); fData->fDSTTel_yoff = -1.*j_y * TMath::RadToDeg(); if( fData->fMCtree ) { fData->fMCtree->Fill(); } return true; } /* main function to read and convert data for each event */ bool DST_fillEvent( VDSTTree* fData, AllHessData* hsdata, map< unsigned int, VDSTTelescopeConfiguration > telescope_list, unsigned int iWriteFADC ) { if( !fData || !hsdata ) { return false; } // Use only high energy events if( hsdata->mc_shower.energy < fMinEnergy ) { return true; } // Use only low energy events if( hsdata->mc_shower.energy > fMaxEnergy ) { return true; } // ntel doesn't change from event to event, but needed by VDST fData->fDSTntel = ( unsigned short int )hsdata->run_header.ntel; if( telescope_list.size() == 0 ) { for( unsigned int i = 0; i < fData->fDSTntel; i++ ) { telescope_list[i + 1].FOV = 0.; } } fData->fDSTntel = telescope_list.size(); // reset all arrays fData->resetDataVectors( 99999, fData->fDSTntel, fGlobalNTelPreviousEvent, fGlobalMaxNumberofPixels, getPulseTimingLevels().size(), fGlobalMaxNumberofSamples, fGlobalTriggerReset, true ); ///////////////////////////////////////////////////////////////////////////////////// // event data fData->fDSTeventnumber = hsdata->mc_event.event; fData->fDSTrunnumber = hsdata->run_header.run; fData->fDSTeventtype = 0; fData->fDSTgpsyear = 2010; //////////////////////////////////////////////// // trigger data fData->fDSTNTrig = hsdata->event.central.num_teltrg; unsigned int i_ntel_trig = 0; bitset<8 * sizeof( unsigned long ) > i_localTrigger; // loop over all triggered events for( unsigned int t = 0; t < ( unsigned int )hsdata->event.central.num_teltrg; t++ ) { if( telescope_list.find( hsdata->event.central.teltrg_list[t] ) != telescope_list.end() ) { if( hsdata->event.central.teltrg_list[t] < ( int )i_localTrigger.size() ) { i_localTrigger.set( hsdata->event.central.teltrg_list[t] - 1, true ); } if( t < ( unsigned int )hsdata->run_header.ntel ) { fData->fDSTLTrig_list[i_ntel_trig] = hsdata->event.central.teltrg_list[t]; fData->fDSTLTtime[i_ntel_trig] = hsdata->event.central.teltrg_time[t]; // read L2 trigger type // (filled for >= prod2 only; // although not filled in prod3) // PROD2: bit1: majority // bit2: analog sum // bit3: digital sum // bit4: pe trigger (set with fMinNumber_pe_per_telescope) #if defined(CTA_PROD2) || defined(CTA_PROD3) || defined(CTA_MAX_SC) || defined(CTA_PROD3_MERGE) fData->fDSTL2TrigType[i_ntel_trig] = ( unsigned short int )hsdata->event.central.teltrg_type_mask[t]; #else fData->fDSTL2TrigType[i_ntel_trig] = 99; #endif // trigger corrects (from log files - needed for Spring 2013 prod2 files) #ifdef CTA_PROD2_TRGMASK if( fTriggerMask_hash_set ) { struct trgmask_entry* h_te = find_trgmask( fTriggerMask_hash_set, hsdata->mc_event.event, hsdata->event.central.teltrg_list[t] ); if( h_te ) { fData->fDSTL2TrigType[i_ntel_trig] = ( unsigned short int )h_te->trg_mask; } else { cout << "No trigger mask event found: event " << hsdata->mc_event.event; cout << ", telescope " << hsdata->event.central.teltrg_list[t] << endl; fData->fDSTL2TrigType[i_ntel_trig] = 99; } } #endif // add an additional artificial trigger flag on minimum number of pe if( hsdata->mc_event.mc_pe_list[t].npe > fMinNumber_pe_per_telescope && fData->fDSTL2TrigType[i_ntel_trig] != 99 ) { fData->fDSTL2TrigType[i_ntel_trig] += 8; } } i_ntel_trig++; } } fData->fDSTLTrig = i_localTrigger.to_ulong(); fData->fDSTNTrig = i_ntel_trig; // check array trigger condition again if( fData->fDSTNTrig < ( unsigned int )hsdata->run_header.min_tel_trig ) { // set trigger reset variable (needed for efficient resetting of DST arrays) fGlobalTriggerReset = true; return true; } fGlobalTriggerReset = false; ///////////////////////////////////////////////////////////////////////////////////// // tracking data unsigned int z = 0; for( unsigned short int i = 0; i < ( unsigned short int )hsdata->run_header.ntel; i++ ) { if( telescope_list.find( hsdata->event.trackdata[i].tel_id ) != telescope_list.end() ) { fData->fDSTpointAzimuth[z] = hsdata->event.trackdata[i].azimuth_raw * TMath::RadToDeg(); fData->fDSTpointElevation[z] = hsdata->event.trackdata[i].altitude_raw * TMath::RadToDeg(); fData->fDSTpointTrackingKnown[z] = hsdata->event.trackdata[i].raw_known; z++; } } ///////////////////////////////////////////////////////////////////////////////////// // event data // (main loop) fData->fDSTntel_data = ( unsigned short int )hsdata->event.central.num_teldata; unsigned short int i_ntel_data = 0; // loop over all telescopes for( unsigned short int i = 0; i < fData->fDSTntel_data; i++ ) { // check that this telescope is defined in the current array if( telescope_list.find( hsdata->event.central.teldata_list[i] ) == telescope_list.end() ) { continue; } // get telescope ID fData->fDSTtel_data[i_ntel_data] = ( unsigned int )hsdata->event.central.teldata_list[i]; unsigned int telID = fData->fDSTtel_data[i_ntel_data] - 1; if( fTelescopeSimTelList.find( telID + 1 ) != fTelescopeSimTelList.end() ) { telID = fTelescopeSimTelList[telID + 1]; } else { cout << "Error in DST_fillEvent: unknown telescope " << endl; cout << "\t telescope ID: " << telID + 1 << endl; cout << "\t telescope # in list: " << i << endl; cout << "\t total number of telescopes: " << hsdata->event.num_tel << endl; cout << "\t number of telescopes in this list: " << hsdata->event.central.num_teldata << endl; exit( EXIT_FAILURE ); } // newer hessio versions need this statement for whatever reason #if CTA_SC>1 if( hsdata->event.teldata[telID].known == 0 ) { continue; } #endif //////////////////////////////////////////////// // get pixel data fData->fDSTTelescopeZeroSupression[i_ntel_data] = ( unsigned short int )hsdata->event.teldata[telID].raw->zero_sup_mode; fData->fDSTnumSamples[i_ntel_data] = ( unsigned short int )hsdata->event.teldata[telID].raw->num_samples; // test of FADC samples are requested and then, if there are samples if( iWriteFADC == 1 && fData->fDSTnumSamples[i_ntel_data] == 0 ) { cout << "Error in DST_fillEvent: sample length in hessio file is null for telescope "; cout << telID << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } // set maximum number of FADC samples (needed for efficient resetting of DST arrays) if( fData->fDSTnumSamples[i_ntel_data] > fGlobalMaxNumberofSamples ) { fGlobalMaxNumberofSamples = fData->fDSTnumSamples[i_ntel_data]; } // check number of pixel (change in inc/VGlobalRunParameters if not sufficient if( hsdata->camera_set[telID].num_pixels >= VDST_MAXCHANNELS ) { cout << "ERROR: number of pixels too high: telescope " << telID + 1 << ": is: "; cout << hsdata->camera_set[telID].num_pixels << "\t max allowed: " << VDST_MAXCHANNELS << endl; exit( EXIT_FAILURE ); } // get dynamic range from list of telescopes (for low gain) int i_lowGainSwitch = -1; if( telescope_list[fData->fDSTtel_data[i_ntel_data]].DynamicRange > 0 ) { i_lowGainSwitch = ( int )( telescope_list[fData->fDSTtel_data[i_ntel_data]].DynamicRange * 0.99 ); } ///////////////////////////////////// // set maximum number of pixels (needed for efficient resetting of DST arrays) if( ( unsigned int )hsdata->camera_set[telID].num_pixels > fGlobalMaxNumberofPixels ) { fGlobalMaxNumberofPixels = ( unsigned int )hsdata->camera_set[telID].num_pixels; } ///////////////////////////////////// // loop over all pixel for( int p = 0; p < hsdata->camera_set[telID].num_pixels; p++ ) { // reset low gain switch (filled later) unsigned int iLowGain = false; fData->fDSTHiLo[i_ntel_data][p] = iLowGain; fData->fDSTChan[i_ntel_data][p] = ( unsigned int )p; // channels not known are set dead fData->fDSTdead[i_ntel_data][p] = !( hsdata->event.teldata[telID].raw->adc_known[HI_GAIN][p] ); /////////////////////////////////// // fill pe counting if( fFillPELeaf ) { fData->fDSTPe[i_ntel_data][p] = hsdata->mc_event.mc_pe_list[telID].pe_count[p]; } if( fFillPeakADC ) { fData->fDSTPadcHG[i_ntel_data][p] = ( unsigned short int )( hsdata->event.teldata[telID].raw->adc_sum[HI_GAIN][p] ); fData->fDSTPadcLG[i_ntel_data][p] = ( unsigned short int )( hsdata->event.teldata[telID].raw->adc_sum[LO_GAIN][p] ); } //////////////////////////////////////////// // zero suppression: channel recorded? Bit 0: sum, 1: samples // temporary: not clear how that works fData->fDSTZeroSuppressed[i_ntel_data][p] = 0; /* fData->fDSTZeroSuppressed[i_ntel_data][p] = hsdata->event.teldata[telID].raw->significant[p]; // no suppression: 0 // charge suppressed: 1 // samples suppressed: 2 // (tmp) in the following, either charge or samples are filled if( hsdata->event.teldata[telID].raw->significant[p] == 1 ) { fData->fDSTZeroSuppressed[i_ntel_data][p] = 2; // samples suppressed (charge available) } else if( hsdata->event.teldata[telID].raw->significant[p] > 1 ) { fData->fDSTZeroSuppressed[i_ntel_data][p] = 1; // charge suppressed (samples available) } else { fData->fDSTZeroSuppressed[i_ntel_data][p] = 3; // charge and samples suppressed } */ /////////////////////// // fill FADC trace unsigned int iTraceIsZero = 1; if( iWriteFADC ) // allowed values are 0/1/2 { /////////////////////////////////////// // fill FADC trace iTraceIsZero = 0; iLowGain = HI_GAIN; // first bit = samples are available // if ( ((hsdata->event.teldata[telID].raw->adc_known[HI_GAIN][p]) & (1 << (1))) if( hsdata->event.teldata[telID].raw->adc_sample && hsdata->event.teldata[telID].raw->adc_sample[HI_GAIN] && hsdata->event.teldata[telID].raw->num_samples > 0 ) // TMPTMP ZEROSUP && hsdata->event.teldata[telID].raw->significant[p] > 1 ) // channel recorded? Bit 0: sum, 1: samples { // LOW GAIN // check if this trace is in low gain // (simply check if HI_GAIN is above certain value) if( i_lowGainSwitch > 0 && hsdata->event.teldata[telID].raw->num_gains == 2 && hsdata->event.teldata[telID].raw->adc_known[LO_GAIN][p] != 0 && hsdata->event.teldata[telID].raw->adc_sample && hsdata->event.teldata[telID].raw->adc_sample[LO_GAIN] ) { for( int t = 0; t < hsdata->event.teldata[telID].raw->num_samples; t++ ) { // check if HI_GAIN trace value is above threshold, if yes, flip low gain if( ( int )hsdata->event.teldata[telID].raw->adc_sample[HI_GAIN][p][t] > ( int )( i_lowGainSwitch ) ) { iLowGain = LO_GAIN; } } } fData->fDSTHiLo[i_ntel_data][p] = ( bool )( iLowGain == LO_GAIN ); // fill FADC trace into dst tree for( int t = 0; t < hsdata->event.teldata[telID].raw->num_samples; t++ ) { iTraceIsZero += hsdata->event.teldata[telID].raw->adc_sample[iLowGain][p][t]; fData->fDSTtrace[i_ntel_data][t][p] = hsdata->event.teldata[telID].raw->adc_sample[iLowGain][p][t]; } } ///////////////////////////// // no FADC trace available else if( telescope_list.find( fData->fDSTtel_data[i_ntel_data] ) != telescope_list.end() ) { if( telescope_list[fData->fDSTtel_data[i_ntel_data]].RAWsum ) // && hsdata->event.teldata[telID].raw->significant[p] > 0 ) { fData->fDSTsums[i_ntel_data][p] = hsdata->event.teldata[telID].raw->adc_sum[HI_GAIN][p] - hsdata->tel_moni[telID].pedestal[HI_GAIN][p] - fPedestalShift; } else { fData->fDSTsums[i_ntel_data][p] = calibrate_pixel_amplitude( hsdata, telID, p, FLAG_AMP_TMP, iLowGain ); } fData->fDSTHiLo[i_ntel_data][p] = false; // use raw sum for low-gain determination if( i_lowGainSwitch > 0 && hsdata->event.teldata[telID].raw->num_gains == 2 ) { if( ( int )hsdata->event.teldata[telID].raw->adc_sum[HI_GAIN][p] > i_lowGainSwitch ) { if( telescope_list[fData->fDSTtel_data[i_ntel_data]].RAWsum ) { fData->fDSTsums[i_ntel_data][p] = hsdata->event.teldata[telID].raw->adc_sum[LO_GAIN][p] - hsdata->tel_moni[telID].pedestal[LO_GAIN][p]; } else { fData->fDSTsums[i_ntel_data][p] = calibrate_pixel_amplitude( hsdata, telID, p, FLAG_AMP_TMP, iLowGain ); } // apply hi/lo multiplier if( hsdata->tel_lascal[telID].calib[HI_GAIN][p] > 0. ) { fData->fDSTsums[i_ntel_data][p] *= hsdata->tel_lascal[telID].calib[LO_GAIN][p] / hsdata->tel_lascal[telID].calib[HI_GAIN][p]; } fData->fDSTHiLo[i_ntel_data][p] = true; } } } // pedestal if( hsdata->tel_moni[telID].num_ped_slices > 0 ) { fData->fDSTpedestal[i_ntel_data][p] = hsdata->tel_moni[telID].pedestal[iLowGain][p] / ( double )( hsdata->tel_moni[telID].num_ped_slices ); } // fill pulse timing level as set in sim_telarray: note, there are some hardwired levels here! for( int t = 0; t < hsdata->event.teldata[telID].pixtm->num_types; t++ ) { if( t < ( int )fData->getDSTpulsetiminglevelsN() && getTimingLevelIndex( t ) < fData->getDSTpulsetiminglevelsN() ) { fData->fDSTpulsetiminglevels[i_ntel_data][getTimingLevelIndex( t )] = hsdata->event.teldata[telID].pixtm->time_level[t]; } } //////////////////////////////////////////////// // mean pulse timing and pulse timing levels for( int t = 0; t < hsdata->event.teldata[telID].pixtm->num_types; t++ ) { // sim_telarray timing levels if( t < ( int )fData->getDSTpulsetiminglevelsN() && getTimingLevelIndex( t ) < fData->getDSTpulsetiminglevelsN() ) { fData->fDSTpulsetiming[i_ntel_data][getTimingLevelIndex( t )][p] = hsdata->event.teldata[telID].pixtm->timval[p][t]; if( getTimingLevelIndex( t ) == 1 && fData->fDSTsums[i_ntel_data][p] > fData->getDSTMeanPulseTimingMinLightLevel() && hsdata->event.teldata[telID].pixtm->timval[p][t] > 1.e-1 ) { fData->fillDSTMeanPulseTiming( telID, p, hsdata->event.teldata[telID].pixtm->peak_global, hsdata->event.teldata[telID].raw->num_samples ); } } } // fill characteristic trigger time in pulse timing level vector after all entries before: if( getPulseTimingLevels().size() < fData->getDSTpulsetiminglevelsN() ) { unsigned int iTriggerTimeIndex = getPulseTimingLevels().size(); fData->fDSTpulsetiminglevels[i_ntel_data][iTriggerTimeIndex] = -1.; // read timing from trigger timing (for ASTRI - prod4) if( hsdata->event.teldata[telID].pixeltrg_time.known && hsdata->event.teldata[telID].pixeltrg_time.num_times > 0 ) { bool b_PixTimeFound = false; // current pixel is p - search for it in list for( int ip = 0; ip < hsdata->event.teldata[telID].pixeltrg_time.num_times; ip++ ) { if( hsdata->event.teldata[telID].pixeltrg_time.pixel_list[ip] == p ) { fData->fDSTpulsetiming[i_ntel_data][iTriggerTimeIndex][p] = hsdata->event.teldata[telID].pixeltrg_time.pixel_time[ip]; fData->fDSTpulsetiming[i_ntel_data][iTriggerTimeIndex][p] *= hsdata->event.teldata[telID].pixeltrg_time.time_step; b_PixTimeFound = true; break; } } if( !b_PixTimeFound ) { fData->fDSTpulsetiming[i_ntel_data][iTriggerTimeIndex][p] = -999.; } } } } ///////////////////////////// // fill QADC results else { fData->fDSTRecord[i_ntel_data][p] = hsdata->event.teldata[telID].raw->significant[p]; // (low gain is not treated correctly here) fData->fDSTsums[i_ntel_data][p] = calibrate_pixel_amplitude( hsdata, telID, p, FLAG_AMP_TMP, iLowGain ); fData->fDSTMax[i_ntel_data][p] = ( short )( hsdata->event.teldata[telID].pixtm->pulse_sum_loc[HI_GAIN][p] ); if( FLAG_AMP_TMP > 0 ) { fData->fDSTsumwindow[i_ntel_data][p] = hsdata->event.teldata[telID].pixtm->after_peak; fData->fDSTsumwindow[i_ntel_data][p] -= hsdata->event.teldata[telID].pixtm->before_peak; } else { fData->fDSTsumwindow[i_ntel_data][p] = hsdata->pixel_set[telID].sum_bins; } // fill timing information for( int t = 0; t < hsdata->event.teldata[telID].pixtm->num_types; t++ ) { if( t < ( int )fData->getDSTpulsetiminglevelsN() && getTimingLevelIndex( t ) < fData->getDSTpulsetiminglevelsN() ) { fData->fDSTpulsetiming[i_ntel_data][getTimingLevelIndex( t )][p] = hsdata->event.teldata[telID].pixtm->timval[p][t]; } } } } ////////////////////////////// // get local trigger data (this is not corrected for clipping!) unsigned int i_nL1trig = 0; for( int p = 0; p < hsdata->event.teldata[telID].trigger_pixels.pixels; p++ ) { if( hsdata->event.teldata[telID].trigger_pixels.pixel_list[p] < VDST_MAXCHANNELS ) { fData->fDSTL1trig[i_ntel_data][hsdata->event.teldata[telID].trigger_pixels.pixel_list[p]] = 1; i_nL1trig++; } } fData->fDSTnL1trig[i_ntel_data] = i_nL1trig; i_ntel_data++; // telescope counter } fGlobalNTelPreviousEvent = i_ntel_data; fData->fDSTntel_data = i_ntel_data; /////////////////// // MC event data fData->fDSTprimary = hsdata->mc_shower.primary_id; fData->fDSTenergy = hsdata->mc_shower.energy; fData->fDSTaz = hsdata->mc_shower.azimuth * TMath::RadToDeg(); fData->fDSTze = 90. - hsdata->mc_shower.altitude * TMath::RadToDeg(); // Observe: transform to VERITAS coordinate system // x: East, y: North fData->fDSTxcore = -1.*hsdata->mc_event.ycore; fData->fDSTycore = hsdata->mc_event.xcore; ///////////////////////////////////////////////////////////////////////////// // calculate offset in camera coordinates from telescope and MC direction // (OBS: this assumes that all telescopes are pointing into the same direction) double i_tel_el = 0.; double i_tel_az = 0.; for( int itel = 0; itel < hsdata->run_header.ntel; itel++ ) { if( fData->fDSTpointTrackingKnown[itel] > 0 ) { i_tel_el = fData->fDSTpointElevation[itel]; i_tel_az = fData->fDSTpointAzimuth[itel]; break; } } double j_x, j_y = 0.; int j_j = 0; VAstronometry::vlaDs2tp( fData->fDSTaz * TMath::DegToRad(), ( 90. - fData->fDSTze )*TMath::DegToRad(), i_tel_az * TMath::DegToRad(), i_tel_el * TMath::DegToRad(), &j_x, &j_y, &j_j ); fData->fDSTTel_xoff = j_x * TMath::RadToDeg();; fData->fDSTTel_yoff = -1.*j_y * TMath::RadToDeg();; ///////////////////////////////////////////////////////////////////////////// if( fData->fDST_tree ) { fData->fDST_tree->Fill(); } return true; } /* fill calibration tree e.g. pedestals, tzeros, gains, etc. */ TList* DST_fillCalibrationTree( VDSTTree* fData, AllHessData* hsdata, map< unsigned int, VDSTTelescopeConfiguration> telescope_list, string ipedfile, float iNSBScaling ) { if( !hsdata || fWriteTelConfigTreeOnly ) { return 0; } cout << "filling calibration tree "; if( ipedfile.size() > 0 ) { cout << " (using data from external ped file: " << ipedfile << ")"; } else { cout << " (using data from simtelarray file)"; } cout << endl; if( iNSBScaling <= 0. ) { cout << "DST_fillCalibrationTree: invalid NSB scaling factor (should be >0): iNSBScaling" << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } int fTelID = 0; // save current directory TDirectory* i_curDir = gDirectory; // number of pixels unsigned int nPixel = 0; // integration window unsigned int fnum_sumwindow = 1; unsigned int fsumwindow[VDST_MAXSUMWINDOW]; float fPed_high[VDST_MAXCHANNELS]; float* fPedvar_high = new float[VDST_MAXCHANNELS * VDST_MAXSUMWINDOW]; float fPed_low[VDST_MAXCHANNELS]; float* fPedvar_low = new float[VDST_MAXCHANNELS * VDST_MAXSUMWINDOW]; float fConv_high[VDST_MAXCHANNELS]; float fConv_low[VDST_MAXCHANNELS]; float fTZero[VDST_MAXCHANNELS]; float fTZeroMean = -999.; float fTZeroMedian = -999.; float fTZeroRMS = -999.; float fTZeroN = 0.; for( unsigned int i = 0; i < VDST_MAXCHANNELS; i++ ) { fPed_high[i] = 0.; fPed_low[i] = 0.; fConv_high[i] = 0.; fConv_low[i] = 0.; fTZero[i] = -999.; for( unsigned int j = 0; j < VDST_MAXSUMWINDOW; j++ ) { fPedvar_high[i * VDST_MAXSUMWINDOW + j] = 0.; fPedvar_low[i * VDST_MAXSUMWINDOW + j] = 0.; } } // the following variables are needed for reading of external pedestal files float iT_sumwindow[VDST_MAXSUMWINDOW]; float iT_pedvars[VDST_MAXSUMWINDOW]; // list with root objects which are saved to file TList* hisList = new TList(); // definition of calibration tree TTree* t = new TTree( "calibration", "calibration data" ); hisList->Add( t ); char hname[200]; t->Branch( "TelID", &fTelID, "TelID/I" ); t->Branch( "NPixel", &nPixel, "NPixel/i" ); t->Branch( "num_sumwindow", &fnum_sumwindow, "num_sumwindow/i" ); t->Branch( "sumwindow", fsumwindow, "sumwindow[num_sumwindow]/i" ); t->Branch( "ped_high", fPed_high, "ped_high[NPixel]/F" ); sprintf( hname, "pedvar_high[%d]/F", VDST_MAXCHANNELS * VDST_MAXSUMWINDOW ); t->Branch( "pedvar_high", fPedvar_high, hname, VDST_MAXCHANNELS * VDST_MAXSUMWINDOW * 4 ); t->Branch( "ped_low", fPed_low, "ped_low[NPixel]/F" ); sprintf( hname, "pedvar_low[%d]/F", VDST_MAXCHANNELS * VDST_MAXSUMWINDOW ); t->Branch( "pedvar_low", fPedvar_low, hname, VDST_MAXCHANNELS * VDST_MAXSUMWINDOW * 4 ); t->Branch( "conv_high", fConv_high, "conv_high[NPixel]/F" ); t->Branch( "conv_low", fConv_low, "conv_low[NPixel]/F" ); t->Branch( "tzero", fTZero, "tzero[NPixel]/F" ); t->Branch( "tzero_mean_tel", &fTZeroMean, "tzero_mean_tel/F" ); t->Branch( "tzero_med_tel", &fTZeroMedian, "tzero_med_tel/F" ); t->Branch( "tzero_rms_tel", &fTZeroRMS, "tzero_rms_tel/F" ); t->Branch( "tzero_n_tel", &fTZeroN, "tzero_n_tel/F" ); /////////////////////////////////////////////////////// // open external file with pedestals TFile* iPedFile = 0; if( ipedfile.size() > 0 ) { iPedFile = new TFile( ipedfile.c_str(), "READ" ); if( iPedFile->IsZombie() ) { cout << "DST_fillCalibrationTree: error while opening external pedestal file: " << ipedfile << endl; exit( EXIT_FAILURE ); } } //////////////////////////////////////////////////////// // loop over all telescopes and fill calibration trees for( int itel = 0; itel < hsdata->run_header.ntel; itel++ ) { fTelID = hsdata->tel_moni[itel].tel_id; // select telescopes for this analysis if( telescope_list.size() == 0 || telescope_list.find( fTelID ) != telescope_list.end() ) { cout << "\t filling calibration values for Telescope: " << itel << "\t" << fTelID; if( telescope_list[fTelID].TelescopeName.size() > 0 ) { cout << "\t" << telescope_list[fTelID].TelescopeName; } cout << " (FOV " << telescope_list[fTelID].FOV << " deg,"; cout << " dynamic range: " << telescope_list[fTelID].DynamicRange; cout << ", RAWsum: " << telescope_list[fTelID].RAWsum; cout << ")" << endl; nPixel = ( unsigned int )hsdata->tel_moni[itel].num_pixels; if( VDST_MAXCHANNELS < nPixel ) { cout << "DST_fillCalibrationTree error: number of pixels (" << nPixel; cout << ") exeeds allowed range (" << VDST_MAXCHANNELS << ")" << endl; cout << "\t adjust arrays..." << endl; exit( EXIT_FAILURE ); } // pedestal (always taken from hessio file, as it might change from run to run) for( unsigned int p = 0; p < nPixel; p++ ) { if( hsdata->tel_moni[itel].num_ped_slices > 0. ) { fPed_high[p] = hsdata->tel_moni[itel].pedestal[HI_GAIN][p] / ( double )( hsdata->tel_moni[itel].num_ped_slices ); fPed_low[p] = hsdata->tel_moni[itel].pedestal[LO_GAIN][p] / ( double )( hsdata->tel_moni[itel].num_ped_slices ); } else { fPed_high[p] = 0.; fPed_low[p] = 0.; } } /////////////////////////////////////////////////////////////////////////////////// // fill pedestal variances from external root file if( iPedFile && fTelescopeType.find( itel ) != fTelescopeType.end() ) { std::ostringstream iSname; iSname << "tPeds_" << fTelescopeType[itel]; TTree* iT = ( TTree* )iPedFile->Get( iSname.str().c_str() ); if( !iT ) { cout << "DST_fillCalibrationTree error: pedestal tree not found for telescope "; cout << itel << " (type " << fTelescopeType[itel] << ")" << endl; continue; } // now copy values over to new tree iT->SetBranchAddress( "nsumwindows", &fnum_sumwindow ); iT->SetBranchAddress( "sumwindow", iT_sumwindow ); iT->SetBranchAddress( "pedvars", iT_pedvars ); if( iT->GetEntries() < nPixel ) { cout << "DST_fillCalibrationTree error: number of pixels different in pedestal tree: "; cout << nPixel << "\t" << iT->GetEntries() << endl; return 0; } for( unsigned int p = 0; p < nPixel; p++ ) { iT->GetEntry( p ); for( unsigned int w = 0; w < fnum_sumwindow; w++ ) { fPedvar_high[p * VDST_MAXSUMWINDOW + w] = iT_pedvars[w] * sqrt( iNSBScaling ); fPedvar_low[p * VDST_MAXSUMWINDOW + w] = hsdata->tel_moni[itel].noise[LO_GAIN][p] * sqrt( iNSBScaling ); } } if( i_curDir ) { i_curDir->cd(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // read calibration data from simtel files // (not clear yet how to use this information later in the analysis) else { for( unsigned int p = 0; p < nPixel; p++ ) { fnum_sumwindow = 1; fsumwindow[0] = ( unsigned int )hsdata->tel_moni[itel].num_ped_slices; for( unsigned int w = 0; w < fnum_sumwindow; w++ ) { fPedvar_high[p * VDST_MAXSUMWINDOW + w] = hsdata->tel_moni[itel].noise[HI_GAIN][p]; fPedvar_low[p * VDST_MAXSUMWINDOW + w] = hsdata->tel_moni[itel].noise[LO_GAIN][p]; } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // dc/pe conversion and pulse arrival time for( unsigned int p = 0; p < nPixel; p++ ) { fConv_high[p] = hsdata->tel_lascal[itel].calib[HI_GAIN][p] * CALIB_SCALE; if( hsdata->tel_lascal[itel].known && hsdata->tel_lascal[itel].num_gains > 1 ) { fConv_low[p] = hsdata->tel_lascal[itel].calib[LO_GAIN][p] * CALIB_SCALE; } else { fConv_low[p] = -999.; } fTZero[p] = -999.; if( fData ) { fTZero[p] = fData->getDSTMeanPulseTiming( itel, p ); } } if( fData ) { fTZeroMean = fData->getDSTMeanPulseTimingPerTelescope( itel ); fTZeroMedian = fData->getDSTMedianPulseTimingPerTelescope( itel ); fTZeroRMS = fData->getDSTRMSPulseTimingPerTelescope( itel ); fTZeroN = fData->getDSTNEventsPulseTimingPerTelescope( itel ); } for( unsigned int w = 0; w < fnum_sumwindow; w++ ) { fsumwindow[w] = ( unsigned int )( TMath::Nint( iT_sumwindow[w] ) ); } t->Fill(); } } // copy directories with pedestal distributions // loop over all telescope types // bool iFillPedDistributions = false; if( iFillPedDistributions ) { cout << "copy directories with pedestal distributions..." << endl; set< ULong64_t >::iterator it; for( it = fTelescopeTypeList.begin(); it != fTelescopeTypeList.end(); ++it ) { ULong64_t iTelescopeType = *it; std::ostringstream iDname; iDname << "distributions_" << iTelescopeType; if( iPedFile && iPedFile->cd( iDname.str().c_str() ) ) { for( unsigned int w = 0; w < fnum_sumwindow; w++ ) { for( unsigned int p = 0; p < VDST_MAXCHANNELS; p++ ) { std::ostringstream iHname; iHname << "hpedPerTelescopeType_" << iTelescopeType << "_" << TMath::Nint( iT_sumwindow[w] ) << "_" << p ; if( gDirectory->Get( iHname.str().c_str() ) ) { hisList->Add( gDirectory->Get( iHname.str().c_str() ) ); } } /* std::ostringstream iHname; iHname << "hpedPerTelescopeType_" << iTelescopeType << "_" << TMath::Nint( iT_sumwindow[w] ); if( gDirectory->Get( iHname.str().c_str() ) ) { hisList->Add( gDirectory->Get( iHname.str().c_str() ) ); } */ } } if( i_curDir ) { i_curDir->cd(); } } } // copy IPR graphs if( iPedFile ) { i_curDir->cd(); unsigned int iIPRgraphs = 0; // loop over all telescope types set< ULong64_t >::iterator it; for( it = fTelescopeTypeList.begin(); it != fTelescopeTypeList.end(); ++it ) { ULong64_t iTelescopeType = *it; // loop over all summation windows (guess that there is a max) for( unsigned int w = 1; w < 100; w++ ) { std::ostringstream iHname; iHname << "IPRcharge_TelType" << iTelescopeType << "_SW" << w; if( iPedFile->Get( iHname.str().c_str() ) ) { hisList->Add( iPedFile->Get( iHname.str().c_str() ) ); iIPRgraphs++; } } } if( iIPRgraphs > 0 ) { cout << "found " << iIPRgraphs << " IPR graphs " << endl; } } delete [] fPedvar_high; delete [] fPedvar_low; return hisList; } /* * fill a tree with all information on the detector * */ TTree* DST_fill_detectorTree( AllHessData* hsdata, map< unsigned int, VDSTTelescopeConfiguration > telescope_list, bool iApplyCameraScaling, map< ULong64_t, float > iCameraScalingMap ) { if( !hsdata ) { return 0; } // HARDCODED: all large telescopes are parabolic // all telescopes with a mirror area larger than this value are // considered to be parabolic (in m^2) double fParabolic_mirrorArea = 380.; // HARDCODED: all telescopes with 2 mirrors only are SC telescopes int fSC_number_of_mirrors = 2; cout << "Info:" << endl; cout << " assume that all telescopes with mirror area larger than " << fParabolic_mirrorArea; cout << " m^2 are of parabolic type" << endl; cout << " assume that all telescopes with " << fSC_number_of_mirrors; cout << " mirrors are Schwarzschild-Couder telescopes" << endl; // define tree int fTelID = 0; unsigned int fNTel = 0; Char_t fTelescopeName[300]; float fTelxpos = 0.; float fTelypos = 0.; float fTelzpos = 0.; float fFocalLength = 0.; float fEffectiveFocalLength = 0.; float fCameraScaleFactor = 1.; float fCameraCentreOffset = 0.; float fCameraRotation = 0.; int fCamCurvature = 0; unsigned int nPixel = 0; unsigned int nPixel_active = 0; unsigned int nSamples = 0; unsigned int fDynRange = 0; float Sample_time_slice = 0.; unsigned int nGains; float fHiLoScale = 0.; int fHiLoThreshold = 0; float fHiLoOffset = 0.; const unsigned int fMaxPixel = 50000; float fXTubeMM[fMaxPixel]; float fYTubeMM[fMaxPixel]; float fRTubeMM[fMaxPixel]; float fXTubeDeg[fMaxPixel]; float fYTubeDeg[fMaxPixel]; float fRTubeDeg[fMaxPixel]; float fATubem2[fMaxPixel]; unsigned int fPixelShape[fMaxPixel]; int nDisabled = 0; int fTubeDisabled[fMaxPixel]; float fMirrorArea = 0.; int fNMirrors = 0; float fFOV = 0.; ULong64_t fTelescope_type = 0; for( unsigned int i = 0; i < fMaxPixel; i++ ) { fXTubeMM[i] = 0.; fYTubeMM[i] = 0.; fRTubeMM[i] = 0.; fXTubeDeg[i] = 0.; fYTubeDeg[i] = 0.; fRTubeDeg[i] = 0.; fTubeDisabled[i] = 0; fATubem2[i] = 0.; } TTree* fTreeDet = new TTree( "telconfig", "detector configuration" ); fTreeDet->Branch( "NTel", &fNTel, "NTel/i" ); fTreeDet->Branch( "TelID", &fTelID, "TelID/I" ); fTreeDet->Branch( "TelescopeName", &fTelescopeName, "TelescopeName/C" ); fTreeDet->Branch( "TelType", &fTelescope_type, "TelType/l" ); fTreeDet->Branch( "TelX", &fTelxpos, "TelX/F" ); fTreeDet->Branch( "TelY", &fTelypos, "TelY/F" ); fTreeDet->Branch( "TelZ", &fTelzpos, "TelZ/F" ); fTreeDet->Branch( "FocalLength", &fFocalLength, "FocalLength/F" ); fTreeDet->Branch( "EffectiveFocalLength", &fEffectiveFocalLength, "EffectiveFocalLength/F" ); fTreeDet->Branch( "FOV", &fFOV, "FOV/F" ); fTreeDet->Branch( "CameraScaleFactor", &fCameraScaleFactor, "CameraScaleFactor/F" ); fTreeDet->Branch( "CameraCentreOffset", &fCameraCentreOffset, "CameraCentreOffset/F" ); fTreeDet->Branch( "CameraRotation", &fCameraRotation, "CameraRotation/F" ); fTreeDet->Branch( "CamCurvature", &fCamCurvature, "CamCurvate/I" ); fTreeDet->Branch( "NPixel", &nPixel, "NPixel/i" ); fTreeDet->Branch( "NPixel_active", &nPixel_active, "NPixel_active/i" ); fTreeDet->Branch( "NSamples", &nSamples, "NSamples/i" ); fTreeDet->Branch( "Sample_time_slice", &Sample_time_slice, "Sample_time_slice/F" ); fTreeDet->Branch( "NGains", &nGains, "NGains/i" ); fTreeDet->Branch( "HiLoScale", &fHiLoScale, "HiLoScale/F" ); fTreeDet->Branch( "HiLoThreshold", &fHiLoThreshold, "HiLoThreshold/I" ); fTreeDet->Branch( "HiLoOffset", &fHiLoOffset, "HiLoOffset/F" ); fTreeDet->Branch( "DynRange", &fDynRange, "DynRange/i" ); fTreeDet->Branch( "XTubeMM", fXTubeMM, "XTubeMM[NPixel]/F" ); fTreeDet->Branch( "YTubeMM", fYTubeMM, "YTubeMM[NPixel]/F" ); fTreeDet->Branch( "RTubeMM", fRTubeMM, "RTubeMM[NPixel]/F" ); fTreeDet->Branch( "XTubeDeg", fXTubeDeg, "XTubeDeg[NPixel]/F" ); fTreeDet->Branch( "YTubeDeg", fYTubeDeg, "YTubeDeg[NPixel]/F" ); fTreeDet->Branch( "RTubeDeg", fRTubeDeg, "RTubeDeg[NPixel]/F" ); fTreeDet->Branch( "AreaTube_m2", fATubem2, "AreaTube_m2[NPixel]/F" ); fTreeDet->Branch( "PixelShape", fPixelShape, "PixelShape[NPixel]/i" ); fTreeDet->Branch( "NTubesOFF", &nDisabled, "NTubesOFF/I" ); fTreeDet->Branch( "TubeOFF", fTubeDisabled, "TubeOFF[NPixel]/I" ); fTreeDet->Branch( "NMirrors", &fNMirrors, "NMirrors/I" ); fTreeDet->Branch( "MirrorArea", &fMirrorArea, "MirrorArea/F" ); // check number of telescopes for( int itel = 0; itel < hsdata->run_header.ntel; itel++ ) { fTelID = hsdata->run_header.tel_id[itel]; if( telescope_list.size() == 0 || telescope_list.find( fTelID ) != telescope_list.end() ) { fNTel++; } } fNTel_checked = fNTel; /////////////////////////////////////////////////////////// // fill the tree with all information about the detector for( int itel = 0; itel < hsdata->run_header.ntel; itel++ ) { // actuall filling of telescope trees fTelID = hsdata->run_header.tel_id[itel]; if( telescope_list.size() == 0 || telescope_list.find( fTelID ) != telescope_list.end() ) { // Observe: transform to VERITAS coordinate system // x: East, y: North fTelxpos = -1.*hsdata->run_header.tel_pos[itel][1]; fTelypos = hsdata->run_header.tel_pos[itel][0]; fTelzpos = hsdata->run_header.tel_pos[itel][2]; fFocalLength = hsdata->camera_set[itel].flen; // effective focal length (set only from prod4 on) if( hsdata->camera_set[itel].eff_flen > 0. ) { fEffectiveFocalLength = hsdata->camera_set[itel].eff_flen; } if( telescope_list[fTelID].DynamicRange > 0 ) { fDynRange = ( unsigned int )telescope_list[fTelID].DynamicRange; } else { fDynRange = 0.; } fCameraCentreOffset = 0.; fCameraRotation = -1.*hsdata->camera_set[itel].cam_rot * TMath::RadToDeg(); #if defined(CTA_PROD2) fCamCurvature = 0; #else fCamCurvature = hsdata->camera_set[itel].curved_surface; #endif fNMirrors = hsdata->camera_set[itel].num_mirrors; fMirrorArea = hsdata->camera_set[itel].mirror_area; nPixel = hsdata->camera_set[itel].num_pixels; nDisabled = hsdata->pixel_disabled[itel].num_HV_disabled; nSamples = hsdata->event.teldata[itel].raw->num_samples; Sample_time_slice = hsdata->pixel_set[itel].time_slice; nGains = hsdata->event.teldata[itel].raw->num_gains; fHiLoScale = hsdata->event.teldata[itel].raw->scale_hg8; fHiLoThreshold = hsdata->event.teldata[itel].raw->threshold; fHiLoOffset = hsdata->event.teldata[itel].raw->offset_hg8; // reset dead pixel list for( unsigned int p = 0; p < fMaxPixel; p++ ) { fTubeDisabled[p] = 0; } nPixel_active = 0; float maxPix_dist = 0.; float pix_size = 0.; if( nPixel < fMaxPixel ) { for( unsigned int p = 0; p < nPixel; p++ ) { fXTubeMM[p] = hsdata->camera_set[itel].xpix[p] * 1.e3; fYTubeMM[p] = hsdata->camera_set[itel].ypix[p] * 1.e3; #if defined(CTA_PROD3) || defined(CTA_MAX_SC) || defined(CTA_PROD3_MERGE) // 0: circ., 1,3: hex, 2: square, -1: unknown fPixelShape[p] = ( unsigned int )hsdata->camera_set[itel].pixel_shape[p]; #endif fPixelShape[p] = 99; #if defined(CTA_PROD3) || defined(CTA_MAX_SC) || defined(CTA_PROD3_MERGE) // use as size the radius of the active area of the tube if( hsdata->camera_set[itel].pixel_shape[p] == 0 || hsdata->camera_set[itel].pixel_shape[p] == 1 ) { fRTubeMM[p] = sqrt( hsdata->camera_set[itel].area[p] / TMath::Pi() ) * 1.e3; } else { fRTubeMM[p] = sqrt( hsdata->camera_set[itel].area[p] ) * 1.e3 * 0.5; } #else fRTubeMM[p] = sqrt( hsdata->camera_set[itel].area[p] / TMath::Pi() ) * 1.e3; #endif fATubem2[p] = hsdata->camera_set[itel].area[p]; if( p == 0 ) { // prod2: pix_size in [deg] (diameter) // (note that this is not entirely correct for the dual-mirror telescopes) pix_size = atan2( ( double )hsdata->camera_set[itel].size[p], ( double )fFocalLength ) * TMath::RadToDeg(); } // mm -> deg fXTubeDeg[p] = atan2( ( double )fXTubeMM[p] / 1000., ( double )fFocalLength ) * TMath::RadToDeg(); fYTubeDeg[p] = atan2( ( double )fYTubeMM[p] / 1000., ( double )fFocalLength ) * TMath::RadToDeg(); fRTubeDeg[p] = atan2( ( double )fRTubeMM[p] / 1000., ( double )fFocalLength ) * TMath::RadToDeg(); float x2 = fXTubeDeg[p] * fXTubeDeg[p]; float y2 = fYTubeDeg[p] * fYTubeDeg[p]; if( sqrt( x2 + y2 ) * 2. > maxPix_dist ) { maxPix_dist = sqrt( x2 + y2 ) * 2.; } // disable pixels which are too far out if( telescope_list.size() != 0 && TMath::Abs( telescope_list[fTelID].FOV ) > 1.e-2 ) { if( sqrt( x2 + y2 ) - fRTubeDeg[p] > telescope_list[fTelID].FOV * 0.5 ) { fTubeDisabled[p] = 2; nDisabled++; } } if( fTubeDisabled[p] == 0 ) { nPixel_active++; } } // check for disabled pixels in sim_telarray for( int p_off = 0; p_off < hsdata->pixel_disabled[itel].num_HV_disabled; p_off++ ) { if( hsdata->pixel_disabled[itel].HV_disabled[p_off] < ( int )nPixel && fTubeDisabled[hsdata->pixel_disabled[itel].HV_disabled[p_off]] == 0 ) { fTubeDisabled[hsdata->pixel_disabled[itel].HV_disabled[p_off]] = 822; nPixel_active--; } } } if( telescope_list.size() == 0 || TMath::Abs( telescope_list[fTelID].FOV ) < 1.e5 ) { fFOV = maxPix_dist; } else if( maxPix_dist < telescope_list[fTelID].FOV ) { fFOV = maxPix_dist; } else { fFOV = telescope_list[fTelID].FOV; } // telescope name if( telescope_list.size() == 0 || telescope_list[fTelID].TelescopeName.size() == 0 ) { sprintf( fTelescopeName, "Tel-%d", fTelID + 1 ); } else { sprintf( fTelescopeName, "%s", telescope_list[fTelID].TelescopeName.c_str() ); } // telescope types fTelescope_type = TMath::Nint( pix_size * 100. ); fTelescope_type += TMath::Nint( fFOV * 10. ) * 100; fTelescope_type += TMath::Nint( fMirrorArea ) * 100 * 10 * 100; // all large telescopes are parabolic, all others are Davies-Cotton (hardwired) if( fMirrorArea > fParabolic_mirrorArea ) { fTelescope_type += 100000000; } // Schwarzschild-Couder: check number of mirrors // (assumption is that SC telescope has 2 mirrors only) else if( fNMirrors == fSC_number_of_mirrors ) { fTelescope_type += 200000000; } // Keep telescope IDs constant between prod3 and prod4 - // despite changing parameters. // ASTRI if( fTelescope_type == 201411619 ) { fTelescope_type += 100000; } // TMP Prod4 fix for MSTs if( fTelescope_type == 10608618 ) { fTelescope_type = 10408618; } // (end of tmp) fTelescopeType[itel] = fTelescope_type; fTelescopeTypeList.insert( fTelescope_type ); //////////////////////////////////////////////// // camera scaling (effective focal length) fCameraScaleFactor = 1.; if( fEffectiveFocalLength > 0. ) { fCameraScaleFactor = fFocalLength / fEffectiveFocalLength; } // scaling factor given from external file? else if( iCameraScalingMap.find( fTelescope_type ) != iCameraScalingMap.end() ) { fCameraScaleFactor = 1. - iCameraScalingMap[fTelescope_type]; } // hard wired value for DC telescopes // (for backwards compatibility, // should not be used anymore) if( iApplyCameraScaling && fTelescope_type < 100000000 ) { // assume that CTA MST is of intermediate-1.2 design if( TMath::Abs( fMirrorArea - 100. ) < 5. ) { // G.Hughes (2011/10/21): 2.79+-0.06 % fCameraScaleFactor = 1. - 0.0279; } } fTreeDet->Fill(); } } return fTreeDet; } /* main program */ int main( int argc, char** argv ) { // stop watch TStopwatch fStopWatch; fStopWatch.Start(); IO_BUFFER* iobuf = NULL; IO_ITEM_HEADER item_header; const char* input_fname = NULL; int itel, rc = 0; int tel_id; int verbose = 0, ignore = 0, quiet = 0; int ntel_trg = 0, min_tel_trg = 0; int nev = 0, ntrg = 0; char* program = argv[0]; int showdata = 0, showhistory = 0; size_t events = 0, max_events = 0; int iarg; fGlobalNTelPreviousEvent = 0; fGlobalMaxNumberofPixels = 0; fGlobalMaxNumberofSamples = 0; fGlobalTriggerReset = false; string config_file = ""; // file with list of telescopes string dst_file = "dst.root"; // output dst file string ped_file = ""; // file with pedestal and pedestal variances string trg_mask_dir = ""; // directory with trigger information (only for 2013 prod2 MC) unsigned int fWriteFADC = 2; // fill FADC traces into converter (0=QADC, 1=FADC, 2=mix of both) bool fApplyCameraScaling = true; // apply camera plate scaling according for DC telescopes map< ULong64_t, float > fCameraScalingMap; // camera plate scale (per telescoe type; read from external file) float fNSB_scaling = 1.; // pedvar scaling due to higher NSB static AllHessData* hsdata; cout << endl; cout << "CTA.convert_hessio_to_VDST: A program to convert hessio data to EVNDISP DST files"; cout << " (" << VGlobalRunParameter::fEVNDISP_VERSION << ")" << endl; cout << " (based on a skeleton program distributed with the hessio package)" << endl; cout << "=====================================================================" << endl; /* Show command line on output */ if( getenv( "SHOWCOMMAND" ) != NULL ) { for( iarg = 0; iarg < argc; iarg++ ) { printf( "%s ", argv[iarg] ); } printf( "\n" ); } /* Catch INTerrupt and TERMinate signals to stop program */ signal( SIGINT, stop_signal_function ); signal( SIGTERM, stop_signal_function ); if( argc < 2 ) { syntax( program ); } interrupted = 0; /* Check assumed limits with the ones compiled into the library. */ H_CHECK_MAX(); if( ( iobuf = allocate_io_buffer( 1000000L ) ) == NULL ) { cout << "Cannot allocate I/O buffer" << endl; exit( EXIT_FAILURE ); } iobuf->max_length = 100000000L; /* Command line options */ while( argc > 1 ) { if( strcmp( argv[1], "-i" ) == 0 ) { ignore = 1; argc--; argv++; continue; } else if( strcmp( argv[1], "-v" ) == 0 ) { verbose = 1; quiet = 0; argc--; argv++; continue; } else if( strcmp( argv[1], "-q" ) == 0 ) { quiet = 1; verbose = 0; argc--; argv++; continue; } else if( strcmp( argv[1], "-h" ) == 0 || strcmp( argv[1], "--history" ) == 0 ) { showhistory = 1; argc--; argv++; continue; } else if( strcmp( argv[1], "-s" ) == 0 ) { showdata = 1; argc--; argv++; continue; } else if( strcmp( argv[1], "-S" ) == 0 ) { showdata = 1; putenv( ( char* )"PRINT_VERBOSE=1" ); argc--; argv++; continue; } else if( strcmp( argv[1], "--max-events" ) == 0 && argc > 2 ) { max_events = atol( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-NSB" ) == 0 ) { fNSB_scaling = atof( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-a" ) == 0 ) { config_file = argv[2]; argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-o" ) == 0 ) { dst_file = argv[2]; argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-t" ) == 0 ) { trg_mask_dir = argv[2]; argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-c" ) == 0 ) { ped_file = argv[2]; argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-f" ) == 0 ) { fWriteFADC = atoi( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-pe" ) == 0 ) { fFillPELeaf = true; argc--; argv++; continue; } else if( strcmp( argv[1], "-peakadc" ) == 0 ) { fFillPeakADC = true; argc--; argv++; continue; } else if( strcmp( argv[1], "-pedshift" ) == 0 ) { fPedestalShift = atof( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-minenergy" ) == 0 ) { fMinEnergy = atof( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "-maxenergy" ) == 0 ) { fMaxEnergy = atof( argv[2] ); argc -= 2; argv += 2; continue; } // apply camera scaling for MSTs only else if( strcmp( argv[1], "-r" ) == 0 ) { fApplyCameraScaling = atoi( argv[2] ); argc -= 2; argv += 2; continue; } // file with camera scaling values per telescope type else if( strcmp( argv[1], "-rfile" ) == 0 ) { fCameraScalingMap = readCameraScalingMap( argv[2] ); argc -= 2; argv += 2; continue; } else if( strcmp( argv[1], "--help" ) == 0 ) { printf( "\nc_DST: A program to convert hessio data to EVNDISP DST files.\n\n" ); syntax( program ); } else if( argv[1][0] == '-' && argv[1][1] != '\0' ) { printf( "Syntax error at '%s'\n", argv[1] ); syntax( program ); } else { break; } } if( verbose && !quiet ) { showhistory = 1; } ////////////////////////////////////////////////////////////////// // initialize eventdisplay dst and run header /////////////////////////////////////////////////////////////////// cout << endl << "NOTE: FIXED TIMING LEVELS READ FROM HESSIO FILE" << endl << endl; /////////////////////////////////////////////////////////////////// // open DST file TFile* fDSTfile = new TFile( dst_file.c_str(), "RECREATE" ); if( fDSTfile->IsZombie() ) { cout << "Error while opening DST output file: " << fDSTfile->GetName() << endl; exit( EXIT_FAILURE ); } cout << "DST tree will be written to " << dst_file << endl; if( fWriteFADC == 1 ) { cout << "Writing FADC samples to DST file" << endl; } else if( fWriteFADC == 2 ) { cout << "Writing FADC samples / QADC to DST file" << endl; } else { cout << "No FADC output" << endl; } if( fApplyCameraScaling ) { cout << "Apply camera plate scaling for DC (intermediate) telescopes" << endl; } if( fMinNumber_pe_per_telescope > 0 ) { cout << "Add trigger type #4 for events with >" << fMinNumber_pe_per_telescope << " pe per telescope" << endl; } if( fPedestalShift > 0. ) { cout << "Apply pedestal shift by " << fPedestalShift << " dc "; cout << "(applied only to non-FADC data)" << endl; } if( fMinEnergy > 0. ) { cout << "Apply minimum energy cut of " << fMinEnergy << " TeV " << endl; } if( fMaxEnergy < 1.e19 ) { cout << "Apply maximum energy cut of " << fMaxEnergy << " TeV " << endl; } // new DST tree VDSTTree* fDST = new VDSTTree(); fDST->setMC(); map< unsigned int, VDSTTelescopeConfiguration > fTelescope_list = fDST->readArrayConfig( config_file ); if( fTelescope_list.size() < 1 ) { cout << "error reading array configuration file" << endl; cout << "(" << config_file << ")" << endl; exit( EXIT_FAILURE ); } fDST->setFADC( fWriteFADC ); fDST->setFillPELeaf( fFillPELeaf ); if( fFillPELeaf ) { cout << "Filling pe leaf " << endl; } fDST->setFillPeakADFLeaf( fFillPeakADC ); if( !fWriteTelConfigTreeOnly ) { fDST->initDSTTree( false ); fDST->initMCTree(); } // MC run header VMonteCarloRunHeader* fMC_header = new VMonteCarloRunHeader(); fMC_header->SetName( "MC_runheader" ); // long list of input file names string fRunPara_InputFileName = ""; unsigned int fRunPara_NumInputFiles = 0; cout << "start proceeding with sim_telarray file" << endl; ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Now go over rest of the command line and read input file names while( argc > 1 || input_fname != NULL ) { if( interrupted ) { break; } if( argc > 1 ) { if( argv[1][0] == '-' && argv[1][1] != '\0' ) { syntax( program ); } else { input_fname = argv[1]; argc--; argv++; } } if( strcmp( input_fname , "-" ) == 0 ) { iobuf->input_file = stdin; } else if( ( iobuf->input_file = fileopen( input_fname, READ_BINARY ) ) == NULL ) { perror( input_fname ); cout << "Cannot open input file." << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } string f_inputfilename = ""; if( input_fname ) { cout << "opening simtel file " << input_fname << endl; fflush( stdout ); fprintf( stderr, "%s\n", input_fname ); f_inputfilename = input_fname; printf( "\nInput file '%s' has been opened.\n", input_fname ); } input_fname = NULL; fRunPara_InputFileName += f_inputfilename; fRunPara_NumInputFiles++; if( fRunPara_NumInputFiles > 0 ) { fRunPara_InputFileName += ", "; } ///////////////////////////////////////////// // read in trigger mask if( trg_mask_dir.size() > 0 ) { string iFile = f_inputfilename; if( iFile.find_last_of( "/\\" ) != string::npos ) { iFile = iFile.substr( iFile.find_last_of( "/\\" ) + 1, iFile.find( "simtel.gz" ) - iFile.find_last_of( "/\\" ) - 1 ); } string trg_mask_file = trg_mask_dir + iFile + "trgmask.gz"; read_trigger_mask( trg_mask_file ); } ///////////////////////////////////////////// // Loop over all data in the input data file for( ;; ) { if( interrupted ) { break; } /* Find and read the next block of data. */ /* In case of problems with the data, just give up. */ if( find_io_block( iobuf, &item_header ) != 0 ) { break; } if( max_events > 0 && events >= max_events ) { if( iobuf->input_file != stdin ) { break; } if( skip_io_block( iobuf, &item_header ) != 0 ) { break; } continue; } if( read_io_block( iobuf, &item_header ) != 0 ) { break; } if( hsdata == NULL && item_header.type > IO_TYPE_HESS_RUNHEADER && item_header.type < IO_TYPE_HESS_RUNHEADER + 200 ) { fprintf( stderr, "Trying to read event data before run header.\n" ); fprintf( stderr, "Skipping this data block.\n" ); continue; } ////////////////////////////////////////// // check header types switch( ( int ) item_header.type ) { /* =================================================== */ case IO_TYPE_HESS_RUNHEADER: /* Summary of a preceding run in the same file ? */ if( nev > 0 ) { printf( "%d of %d events triggered.\n", ntrg, nev ); } nev = ntrg = 0; /* Structures might be allocated from previous run */ if( hsdata != NULL ) { /* Free memory allocated inside ... */ for( itel = 0; itel < hsdata->run_header.ntel; itel++ ) { if( hsdata->event.teldata[itel].raw != NULL ) { free( hsdata->event.teldata[itel].raw ); hsdata->event.teldata[itel].raw = NULL; } if( hsdata->event.teldata[itel].pixtm != NULL ) { free( hsdata->event.teldata[itel].pixtm ); hsdata->event.teldata[itel].pixtm = NULL; } if( hsdata->event.teldata[itel].img != NULL ) { free( hsdata->event.teldata[itel].img ); hsdata->event.teldata[itel].img = NULL; } } /* Free main structure */ free( hsdata ); hsdata = NULL; /* Perhaps some cleaning needed in ROOT as well ... */ } hsdata = ( AllHessData* ) calloc( 1, sizeof( AllHessData ) ); if( ( rc = read_hess_runheader( iobuf, &hsdata->run_header ) ) < 0 ) { cout << "Reading run header failed." << endl; exit( EXIT_FAILURE ); } if( !quiet ) { printf( "Reading simulated data for %d telescope(s)\n", hsdata->run_header.ntel ); } if( verbose || rc != 0 ) { printf( "read_hess_runheader(), rc = %d\n", rc ); } if( showdata ) { print_hess_runheader( iobuf ); } cout << "Telescope configuration: " << endl; for( itel = 0; itel < hsdata->run_header.ntel; itel++ ) { tel_id = hsdata->run_header.tel_id[itel]; hsdata->camera_set[itel].tel_id = tel_id; fTelescopeSimTelList[tel_id] = itel; cout << "\t initialize Telescope ID " << tel_id << " (is telescope # " << itel << ")" << endl; hsdata->camera_org[itel].tel_id = tel_id; hsdata->pixel_set[itel].tel_id = tel_id; hsdata->pixel_disabled[itel].tel_id = tel_id; hsdata->cam_soft_set[itel].tel_id = tel_id; hsdata->tracking_set[itel].tel_id = tel_id; hsdata->point_cor[itel].tel_id = tel_id; hsdata->event.num_tel = hsdata->run_header.ntel; hsdata->event.teldata[itel].tel_id = tel_id; hsdata->event.trackdata[itel].tel_id = tel_id; if( ( hsdata->event.teldata[itel].raw = ( AdcData* ) calloc( 1, sizeof( AdcData ) ) ) == NULL ) { cout << "Not enough memory" << endl; exit( EXIT_FAILURE ); } hsdata->event.teldata[itel].raw->tel_id = tel_id; if( ( hsdata->event.teldata[itel].pixtm = ( PixelTiming* ) calloc( 1, sizeof( PixelTiming ) ) ) == NULL ) { cout << "Not enough memory" << endl; exit( EXIT_FAILURE ); } hsdata->event.teldata[itel].pixtm->tel_id = tel_id; if( ( hsdata->event.teldata[itel].img = ( ImgData* ) calloc( 2, sizeof( ImgData ) ) ) == NULL ) { cout << "Not enough memory" << endl; exit( EXIT_FAILURE ); } hsdata->event.teldata[itel].max_image_sets = 2; hsdata->event.teldata[itel].img[0].tel_id = tel_id; hsdata->event.teldata[itel].img[1].tel_id = tel_id; hsdata->tel_moni[itel].tel_id = tel_id; hsdata->tel_lascal[itel].tel_id = tel_id; } break; /* =================================================== */ case IO_TYPE_HESS_MCRUNHEADER: rc = read_hess_mcrunheader( iobuf, &hsdata->mc_run_header ); if( verbose || rc != 0 ) { printf( "read_hess_mcrunheader(), rc = %d\n", rc ); } // if ( showdata ) print_hess_mcrunheader( iobuf ); // fill EVNDISP DST run header DST_fillMCRunheader( fMC_header, hsdata, ( fRunPara_NumInputFiles > 1 ) ); break; /* =================================================== */ case IO_TYPE_MC_INPUTCFG: { struct linked_string corsika_inputs; corsika_inputs.text = NULL; corsika_inputs.next = NULL; read_input_lines( iobuf, &corsika_inputs ); if( corsika_inputs.text != NULL ) { struct linked_string* xl = NULL, *xln = NULL; if( ! quiet ) { printf( "\nCORSIKA was run with the following input lines:\n" ); } for( xl = &corsika_inputs; xl != NULL; xl = xln ) { if( ! quiet ) { printf( " %s\n", xl->text ); } free( xl->text ); xl->text = NULL; xln = xl->next; xl->next = NULL; if( xl != &corsika_inputs ) { free( xl ); } } } } break; /* =================================================== */ case 70: /* How sim_hessarray was run and how it was configured. */ if( showhistory ) { list_history( iobuf, NULL ); } break; /* =================================================== */ case IO_TYPE_HESS_CAMSETTINGS: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Camera settings for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_camsettings( iobuf, &hsdata->camera_set[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_camsettings(), rc = %d\n", rc ); } break; /* =================================================== */ case IO_TYPE_HESS_CAMORGAN: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Camera organisation for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_camorgan( iobuf, &hsdata->camera_org[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_camorgan(), rc = %d\n", rc ); } if( showdata ) { print_hess_camorgan( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_PIXELSET: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Pixel settings for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_pixelset( iobuf, &hsdata->pixel_set[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_pixelset(), rc = %d\n", rc ); } if( showdata ) { print_hess_pixelset( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_PIXELDISABLE: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Pixel disable block for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_pixeldis( iobuf, &hsdata->pixel_disabled[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_pixeldis(), rc = %d\n", rc ); } break; /* =================================================== */ case IO_TYPE_HESS_CAMSOFTSET: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Camera software settings for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_camsoftset( iobuf, &hsdata->cam_soft_set[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_camsoftset(), rc = %d\n", rc ); } break; /* =================================================== */ case IO_TYPE_HESS_POINTINGCOR: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Pointing correction for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_pointingcor( iobuf, &hsdata->point_cor[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_pointingco(), rc = %d\n", rc ); } break; /* =================================================== */ case IO_TYPE_HESS_TRACKSET: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Tracking settings for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_trackset( iobuf, &hsdata->tracking_set[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_trackset(), rc = %d\n", rc ); } break; /* =================================================== */ case IO_TYPE_HESS_EVENT: rc = read_hess_event( iobuf, &hsdata->event, -1 ); if( verbose || rc != 0 ) { printf( "read_hess_event(), rc = %d\n", rc ); } events++; if( showdata ) { print_hess_event( iobuf ); } /* Count number of telescopes (still) present in data and triggered */ ntel_trg = 0; for( itel = 0; itel < hsdata->run_header.ntel; itel++ ) { if( hsdata->event.teldata[itel].known ) { /* If non-triggered telescopes record data (like HEGRA), we may have to check the central trigger bit as well, but ignore this for now. */ ntel_trg++; } } if( hsdata->event.shower.known ) { hsdata->event.shower.num_trg = ntel_trg; } if( ntel_trg < min_tel_trg ) { continue; } ntrg++; // fill EVNDISP DST event if( !fWriteTelConfigTreeOnly ) { DST_fillEvent( fDST, hsdata, fTelescope_list, fWriteFADC ); } break; /* =================================================== */ case IO_TYPE_HESS_CALIBEVENT: { int type = -1; rc = read_hess_calib_event( iobuf, &hsdata->event, -1, &type ); if( verbose || rc != 0 ) { printf( "read_hess_calib_event(), rc = %d, type=%d\n", rc, type ); } if( !fWriteTelConfigTreeOnly ) { DST_fillEvent( fDST, hsdata, fTelescope_list, fWriteFADC ); } } break; /* =================================================== */ case IO_TYPE_HESS_MC_SHOWER: rc = read_hess_mc_shower( iobuf, &hsdata->mc_shower ); if( verbose || rc != 0 ) { printf( "read_hess_mc_shower(), rc = %d\n", rc ); } if( showdata ) { print_hess_mc_shower( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_MC_EVENT: rc = read_hess_mc_event( iobuf, &hsdata->mc_event ); if( verbose || rc != 0 ) { printf( "read_hess_mc_event(), rc = %d\n", rc ); } if( showdata ) { print_hess_mc_event( iobuf ); } DST_fillMCEvent( fDST, hsdata ); break; /* =================================================== */ case IO_TYPE_MC_TELARRAY: if( hsdata && hsdata->run_header.ntel > 0 ) { rc = read_hess_mc_phot( iobuf, &hsdata->mc_event ); if( verbose || rc != 0 ) { printf( "read_hess_mc_phot(), rc = %d\n", rc ); } } break; /* =================================================== */ case IO_TYPE_HESS_MC_PE_SUM: rc = read_hess_mc_pe_sum( iobuf, &hsdata->mc_event.mc_pesum ); if( verbose || rc != 0 ) { printf( "read_hess_mc_pe_sum(), rc = %d\n", rc ); } if( showdata ) { print_hess_mc_pe_sum( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_TEL_MONI: // Telescope ID among others in the header tel_id = ( item_header.ident & 0xff ) | ( ( item_header.ident & 0x3f000000 ) >> 16 ); if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Telescope monitor block for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_tel_monitor( iobuf, &hsdata->tel_moni[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_tel_monitor(), rc = %d\n", rc ); } if( showdata ) { print_hess_tel_monitor( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_LASCAL: tel_id = item_header.ident; // Telescope ID is in the header if( ( itel = find_tel_idx( tel_id ) ) < 0 ) { char msg[256]; snprintf( msg, sizeof( msg ) - 1, "Laser/LED calibration for unknown telescope %d.", tel_id ); cout << msg << endl; exit( EXIT_FAILURE ); } rc = read_hess_laser_calib( iobuf, &hsdata->tel_lascal[itel] ); if( verbose || rc != 0 ) { printf( "read_hess_laser_calib(), rc = %d\n", rc ); } if( showdata ) { print_hess_laser_calib( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_RUNSTAT: rc = read_hess_run_stat( iobuf, &hsdata->run_stat ); if( verbose || rc != 0 ) { printf( "read_hess_run_stat(), rc = %d\n", rc ); } if( showdata ) { print_hess_run_stat( iobuf ); } break; /* =================================================== */ case IO_TYPE_HESS_MC_RUNSTAT: rc = read_hess_mc_run_stat( iobuf, &hsdata->mc_run_stat ); if( verbose || rc != 0 ) { printf( "read_hess_mc_run_stat(), rc = %d\n", rc ); } if( showdata ) { print_hess_mc_run_stat( iobuf ); } break; default: if( !ignore ) { fprintf( stderr, "Ignoring data block type %ld\n", item_header.type ); } } } if( iobuf->input_file != NULL && iobuf->input_file != stdin ) { fileclose( iobuf->input_file ); } iobuf->input_file = NULL; reset_io_block( iobuf ); if( nev > 0 ) { printf( "%d of %d events triggered\n", ntrg, nev ); } if( hsdata != NULL ) { hsdata->run_header.run = 0; } } // end while loop over all input files //////////////////////////////////////////////////// cout << "writing DST, MC and detector trees" << endl; if( fDST && fDST->getDSTTree() ) { fDST->getDSTTree()->Write(); cout << "\t (writing " << fDST->getDSTTree()->GetEntries() << " events)" << endl; } if( fDST && fDST->getMCTree() ) { cout << "\t (writing " << fDST->getMCTree()->GetEntries() << " MC events)" << endl; fDST->getMCTree()->Write(); } // writing detector tree TTree* i_detTree = DST_fill_detectorTree( hsdata, fTelescope_list, fApplyCameraScaling, fCameraScalingMap ); if( i_detTree ) { i_detTree->Write(); } // writing Monte Carlo header if( fMC_header ) { fMC_header->Write(); fMC_header->print(); } // writing calibration data TList* i_calibTree = DST_fillCalibrationTree( fDST, hsdata, fTelescope_list, ped_file, fNSB_scaling ); if( fDSTfile ) { fDSTfile->cd(); } if( i_calibTree ) { i_calibTree->Write(); } /////////////////////////////////////////////////// // writing run parameters to dst file VEvndispRunParameter* fRunPara = new VEvndispRunParameter( false ); fRunPara->SetName( "runparameterDST" ); fRunPara->setSystemParameters(); fRunPara->fEventDisplayUser = "CTA-DST"; fRunPara->frunnumber = fDST->getDSTRunNumber(); fRunPara->getObservatory() = "CTA"; fRunPara->fsourcetype = 7; // 7 is DST - MC fRunPara->fsourcefile = fRunPara_InputFileName; fRunPara->fIsMC = true; fRunPara->fCalibrationDataType = 0; // no pedvars available fRunPara->fFADCChargeUnit = "PE"; fRunPara->fNTelescopes = fNTel_checked; if( fRunPara->fNTelescopes == 0 && i_detTree ) { fRunPara->fNTelescopes = ( unsigned int )i_detTree->GetEntries(); } fRunPara->fpulsetiminglevels = getPulseTimingLevels(); fRunPara->setPulseZeroIndex(); fRunPara->Write(); /////////////////////////////////////////////////// if( fDSTfile ) { fDSTfile->Close(); } fStopWatch.Stop(); fStopWatch.Print(); cout << "MC events written to DST file: " << dst_file << endl; cout << "exit..." << endl; return 0; }
b5c042e607a3ac1c6bbe148ebdd50d683167c7f9
d90cc5b23233e1a6f48bc2de2d8831370d953a9f
/HACKEDGame/Source/HACKED/InGame/AI/SR_LS/SecurityRobot_LS.cpp
74e719e8f2756785c2a826de0f15d23b011c69aa
[]
no_license
LJH960101/JHNet_HACKED
d1389fd9303932eda57b9742d75fc82a5543035a
13962fc4dc16ad4d852c09bec7a85be6a8b0f9a0
refs/heads/main
2023-06-15T00:43:43.398914
2021-07-04T08:22:38
2021-07-04T08:22:38
326,329,710
0
0
null
null
null
null
UTF-8
C++
false
false
5,149
cpp
SecurityRobot_LS.cpp
// Fill out your copyright notice in the Description page of Project Settings. // Classfication : SecurityRobot using (Laser Sword) // Weapon : Laser Sword // Range : Short #include "SecurityRobot_LS.h" #include "InGame/AI/HACKED_AI.h" #include "SR_LS_AnimInstance.h" #include "../SMR_AIController.h" #include "InGame/Character/HACKEDCharacter.h" #include "../../Stat/HpComponent.h" #include "InGame/Stat/PlayerDamageEvent.h" #include "GameFramework/CharacterMovementComponent.h" // Sets default values ASecurityRobot_LS::ASecurityRobot_LS() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; GetCapsuleComponent()->InitCapsuleSize(45.0f, 88.0f); GetMesh()->SetRelativeLocationAndRotation(FVector(0.0f, 0.0f, 30.0f), FRotator(0.0f, -90.0f, 0.0f)); static ConstructorHelpers::FObjectFinder<USkeletalMesh> SK_CARDBOARD(TEXT("SkeletalMesh'/Game/Resources/Enemy/AI/SecurityRobot_LS/Saver_riggiedmesh.Saver_riggiedmesh'")); if (SK_CARDBOARD.Succeeded()) { GetMesh()->SetSkeletalMesh(SK_CARDBOARD.Object); } GetMesh()->SetAnimationMode(EAnimationMode::AnimationBlueprint); static ConstructorHelpers::FClassFinder<UAnimInstance> SR_LS_AnimationBP(TEXT("AnimBlueprint'/Game/Resources/Enemy/AI/SecurityRobot_LS/SecurityRobot_LS_TEST_BP.SecurityRobot_LS_TEST_BP_C'")); if (SR_LS_AnimationBP.Succeeded()) { GetMesh()->SetAnimInstanceClass(SR_LS_AnimationBP.Class); } AIControllerClass = ASMR_AIController::StaticClass(); AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned; IsAttacking = false; } // Called when the game starts or when spawned void ASecurityRobot_LS::BeginPlay() { Super::BeginPlay(); HpComponent->SetMaxHP(GetMaxHp()); BindRPCFunction(NetBaseCP, ASecurityRobot_LS, LS_Attack1); BindRPCFunction(NetBaseCP, ASecurityRobot_LS, LS_Attack2); } void ASecurityRobot_LS::Reconnect() { Super::Reconnect(); _ResetAI(); } void ASecurityRobot_LS::Reconnected() { Super::Reconnected(); _ResetAI(); } void ASecurityRobot_LS::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); } void ASecurityRobot_LS::PostInitializeComponents() { Super::PostInitializeComponents(); InitAIStatByType(EHackedAIType::SR_LS); LS_Anim = Cast<USR_LS_AnimInstance>(GetMesh()->GetAnimInstance()); CHECK(nullptr != LS_Anim); LS_Anim->OnMontageEnded.AddDynamic(this, &ASecurityRobot_LS::OnAttackMontageEnded); LS_Anim->OnAttackHitCheck.AddUObject(this, &ASecurityRobot_LS::LS_Damaging); } void ASecurityRobot_LS::LS_Attack(UBehaviorTreeComponent* OwnerComp) { savedCp = OwnerComp; if (FMath::RandBool()) LS_Attack1(); else LS_Attack2(); } void ASecurityRobot_LS::LS_NextAttack() { if (currentAnimation == 1) LS_Attack2(); else LS_Attack1(); } bool ASecurityRobot_LS::OnAttack() { return IsAttacking; } void ASecurityRobot_LS::LS_Attack1() { RPC(NetBaseCP, ASecurityRobot_LS, LS_Attack1, ENetRPCType::MULTICAST, true); currentAnimation = 1; LS_Anim->PlayAttackMontage(); LS_Anim->JumpToAttackMontageSection(currentAnimation); IsAttacking = true; } void ASecurityRobot_LS::LS_Attack2() { RPC(NetBaseCP, ASecurityRobot_LS, LS_Attack2, ENetRPCType::MULTICAST, true); currentAnimation = 2; LS_Anim->PlayAttackMontage(); LS_Anim->JumpToAttackMontageSection(currentAnimation); IsAttacking = true; } void ASecurityRobot_LS::_ResetAI() { LS_Anim->StopMontage(); currentAnimation = 0; IsAttacking = false; } void ASecurityRobot_LS::OnEnableAI(bool isEnable) { Super::OnEnableAI(isEnable); if (!isEnable) { _ResetAI(); } } void ASecurityRobot_LS::OnSpawn() { Super::OnSpawn(); LS_Anim->SetDeadAnim(false); _ResetAI(); } void ASecurityRobot_LS::OnAttackMontageEnded(UAnimMontage * Montage, bool bInterrupted) { CHECK(IsAttacking); if (!bInterrupted) { IsAttacking = false; OnAttackEnd.ExecuteIfBound(savedCp); } } void ASecurityRobot_LS::LS_Damaging() { TArray<FHitResult> HitResult; FCollisionQueryParams Params(NAME_None, false, this); bool bResult = GetWorld()->SweepMultiByChannel( HitResult, GetActorLocation(), GetActorLocation() + GetActorForwardVector() * GetAttackRange(), FQuat::Identity, ECollisionChannel::ECC_GameTraceChannel10, FCollisionShape::MakeSphere(70.0f), Params); //#if ENABLE_DRAW_DEBUG // // FVector TraceVec = GetActorForwardVector() * GetAttackRange(); // FVector Center = GetActorLocation() + TraceVec * 0.5f; // float HalfHeight = GetAttackRange() * 0.5f + 50.0f; // FQuat CapsuleRot = FRotationMatrix::MakeFromZ(TraceVec).ToQuat(); // FColor DrawColor = bResult ? FColor::Green : FColor::Red; // float DebugLifeTime = 5.0f; // // DrawDebugCapsule(GetWorld(), // Center, // HalfHeight, // 50.0f, // CapsuleRot, // DrawColor, // false, // DebugLifeTime); // //#endif // TArray<AActor*> hitActors; for (auto Hit : HitResult) { if (Hit.GetActor() && !hitActors.Contains(Hit.GetActor())) { AHACKEDCharacter* pc = Cast<AHACKEDCharacter>(Hit.GetActor()); if (!pc) continue; FDamageEvent DamageEvent; pc->TakeDamage(GetAIAttackDamage(), DamageEvent, GetController(), this); hitActors.Add(Hit.GetActor()); } } }
4226813a22bcd4c1a192ae32067bda219a4e87b7
3a5f43ec453e0fa2873ef82b5ab2e52aa6aaf869
/Project 5 - Inheritance/Bear.h
59cc024ec5da6539c72bb379166bee037a4b094b
[]
no_license
ke-d/Cplusplus-Projects
8091f95ba2dd2e65254a54c96198ba544d5eb16c
dc6fc9bc5813a7f628da11cbd38c1c808afdd131
refs/heads/master
2021-03-24T13:53:05.033616
2016-11-14T20:45:38
2016-11-14T20:45:38
66,525,086
0
1
null
null
null
null
UTF-8
C++
false
false
405
h
Bear.h
/* * Bear.h * * Created on: Oct 31, 2016 * Author: Kenny Do */ #ifndef BEAR_H_ #define BEAR_H_ #include "Mammal.h" class Bear : public Mammal { public: /** * Precondition: * None * Postcondition: * Constructor for Bear */ Bear(); /** * Precondition: * None * Postcondition: * Returns how the bear talks */ std::string talk() const; }; #endif /* BEAR_H_ */
f3f32994bc82904a7bd47be47205d5d1cca3a275
aa2201be6fb519b6b617ac0c7cc4a84c8154d571
/src/Grafics/ImageToGrafics.h
bc61671595ea667f6cabe34af5c20dc60f84b106
[]
no_license
jonasfehr/Laser_tools_V2
a4dd901b599c05e8fe8ca9a8957a72d1697c7c33
4539ab10b443b48b5d17487224af3ae701c7d1d4
refs/heads/master
2020-03-28T12:33:27.104103
2018-09-11T12:00:55
2018-09-11T12:00:55
148,310,304
1
0
null
null
null
null
UTF-8
C++
false
false
2,149
h
ImageToGrafics.h
// // TextToGrafics.h // Laser_tools_V2 // // Created by Jonas Fehr on 19/06/2017. // // #ifndef TextToGrafics_h #define TextToGrafics_h #include "ofxIldaFrame.h" #include "ofxIldaRenderTarget.h" class TextInput{ public: vector<ofxIlda::Poly> polys; ofFloatColor color; ofxIlda::RenderTarget ildaFbo; ofTrueTypeFont font; ofParameterGroup parameters; string fontPath = "fonts/Zebulon.ttf"; TextInput() { ildaFbo.setup(512, 512); parameters.setName("RenderTarget"); parameters.add(ildaFbo.parameters); ofDirectory dir("fonts"); dir.listDir(); if(dir.size()>0) fontPath = dir.getPath(0); font.load(fontPath, 120); }; //void setSpOF() void setSize(float _size) { font.load(fontPath, _size); }; void setColor(ofColor col) { color = col; }; void setColor(ofFloatColor col) { color = col; }; void setText(string _text) { text = _text; }; // Method to update location void update() { //ofPushStyle(); ildaFbo.begin(); { //ofClear(0); ofBackground(255); ofRectangle rect = font.getStringBoundingBox(text, 0,0); // ofRectangle myRect; // myRect.x = 5-rect.width/2; // myRect.y = 5-rect.height; // myRect.width = rect.width+10; // myRect.height = rect.height+10; // // ofDrawRectRounded(myRect, 5); ofSetColor(0); glm::vec3 center = glm::vec3(ildaFbo.getWidth()/2, ildaFbo.getHeight()/2, 0.); font.drawString(text,center.x-rect.width/2,center.y+rect.height/2); } ildaFbo.end(); // ofPopStyle(); ofxIlda::Frame frame; ildaFbo.update(frame); polys = frame.getPolys(); }; private: string text; }; #endif /* TextToGrafics_h */
f2c90b326f3399f4c575d9d45ca09e3e7c74c520
7156b6909eed95b408f399fc2ee3522d8f1be33d
/StarCraft/Stage.cpp
383123de9fd4c6010089cf3d83a14bdff61f1c00
[]
no_license
beckchul/DirectX9_2D_StarCraft
9cfda97a05dfb5e8619edf59b01773ed71b0238e
9bb3c21749efa8c1ac3d9d96509b5074a5eee416
refs/heads/master
2022-11-15T08:24:33.742964
2020-07-13T14:10:59
2020-07-13T14:10:59
279,316,274
0
0
null
null
null
null
UTF-8
C++
false
false
9,793
cpp
Stage.cpp
#include "stdafx.h" #include "Stage.h" #include "TextureMgr.h" #include "ObjMgr.h" #include "Factory.h" #include "BackGround.h" #include "Mouse.h" #include "Interpace.h" #include "Probe.h" #include "MapResource.h" #include "Nexus.h" #include "AStar.h" #include "CollisionMgr.h" #include "Zealot.h" #include "Dragoon.h" #include "HighTemplar.h" #include "DarkTemplar.h" #include "Archon.h" #include "DarkArchon.h" #include "Shuttle.h" #include "Reaver.h" #include "Observer.h" #include "Scout.h" #include "Corsair.h" #include "Carrier.h" #include "Arbiter.h" #include "Fog.h" #include "SoundMgr.h" CStage::CStage() { } CStage::~CStage() { Release(); } HRESULT CStage::Initialize(void) { ObjMgr->AddGameObject(CFactory<CFog>::CreateGameObject(), OBJ_FOG); ObjMgr->AddGameObject(CFactory<CBackGround>::CreateGameObject(), OBJ_BACKGROUND); ObjMgr->AddGameObject(CFactory<CMouse>::CreateGameObject(TEAM_PLAYER), OBJ_MOUSE); ObjMgr->AddGameObject(CFactory<CInterpace>::CreateGameObject(TEAM_PLAYER), OBJ_INTERPACE); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 300.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 330.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 360.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 390.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); /*ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 200.f, MAXSCROLLY + 100.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 200.f, MAXSCROLLY + 140.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 200.f, MAXSCROLLY + 160.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 200.f, MAXSCROLLY + 180.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDragoon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 50.f, 0.f), TEAM_PLAYER), OBJ_UNIT);*/ //ObjMgr->AddGameObject(CFactory<CHighTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 100.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CHighTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 130.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CDarkTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 160.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CDarkTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 190.f, 0.f), TEAM_PLAYER), OBJ_UNIT); // //ObjMgr->AddGameObject(CFactory<CDarkArchon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 100.f, MAXSCROLLY + 250.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CShuttle>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 150.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CReaver>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 150.f, MAXSCROLLY + 50.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CObserver>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 150.f, MAXSCROLLY + 100.f, 0.f), TEAM_PLAYER), OBJ_UNIT); //ObjMgr->AddGameObject(CFactory<CScout>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 150.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); /*ObjMgr->AddGameObject(CFactory<CCorsair>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 190.f, MAXSCROLLY + 150.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCarrier>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 170.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCarrier>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 200.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCarrier>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 230.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCarrier>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 260.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT);*/ //ObjMgr->AddGameObject(CFactory<CArbiter>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX + 300.f, MAXSCROLLY + 0.f, 0.f), TEAM_PLAYER), OBJ_UNIT); /*ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 100.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 140.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 180.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 220.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 550.f, MAXSCROLLY - 100.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 550.f, MAXSCROLLY - 140.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 550.f, MAXSCROLLY - 180.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CZealot>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 550.f, MAXSCROLLY - 220.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDragoon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 260.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDragoon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDragoon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 500.f, MAXSCROLLY - 340.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDragoon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 100.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CHighTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 140.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDarkTemplar>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 180.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CArchon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 220.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CDarkArchon>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 260.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CShuttle>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CReaver>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 460.f, MAXSCROLLY - 340.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CObserver>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 1000.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CScout>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 600.f, MAXSCROLLY -300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCorsair>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 700.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CCarrier>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 800.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CArbiter>::CreateGameObject(D3DXVECTOR3(MAXSCROLLX - 900.f, MAXSCROLLY - 300.f, 0.f), TEAM_ENEMY), OBJ_UNIT);*/ SoundMgr->PlayBGM(L"protoss.wav", CHANNEL_BGM, 0.35f); ObjMgr->AddGameObject(CFactory<CNexus>::CreateGameObject(D3DXVECTOR3(3809.f, 3793.f, 0.f), TEAM_PLAYER), OBJ_BUILD); ObjMgr->AddGameObject(CFactory<CNexus>::CreateGameObject(D3DXVECTOR3(3808.f, 240.f, 0.f), TEAM_ENEMY), OBJ_BUILD); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(3898.f, 200.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(3898.f, 240.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(3898.f, 280.f, 0.f), TEAM_ENEMY), OBJ_UNIT); ObjMgr->AddGameObject(CFactory<CProbe>::CreateGameObject(D3DXVECTOR3(3898.f, 350.f, 0.f), TEAM_ENEMY), OBJ_UNIT); list<RESOURCE*> ResourceList = ObjMgr->GetReourceList(); list<RESOURCE*>::iterator iter = ResourceList.begin(); list<RESOURCE*>::iterator iter_end = ResourceList.end(); for (; iter != iter_end; ++iter) { ObjMgr->AddGameObject(CFactory<CMapResource>::CreateGameResource( (*iter)->vPos, (*iter)->vSize, (*iter)->eType), OBJ_RESOURCE); } return S_OK; } int CStage::Update(void) { list<CGameObject*> pGroundUnitList = ObjMgr->GetList()[OBJ_UNIT]; list<CGameObject*> pGroundUnitList2 = ObjMgr->GetList()[OBJ_UNIT]; for (list<CGameObject*>::iterator iter = pGroundUnitList.begin(); iter != pGroundUnitList.end(); ++iter) { CCollisionMgr::CollisionObjectRectEX((*iter), pGroundUnitList); } //list<CGameObject*> pArrUnitList = ObjMgr->GetList()[OBJ_UNIT]; //CCollisionMgr::CollisionObjectRectAirEX(pArrUnitList, pArrUnitList); ObjMgr->Update(); CGameObject* pMouse = ObjMgr->GetList()[OBJ_MOUSE].front(); if (pMouse->GetSubState() == MOUSE_ATTACK_POINT_NOMAL || pMouse->GetSubState() == MOUSE_ATTACK_POINT_PATOL || pMouse->GetSubState() == MOUSE_SKILL_POINT) pMouse->SetSubState(MOUSE_NOMAL); return 0; } void CStage::Render(void) { ObjMgr->Render(); } void CStage::Release(void) { ObjMgr->DestroyInstance(); TextureMgr->DestroyInstance(); }
9ee39b57a9cc4e6f115f4af7af1d4b480c48341b
c55228590659819de99e2d06f89fe2cb31f90dcb
/problemsolutions.hpp
c048aa3a308bc7fc7193ad740d82e83d83ddeaa3
[ "Apache-2.0" ]
permissive
raoasifraza11/Practice-OnArray-DS
d440ad9904dae0f46bd5309e1c8a2a23e9f4723f
882e31cccd6b943181dd8e82c0cd31baf160688b
refs/heads/master
2020-09-15T19:47:04.655435
2016-09-04T10:14:43
2016-09-04T10:14:43
67,281,996
0
1
null
2016-09-04T10:14:44
2016-09-03T09:24:21
C++
UTF-8
C++
false
false
462
hpp
problemsolutions.hpp
// // problem_solution_1.hpp // AssignmentNo1 // // ******** problemsolutions.hpp ********** // // // Created by Asif Raza on 03/09/2016. // Copyright © 2016 Asif Raza. All rights reserved. // #ifndef problemsolutions_hpp #define problemsolutions_hpp #include <stdio.h> #include <iostream> // <<, >>, cout, cin void problem1(); void problem2(); void problem3(); void problem4(); void problem5(); void problem6(); #endif /* problemsolutions_hpp */
6f2a20c7a7ef0b06a2895de18d77b2a7321cf2f8
4f457fd302f960d7db7228b78910c1bde98460ea
/Codechef/TALAZY.cpp
5dde27b385a6e36efef62d6a2f726a9875285287
[]
no_license
pechavarriaa/CP
36fc174b6c379541d20ecc01cb254c13a917984a
bf65e80f36309aa8b936d805ba97cb048edf049b
refs/heads/master
2020-06-10T04:18:47.910135
2019-10-24T20:55:13
2019-10-24T20:55:13
76,089,688
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
TALAZY.cpp
#include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std; int i, j,t,arr[1200]; long long res,m,n,ni,b,fg; int main() { scanf("%d",&t); while(t--) { scanf("%lld%lld%lld",&n,&b,&m); res=0;fg=1; ni=n; while(fg && n>0) { if(n>1) n=(n+1)/2; else fg=0; res=res+b+n*m; m=m*2; ni=ni-n; n=ni; } printf("%lld\n",res-b); } }
9de15dece22cf13a5191c663b1b2ab97b07563c7
1042718b2da9c125e21542987d451376566fab02
/b1lib/src/win32/dlfcn.cc
ddadceb3c45af29dd862500b43ff66c236a663f4
[]
no_license
pingworld/base
be251fca879f3a52bcefb5d0a7606a3d738b2fc1
aa626c0b8f36ab4dbcb267ecbca1208b8e6cc48d
refs/heads/master
2021-01-19T01:02:40.820859
2016-07-30T07:00:18
2016-07-30T07:00:18
64,270,360
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cc
dlfcn.cc
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <stdio.h> #include <windows.h> #include <stdbool.h> #include "dlfcn.h" /* * Keep track if the user tried to call dlopen(NULL, xx) to be able to give a sane * error message */ static bool self = false; void* dlopen(const char* path, int mode) { if (path == NULL) { // We don't support opening ourself self = true; return NULL; } void* handle = LoadLibrary(path); if (handle == NULL) { char *buf = (char *)malloc(strlen(path) + 20); sprintf(buf, "%s.dll", path); handle = LoadLibrary(buf); free(buf); } return handle; } void* dlsym(void* handle, const char* symbol) { return GetProcAddress((HMODULE)handle, symbol); } int dlclose(void* handle) { // dlclose returns zero on success. // FreeLibrary returns nonzero on success. return FreeLibrary((HMODULE)handle) != 0; } static char dlerror_buf[200]; const char *dlerror(void) { if (self) { return "not supported"; } DWORD err = GetLastError(); LPVOID error_msg; if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, (LPTSTR)&error_msg, 0, NULL) != 0) { strncpy(dlerror_buf, (const char *)error_msg, sizeof(dlerror_buf)); dlerror_buf[sizeof(dlerror_buf) - 1] = '\0'; LocalFree(error_msg); } else { return "Failed to get error message"; } return dlerror_buf; }
7a9f4dc23f5ac3044bbb8cb9835bb3f38cc6cb83
24dbf1229661f54dba50712b9b65443d2fe43dbd
/Leetcode/July LeetCoding Challenge/Day 2 Binary Tree Level Order Traversal II.cpp
df31ce12d8da0072fed5e07fa337377c74131b25
[]
no_license
royantar0311/Problem-Solving
f55a072ba01f67a7ed136786bce5caceb2d03035
f1338be55eae2cc4888e31d5155f65c6ceffdf2e
refs/heads/master
2020-12-21T20:23:43.832945
2020-07-02T14:38:33
2020-07-02T14:38:33
236,548,109
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
Day 2 Binary Tree Level Order Traversal II.cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { map<int, vector<int>>soln; void dfs(TreeNode* cur, int level){ if(cur == NULL)return; dfs(cur->left,level+1); dfs(cur->right,level+1); soln[level].push_back(cur->val); return; } public: vector<vector<int>> levelOrderBottom(TreeNode* root) { dfs(root,0); vector<vector<int>>ret(soln.size()); for(auto i:soln){ for(auto j:i.second){ ret[ret.size()-i.first-1].push_back(j); } } return ret; } };
63a2df5eb96a162dd2a9fd7cc3275e062dd23243
d71dd68917da0d3dce22a71dd81cace3052c11c7
/Source/CLI/CLI_Main.cpp
11c88a25fe9717bb81653aff6f187f248c653126
[ "BSD-3-Clause" ]
permissive
mipops/dvrescue
9b17508218904ffafb9a50c48db4bd047d41dfb2
5dbc67e460af4d9c794b21dc5da45145923ffde7
refs/heads/main
2023-08-21T14:52:57.242835
2023-08-14T13:35:11
2023-08-14T13:35:11
185,495,687
70
14
BSD-3-Clause
2023-08-14T13:35:13
2019-05-08T00:06:10
C++
UTF-8
C++
false
false
1,075
cpp
CLI_Main.cpp
/* Copyright (c) MIPoPS. All Rights Reserved. * * Use of this source code is governed by a BSD-3-Clause license that can * be found in the LICENSE.txt file in the root of the source tree. */ //--------------------------------------------------------------------------- #include "CLI/CommandLine_Parser.h" #include "Common/Core.h" #include <iostream> //--------------------------------------------------------------------------- //*************************************************************************** // Main //*************************************************************************** int main(int argc, const char* argv[]) { // Environment setlocale(LC_ALL, ""); // Configure Core C; C.Out = &cout; C.Err = &cerr; if (auto ReturnValue = Parse(C, argc, argv)) return ReturnValue; if (C.Inputs.empty()) return ReturnValue_OK; // Process auto ReturnValue = C.Process(); // Exit Clean(C); return ReturnValue; } //---------------------------------------------------------------------------