blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
bb2b255e3daa9c34584cf861a1683c414699e03b
5b702c0311e041b2a04763be9dd69bfccc4bfe5a
/lab1/Q9.cpp
03316a4c4440bc3e76da1090d7a380be350b38db
[]
no_license
locpk/Programming-I
77769c7ee814b448a465e5268593f20a38adb802
66b00001f889a0bb4c44fa2198a806e60e6280aa
refs/heads/master
2021-01-01T16:06:56.475314
2014-11-06T20:44:32
2014-11-06T20:44:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
#include "lab1.h" #include "..\Console.h" using namespace std; using namespace System; int Q9() { char ch = 'a'; cout << "What is your favorite letter? "; cin >> ch; cout << "The letter " << ch << " is between " << static_cast<char> (ch - 1) << " and " << static_cast<char> (ch + 1) << ".\n"; return EXIT_SUCCESS; }
[ "locpk123@gmail.com" ]
locpk123@gmail.com
6df0007c882da9cf942e32e2cccf2c7f4e9b0540
619a1b57f9f5741d7e05a063d9096456008c08f6
/src/display/ScorePanel.cpp
3f2f236ec5a96d9ed0c21f6a5340c4a946e29300
[]
no_license
aeonphyxius/AeonMidasMiner
2e1d245e59ba044620a33c9b88b72f2c62782561
a036df325f955e36dfd73f29952147232a1ea0da
refs/heads/master
2021-01-22T15:58:45.524980
2016-09-17T14:19:41
2016-09-17T14:19:41
68,412,732
0
0
null
null
null
null
UTF-8
C++
false
false
2,042
cpp
#include "ScorePanel.h" #include "EventManager.h" #include "ServiceManager.h" #include "GenericDelegate.h" #include "GameEvents.h" #include "EventData.h" #include <ScoreManager.h> #include <string> using namespace Display; using namespace Core; ScorePanel::ScorePanel(){ points_obj = new TextObject(); points_text_obj = new TextObject(); } ScorePanel::~ScorePanel(){ delete points_obj; delete points_text_obj; } void ScorePanel::onInitialize(){ //register events auto em = ServiceManager::getInstance()->getService<EventManager>(Services::EVENTS); em->addEventListener(events::SCORE_UPDATED, GenericDelegate::create <ScorePanel, &ScorePanel::onEvent>(this)); // load panel texture setTexture(Aeonphyxius::Engine::TEXTURE_SCORE_PANEL); // Score text and value points_text.assign("Points: "); points_obj->setPosition(glm::vec3(30.f, 40.f, 1)); points_obj->setScale(glm::vec3(0.5f, 0.5f, 1)); points_obj->setText(points_text); points_value_text.assign("0"); points_text_obj->setText(points_value_text); points_text_obj->setPosition(glm::vec3(70.f, 70.f, 1)); points_text_obj->setScale(glm::vec3(0.7f, 0.7f, 1)); addChild(points_obj); addChild(points_text_obj); auto ge = ServiceManager::getInstance()->getService<Aeonphyxius::Engine>(Services::ENGINE); obj_size = glm::vec2(ge->GetTextureHeight(Aeonphyxius::Engine::TEXTURE_SCORE_PANEL), ge->GetTextureHeight(Aeonphyxius::Engine::TEXTURE_SCORE_PANEL)); } void ScorePanel::onUpdate(){ DisplayObject::onUpdate(); auto score = ServiceManager::getInstance()->getService<ScoreManager>(Services::SCORE); points_value_text = std::to_string(score->getPoints()); points_text_obj->setText(points_value_text); auto engine = ServiceManager::getInstance()->getService<Aeonphyxius::Engine>(Services::ENGINE); engine->Write(points_obj); engine->Write(points_text_obj); } void ScorePanel::onEvent(EventData *par_evtdata){ if (par_evtdata->getEventName().compare(events::SCORE_UPDATED) == 0){ onScoreUpdated(); } } void ScorePanel::onScoreUpdated(){ }
[ "alejandro@2awesomestudio.com" ]
alejandro@2awesomestudio.com
e99458da12329bd5ca1a55fb2f00fba8dce1c07f
2446967f95e6ecf28508f6ccfe8f950e9dca9d12
/xcsp2test/bbstest/nbs_nei.cpp
9986560bbb32dd53f547b56b83d2a47a26cc678c
[]
no_license
JLUCPGROUP/xcsp2test
b9721fd7d9d49c394183a9dd2e41748c025cb62d
f7ebcea8b5334896a0c8ce7bb2630de7d097c211
refs/heads/master
2018-12-15T15:03:08.092900
2018-09-14T14:31:07
2018-09-14T14:31:07
118,115,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,743
cpp
//#pragma once //#include <sstream> //#include <string> //#include "BuildGModel.h" //#include "Timer.h" //#include "CPUSolver.h" //#include "XBuilder.h" //#include "GModel.h" //#include "SAC1o.h" //using namespace cp; //using namespace std; //#define LOGFILE // //const int TimeLimit = 600000; //const string X_PATH = "BMPath.xml"; // //int main() { // XBuilder builder(X_PATH, XRT_BM_PATH); // HModel* hm = new HModel(); // builder.GenerateHModel(hm); // GModel* gm = new GModel(); // BuildGModel(hm, gm); // //rel(gm*, gm->vs[0] , 0rel(*s, s->vs[i] == j.val());); // rel(*gm, gm->vs[0] == 0); // gm->status(); // //hm->show(); // gm->print(); // delete gm; // //vector<int> a; // //cout << "------------------modeling------------------" << endl; // //const SearchStatistics statistics = StartSearch(hm, Heuristic::DS_NB, Heuristic::VRH_DOM_MIN, Heuristic::VLH_MIN, TimeLimit, true, a, 0); // ////const SearchStatistics statistics = StartSearch(gm, hm, Heuristic::DS_BI, Heuristic::VRH_DOM_WDEG_MIN, Heuristic::VLH_MIN, TimeLimit, false, sac_time); // ////const SearchStatistics statistics = StartSearch(hm, Heuristic::VRH_DOM_DEG_MIN, Heuristic::VLH_MIN, TimeLimit, true, 0); // ////const SearchStatistics statistics = StartSearch(hm, Heuristic::VRH_DOM_WDEG_MIN, Heuristic::VLH_MIN, TimeLimit, true, 0); // //const string slv_str = (statistics.num_sol > 0) ? "SAT!!" : "UNSAT"; // //delete hm; // //cout << "|| Build time = " << statistics.build_time << endl; // //cout << "------------------solving-------------------" << endl; // //cout << slv_str << "|| Solve time = " << statistics.solve_time << "|| nodes = " << statistics.nodes << endl; // //cout << "------------------sleeping------------------" << endl; // // return 0; //} //
[ "leezear@live.cn" ]
leezear@live.cn
d3e98541e36bf273ffe561011b45a86a56f9aebe
0663da7c49f34ef6478fbe9e6598eeacf613ee07
/test/copy_construct_test1.cpp
0b9deca1a362b200ce2a51f9499d25007a5d97d6
[]
no_license
shijie152/demo
bc143a799c80f8b981a310575cfc95087df044a6
d225ea88a2db918485475c599abe5d9875e101d1
refs/heads/master
2022-04-26T22:43:32.419577
2020-04-30T06:09:35
2020-04-30T06:09:35
259,166,631
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
/*默认的copy_construct*/ #include <iostream> using namespace std; class People { private: int m_age; public: People(int age) : m_age(age) { cout << "constructor" << endl; } ~People() { cout << "destructor" << endl; } int getAge() const { return m_age; } }; int main() { People p1(18); cout << "p1's age " << p1.getAge() << endl; People p2(p1); cout << "p2's age " << p2.getAge() << endl; }
[ "32998158+shijie152@users.noreply.github.com" ]
32998158+shijie152@users.noreply.github.com
578be43c2a6d5a9fcb9dde2892b70338fff6ec6d
0aa065db5a5c88caed37a32b82adcad9d5df2505
/C++/Day/Day.cpp
7bc2ffe8c5ea81781396734e4c12ebca44fa8572
[]
no_license
psyoongsc/LauguageStudy
b62ec2fe0cf1b0acf794ee8fac8dcaf082fd2870
4eecab943cd112d28e7d3778a3abc02bf844c36d
refs/heads/master
2023-01-22T03:30:09.271492
2021-05-04T08:02:20
2021-05-04T08:02:20
140,408,832
0
0
null
2023-01-11T22:23:12
2018-07-10T09:25:31
C#
UHC
C++
false
false
3,878
cpp
#include "Day.h" /* January 31; February 28; LeapFrebruary 29; March 31; April 30; May 31; June 30; July 31; August 31; September 30; October 31; November 30; December 31; */ Day::Day() { time_t timer; struct tm *t; timer = time(NULL); t = localtime(&timer); year = t->tm_year + 1900; month = t->tm_mon + 1; day = t->tm_mday; dday = 0; } int Day::howManyDays() { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: //년도가 4라 나누어 떨어지면 윤년, 하지만 100으로 나누어 떨어지면 평년, 그 중에서도 400으로 나누어 떨어지면 윤년 if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { return 29; } else { return 28; } } else { return 29; } } else { return 28; } } } int Day::getYear() const { return year; } int Day::getMonth() const { return month; } int Day::getDay() const { return day; } void Day::setYear(int y) { year = y; } void Day::setMonth(int m) { month = m; } void Day::setDay(int d) { day = d; } const Day operator +(const Day& date, int day) { Day result; result.year = date.year; result.month = date.month; result.day = date.day + day; while (result.howManyDays() < result.day) { result.day -= result.howManyDays(); result.month++; if (result.month > 12) { result.year++; result.month = 1; } } return result; } const Day operator -(const Day& date, int day) { Day result; result.year = date.year; result.month = date.month; result.day = date.day - day; while (result.day < 0) { result.month--; if (result.month < 1) { result.year--; result.month = 12; } result.day += result.howManyDays(); } return result; } const Day& Day::operator ++() { day++; if (this->howManyDays() < day) { month++; day = 1; } if (month == 13) { year++; month = 1; } return *this; } const Day& Day::operator --() { day--; if (day == 0) { month--; if (month == 0) { year--; month = 12; } day = this->howManyDays(); } return *this; } void Day::moveDate(const char* date) { int tmp = atoi(date); year = tmp / 10000; tmp %= 10000; month = tmp / 100; tmp %= 100; day = tmp; while (month > 12) { month -= 12; year++; } while (day > this->howManyDays()) { day -= this->howManyDays(); if (++month == 13) { year++; month = 1; } } } ostream& operator <<(ostream& outputStream, const Day& d) { Day dd; outputStream << "[현재 날짜] " << d.year << "년 " << d.month << "월 " << d.day << "일 "; if (d.dday == 0) outputStream << "[D-day 없음] "; else { outputStream << "[D"; if (d.dday > 0) outputStream << "+"; outputStream << d.dday << "] "; if (d.dday > 0) dd = d + d.dday; else dd = d - abs(d.dday); outputStream << dd.year << "년 " << dd.month << "월 " << dd.day << "일"; } return outputStream; } istream& operator >>(istream& inputStream, Day& d) { string integer; char input; char sign; cout << "날짜 이동(년월일, (다음날)+, (전날)-), D-day 계산(+/- 날짜), 종료(Q) : "; inputStream >> input; if (input == 'Q' || input == 'q') exit(0); if (input == '+' || input == '-') { sign = input; inputStream.get(input); while (isdigit(input)) // 0-9 인 숫자만 받아들인다 { integer += input; inputStream.get(input); } if (integer != "") { d.dday = atoi(integer.c_str()); if (sign == '-') d.dday *= -1; } else { if (sign == '+') ++d; else --d; } } else if (!isdigit(input)) exit(0); else { while (isdigit(input)) { integer += input; inputStream.get(input); } if (integer.length() == 8) d.moveDate(integer.c_str()); // yyyymmdd 의 입력이 아니면 skip } return inputStream; }
[ "40999564+psyoongsc@users.noreply.github.com" ]
40999564+psyoongsc@users.noreply.github.com
e38e1eb9d7b7b254c2c9cded1bff602b3dccffd9
84cc4580e5bb8dda365932e31ec20ca45702f970
/Spike11/Spike11/Spike11/Message.h
f871134c513d7e4af8c663474b11e4960465fd8e
[]
no_license
PubFork/gp-code
e21573b3dc5dd580ee6cc078336e5031ae4e932f
e7b7e1cd785afd58fe7e6e0d58293608c11c60e3
refs/heads/master
2020-07-08T16:36:03.620807
2016-11-07T10:45:44
2016-11-07T10:45:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
405
h
#pragma once #include <sstream> #include "Object.h" #include "BinaryReader.h" #include "BinaryWriter.h" class Message : public Object { private: std::stringstream _content; BinaryReader _reader; BinaryWriter _writer; protected: BinaryWriter& write(); public: Message(std::string content); Message(); virtual ~Message(); virtual std::string to_string() const override; BinaryReader& read(); };
[ "jtunaley@gmail.com" ]
jtunaley@gmail.com
bdac2f5fdeff023057a57c8dd55cc3881ff7628c
27c75711bbe10b3120c158971bb4e830af0c33e8
/Codeforces/CF538/C.cpp
84eb8b8faf9e916538aa7e26ee326c1ca2e6be18
[]
no_license
yl3i/ACM
9d2f7a6f3faff905eb2ed6854c2dbf040a002372
29bb023cb13489bda7626f8105756ef64f89674f
refs/heads/master
2021-05-22T02:00:56.486698
2020-04-04T05:45:10
2020-04-04T05:45:10
252,918,033
0
0
null
2020-04-04T05:36:11
2020-04-04T05:36:11
null
UTF-8
C++
false
false
988
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <ctime> #include <cassert> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <set> #include <map> #include <queue> #include <deque> #include <bitset> #include <algorithm> #define MST(a, b) memset(a, b, sizeof(a)) #define REP(i, a) for (int i = 0; i < int(a); i++) #define REPP(i, a, b) for (int i = int(a); i <= int(b); i++) using namespace std; const int N = 1e5 + 5; int h[N], d[N]; int main() { ios :: sync_with_stdio(0); int ans = 0, good = 1; int n, m; cin >> n >> m; REPP(i, 1, m) cin >> d[i] >> h[i]; REPP(i, 2, m) { if (abs(h[i] - h[i - 1]) > d[i] - d[i - 1]) { good = 0; break; } else { ans = max(ans, (h[i] + h[i - 1] + d[i] - d[i - 1]) / 2); } } if (good) { ans = max(ans, h[m] + (n - d[m])); ans = max(ans, h[1] + d[1] - 1); cout << ans << endl; } else { cout << "IMPOSSIBLE" << endl; } return 0; }
[ "yuzhou627@gmail.com" ]
yuzhou627@gmail.com
ea8225056685b6b87f301da3d1cfbf04c6e602fd
8e390bed32bc6662e433a244a576d3835bd79cd5
/src/log.h
0f7e1fd0f6c02531020bb559c4eac25e3c165dcd
[]
no_license
SamuelBailey/Cpp-Classes
d533f5d51f82e9a0927783cb8854d813b26960bb
9b9b817635da0113331eaf713b7f07418156c3ef
refs/heads/master
2022-11-02T06:36:59.099837
2020-06-21T19:53:48
2020-06-21T19:53:48
273,763,014
0
0
null
null
null
null
UTF-8
C++
false
false
309
h
#pragma once class Log { public: enum Level : unsigned char { ERROR, WARNING, INFO }; private: Level logLevel = INFO; public: void setLevel(Level level); void warn(const char* message); void error(const char* message); void info(const char* message); };
[ "samuelrbailey19@gmail.com" ]
samuelrbailey19@gmail.com
7c78576547316f5bd5e3688b7897bdd133601f03
583b2b81e0e7ac3c910bc00204f877aa9c48bdae
/Analysis/HiggsNuNu/LightTreeAna/interface/DataNormShape.h
8e6667baab0f24b8f7a408744a126e5bc542783d
[]
no_license
danielwinterbottom/ICHiggsTauTau
8c88a3322c8e362114a53c559634a7ecceb266d2
69f6b580ec1faa4e5b6ef931be880f939f409979
refs/heads/master
2023-09-01T17:49:18.865198
2023-02-07T13:14:15
2023-02-07T13:14:15
10,723,688
4
12
null
2023-09-07T08:41:44
2013-06-16T18:08:22
Python
UTF-8
C++
false
false
2,311
h
#ifndef ICHiggsTauTau_HiggsNuNu_DataNormShape_h #define ICHiggsTauTau_HiggsNuNu_DataNormShape_h #include "UserCode/ICHiggsTauTau/Analysis/HiggsNuNu/LightTreeAna/interface/LightTreeModule.h" #include "UserCode/ICHiggsTauTau/Analysis/HiggsNuNu/LightTreeAna/interface/LightTreeFiles.h" #include "UserCode/ICHiggsTauTau/Analysis/HiggsNuNu/interface/HiggsNuNuAnalysisTools.h" #include <string> namespace ic { class DataNormShape : public LTModule{ CLASS_MEMBER(DataNormShape,std::vector<std::string>,shape) CLASS_MEMBER(DataNormShape,std::vector<std::string>,shapename) CLASS_MEMBER(DataNormShape,std::string,sigmcset) CLASS_MEMBER(DataNormShape,std::string,contmcset) CLASS_MEMBER(DataNormShape,std::vector<std::string>,contbkgset) CLASS_MEMBER(DataNormShape,std::vector<std::string>,contbkgextrafactordir) CLASS_MEMBER(DataNormShape,std::vector<int>,contbkgisz) CLASS_MEMBER(DataNormShape,std::string,contdataset) CLASS_MEMBER(DataNormShape,std::string,sigcat) CLASS_MEMBER(DataNormShape,std::string,zextracontcat) CLASS_MEMBER(DataNormShape,std::string,contcat) CLASS_MEMBER(DataNormShape,std::string,contdataextrasel) CLASS_MEMBER(DataNormShape,std::string,contmcextrasel) CLASS_MEMBER(DataNormShape,std::string,contbkgextrasel) CLASS_MEMBER(DataNormShape,std::string,basesel) CLASS_MEMBER(DataNormShape,std::string,sigmcweight) CLASS_MEMBER(DataNormShape,std::string,contmcweight) CLASS_MEMBER(DataNormShape,std::string,contmczweight) CLASS_MEMBER(DataNormShape,std::string,contdataweight) CLASS_MEMBER(DataNormShape,double,sigcontextrafactor) CLASS_MEMBER(DataNormShape,bool,do_latex) CLASS_MEMBER(DataNormShape,bool,do_subsets) CLASS_MEMBER(DataNormShape,std::vector<std::string>,subsets) CLASS_MEMBER(DataNormShape,std::vector<std::string>,subsetdirs) CLASS_MEMBER(DataNormShape,std::string,dirname) public: virtual DataNormShape & set_shape(std::string const& shape) { std::vector<std::string> shapes; shapes.push_back(shape); shape_ = shapes; return *this; } DataNormShape(std::string); virtual ~DataNormShape(); virtual int Init(TFile*); virtual int Run(LTFiles*); }; } #endif
[ "pdunne@cern.ch" ]
pdunne@cern.ch
e6d8e72d7b300044987fd1e04e87cc8236d1519c
062b913ea243ce9ef85542d934c1ebfa116e2b77
/behavior_algorithms/src/current_translational_wiggle_pull.cpp
75706720c8c5fedefe2063ccbb6313b951e4b721
[]
no_license
cwru-robotics/compliant_behaviors
34afad570b9937c389ae5d6dc162be03accddf4c
a09e2cf6fa9d455fd846fe13eec1e68c7e6539a3
refs/heads/master
2023-05-23T16:29:46.340181
2021-06-18T15:51:14
2021-06-18T15:51:14
293,548,372
1
0
null
null
null
null
UTF-8
C++
false
false
11,468
cpp
// Translational Wiggle // Matthew Haberbusch, Surag Balajepalli, and Rahul Pokharna // Last updated 10/15/19 // // All ROS-specific code labeled with "ROS:" comments // ROS: include libraries #include <iostream> #include <sstream> #include <ros/ros.h> #include <cmath> #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/Wrench.h> #include <std_msgs/Float64.h> #include <std_msgs/Int8.h> #include <irb120_accomodation_control/freeze_service.h> // used to toggle the freeze service #include <behavior_algorithms/status_service.h> using namespace std; std_msgs::Int8 freeze_mode_status; bool freeze_mode; // maybe don't define it as having a starting value? bool freeze_updated = false; // Declare variables geometry_msgs::Pose current_pose; geometry_msgs::PoseStamped virtual_attractor; geometry_msgs::Wrench ft_in_current_frame; // ROS: callback functions for how we receive data void cartesian_state_callback(const geometry_msgs::PoseStamped& cartesian_pose) { current_pose = cartesian_pose.pose; } void ft_callback(const geometry_msgs::Wrench& ft_values) { // These are not values from the sensor. They are f/t values transformed into robot base frame. ft_in_current_frame = ft_values; } void freeze_status_callback(const std_msgs::Int8& freeze_status_msg) { freeze_updated = true; freeze_mode_status = freeze_status_msg; // cout<<freeze_mode_status<<endl; if(freeze_mode_status.data == 1) freeze_mode = true; else freeze_mode = false; } // ROS: main program int main(int argc, char** argv) { // ROS: for communication between programs ros::init(argc,argv,"translational_wiggle_pull"); ros::NodeHandle nh; // ROS: Define subscribers and publishers for the program ros::Subscriber cartesian_state_subscriber = nh.subscribe("interaction_port_frame",1, cartesian_state_callback); // subscribe to the topic publishing the cartesian state of the end effector ros::Subscriber ft_subscriber = nh.subscribe("current_frame_ft_wrench",1,ft_callback); // subscribe to the force/torque sensor data ros::Publisher virtual_attractor_publisher = nh.advertise<geometry_msgs::PoseStamped>("Virt_attr_pose",1); // publish the pose of the virtual attractor for the accomodation controller // ROS: Services used in conjunction with buffer.cpp to have delayed program status sent to operator ros::ServiceClient client = nh.serviceClient<behavior_algorithms::status_service>("status_service"); ros::ServiceClient client_start = nh.serviceClient<behavior_algorithms::status_service>("start_service"); // subscriber for freeze mode status (used in loop cond) ros::Subscriber freeze_mode_sub = nh.subscribe("freeze_mode_topic",1,freeze_status_callback); // service client for setting and unsetting freeze mode at start of program ros::ServiceClient freeze_client = nh.serviceClient<irb120_accomodation_control::freeze_service>("freeze_service"); // ROS: Service status variable for use with buffer.cpp behavior_algorithms::status_service srv; srv.request.name = "Translational Wiggle Pull"; // Declare constants /* How to tune params: MOVE_DISTANCE: The distance between the end effector and the virtual attractor in the axis of pull but not the rotation, keep positive as it is a pull, increase for greater force, decrease for lesser force FORCE_THRESHOLD: The limit at which the program will stop if the force threshold is crossed TORQUE_THRESHOLD: The limit at which the program will stop if the torque threshold is crossed WIGGLE_RADIUS: Radius of the wiggle, increase for larger virtual circle that the end effector follows WIGGLE_RATE: How many rotations we do per second in Hz Params not needed to be tuned: DT: Loop rate, how fast each iteration of the loop is (most likely not needed to be changed) WIGGLE_TIME: How long the program will run before timing out and ending, defined by user input, but has a default value of 5 */ double MOVE_DISTANCE = 0.01, DT = 0.01; double WIGGLE_RADIUS = 0.005, WIGGLE_RATE = 0.5, WIGGLE_TIME = 5; //! may want to change the radius double TORQUE_THRESHOLD = 2, FORCE_THRESHOLD = 20; // Params for iteration double current_loop = 0; // ROS: for loop rate ros::Rate naptime(1/DT); // ROS: for communication between programs ros::spinOnce(); naptime.sleep(); // The end effector pose (current_pose) and force torque data (ft_in_current_frame) are global variables. // ROS: get parameter from server, passed by command line (if nothing passed in, results in default, which is the final number) nh.param("/translational_wiggle_pull/wiggle_time", WIGGLE_TIME, 5.0); // clear parameter from server nh.deleteParam("/translational_wiggle_pull/wiggle_time"); ROS_INFO("Output from parameter for runtime; %f", WIGGLE_TIME); // With labeled parameter, now call service to send message that program will start std::ostringstream request_status; request_status << "runtime " << WIGGLE_TIME << " seconds"; srv.request.status = request_status.str(); // ROS: Call the client start service, used in buffer.cpp for operator output // if(client_start.call(srv)){ // uncomment for time delay // // success // cout<<"Called service_start with name succesfully"<<endl; // } // else{ // // failed to call service // ROS_ERROR("Failed to call service service_start"); // } // Set as unknown in case program somehow progresses past loop without any of the 3 conditions srv.request.status = "Unkown"; double MAX_LOOPS = WIGGLE_TIME / DT; // Updated for frequency cout<<"MAX_LOOPS"<<endl<<MAX_LOOPS<<endl; // ROS: Wait until we have position data. Our default position is 0. while(current_pose.position.x == 0) ros::spinOnce(); //! we want to unfreeze here before the loop // spin, while we don't have data while(!freeze_updated){ ros::spinOnce(); naptime.sleep(); } irb120_accomodation_control::freeze_service freeze_srv; cout<<freeze_mode_status<<endl; cout<<freeze_srv.response<<endl; // Check here after a spin, and unfreeze if it is frozen //! uncomment after checking with current_frame based math while(freeze_mode_status.data == 1 && freeze_mode){ if(freeze_updated && freeze_client.call(freeze_srv)){ // success cout<<"Called freeze mode service succesfully"<<endl; } else{ // failed to call service ROS_ERROR("Failed to call freeze service"); } ros::spinOnce(); naptime.sleep(); freeze_updated = false; } // spin, while we don't have data while(!freeze_updated){ ros::spinOnce(); naptime.sleep(); } cout<<freeze_mode_status<<endl; cout<<freeze_srv.response<<endl; // Keep virtual attractor at a distance, to pull the end effector virtual_attractor.pose = current_pose; // Loop variable to check effort limit condition bool effort_limit_crossed = false; effort_limit_crossed = ((abs(ft_in_current_frame.torque.x) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.torque.y) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.torque.z) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.force.x) > FORCE_THRESHOLD) || (abs(ft_in_current_frame.force.y) > FORCE_THRESHOLD) || (abs(ft_in_current_frame.force.z) > FORCE_THRESHOLD)); // Start main Loop /* Loop End Conditions: 1. The operation has timed out (ran the max alloted time) 2. One of the effort thresholds has been crossed */ while(current_loop <= MAX_LOOPS && !effort_limit_crossed && !freeze_mode){ //! Freeze mode check? //ROS: To get callback data ros::spinOnce(); // Use sin cos and some angle for rotations, and pull down in z virtual_attractor.pose.position.x = current_pose.position.x + cos((current_loop * DT * WIGGLE_RATE * 2 * M_PI)) * WIGGLE_RADIUS; virtual_attractor.pose.position.y = current_pose.position.y + sin((current_loop * DT * WIGGLE_RATE * 2 * M_PI)) * WIGGLE_RADIUS; virtual_attractor.pose.position.z = current_pose.position.z - MOVE_DISTANCE; // predefined value to pull down // Check if the effort limit is crossed effort_limit_crossed = ((abs(ft_in_current_frame.torque.x) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.torque.y) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.torque.z) > TORQUE_THRESHOLD) || (abs(ft_in_current_frame.force.x) > FORCE_THRESHOLD) || (abs(ft_in_current_frame.force.y) > FORCE_THRESHOLD) || (abs(ft_in_current_frame.force.z) > FORCE_THRESHOLD)); // Increment counters current_loop++; virtual_attractor_publisher.publish(virtual_attractor); naptime.sleep(); } // Set final attractor pose to current ee position // virtual_attractor.pose = current_pose; virtual_attractor_publisher.publish(virtual_attractor); naptime.sleep(); srv.request.status = "Completed run of specified length"; // If we've crossed the effort limts, check which is crossed for the status output if(effort_limit_crossed){ // Print message if(abs(ft_in_current_frame.torque.x) > TORQUE_THRESHOLD){ cout<<"X Torque threshold crossed"<<endl; srv.request.status = "X Torque threshold crossed"; } else if(abs(ft_in_current_frame.torque.y) > TORQUE_THRESHOLD){ cout<<"Y Torque threshold crossed"<<endl; srv.request.status = "Y Torque threshold crossed"; } else if(abs(ft_in_current_frame.torque.z) > TORQUE_THRESHOLD){ cout<<"Z Torque threshold crossed"<<endl; srv.request.status = "Z Torque threshold crossed"; } else if(abs(ft_in_current_frame.force.x) > FORCE_THRESHOLD){ cout<<"X Force threshold crossed"<<endl; srv.request.status = "X Force threshold crossed"; } else if(abs(ft_in_current_frame.force.y) > FORCE_THRESHOLD){ cout<<"Y Force threshold crossed"<<endl; srv.request.status = "Y Force threshold crossed"; } else if(abs(ft_in_current_frame.force.z) > FORCE_THRESHOLD){ cout<<"Z Force threshold crossed"<<endl; srv.request.status = "Z Force threshold crossed"; } else{ cout<<"Effort threshold crossed"<<endl; srv.request.status = "Effort threshold crossed"; } } // If we are not in the freeze mode, put the system into freeze mode before we exit if(!freeze_mode){ srv.request.status = "Completed run of specified length"; freeze_client.call(freeze_srv); cout<<"Completed run of "<<WIGGLE_TIME<<" seconds"<<endl; }else{ cout<<"Freeze mode called during loop"<<endl; } // ROS: Call service to send reason for program end to buffer.cpp // if(client.call(srv)){ // // success // cout<<"Called service with name succesfully"<<endl; // } // else{ // // failed to call service // ROS_ERROR("Failed to call service status_service"); // } cout<<"End"<<endl; // End of program }
[ "matthew.haberbusch@case.edu" ]
matthew.haberbusch@case.edu
86924627a4af4f1bfd12da2887a0348b848a2725
0560aee2a84c507d2e91cb712393b37a7cfd4117
/doc/archive/public/lib/vendor/Selenium/selenium-read-only/cpp/IEDriver/IECommandExecutor.cpp
0e0fd28e3887a7868fcfb90ed5d622045d593b32
[ "Apache-2.0" ]
permissive
Mujj/Constellation
804df1190c7bf09c7498e0b6bcff247f5ae9c376
6bd9413cdd6bc835c0eddc48b1288b4132293cb6
refs/heads/master
2020-12-03T05:12:41.365567
2013-06-20T20:29:02
2013-06-20T20:29:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,066
cpp
// Copyright 2011 Software Freedom Conservancy // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "IECommandExecutor.h" #include "CommandHandlers/AcceptAlertCommandHandler.h" #include "CommandHandlers/AddCookieCommandHandler.h" #include "CommandHandlers/ClickElementCommandHandler.h" #include "CommandHandlers/ClearElementCommandHandler.h" #include "CommandHandlers/CloseWindowCommandHandler.h" #include "CommandHandlers/DeleteAllCookiesCommandHandler.h" #include "CommandHandlers/DeleteCookieCommandHandler.h" #include "CommandHandlers/DismissAlertCommandHandler.h" #include "CommandHandlers/ElementEqualsCommandHandler.h" #include "CommandHandlers/ExecuteAsyncScriptCommandHandler.h" #include "CommandHandlers/ExecuteScriptCommandHandler.h" #include "CommandHandlers/FindChildElementCommandHandler.h" #include "CommandHandlers/FindChildElementsCommandHandler.h" #include "CommandHandlers/FindElementCommandHandler.h" #include "CommandHandlers/FindElementsCommandHandler.h" #include "CommandHandlers/GetActiveElementCommandHandler.h" #include "CommandHandlers/GetAlertTextCommandHandler.h" #include "CommandHandlers/GetAllCookiesCommandHandler.h" #include "CommandHandlers/GetAllWindowHandlesCommandHandler.h" #include "CommandHandlers/GetCurrentUrlCommandHandler.h" #include "CommandHandlers/GetCurrentWindowHandleCommandHandler.h" #include "CommandHandlers/GetElementAttributeCommandHandler.h" #include "CommandHandlers/GetElementLocationCommandHandler.h" #include "CommandHandlers/GetElementLocationOnceScrolledIntoViewCommandHandler.h" #include "CommandHandlers/GetElementSizeCommandHandler.h" #include "CommandHandlers/GetElementTagNameCommandHandler.h" #include "CommandHandlers/GetElementTextCommandHandler.h" #include "CommandHandlers/GetElementValueOfCssPropertyCommandHandler.h" #include "CommandHandlers/GetSessionCapabilitiesCommandHandler.h" #include "CommandHandlers/GetPageSourceCommandHandler.h" #include "CommandHandlers/GetTitleCommandHandler.h" #include "CommandHandlers/GoBackCommandHandler.h" #include "CommandHandlers/GoForwardCommandHandler.h" #include "CommandHandlers/GoToUrlCommandHandler.h" #include "CommandHandlers/IsElementDisplayedCommandHandler.h" #include "CommandHandlers/IsElementEnabledCommandHandler.h" #include "CommandHandlers/IsElementSelectedCommandHandler.h" #include "CommandHandlers/MouseMoveToCommandHandler.h" #include "CommandHandlers/MouseClickCommandHandler.h" #include "CommandHandlers/MouseDoubleClickCommandHandler.h" #include "CommandHandlers/MouseButtonDownCommandHandler.h" #include "CommandHandlers/MouseButtonUpCommandHandler.h" #include "CommandHandlers/NewSessionCommandHandler.h" #include "CommandHandlers/QuitCommandHandler.h" #include "CommandHandlers/RefreshCommandHandler.h" #include "CommandHandlers/ScreenshotCommandHandler.h" #include "CommandHandlers/SendKeysCommandHandler.h" #include "CommandHandlers/SendKeysToActiveElementCommandHandler.h" #include "CommandHandlers/SendKeysToAlertCommandHandler.h" #include "CommandHandlers/SetAsyncScriptTimeoutCommandHandler.h" #include "CommandHandlers/SetImplicitWaitTimeoutCommandHandler.h" #include "CommandHandlers/SubmitElementCommandHandler.h" #include "CommandHandlers/SwitchToFrameCommandHandler.h" #include "CommandHandlers/SwitchToWindowCommandHandler.h" namespace webdriver { LRESULT IECommandExecutor::OnInit(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // If we wanted to be a little more clever, we could create a struct // containing the HWND and the port number and pass them into the // ThreadProc via lpParameter and avoid this message handler altogether. this->port_ = (int)wParam; return 0; } LRESULT IECommandExecutor::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { // NOTE: COM should be initialized on this thread, so we // could use CoCreateGuid() and StringFromGUID2() instead. UUID guid; RPC_WSTR guid_string = NULL; RPC_STATUS status = ::UuidCreate(&guid); status = ::UuidToString(&guid, &guid_string); // RPC_WSTR is currently typedef'd in RpcDce.h (pulled in by rpc.h) // as unsigned short*. It needs to be typedef'd as wchar_t* wchar_t* cast_guid_string = reinterpret_cast<wchar_t*>(guid_string); this->SetWindowText(cast_guid_string); std::string session_id = CW2A(cast_guid_string, CP_UTF8); this->session_id_ = session_id; this->is_valid_ = true; ::RpcStringFree(&guid_string); this->PopulateCommandHandlers(); this->PopulateElementFinderMethods(); this->current_browser_id_ = ""; this->serialized_response_ = ""; this->ignore_protected_mode_settings_ = false; this->speed_ = 0; this->implicit_wait_timeout_ = 0; this->last_known_mouse_x_ = 0; this->last_known_mouse_y_ = 0; return 0; } LRESULT IECommandExecutor::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { this->managed_elements_.clear(); this->DestroyWindow(); return 0; } LRESULT IECommandExecutor::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { ::PostQuitMessage(0); return 0; } LRESULT IECommandExecutor::OnSetCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LPCSTR json_command = reinterpret_cast<LPCSTR>(lParam); this->current_command_.Populate(json_command); return 0; } LRESULT IECommandExecutor::OnExecCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { this->DispatchCommand(); return 0; } LRESULT IECommandExecutor::OnGetResponseLength(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { size_t response_length = 0; if (!this->is_waiting_) { response_length = this->serialized_response_.size(); } return response_length; } LRESULT IECommandExecutor::OnGetResponse(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LPSTR str = reinterpret_cast<LPSTR>(lParam); strcpy_s(str, this->serialized_response_.size() + 1, this->serialized_response_.c_str()); // Reset the serialized response for the next command. this->serialized_response_ = ""; return 0; } LRESULT IECommandExecutor::OnWait(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { BrowserHandle browser; int status_code = this->GetCurrentBrowser(&browser); if (status_code == SUCCESS && !browser->is_closing()) { this->is_waiting_ = !(browser->Wait()); if (this->is_waiting_) { // If we are still waiting, we need to wait a bit then post a message to // ourselves to run the wait again. However, we can't wait using Sleep() // on this thread. This call happens in a message loop, and we would be // unable to process the COM events in the browser if we put this thread // to sleep. unsigned int thread_id = 0; HANDLE thread_handle = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &IECommandExecutor::WaitThreadProc, (void *)this->m_hWnd, 0, &thread_id)); if (thread_handle != NULL) { ::CloseHandle(thread_handle); } } } else { this->is_waiting_ = false; } return 0; } LRESULT IECommandExecutor::OnBrowserNewWindow(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { IWebBrowser2* browser = this->factory_.CreateBrowser(); BrowserHandle new_window_wrapper(new Browser(browser, NULL, this->m_hWnd)); this->AddManagedBrowser(new_window_wrapper); LPSTREAM* stream = reinterpret_cast<LPSTREAM*>(lParam); HRESULT hr = ::CoMarshalInterThreadInterfaceInStream(IID_IWebBrowser2, browser, stream); return 0; } LRESULT IECommandExecutor::OnBrowserQuit(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { LPCSTR str = reinterpret_cast<LPCSTR>(lParam); std::string browser_id(str); delete[] str; BrowserMap::iterator found_iterator = this->managed_browsers_.find(browser_id); if (found_iterator != this->managed_browsers_.end()) { this->managed_browsers_.erase(browser_id); if (this->managed_browsers_.size() == 0) { this->current_browser_id_ = ""; } } return 0; } LRESULT IECommandExecutor::OnIsSessionValid(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { return this->is_valid_ ? 1 : 0; } LRESULT IECommandExecutor::OnNewHtmlDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandles) { HWND dialog_handle = reinterpret_cast<HWND>(lParam); BrowserMap::const_iterator it = this->managed_browsers_.begin(); for (; it != this->managed_browsers_.end(); ++it) { if (dialog_handle == it->second->window_handle()) { return 0; } } CComPtr<IHTMLDocument2> document; if (this->factory_.GetDocumentFromWindowHandle(dialog_handle, &document)) { CComPtr<IHTMLWindow2> window; document->get_parentWindow(&window); this->AddManagedBrowser(BrowserHandle(new HtmlDialog(window, dialog_handle, this->m_hWnd))); } return 0; } unsigned int WINAPI IECommandExecutor::WaitThreadProc(LPVOID lpParameter) { HWND window_handle = reinterpret_cast<HWND>(lpParameter); ::Sleep(WAIT_TIME_IN_MILLISECONDS); ::PostMessage(window_handle, WD_WAIT, NULL, NULL); return 0; } unsigned int WINAPI IECommandExecutor::ThreadProc(LPVOID lpParameter) { // Optional TODO: Create a struct to pass in via lpParameter // instead of just a pointer to an HWND. That way, we could // pass the mongoose server port via a single call, rather than // having to send an init message after the window is created. HWND *window_handle = reinterpret_cast<HWND*>(lpParameter); DWORD error = 0; HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); IECommandExecutor new_session; HWND session_window_handle = new_session.Create(HWND_MESSAGE, CWindow::rcDefault); if (session_window_handle == NULL) { error = ::GetLastError(); } // Return the HWND back through lpParameter, and signal that the // window is ready for messages. *window_handle = session_window_handle; HANDLE event_handle = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME); if (event_handle != NULL) { ::SetEvent(event_handle); ::CloseHandle(event_handle); } // Run the message loop MSG msg; while (::GetMessage(&msg, NULL, 0, 0) > 0) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::CoUninitialize(); return 0; } void IECommandExecutor::DispatchCommand() { Response response(this->session_id_); CommandHandlerMap::const_iterator found_iterator = this->command_handlers_.find(this->current_command_.command_type()); if (found_iterator == this->command_handlers_.end()) { response.SetErrorResponse(501, "Command not implemented"); } else { CommandHandlerHandle command_handler = found_iterator->second; command_handler->Execute(*this, this->current_command_, &response); BrowserHandle browser; int status_code = this->GetCurrentBrowser(&browser); if (status_code == SUCCESS) { this->is_waiting_ = browser->wait_required(); if (this->is_waiting_) { ::PostMessage(this->m_hWnd, WD_WAIT, NULL, NULL); } } } this->serialized_response_ = response.Serialize(); } int IECommandExecutor::GetCurrentBrowser(BrowserHandle* browser_wrapper) const { return this->GetManagedBrowser(this->current_browser_id_, browser_wrapper); } int IECommandExecutor::GetManagedBrowser(const std::string& browser_id, BrowserHandle* browser_wrapper) const { if (browser_id == "") { return ENOSUCHDRIVER; } BrowserMap::const_iterator found_iterator = this->managed_browsers_.find(browser_id); if (found_iterator == this->managed_browsers_.end()) { return ENOSUCHDRIVER; } *browser_wrapper = found_iterator->second; return SUCCESS; } void IECommandExecutor::GetManagedBrowserHandles(std::vector<std::string>* managed_browser_handles) const { // TODO: Enumerate windows looking for browser windows // created by showModalDialog(). BrowserMap::const_iterator it = this->managed_browsers_.begin(); for (; it != this->managed_browsers_.end(); ++it) { managed_browser_handles->push_back(it->first); } } void IECommandExecutor::AddManagedBrowser(BrowserHandle browser_wrapper) { this->managed_browsers_[browser_wrapper->browser_id()] = browser_wrapper; if (this->current_browser_id_ == "") { this->current_browser_id_ = browser_wrapper->browser_id(); } } int IECommandExecutor::CreateNewBrowser(void) { DWORD dwProcId = this->factory_.LaunchBrowserProcess(this->port_, this->ignore_protected_mode_settings_); if (dwProcId == NULL) { this->is_waiting_ = false; return ENOSUCHDRIVER; } ProcessWindowInfo process_window_info; process_window_info.dwProcessId = dwProcId; process_window_info.hwndBrowser = NULL; process_window_info.pBrowser = NULL; this->factory_.AttachToBrowser(&process_window_info); BrowserHandle wrapper(new Browser(process_window_info.pBrowser, process_window_info.hwndBrowser, this->m_hWnd)); this->AddManagedBrowser(wrapper); return SUCCESS; } int IECommandExecutor::GetManagedElement(const std::string& element_id, ElementHandle* element_wrapper) const { ElementMap::const_iterator found_iterator = this->managed_elements_.find(element_id); if (found_iterator == this->managed_elements_.end()) { return ENOSUCHELEMENT; } *element_wrapper = found_iterator->second; return SUCCESS; } void IECommandExecutor::AddManagedElement(IHTMLElement* element, ElementHandle* element_wrapper) { // TODO: This method needs much work. If we are already managing a // given element, we don't want to assign it a new ID, but to find // out if we're managing it already, we need to compare to all of // the elements already in our map, which means iterating through // the map. For long-running tests, this means the addition of a // new managed element may take longer and longer as we have no // good algorithm for removing dead elements from the map. bool element_already_managed = false; ElementMap::iterator it = this->managed_elements_.begin(); for (; it != this->managed_elements_.end(); ++it) { if (it->second->element() == element) { *element_wrapper = it->second; element_already_managed = true; break; } } if (!element_already_managed) { BrowserHandle current_browser; this->GetCurrentBrowser(&current_browser); ElementHandle new_wrapper(new Element(element, current_browser->GetWindowHandle())); this->managed_elements_[new_wrapper->element_id()] = new_wrapper; *element_wrapper = new_wrapper; } } void IECommandExecutor::RemoveManagedElement(const std::string& element_id) { ElementMap::iterator found_iterator = this->managed_elements_.find(element_id); if (found_iterator != this->managed_elements_.end()) { this->managed_elements_.erase(element_id); } } void IECommandExecutor::ListManagedElements() { ElementMap::iterator it = this->managed_elements_.begin(); for (; it != this->managed_elements_.end(); ++it) { std::cout << it->first << "\n"; } } int IECommandExecutor::GetElementFindMethod(const std::string& mechanism, std::wstring* translation) const { ElementFindMethodMap::const_iterator found_iterator = this->element_find_methods_.find(mechanism); if (found_iterator == this->element_find_methods_.end()) { return EUNHANDLEDERROR; } *translation = found_iterator->second; return SUCCESS; } int IECommandExecutor::LocateElement(const ElementHandle parent_wrapper, const std::string& mechanism, const std::string& criteria, Json::Value* found_element) const { std::wstring mechanism_translation = L""; int status_code = this->GetElementFindMethod(mechanism, &mechanism_translation); if (status_code != SUCCESS) { return status_code; } std::wstring wide_criteria = CA2W(criteria.c_str(), CP_UTF8); return this->element_finder().FindElement(*this, parent_wrapper, mechanism_translation, wide_criteria, found_element); } int IECommandExecutor::LocateElements(const ElementHandle parent_wrapper, const std::string& mechanism, const std::string& criteria, Json::Value* found_elements) const { std::wstring mechanism_translation = L""; int status_code = this->GetElementFindMethod(mechanism, &mechanism_translation); if (status_code != SUCCESS) { return status_code; } std::wstring wide_criteria = CA2W(criteria.c_str(), CP_UTF8); return this->element_finder().FindElements(*this, parent_wrapper, mechanism_translation, wide_criteria, found_elements); } void IECommandExecutor::PopulateElementFinderMethods(void) { this->element_find_methods_["id"] = L"id"; this->element_find_methods_["name"] = L"name"; this->element_find_methods_["tag name"] = L"tagName"; this->element_find_methods_["link text"] = L"linkText"; this->element_find_methods_["partial link text"] = L"partialLinkText"; this->element_find_methods_["class name"] = L"className"; this->element_find_methods_["xpath"] = L"xpath"; this->element_find_methods_["css selector"] = L"css"; } void IECommandExecutor::PopulateCommandHandlers() { this->command_handlers_[NoCommand] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[GetCurrentWindowHandle] = CommandHandlerHandle(new GetCurrentWindowHandleCommandHandler); this->command_handlers_[GetWindowHandles] = CommandHandlerHandle(new GetAllWindowHandlesCommandHandler); this->command_handlers_[SwitchToWindow] = CommandHandlerHandle(new SwitchToWindowCommandHandler); this->command_handlers_[SwitchToFrame] = CommandHandlerHandle(new SwitchToFrameCommandHandler); this->command_handlers_[Get] = CommandHandlerHandle(new GoToUrlCommandHandler); this->command_handlers_[GoForward] = CommandHandlerHandle(new GoForwardCommandHandler); this->command_handlers_[GoBack] = CommandHandlerHandle(new GoBackCommandHandler); this->command_handlers_[Refresh] = CommandHandlerHandle(new RefreshCommandHandler); this->command_handlers_[ImplicitlyWait] = CommandHandlerHandle(new SetImplicitWaitTimeoutCommandHandler); this->command_handlers_[SetAsyncScriptTimeout] = CommandHandlerHandle(new SetAsyncScriptTimeoutCommandHandler); this->command_handlers_[NewSession] = CommandHandlerHandle(new NewSessionCommandHandler); this->command_handlers_[GetSessionCapabilities] = CommandHandlerHandle(new GetSessionCapabilitiesCommandHandler); this->command_handlers_[Close] = CommandHandlerHandle(new CloseWindowCommandHandler); this->command_handlers_[Quit] = CommandHandlerHandle(new QuitCommandHandler); this->command_handlers_[GetTitle] = CommandHandlerHandle(new GetTitleCommandHandler); this->command_handlers_[GetPageSource] = CommandHandlerHandle(new GetPageSourceCommandHandler); this->command_handlers_[GetCurrentUrl] = CommandHandlerHandle(new GetCurrentUrlCommandHandler); this->command_handlers_[ExecuteAsyncScript] = CommandHandlerHandle(new ExecuteAsyncScriptCommandHandler); this->command_handlers_[ExecuteScript] = CommandHandlerHandle(new ExecuteScriptCommandHandler); this->command_handlers_[GetActiveElement] = CommandHandlerHandle(new GetActiveElementCommandHandler); this->command_handlers_[FindElement] = CommandHandlerHandle(new FindElementCommandHandler); this->command_handlers_[FindElements] = CommandHandlerHandle(new FindElementsCommandHandler); this->command_handlers_[FindChildElement] = CommandHandlerHandle(new FindChildElementCommandHandler); this->command_handlers_[FindChildElements] = CommandHandlerHandle(new FindChildElementsCommandHandler); this->command_handlers_[GetElementTagName] = CommandHandlerHandle(new GetElementTagNameCommandHandler); this->command_handlers_[GetElementLocation] = CommandHandlerHandle(new GetElementLocationCommandHandler); this->command_handlers_[GetElementSize] = CommandHandlerHandle(new GetElementSizeCommandHandler); this->command_handlers_[GetElementLocationOnceScrolledIntoView] = CommandHandlerHandle(new GetElementLocationOnceScrolledIntoViewCommandHandler); this->command_handlers_[GetElementAttribute] = CommandHandlerHandle(new GetElementAttributeCommandHandler); this->command_handlers_[GetElementText] = CommandHandlerHandle(new GetElementTextCommandHandler); this->command_handlers_[GetElementValueOfCssProperty] = CommandHandlerHandle(new GetElementValueOfCssPropertyCommandHandler); this->command_handlers_[ClickElement] = CommandHandlerHandle(new ClickElementCommandHandler); this->command_handlers_[ClearElement] = CommandHandlerHandle(new ClearElementCommandHandler); this->command_handlers_[SubmitElement] = CommandHandlerHandle(new SubmitElementCommandHandler); this->command_handlers_[IsElementDisplayed] = CommandHandlerHandle(new IsElementDisplayedCommandHandler); this->command_handlers_[IsElementSelected] = CommandHandlerHandle(new IsElementSelectedCommandHandler); this->command_handlers_[IsElementEnabled] = CommandHandlerHandle(new IsElementEnabledCommandHandler); this->command_handlers_[SendKeysToElement] = CommandHandlerHandle(new SendKeysCommandHandler); this->command_handlers_[ElementEquals] = CommandHandlerHandle(new ElementEqualsCommandHandler); this->command_handlers_[AddCookie] = CommandHandlerHandle(new AddCookieCommandHandler); this->command_handlers_[GetAllCookies] = CommandHandlerHandle(new GetAllCookiesCommandHandler); this->command_handlers_[DeleteCookie] = CommandHandlerHandle(new DeleteCookieCommandHandler); this->command_handlers_[DeleteAllCookies] = CommandHandlerHandle(new DeleteAllCookiesCommandHandler); this->command_handlers_[Screenshot] = CommandHandlerHandle(new ScreenshotCommandHandler); this->command_handlers_[AcceptAlert] = CommandHandlerHandle(new AcceptAlertCommandHandler); this->command_handlers_[DismissAlert] = CommandHandlerHandle(new DismissAlertCommandHandler); this->command_handlers_[GetAlertText] = CommandHandlerHandle(new GetAlertTextCommandHandler); this->command_handlers_[SendKeysToAlert] = CommandHandlerHandle(new SendKeysToAlertCommandHandler); this->command_handlers_[MouseMoveTo] = CommandHandlerHandle(new MouseMoveToCommandHandler); this->command_handlers_[MouseClick] = CommandHandlerHandle(new MouseClickCommandHandler); this->command_handlers_[MouseDoubleClick] = CommandHandlerHandle(new MouseDoubleClickCommandHandler); this->command_handlers_[MouseButtonDown] = CommandHandlerHandle(new MouseButtonDownCommandHandler); this->command_handlers_[MouseButtonUp] = CommandHandlerHandle(new MouseButtonUpCommandHandler); this->command_handlers_[SendKeysToActiveElement] = CommandHandlerHandle(new SendKeysToActiveElementCommandHandler); // As-yet unimplemented commands this->command_handlers_[Status] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[GetOrientation] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[SetOrientation] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[ListAvailableImeEngines] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[GetActiveImeEngine] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[IsImeActivated] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[ActivateImeEngine] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[DeactivateImeEngine] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchClick] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchDown] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchUp] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchMove] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchScroll] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchDoubleClick] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchLongClick] = CommandHandlerHandle(new IECommandHandler); this->command_handlers_[TouchFlick] = CommandHandlerHandle(new IECommandHandler); } } // namespace webdriver
[ "root@development.motormeme.com" ]
root@development.motormeme.com
acfc882d8a86c7effdc9404949ca87a547594410
5bc04daeef5284871264a7446aadf7552ec0d195
/lib/darknet/include/yolo_v2_class.hpp
efe2b5f334b5671f61c89a7a5f18108f45bcd765
[ "MIT" ]
permissive
Ace-Ma/LSOracle
a8fd7efe8927f8154ea37407bac727e409098ed5
6e940906303ef6c2c6b96352f44206567fdd50d3
refs/heads/master
2020-07-23T15:36:18.224385
2019-08-16T15:58:33
2019-08-16T15:58:33
207,612,130
0
0
MIT
2019-09-10T16:42:43
2019-09-10T16:42:43
null
UTF-8
C++
false
false
25,006
hpp
#ifndef YOLO_V2_CLASS_HPP #define YOLO_V2_CLASS_HPP #ifndef LIB_API #ifdef LIB_EXPORTS #if defined(_MSC_VER) #define LIB_API __declspec(dllexport) #else #define LIB_API __attribute__((visibility("default"))) #endif #else #if defined(_MSC_VER) #define LIB_API #else #define LIB_API #endif #endif #endif #define C_SHARP_MAX_OBJECTS 1000 struct bbox_t { unsigned int x, y, w, h; // (x,y) - top-left corner, (w, h) - width & height of bounded box float prob; // confidence - probability that the object was found correctly unsigned int obj_id; // class of object - from range [0, classes-1] unsigned int track_id; // tracking id for video (0 - untracked, 1 - inf - tracked object) unsigned int frames_counter; // counter of frames on which the object was detected }; struct image_t { int h; // height int w; // width int c; // number of chanels (3 - for RGB) float *data; // pointer to the image data }; struct bbox_t_container { bbox_t candidates[C_SHARP_MAX_OBJECTS]; }; #ifdef __cplusplus #include <memory> #include <vector> #include <deque> #include <algorithm> #ifdef OPENCV #include <opencv2/opencv.hpp> // C++ #include <opencv2/highgui/highgui_c.h> // C #include <opencv2/imgproc/imgproc_c.h> // C #endif extern "C" LIB_API int init(const char *configurationFilename, const char *weightsFilename, int gpu); extern "C" LIB_API int detect_image(const char *filename, bbox_t_container &container); extern "C" LIB_API int detect_mat(const uint8_t* data, const size_t data_length, bbox_t_container &container); extern "C" LIB_API int dispose(); extern "C" LIB_API int get_device_count(); extern "C" LIB_API int get_device_name(int gpu, char* deviceName); class Detector { std::shared_ptr<void> detector_gpu_ptr; std::deque<std::vector<bbox_t>> prev_bbox_vec_deque; const int cur_gpu_id; public: float nms = .4; bool wait_stream; LIB_API Detector(std::string cfg_filename, std::string weight_filename, int gpu_id = 0); LIB_API ~Detector(); LIB_API std::vector<bbox_t> detect(std::string image_filename, float thresh = 0.2, bool use_mean = false); LIB_API std::vector<bbox_t> detect(image_t img, float thresh = 0.2, bool use_mean = false); static LIB_API image_t load_image(std::string image_filename); static LIB_API void free_image(image_t m); LIB_API int get_net_width() const; LIB_API int get_net_height() const; LIB_API int get_net_color_depth() const; LIB_API std::vector<bbox_t> tracking_id(std::vector<bbox_t> cur_bbox_vec, bool const change_history = true, int const frames_story = 5, int const max_dist = 40); std::vector<bbox_t> detect_resized(image_t img, int init_w, int init_h, float thresh = 0.2, bool use_mean = false) { if (img.data == NULL) throw std::runtime_error("Image is empty"); auto detection_boxes = detect(img, thresh, use_mean); float wk = (float)init_w / img.w, hk = (float)init_h / img.h; for (auto &i : detection_boxes) i.x *= wk, i.w *= wk, i.y *= hk, i.h *= hk; return detection_boxes; } #ifdef OPENCV std::vector<bbox_t> detect(cv::Mat mat, float thresh = 0.2, bool use_mean = false) { if(mat.data == NULL) throw std::runtime_error("Image is empty"); auto image_ptr = mat_to_image_resize(mat); return detect_resized(*image_ptr, mat.cols, mat.rows, thresh, use_mean); } std::shared_ptr<image_t> mat_to_image_resize(cv::Mat mat) const { if (mat.data == NULL) return std::shared_ptr<image_t>(NULL); cv::Size network_size = cv::Size(get_net_width(), get_net_height()); cv::Mat det_mat; if (mat.size() != network_size) cv::resize(mat, det_mat, network_size); else det_mat = mat; // only reference is copied return mat_to_image(det_mat); } static std::shared_ptr<image_t> mat_to_image(cv::Mat img_src) { cv::Mat img; cv::cvtColor(img_src, img, cv::COLOR_RGB2BGR); std::shared_ptr<image_t> image_ptr(new image_t, [](image_t *img) { free_image(*img); delete img; }); std::shared_ptr<IplImage> ipl_small = std::make_shared<IplImage>(img); *image_ptr = ipl_to_image(ipl_small.get()); return image_ptr; } private: static image_t ipl_to_image(IplImage* src) { unsigned char *data = (unsigned char *)src->imageData; int h = src->height; int w = src->width; int c = src->nChannels; int step = src->widthStep; image_t out = make_image_custom(w, h, c); int count = 0; for (int k = 0; k < c; ++k) { for (int i = 0; i < h; ++i) { int i_step = i*step; for (int j = 0; j < w; ++j) { out.data[count++] = data[i_step + j*c + k] / 255.; } } } return out; } static image_t make_empty_image(int w, int h, int c) { image_t out; out.data = 0; out.h = h; out.w = w; out.c = c; return out; } static image_t make_image_custom(int w, int h, int c) { image_t out = make_empty_image(w, h, c); out.data = (float *)calloc(h*w*c, sizeof(float)); return out; } #endif // OPENCV }; #if defined(TRACK_OPTFLOW) && defined(OPENCV) && defined(GPU) #include <opencv2/cudaoptflow.hpp> #include <opencv2/cudaimgproc.hpp> #include <opencv2/cudaarithm.hpp> #include <opencv2/core/cuda.hpp> class Tracker_optflow { public: const int gpu_count; const int gpu_id; const int flow_error; Tracker_optflow(int _gpu_id = 0, int win_size = 9, int max_level = 3, int iterations = 8000, int _flow_error = -1) : gpu_count(cv::cuda::getCudaEnabledDeviceCount()), gpu_id(std::min(_gpu_id, gpu_count-1)), flow_error((_flow_error > 0)? _flow_error:(win_size*4)) { int const old_gpu_id = cv::cuda::getDevice(); cv::cuda::setDevice(gpu_id); stream = cv::cuda::Stream(); sync_PyrLKOpticalFlow_gpu = cv::cuda::SparsePyrLKOpticalFlow::create(); sync_PyrLKOpticalFlow_gpu->setWinSize(cv::Size(win_size, win_size)); // 9, 15, 21, 31 sync_PyrLKOpticalFlow_gpu->setMaxLevel(max_level); // +- 3 pt sync_PyrLKOpticalFlow_gpu->setNumIters(iterations); // 2000, def: 30 cv::cuda::setDevice(old_gpu_id); } // just to avoid extra allocations cv::cuda::GpuMat src_mat_gpu; cv::cuda::GpuMat dst_mat_gpu, dst_grey_gpu; cv::cuda::GpuMat prev_pts_flow_gpu, cur_pts_flow_gpu; cv::cuda::GpuMat status_gpu, err_gpu; cv::cuda::GpuMat src_grey_gpu; // used in both functions cv::Ptr<cv::cuda::SparsePyrLKOpticalFlow> sync_PyrLKOpticalFlow_gpu; cv::cuda::Stream stream; std::vector<bbox_t> cur_bbox_vec; std::vector<bool> good_bbox_vec_flags; cv::Mat prev_pts_flow_cpu; void update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec) { cur_bbox_vec = _cur_bbox_vec; good_bbox_vec_flags = std::vector<bool>(cur_bbox_vec.size(), true); cv::Mat prev_pts, cur_pts_flow_cpu; for (auto &i : cur_bbox_vec) { float x_center = (i.x + i.w / 2.0F); float y_center = (i.y + i.h / 2.0F); prev_pts.push_back(cv::Point2f(x_center, y_center)); } if (prev_pts.rows == 0) prev_pts_flow_cpu = cv::Mat(); else cv::transpose(prev_pts, prev_pts_flow_cpu); if (prev_pts_flow_gpu.cols < prev_pts_flow_cpu.cols) { prev_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type()); cur_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type()); status_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_8UC1); err_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_32FC1); } prev_pts_flow_gpu.upload(cv::Mat(prev_pts_flow_cpu), stream); } void update_tracking_flow(cv::Mat src_mat, std::vector<bbox_t> _cur_bbox_vec) { int const old_gpu_id = cv::cuda::getDevice(); if (old_gpu_id != gpu_id) cv::cuda::setDevice(gpu_id); if (src_mat.channels() == 3) { if (src_mat_gpu.cols == 0) { src_mat_gpu = cv::cuda::GpuMat(src_mat.size(), src_mat.type()); src_grey_gpu = cv::cuda::GpuMat(src_mat.size(), CV_8UC1); } update_cur_bbox_vec(_cur_bbox_vec); //src_grey_gpu.upload(src_mat, stream); // use BGR src_mat_gpu.upload(src_mat, stream); cv::cuda::cvtColor(src_mat_gpu, src_grey_gpu, CV_BGR2GRAY, 1, stream); } if (old_gpu_id != gpu_id) cv::cuda::setDevice(old_gpu_id); } std::vector<bbox_t> tracking_flow(cv::Mat dst_mat, bool check_error = true) { if (sync_PyrLKOpticalFlow_gpu.empty()) { std::cout << "sync_PyrLKOpticalFlow_gpu isn't initialized \n"; return cur_bbox_vec; } int const old_gpu_id = cv::cuda::getDevice(); if(old_gpu_id != gpu_id) cv::cuda::setDevice(gpu_id); if (dst_mat_gpu.cols == 0) { dst_mat_gpu = cv::cuda::GpuMat(dst_mat.size(), dst_mat.type()); dst_grey_gpu = cv::cuda::GpuMat(dst_mat.size(), CV_8UC1); } //dst_grey_gpu.upload(dst_mat, stream); // use BGR dst_mat_gpu.upload(dst_mat, stream); cv::cuda::cvtColor(dst_mat_gpu, dst_grey_gpu, CV_BGR2GRAY, 1, stream); if (src_grey_gpu.rows != dst_grey_gpu.rows || src_grey_gpu.cols != dst_grey_gpu.cols) { stream.waitForCompletion(); src_grey_gpu = dst_grey_gpu.clone(); cv::cuda::setDevice(old_gpu_id); return cur_bbox_vec; } ////sync_PyrLKOpticalFlow_gpu.sparse(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, &err_gpu); // OpenCV 2.4.x sync_PyrLKOpticalFlow_gpu->calc(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, err_gpu, stream); // OpenCV 3.x cv::Mat cur_pts_flow_cpu; cur_pts_flow_gpu.download(cur_pts_flow_cpu, stream); dst_grey_gpu.copyTo(src_grey_gpu, stream); cv::Mat err_cpu, status_cpu; err_gpu.download(err_cpu, stream); status_gpu.download(status_cpu, stream); stream.waitForCompletion(); std::vector<bbox_t> result_bbox_vec; if (err_cpu.cols == cur_bbox_vec.size() && status_cpu.cols == cur_bbox_vec.size()) { for (size_t i = 0; i < cur_bbox_vec.size(); ++i) { cv::Point2f cur_key_pt = cur_pts_flow_cpu.at<cv::Point2f>(0, i); cv::Point2f prev_key_pt = prev_pts_flow_cpu.at<cv::Point2f>(0, i); float moved_x = cur_key_pt.x - prev_key_pt.x; float moved_y = cur_key_pt.y - prev_key_pt.y; if (abs(moved_x) < 100 && abs(moved_y) < 100 && good_bbox_vec_flags[i]) if (err_cpu.at<float>(0, i) < flow_error && status_cpu.at<unsigned char>(0, i) != 0 && ((float)cur_bbox_vec[i].x + moved_x) > 0 && ((float)cur_bbox_vec[i].y + moved_y) > 0) { cur_bbox_vec[i].x += moved_x + 0.5; cur_bbox_vec[i].y += moved_y + 0.5; result_bbox_vec.push_back(cur_bbox_vec[i]); } else good_bbox_vec_flags[i] = false; else good_bbox_vec_flags[i] = false; //if(!check_error && !good_bbox_vec_flags[i]) result_bbox_vec.push_back(cur_bbox_vec[i]); } } cur_pts_flow_gpu.swap(prev_pts_flow_gpu); cur_pts_flow_cpu.copyTo(prev_pts_flow_cpu); if (old_gpu_id != gpu_id) cv::cuda::setDevice(old_gpu_id); return result_bbox_vec; } }; #elif defined(TRACK_OPTFLOW) && defined(OPENCV) //#include <opencv2/optflow.hpp> #include <opencv2/video/tracking.hpp> class Tracker_optflow { public: const int flow_error; Tracker_optflow(int win_size = 9, int max_level = 3, int iterations = 8000, int _flow_error = -1) : flow_error((_flow_error > 0)? _flow_error:(win_size*4)) { sync_PyrLKOpticalFlow = cv::SparsePyrLKOpticalFlow::create(); sync_PyrLKOpticalFlow->setWinSize(cv::Size(win_size, win_size)); // 9, 15, 21, 31 sync_PyrLKOpticalFlow->setMaxLevel(max_level); // +- 3 pt } // just to avoid extra allocations cv::Mat dst_grey; cv::Mat prev_pts_flow, cur_pts_flow; cv::Mat status, err; cv::Mat src_grey; // used in both functions cv::Ptr<cv::SparsePyrLKOpticalFlow> sync_PyrLKOpticalFlow; std::vector<bbox_t> cur_bbox_vec; std::vector<bool> good_bbox_vec_flags; void update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec) { cur_bbox_vec = _cur_bbox_vec; good_bbox_vec_flags = std::vector<bool>(cur_bbox_vec.size(), true); cv::Mat prev_pts, cur_pts_flow; for (auto &i : cur_bbox_vec) { float x_center = (i.x + i.w / 2.0F); float y_center = (i.y + i.h / 2.0F); prev_pts.push_back(cv::Point2f(x_center, y_center)); } if (prev_pts.rows == 0) prev_pts_flow = cv::Mat(); else cv::transpose(prev_pts, prev_pts_flow); } void update_tracking_flow(cv::Mat new_src_mat, std::vector<bbox_t> _cur_bbox_vec) { if (new_src_mat.channels() == 3) { update_cur_bbox_vec(_cur_bbox_vec); cv::cvtColor(new_src_mat, src_grey, CV_BGR2GRAY, 1); } } std::vector<bbox_t> tracking_flow(cv::Mat new_dst_mat, bool check_error = true) { if (sync_PyrLKOpticalFlow.empty()) { std::cout << "sync_PyrLKOpticalFlow isn't initialized \n"; return cur_bbox_vec; } cv::cvtColor(new_dst_mat, dst_grey, CV_BGR2GRAY, 1); if (src_grey.rows != dst_grey.rows || src_grey.cols != dst_grey.cols) { src_grey = dst_grey.clone(); return cur_bbox_vec; } if (prev_pts_flow.cols < 1) { return cur_bbox_vec; } ////sync_PyrLKOpticalFlow_gpu.sparse(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, &err_gpu); // OpenCV 2.4.x sync_PyrLKOpticalFlow->calc(src_grey, dst_grey, prev_pts_flow, cur_pts_flow, status, err); // OpenCV 3.x dst_grey.copyTo(src_grey); std::vector<bbox_t> result_bbox_vec; if (err.rows == cur_bbox_vec.size() && status.rows == cur_bbox_vec.size()) { for (size_t i = 0; i < cur_bbox_vec.size(); ++i) { cv::Point2f cur_key_pt = cur_pts_flow.at<cv::Point2f>(0, i); cv::Point2f prev_key_pt = prev_pts_flow.at<cv::Point2f>(0, i); float moved_x = cur_key_pt.x - prev_key_pt.x; float moved_y = cur_key_pt.y - prev_key_pt.y; if (abs(moved_x) < 100 && abs(moved_y) < 100 && good_bbox_vec_flags[i]) if (err.at<float>(0, i) < flow_error && status.at<unsigned char>(0, i) != 0 && ((float)cur_bbox_vec[i].x + moved_x) > 0 && ((float)cur_bbox_vec[i].y + moved_y) > 0) { cur_bbox_vec[i].x += moved_x + 0.5; cur_bbox_vec[i].y += moved_y + 0.5; result_bbox_vec.push_back(cur_bbox_vec[i]); } else good_bbox_vec_flags[i] = false; else good_bbox_vec_flags[i] = false; //if(!check_error && !good_bbox_vec_flags[i]) result_bbox_vec.push_back(cur_bbox_vec[i]); } } prev_pts_flow = cur_pts_flow.clone(); return result_bbox_vec; } }; #else class Tracker_optflow {}; #endif // defined(TRACK_OPTFLOW) && defined(OPENCV) #ifdef OPENCV static cv::Scalar obj_id_to_color(int obj_id) { int const colors[6][3] = { { 1,0,1 },{ 0,0,1 },{ 0,1,1 },{ 0,1,0 },{ 1,1,0 },{ 1,0,0 } }; int const offset = obj_id * 123457 % 6; int const color_scale = 150 + (obj_id * 123457) % 100; cv::Scalar color(colors[offset][0], colors[offset][1], colors[offset][2]); color *= color_scale; return color; } class preview_boxes_t { enum { frames_history = 30 }; // how long to keep the history saved struct preview_box_track_t { unsigned int track_id, obj_id, last_showed_frames_ago; bool current_detection; bbox_t bbox; cv::Mat mat_obj, mat_resized_obj; preview_box_track_t() : track_id(0), obj_id(0), last_showed_frames_ago(frames_history), current_detection(false) {} }; std::vector<preview_box_track_t> preview_box_track_id; size_t const preview_box_size, bottom_offset; bool const one_off_detections; public: preview_boxes_t(size_t _preview_box_size = 100, size_t _bottom_offset = 100, bool _one_off_detections = false) : preview_box_size(_preview_box_size), bottom_offset(_bottom_offset), one_off_detections(_one_off_detections) {} void set(cv::Mat src_mat, std::vector<bbox_t> result_vec) { size_t const count_preview_boxes = src_mat.cols / preview_box_size; if (preview_box_track_id.size() != count_preview_boxes) preview_box_track_id.resize(count_preview_boxes); // increment frames history for (auto &i : preview_box_track_id) i.last_showed_frames_ago = std::min((unsigned)frames_history, i.last_showed_frames_ago + 1); // occupy empty boxes for (auto &k : result_vec) { bool found = false; // find the same (track_id) for (auto &i : preview_box_track_id) { if (i.track_id == k.track_id) { if (!one_off_detections) i.last_showed_frames_ago = 0; // for tracked objects found = true; break; } } if (!found) { // find empty box for (auto &i : preview_box_track_id) { if (i.last_showed_frames_ago == frames_history) { if (!one_off_detections && k.frames_counter == 0) break; // don't show if obj isn't tracked yet i.track_id = k.track_id; i.obj_id = k.obj_id; i.bbox = k; i.last_showed_frames_ago = 0; break; } } } } // draw preview box (from old or current frame) for (size_t i = 0; i < preview_box_track_id.size(); ++i) { // get object image cv::Mat dst = preview_box_track_id[i].mat_resized_obj; preview_box_track_id[i].current_detection = false; for (auto &k : result_vec) { if (preview_box_track_id[i].track_id == k.track_id) { if (one_off_detections && preview_box_track_id[i].last_showed_frames_ago > 0) { preview_box_track_id[i].last_showed_frames_ago = frames_history; break; } bbox_t b = k; cv::Rect r(b.x, b.y, b.w, b.h); cv::Rect img_rect(cv::Point2i(0, 0), src_mat.size()); cv::Rect rect_roi = r & img_rect; if (rect_roi.width > 1 || rect_roi.height > 1) { cv::Mat roi = src_mat(rect_roi); cv::resize(roi, dst, cv::Size(preview_box_size, preview_box_size), cv::INTER_NEAREST); preview_box_track_id[i].mat_obj = roi.clone(); preview_box_track_id[i].mat_resized_obj = dst.clone(); preview_box_track_id[i].current_detection = true; preview_box_track_id[i].bbox = k; } break; } } } } void draw(cv::Mat draw_mat, bool show_small_boxes = false) { // draw preview box (from old or current frame) for (size_t i = 0; i < preview_box_track_id.size(); ++i) { auto &prev_box = preview_box_track_id[i]; // draw object image cv::Mat dst = prev_box.mat_resized_obj; if (prev_box.last_showed_frames_ago < frames_history && dst.size() == cv::Size(preview_box_size, preview_box_size)) { cv::Rect dst_rect_roi(cv::Point2i(i * preview_box_size, draw_mat.rows - bottom_offset), dst.size()); cv::Mat dst_roi = draw_mat(dst_rect_roi); dst.copyTo(dst_roi); cv::Scalar color = obj_id_to_color(prev_box.obj_id); int thickness = (prev_box.current_detection) ? 5 : 1; cv::rectangle(draw_mat, dst_rect_roi, color, thickness); unsigned int const track_id = prev_box.track_id; std::string track_id_str = (track_id > 0) ? std::to_string(track_id) : ""; putText(draw_mat, track_id_str, dst_rect_roi.tl() - cv::Point2i(-4, 5), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.9, cv::Scalar(0, 0, 0), 2); std::string size_str = std::to_string(prev_box.bbox.w) + "x" + std::to_string(prev_box.bbox.h); putText(draw_mat, size_str, dst_rect_roi.tl() + cv::Point2i(0, 12), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0, 0, 0), 1); if (!one_off_detections && prev_box.current_detection) { cv::line(draw_mat, dst_rect_roi.tl() + cv::Point2i(preview_box_size, 0), cv::Point2i(prev_box.bbox.x, prev_box.bbox.y + prev_box.bbox.h), color); } if (one_off_detections && show_small_boxes) { cv::Rect src_rect_roi(cv::Point2i(prev_box.bbox.x, prev_box.bbox.y), cv::Size(prev_box.bbox.w, prev_box.bbox.h)); unsigned int const color_history = (255 * prev_box.last_showed_frames_ago) / frames_history; color = cv::Scalar(255 - 3 * color_history, 255 - 2 * color_history, 255 - 1 * color_history); if (prev_box.mat_obj.size() == src_rect_roi.size()) { prev_box.mat_obj.copyTo(draw_mat(src_rect_roi)); } cv::rectangle(draw_mat, src_rect_roi, color, thickness); putText(draw_mat, track_id_str, src_rect_roi.tl() - cv::Point2i(0, 10), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0, 0, 0), 1); } } } } }; #endif // OPENCV //extern "C" { #endif // __cplusplus /* // C - wrappers LIB_API void create_detector(char const* cfg_filename, char const* weight_filename, int gpu_id); LIB_API void delete_detector(); LIB_API bbox_t* detect_custom(image_t img, float thresh, bool use_mean, int *result_size); LIB_API bbox_t* detect_resized(image_t img, int init_w, int init_h, float thresh, bool use_mean, int *result_size); LIB_API bbox_t* detect(image_t img, int *result_size); LIB_API image_t load_img(char *image_filename); LIB_API void free_img(image_t m); #ifdef __cplusplus } // extern "C" static std::shared_ptr<void> c_detector_ptr; static std::vector<bbox_t> c_result_vec; void create_detector(char const* cfg_filename, char const* weight_filename, int gpu_id) { c_detector_ptr = std::make_shared<LIB_API Detector>(cfg_filename, weight_filename, gpu_id); } void delete_detector() { c_detector_ptr.reset(); } bbox_t* detect_custom(image_t img, float thresh, bool use_mean, int *result_size) { c_result_vec = static_cast<Detector*>(c_detector_ptr.get())->detect(img, thresh, use_mean); *result_size = c_result_vec.size(); return c_result_vec.data(); } bbox_t* detect_resized(image_t img, int init_w, int init_h, float thresh, bool use_mean, int *result_size) { c_result_vec = static_cast<Detector*>(c_detector_ptr.get())->detect_resized(img, init_w, init_h, thresh, use_mean); *result_size = c_result_vec.size(); return c_result_vec.data(); } bbox_t* detect(image_t img, int *result_size) { return detect_custom(img, 0.24, true, result_size); } image_t load_img(char *image_filename) { return static_cast<Detector*>(c_detector_ptr.get())->load_image(image_filename); } void free_img(image_t m) { static_cast<Detector*>(c_detector_ptr.get())->free_image(m); } #endif // __cplusplus */ #endif
[ "max.austin@utah.edu" ]
max.austin@utah.edu
82348cdc8a199631c0ab9f3dde7d9e049e9fea1f
6bbb8c1ecd49aada4c990ab7caefb6564f66b900
/GameArch.Programming.Practice/PP09.Inheritance/TextureManager.h
88108c4932308a3ac76c215c8af2da7b52c021f4
[]
no_license
BeFreeCODE/SDL
6978b5afd99f627f23cc347c74fa5079c7939fd2
d5f8d56bd8796c1132ca188f413210a4e292dee2
refs/heads/master
2020-06-03T15:58:45.505908
2014-05-01T03:26:03
2014-05-01T03:26:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
843
h
#pragma once #include <SDL.h> #include <map> #include <string> class TextureManager { private: static TextureManager* s_pInstance; public: static TextureManager* Instance() { if(s_pInstance == 0) { s_pInstance = new TextureManager(); return s_pInstance; } return s_pInstance; } ~TextureManager(void); std::map<std::string, SDL_Texture*> m_textureMap; bool load(std::string fileName, std::string id, SDL_Renderer* pRenderer); void draw(std::string id, int x, int y, int width, int height, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); void drawFrame(std::string id, int x, int y, int width, int height, int currentRow, int currentFrame, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE); private: TextureManager(void); }; typedef TextureManager GlobalTextureManager;
[ "kihanlll@gmail.com" ]
kihanlll@gmail.com
299e570e009228ab8ebcba791d73bbbac271fd9c
34487da73ed9ca3bee5cd0bea70fb60f59668377
/quiz2.cpp
5f7bd70c580919f39abc04137556f64d51c09904
[]
no_license
ldai100/Codes-Saved-for-future-look-back
595698226e38cc788a34c66fcb7284fc4661997c
d67bc88efd154ed42f53c029535c33ea4632548d
refs/heads/master
2021-01-10T09:17:25.570642
2016-02-06T02:48:48
2016-02-06T02:48:48
51,186,728
0
0
null
null
null
null
UTF-8
C++
false
false
1,424
cpp
#include<iostream> #include<vector> using namespace std; //without function; vector<int> merge(vector<int> a, vector<int> b){ vector<int> c; int helper[a.size()+b.size()], asize=a.size(), bsize=b.size(), temp; //merging all the objects into one helper array; for(int i=0;i<asize;i++){ helper[i]=a.back(); a.pop_back(); } for(int j=asize;j<bsize;j++){ helper[j]=b.back(); b.pop_back(); } //bubble sort the array; for(int k=0;k<asize+bsize;k++) for(int l=0;l<asize+bsize-1;l++) if(helper[l]<helper[k]){ temp = helper[k]; helper[k]=helper[l]; helper[l]=temp; } //push everything in sorted helper array to vector c; for(int o=0;o<asize+bsize;o++){ c.push_back(helper[o]); } return c; } //with function //sorting function void sort(int *array,int size){ int temp; for(int k=0;k<size;k++) for(int l=0;l<size-1;l++) if(array[l]<array[k]){ temp = array[k]; array[k]=array[l]; array[l]=array[k]; } } vector<int> merge2(vector<int> a, vector<int> b){ vector<int> c; int helper[a.size()+b.size()], asize=a.size(), bsize=b.size(); //merging all the objects into one helper array; for(int i=0;i<asize;i++){ helper[i]=a.back(); a.pop_back(); } for(int j=asize;j<bsize;j++){ helper[j]=b.back(); b.pop_back(); } sort(helper,asize+bsize); //push everything in sorted helper array to vector c; for(int o=0;o<asize+bsize;o++){ c.push_back(helper[o]); } return c; } int main(){ return 0; }
[ "dali0813@venus.cs.qc.cuny.edu" ]
dali0813@venus.cs.qc.cuny.edu
f765ef0f56c43cadbd460d9aff9ba694bb2c5fcd
2f8dbbde4c545deacc47fde5eef035205746686f
/problemas/1042 - Sort Simples.cpp
4d24ba0193561f15e8c9673649e547c9e027de88
[]
no_license
ElianMelo/urionlinejudge-cpp
4e98fa22015d88e2a35db688e1e9923faafd6538
a67d47a0dbd06285f6125e9436a504ad225675aa
refs/heads/master
2020-04-03T17:39:49.604574
2019-05-26T03:20:32
2019-05-26T03:20:32
155,454,493
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int num1, num2, num3, maior, menor, medio, aux; scanf("%d %d %d", &num1, &num2, &num3); maior = num1; if(num2 >= maior){ maior = num2; menor = num1; medio = num3; }else if(num3 >= maior){ maior = num3; medio = num2; menor = num1; }else{ if(num2 >= num3){ medio = num2; menor = num3; }else{ medio = num3; menor = num2; } } if(menor >= medio){ aux = medio; medio = menor; menor = aux; } if(medio >= maior){ aux = maior; maior = medio; medio = aux; } printf("%d\n", menor); printf("%d\n", medio); printf("%d\n", maior); printf("\n"); printf("%d\n", num1); printf("%d\n", num2); printf("%d\n", num3); }
[ "elianmelomorais@gmail.com" ]
elianmelomorais@gmail.com
187145ef9d67f523ce4e14a2f55ea295e54e6ddc
602ea0c05970cbd766df068b003671c561f59661
/chrome/browser/chromeos/crostini/crostini_export_import.cc
4f87d7229dbe0486729087b3e1e318ebe5e0b197
[ "BSD-3-Clause" ]
permissive
VitalyKononenko/chromium
088de78a639375b073cabb7665afc638334e8672
b8ad2cadb6a163269cd7851bc7962744743785bd
refs/heads/master
2023-03-01T10:15:00.815394
2019-08-15T19:51:40
2019-08-15T19:51:40
202,603,102
1
0
BSD-3-Clause
2019-08-15T19:54:34
2019-08-15T19:54:33
null
UTF-8
C++
false
false
22,614
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/crostini/crostini_export_import.h" #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" #include "base/task/post_task.h" #include "base/time/time.h" #include "chrome/browser/chromeos/crostini/crostini_manager_factory.h" #include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/chromeos/guest_os/guest_os_share_path.h" #include "chrome/browser/chromeos/guest_os/guest_os_share_path_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/prefs/pref_service.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" namespace crostini { class CrostiniExportImportFactory : public BrowserContextKeyedServiceFactory { public: static CrostiniExportImport* GetForProfile(Profile* profile) { return static_cast<CrostiniExportImport*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } static CrostiniExportImportFactory* GetInstance() { static base::NoDestructor<CrostiniExportImportFactory> factory; return factory.get(); } private: friend class base::NoDestructor<CrostiniExportImportFactory>; CrostiniExportImportFactory() : BrowserContextKeyedServiceFactory( "CrostiniExportImportService", BrowserContextDependencyManager::GetInstance()) { DependsOn(guest_os::GuestOsSharePathFactory::GetInstance()); DependsOn(CrostiniManagerFactory::GetInstance()); } ~CrostiniExportImportFactory() override = default; // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override { Profile* profile = Profile::FromBrowserContext(context); return new CrostiniExportImport(profile); } }; CrostiniExportImport* CrostiniExportImport::GetForProfile(Profile* profile) { return CrostiniExportImportFactory::GetForProfile(profile); } CrostiniExportImport::CrostiniExportImport(Profile* profile) : profile_(profile), weak_ptr_factory_(this) { CrostiniManager* manager = CrostiniManager::GetForProfile(profile_); manager->AddExportContainerProgressObserver(this); manager->AddImportContainerProgressObserver(this); } CrostiniExportImport::~CrostiniExportImport() = default; void CrostiniExportImport::Shutdown() { CrostiniManager* manager = CrostiniManager::GetForProfile(profile_); manager->RemoveExportContainerProgressObserver(this); manager->RemoveImportContainerProgressObserver(this); } void CrostiniExportImport::ExportContainer(content::WebContents* web_contents) { if (!IsCrostiniExportImportUIAllowedForProfile(profile_)) { return; } OpenFileDialog(ExportImportType::EXPORT, web_contents); } void CrostiniExportImport::ImportContainer(content::WebContents* web_contents) { if (!IsCrostiniExportImportUIAllowedForProfile(profile_)) { return; } OpenFileDialog(ExportImportType::IMPORT, web_contents); } void CrostiniExportImport::OpenFileDialog(ExportImportType type, content::WebContents* web_contents) { PrefService* pref_service = profile_->GetPrefs(); ui::SelectFileDialog::Type file_selector_mode; unsigned title = 0; base::FilePath default_path; ui::SelectFileDialog::FileTypeInfo file_types; file_types.allowed_paths = ui::SelectFileDialog::FileTypeInfo::NATIVE_OR_DRIVE_PATH; file_types.extensions = {{"tini", "tar.gz", "tgz"}}; switch (type) { case ExportImportType::EXPORT: file_selector_mode = ui::SelectFileDialog::SELECT_SAVEAS_FILE; title = IDS_SETTINGS_CROSTINI_EXPORT; base::Time::Exploded exploded; base::Time::Now().LocalExplode(&exploded); default_path = pref_service->GetFilePath(prefs::kDownloadDefaultDirectory) .Append(base::StringPrintf("chromeos-linux-%04d-%02d-%02d.tini", exploded.year, exploded.month, exploded.day_of_month)); break; case ExportImportType::IMPORT: file_selector_mode = ui::SelectFileDialog::SELECT_OPEN_FILE, title = IDS_SETTINGS_CROSTINI_IMPORT; default_path = pref_service->GetFilePath(prefs::kDownloadDefaultDirectory); break; } select_folder_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_contents)); select_folder_dialog_->SelectFile( file_selector_mode, l10n_util::GetStringUTF16(title), default_path, &file_types, 0, base::FilePath::StringType(), web_contents->GetTopLevelNativeWindow(), reinterpret_cast<void*>(type)); } void CrostiniExportImport::FileSelected(const base::FilePath& path, int index, void* params) { ExportImportType type = static_cast<ExportImportType>(reinterpret_cast<uintptr_t>(params)); Start(type, ContainerId(kCrostiniDefaultVmName, kCrostiniDefaultContainerName), path, base::DoNothing()); } void CrostiniExportImport::ExportContainer( ContainerId container_id, base::FilePath path, CrostiniManager::CrostiniResultCallback callback) { Start(ExportImportType::EXPORT, container_id, path, std::move(callback)); } void CrostiniExportImport::ImportContainer( ContainerId container_id, base::FilePath path, CrostiniManager::CrostiniResultCallback callback) { Start(ExportImportType::IMPORT, container_id, path, std::move(callback)); } void CrostiniExportImport::Start( ExportImportType type, ContainerId container_id, base::FilePath path, CrostiniManager::CrostiniResultCallback callback) { auto* notification = CrostiniExportImportNotification::Create( profile_, type, GetUniqueNotificationId(), path, container_id); auto it = notifications_.find(container_id); if (it != notifications_.end()) { // There is already an operation in progress. Ensure the existing // notification is (re)displayed so the user knows why this new concurrent // operation failed, and show a failure notification for the new request. it->second->ForceRedisplay(); notification->SetStatusFailedConcurrentOperation(it->second->type()); return; } else { notifications_.emplace_hint(it, container_id, notification); for (auto& observer : observers_) { observer.OnCrostiniExportImportOperationStatusChanged(true); } } switch (type) { case ExportImportType::EXPORT: base::PostTaskAndReply( FROM_HERE, {base::ThreadPool(), base::MayBlock()}, // Ensure file exists so that it can be shared. base::BindOnce( [](const base::FilePath& path) { base::File file(path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); DCHECK(file.IsValid()) << path << " is invalid"; }, path), base::BindOnce( &guest_os::GuestOsSharePath::SharePath, base::Unretained( guest_os::GuestOsSharePath::GetForProfile(profile_)), kCrostiniDefaultVmName, path, false, base::BindOnce(&CrostiniExportImport::ExportAfterSharing, weak_ptr_factory_.GetWeakPtr(), std::move(container_id), std::move(callback)) )); break; case ExportImportType::IMPORT: guest_os::GuestOsSharePath::GetForProfile(profile_)->SharePath( kCrostiniDefaultVmName, path, false, base::BindOnce(&CrostiniExportImport::ImportAfterSharing, weak_ptr_factory_.GetWeakPtr(), std::move(container_id), std::move(callback))); break; } } void CrostiniExportImport::ExportAfterSharing( const ContainerId& container_id, CrostiniManager::CrostiniResultCallback callback, const base::FilePath& container_path, bool result, const std::string failure_reason) { if (!result) { LOG(ERROR) << "Error sharing for export " << container_path.value() << ": " << failure_reason; auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; RemoveNotification(it).SetStatusFailed(); return; } CrostiniManager::GetForProfile(profile_)->ExportLxdContainer( kCrostiniDefaultVmName, kCrostiniDefaultContainerName, container_path, base::BindOnce(&CrostiniExportImport::OnExportComplete, weak_ptr_factory_.GetWeakPtr(), base::Time::Now(), container_id, std::move(callback))); } void CrostiniExportImport::OnExportComplete( const base::Time& start, const ContainerId& container_id, CrostiniManager::CrostiniResultCallback callback, CrostiniResult result) { auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; ExportContainerResult enum_hist_result = ExportContainerResult::kSuccess; if (result == CrostiniResult::SUCCESS) { switch (it->second->status()) { case CrostiniExportImportNotification::Status::CANCELLING: { // If a user requests to cancel, but the export completes before the // cancel can happen (|result| == SUCCESS), then removing the exported // file is functionally the same as a successful cancel. base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), it->second->path(), false)); RemoveNotification(it).SetStatusCancelled(); break; } case CrostiniExportImportNotification::Status::RUNNING: UMA_HISTOGRAM_LONG_TIMES("Crostini.BackupTimeSuccess", base::Time::Now() - start); RemoveNotification(it).SetStatusDone(); break; default: NOTREACHED(); } } else if (result == CrostiniResult::CONTAINER_EXPORT_IMPORT_CANCELLED) { switch (it->second->status()) { case CrostiniExportImportNotification::Status::CANCELLING: { // If a user requests to cancel, and the export is cancelled (|result| // == CONTAINER_EXPORT_IMPORT_CANCELLED), then the partially exported // file needs to be cleaned up. base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), it->second->path(), false)); RemoveNotification(it).SetStatusCancelled(); break; } default: NOTREACHED(); } } else { LOG(ERROR) << "Error exporting " << int(result); base::PostTask( FROM_HERE, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), it->second->path(), false)); switch (result) { case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED: enum_hist_result = ExportContainerResult::kFailedVmStopped; break; case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED: enum_hist_result = ExportContainerResult::kFailedVmStarted; break; default: DCHECK(result == CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED); enum_hist_result = ExportContainerResult::kFailed; } UMA_HISTOGRAM_LONG_TIMES("Crostini.BackupTimeFailed", base::Time::Now() - start); DCHECK(it->second->status() == CrostiniExportImportNotification::Status::RUNNING || it->second->status() == CrostiniExportImportNotification::Status::CANCELLING); RemoveNotification(it).SetStatusFailed(); } UMA_HISTOGRAM_ENUMERATION("Crostini.Backup", enum_hist_result); std::move(callback).Run(result); } void CrostiniExportImport::OnExportContainerProgress( const std::string& vm_name, const std::string& container_name, ExportContainerProgressStatus status, int progress_percent, uint64_t progress_speed) { ContainerId container_id(vm_name, container_name); auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; switch (status) { // Rescale PACK:1-100 => 0-50. case ExportContainerProgressStatus::PACK: it->second->SetStatusRunning(progress_percent / 2); break; // Rescale DOWNLOAD:1-100 => 50-100. case ExportContainerProgressStatus::DOWNLOAD: it->second->SetStatusRunning(50 + progress_percent / 2); break; default: LOG(WARNING) << "Unknown Export progress status " << int(status); } } void CrostiniExportImport::OnExportContainerProgress( const std::string& vm_name, const std::string& container_name, const StreamingExportStatus& status) { ContainerId container_id(vm_name, container_name); auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; const auto files_percent = 100.0 * status.exported_files / status.total_files; const auto bytes_percent = 100.0 * status.exported_bytes / status.total_bytes; // Averaging the two percentages gives a more accurate estimation. // TODO(juwa): investigate more accurate approximations of percent. const auto percent = (files_percent + bytes_percent) / 2.0; it->second->SetStatusRunning(static_cast<int>(percent)); } void CrostiniExportImport::ImportAfterSharing( const ContainerId& container_id, CrostiniManager::CrostiniResultCallback callback, const base::FilePath& container_path, bool result, const std::string failure_reason) { if (!result) { LOG(ERROR) << "Error sharing for import " << container_path.value() << ": " << failure_reason; auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; RemoveNotification(it).SetStatusFailed(); return; } CrostiniManager::GetForProfile(profile_)->ImportLxdContainer( kCrostiniDefaultVmName, kCrostiniDefaultContainerName, container_path, base::BindOnce(&CrostiniExportImport::OnImportComplete, weak_ptr_factory_.GetWeakPtr(), base::Time::Now(), container_id, std::move(callback))); } void CrostiniExportImport::OnImportComplete( const base::Time& start, const ContainerId& container_id, CrostiniManager::CrostiniResultCallback callback, CrostiniResult result) { auto it = notifications_.find(container_id); ImportContainerResult enum_hist_result = ImportContainerResult::kSuccess; if (result == CrostiniResult::SUCCESS) { UMA_HISTOGRAM_LONG_TIMES("Crostini.RestoreTimeSuccess", base::Time::Now() - start); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; switch (it->second->status()) { case CrostiniExportImportNotification::Status::RUNNING: // If a user requests to cancel, but the import completes before the // cancel can happen, then the container will have been imported over // and the cancel will have failed. However the period of time in which // this can happen is very small (<5s), so it feels quite natural to // pretend the cancel did not happen, and instead display success. case CrostiniExportImportNotification::Status::CANCELLING: RemoveNotification(it).SetStatusDone(); break; default: NOTREACHED(); } } else if (result == crostini::CrostiniResult::CONTAINER_EXPORT_IMPORT_CANCELLED) { DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; switch (it->second->status()) { case CrostiniExportImportNotification::Status::CANCELLING: RemoveNotification(it).SetStatusCancelled(); break; default: NOTREACHED(); } } else { LOG(ERROR) << "Error importing " << int(result); switch (result) { case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED: enum_hist_result = ImportContainerResult::kFailedVmStopped; break; case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED: enum_hist_result = ImportContainerResult::kFailedVmStarted; break; case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_ARCHITECTURE: enum_hist_result = ImportContainerResult::kFailedArchitecture; break; case CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_SPACE: enum_hist_result = ImportContainerResult::kFailedSpace; break; default: DCHECK(result == CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED); enum_hist_result = ImportContainerResult::kFailed; } // If the operation didn't start successfully or the vm stops during the // import, then the notification status will not have been set in // OnImportContainerProgress, so it needs to be updated. if (result == CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED || result == CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STOPPED || result == CrostiniResult::CONTAINER_EXPORT_IMPORT_FAILED_VM_STARTED) { DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; DCHECK(it->second->status() == CrostiniExportImportNotification::Status::RUNNING); RemoveNotification(it).SetStatusFailed(); } else { DCHECK(it == notifications_.end()) << ContainerIdToString(container_id) << " has unexpected notification"; } UMA_HISTOGRAM_LONG_TIMES("Crostini.RestoreTimeFailed", base::Time::Now() - start); } UMA_HISTOGRAM_ENUMERATION("Crostini.Restore", enum_hist_result); // Restart from CrostiniManager. CrostiniManager::GetForProfile(profile_)->RestartCrostini( container_id.first, container_id.second, std::move(callback)); } void CrostiniExportImport::OnImportContainerProgress( const std::string& vm_name, const std::string& container_name, ImportContainerProgressStatus status, int progress_percent, uint64_t progress_speed, const std::string& architecture_device, const std::string& architecture_container, uint64_t available_space, uint64_t minimum_required_space) { ContainerId container_id(vm_name, container_name); auto it = notifications_.find(container_id); DCHECK(it != notifications_.end()) << ContainerIdToString(container_id) << " has no notification to update"; switch (status) { // Rescale UPLOAD:1-100 => 0-50. case ImportContainerProgressStatus::UPLOAD: it->second->SetStatusRunning(progress_percent / 2); break; // Rescale UNPACK:1-100 => 50-100. case ImportContainerProgressStatus::UNPACK: it->second->SetStatusRunning(50 + progress_percent / 2); break; // Failure, set error message. case ImportContainerProgressStatus::FAILURE_ARCHITECTURE: RemoveNotification(it).SetStatusFailedArchitectureMismatch( architecture_container, architecture_device); break; case ImportContainerProgressStatus::FAILURE_SPACE: DCHECK_GE(minimum_required_space, available_space); RemoveNotification(it).SetStatusFailedInsufficientSpace( minimum_required_space - available_space); break; default: LOG(WARNING) << "Unknown Export progress status " << int(status); } } std::string CrostiniExportImport::GetUniqueNotificationId() { return base::StringPrintf("crostini_export_import_%d", next_notification_id_++); } CrostiniExportImportNotification& CrostiniExportImport::RemoveNotification( std::map<ContainerId, CrostiniExportImportNotification*>::iterator it) { DCHECK(it != notifications_.end()); auto& notification = *it->second; notifications_.erase(it); for (auto& observer : observers_) { observer.OnCrostiniExportImportOperationStatusChanged(false); } return notification; } void CrostiniExportImport::CancelOperation(ExportImportType type, ContainerId container_id) { auto it = notifications_.find(container_id); if (it == notifications_.end()) { NOTREACHED() << ContainerIdToString(container_id) << " has no notification to cancel"; return; } it->second->SetStatusCancelling(); auto& manager = *CrostiniManager::GetForProfile(profile_); switch (type) { case ExportImportType::EXPORT: manager.CancelExportLxdContainer(std::move(container_id)); return; case ExportImportType::IMPORT: manager.CancelImportLxdContainer(std::move(container_id)); return; default: NOTREACHED(); } } bool CrostiniExportImport::GetExportImportOperationStatus() const { ContainerId id(kCrostiniDefaultVmName, kCrostiniDefaultContainerName); return notifications_.find(id) != notifications_.end(); } CrostiniExportImportNotification* CrostiniExportImport::GetNotificationForTesting(ContainerId container_id) { auto it = notifications_.find(container_id); return it != notifications_.end() ? it->second : nullptr; } } // namespace crostini
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
7764eadbc5300799a52ed3f0fbdde3bc7768f304
134a7f55303c259393fe97f941846d6b0c984352
/AnsiItDlg.cpp
752bba4769e0e2c7113dadc8f1553f75d755fac1
[]
no_license
Abin-Liu/AnsiIt
74841f27e20f81900adea35d88dcdfd64d649425
290bad4dd9dd73d1f4f46f07c5a9600a7c0159c4
refs/heads/master
2020-03-19T16:43:58.187541
2018-06-09T13:53:47
2018-06-09T13:53:47
136,727,651
0
0
null
null
null
null
UTF-8
C++
false
false
4,686
cpp
// AnsiItDlg.cpp : implementation file // #include "stdafx.h" #include "AnsiIt.h" #include "AnsiItDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAnsiItDlg dialog CAnsiItDlg::CAnsiItDlg() : CDialog(CAnsiItDlg::IDD, NULL) { //{{AFX_DATA_INIT(CAnsiItDlg) m_bStructual = FALSE; m_bUnicode = FALSE; m_sInput = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CAnsiItDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAnsiItDlg) DDX_Control(pDX, IDC_OUTPUT, m_wndOutput); DDX_Control(pDX, IDC_INPUT, m_wndInput); DDX_Check(pDX, IDC_STRUCTUAL, m_bStructual); DDX_Check(pDX, IDC_UNICODE, m_bUnicode); DDX_Text(pDX, IDC_INPUT, m_sInput); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAnsiItDlg, CDialog) //{{AFX_MSG_MAP(CAnsiItDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_BN_CLICKED(IDC_CONVERT, OnConvert) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CAnsiItDlg message handlers BOOL CAnsiItDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CAnsiItDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CAnsiItDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } void CAnsiItDlg::OnConvert() { // TODO: Add your control notification handler code here UpdateData(TRUE); const int LEN = m_sInput.GetLength(); CString sText = m_bStructual ? _T("{ ") : _T("_T(\""); CString sTemp; if (m_bUnicode) { // unicode LPWORD psz = new WORD[LEN]; int nResult = ::MultiByteToWideChar(CP_ACP, 0, m_sInput, LEN, (LPWSTR)psz, LEN); for (int i = 0; i < nResult; i++) { sTemp.Format(m_bStructual ? _T("0x%04x, ") : _T("\\x%04x"), psz[i]); sText += sTemp; } delete [] psz; } else { // mbcs for (int i = 0; i < LEN; i++) { sTemp.Format(m_bStructual ? _T("0x%02x, ") : _T("\\x%02x"), (BYTE)m_sInput[i]); sText += sTemp; } } sText += m_bStructual ? _T("0 }") : _T("\")"); m_wndOutput.SetWindowText(sText); }
[ "abinn32@163.com" ]
abinn32@163.com
38d18e2e70756be70af247818a85b47ebddd8ce4
daf52f4913219c520bb781fca9937aeb9430889f
/linkedList/mergeNode.cpp
b5525c99f90f82e0b48e209c173608f1b9ffb184
[]
no_license
rostun/teenyWeeny
4c3a34a9854b591d5e6916934365a197f2304539
e1bf18d78bdad9251915c95e481192a831628482
refs/heads/master
2020-12-11T17:06:24.449542
2016-08-16T16:50:57
2016-08-16T16:50:57
54,285,702
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
#include <stack> /* Find merge point of two linked lists Node is defined as struct Node { int data; Node* next; } */ int FindMergeNode(Node *headA, Node *headB) { Node *currentA = headA; Node *currentB = headB; stack <int> listA; stack <int> listB; while(currentA){ listA.push(currentA->data); currentA = currentA->next; } while(currentB){ listB.push(currentB->data); currentB = currentB->next; } int A; int B; int mergeNode = listA.top(); while(listA.size() > 0 && listB.size() > 0){ A = listA.top(); B = listB.top(); if(A == B){ mergeNode = A; } else { return mergeNode; } listA.pop(); listB.pop(); } return mergeNode; }
[ "rosa.m.tung@gmail.com" ]
rosa.m.tung@gmail.com
1ea443412e66c43751569a03914b81ef263216f2
7d5691687676b900553628f9287b7cb9094dac9a
/3party/glm/test/external/gli/gtx/loader_dds9.inl
23a0f332a457bf321cc7572a7476d818489624eb
[ "MIT", "Apache-2.0" ]
permissive
mapsme/omim
bf3ea4f419a547b7c124107e344d7f565d707c12
1892903b63f2c85b16ed4966d21fe76aba06b9ba
refs/heads/master
2023-02-20T16:31:08.733960
2021-04-27T13:57:41
2021-04-28T14:44:52
42,798,033
5,032
1,527
Apache-2.0
2022-10-03T08:28:24
2015-09-20T02:57:13
C++
UTF-8
C++
false
false
23,471
inl
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Image Copyright (c) 2008 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2010-09-08 // Updated : 2010-09-27 // Licence : This source is under MIT License // File : gli/gtx/loader_dds9.inl /////////////////////////////////////////////////////////////////////////////////////////////////// namespace gli{ namespace gtx{ namespace loader_dds9{ namespace detail { // DDS Documentation /* http://msdn.microsoft.com/en-us/library/bb943991(VS.85).aspx#File_Layout1 http://msdn.microsoft.com/en-us/library/bb943992.aspx */ #define GLI_MAKEFOURCC(ch0, ch1, ch2, ch3) \ (glm::uint32)( \ (((glm::uint32)(glm::uint8)(ch3) << 24) & 0xFF000000) | \ (((glm::uint32)(glm::uint8)(ch2) << 16) & 0x00FF0000) | \ (((glm::uint32)(glm::uint8)(ch1) << 8) & 0x0000FF00) | \ ((glm::uint32)(glm::uint8)(ch0) & 0x000000FF) ) //enum dds_format //{ // GLI_D3DFMT_R8G8B8 = 20, // GLI_D3DFMT_A8R8G8B8 = 21, // GLI_D3DFMT_X8R8G8B8 = 22, // GLI_D3DFMT_A8 = 28, // GLI_D3DFMT_A2B10G10R10 = 31, // GLI_D3DFMT_A8B8G8R8 = 32, // GLI_D3DFMT_X8B8G8R8 = 33, // GLI_D3DFMT_G16R16 = 34, // GLI_D3DFMT_A2R10G10B10 = 35, // GLI_D3DFMT_A16B16G16R16 = 36, // GLI_D3DFMT_L8 = 50, // GLI_D3DFMT_A8L8 = 51, // GLI_D3DFMT_DXT1 = GLI_MAKEFOURCC('D', 'X', 'T', '1'), // GLI_D3DFMT_DXT2 = GLI_MAKEFOURCC('D', 'X', 'T', '2'), // GLI_D3DFMT_DXT3 = GLI_MAKEFOURCC('D', 'X', 'T', '3'), // GLI_D3DFMT_DXT4 = GLI_MAKEFOURCC('D', 'X', 'T', '4'), // GLI_D3DFMT_DXT5 = GLI_MAKEFOURCC('D', 'X', 'T', '5'), // GLI_D3DFMT_DX10 = GLI_MAKEFOURCC('D', 'X', '1', '0'), // GLI_D3DFMT_D32 = 71, // GLI_D3DFMT_D24S8 = 75, // GLI_D3DFMT_D24X8 = 77, // GLI_D3DFMT_D16 = 80, // GLI_D3DFMT_L16 = 81, // GLI_D3DFMT_D32F_LOCKABLE = 82, // GLI_D3DFMT_D24FS8 = 83, // GLI_D3DFMT_R16F = 111, // GLI_D3DFMT_G16R16F = 112, // GLI_D3DFMT_A16B16G16R16F = 113, // GLI_D3DFMT_R32F = 114, // GLI_D3DFMT_G32R32F = 115, // GLI_D3DFMT_A32B32G32R32F = 116 //}; enum ddsCubemapflag { GLI_DDSCAPS2_CUBEMAP = 0x00000200, GLI_DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400, GLI_DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800, GLI_DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000, GLI_DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000, GLI_DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000, GLI_DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000, GLI_DDSCAPS2_VOLUME = 0x00200000 }; enum ddsSurfaceflag { GLI_DDSCAPS_COMPLEX = 0x00000008, GLI_DDSCAPS_MIPMAP = 0x00400000, GLI_DDSCAPS_TEXTURE = 0x00001000 }; struct ddsPixelFormat { glm::uint32 size; // 32 glm::uint32 flags; glm::uint32 fourCC; glm::uint32 bpp; glm::uint32 redMask; glm::uint32 greenMask; glm::uint32 blueMask; glm::uint32 alphaMask; }; struct ddsHeader { glm::uint32 size; glm::uint32 flags; glm::uint32 height; glm::uint32 width; glm::uint32 pitch; glm::uint32 depth; glm::uint32 mipMapLevels; glm::uint32 reserved1[11]; ddsPixelFormat format; glm::uint32 surfaceFlags; glm::uint32 cubemapFlags; glm::uint32 reserved2[3]; }; glm::uint32 const GLI_D3DFMT_R8G8B8 = 20; glm::uint32 const GLI_D3DFMT_A8R8G8B8 = 21; glm::uint32 const GLI_D3DFMT_X8R8G8B8 = 22; glm::uint32 const GLI_D3DFMT_R5G6B5 = 23; glm::uint32 const GLI_D3DFMT_X1R5G5B5 = 24; glm::uint32 const GLI_D3DFMT_A1R5G5B5 = 25; glm::uint32 const GLI_D3DFMT_A4R4G4B4 = 26; glm::uint32 const GLI_D3DFMT_X4R4G4B4 = 30; glm::uint32 const GLI_D3DFMT_A2B10G10R10 = 31; glm::uint32 const GLI_D3DFMT_A8B8G8R8 = 32; glm::uint32 const GLI_D3DFMT_X8B8G8R8 = 33; glm::uint32 const GLI_D3DFMT_G16R16 = 34; glm::uint32 const GLI_D3DFMT_A2R10G10B10 = 35; glm::uint32 const GLI_D3DFMT_A16B16G16R16 = 36; glm::uint32 const GLI_FOURCC_DXT1 = GLI_MAKEFOURCC('D', 'X', 'T', '1'); glm::uint32 const GLI_FOURCC_DXT2 = GLI_MAKEFOURCC('D', 'X', 'T', '2'); glm::uint32 const GLI_FOURCC_DXT3 = GLI_MAKEFOURCC('D', 'X', 'T', '3'); glm::uint32 const GLI_FOURCC_DXT4 = GLI_MAKEFOURCC('D', 'X', 'T', '4'); glm::uint32 const GLI_FOURCC_DXT5 = GLI_MAKEFOURCC('D', 'X', 'T', '5'); glm::uint32 const GLI_FOURCC_ATI1 = GLI_MAKEFOURCC('A', 'T', 'I', '1'); // ATI1 glm::uint32 const GLI_FOURCC_ATI2 = GLI_MAKEFOURCC('A', 'T', 'I', '2'); // ATI2 (AKA 3Dc) glm::uint32 const GLI_FOURCC_DX10 = GLI_MAKEFOURCC('D', 'X', '1', '0'); glm::uint32 const GLI_FOURCC_BC4U = GLI_MAKEFOURCC('B', 'C', '4', 'U'); glm::uint32 const GLI_FOURCC_BC4S = GLI_MAKEFOURCC('B', 'C', '4', 'S'); glm::uint32 const GLI_FOURCC_BC5U = GLI_MAKEFOURCC('B', 'C', '5', 'U'); glm::uint32 const GLI_FOURCC_BC5S = GLI_MAKEFOURCC('B', 'C', '5', 'S'); glm::uint32 const GLI_FOURCC_BC6H = GLI_MAKEFOURCC('B', 'C', '6', 'H'); glm::uint32 const GLI_FOURCC_BC7 = GLI_MAKEFOURCC('B', 'C', '7', 'U'); glm::uint32 const GLI_FOURCC_R16F = 0x0000006f; // 16-bit float Red glm::uint32 const GLI_FOURCC_G16R16F = 0x00000070; // 16-bit float Red/Green glm::uint32 const GLI_FOURCC_A16B16G16R16F = 0x00000071; // 16-bit float RGBA glm::uint32 const GLI_FOURCC_R32F = 0x00000072; // 32-bit float Red glm::uint32 const GLI_FOURCC_G32R32F = 0x00000073; // 32-bit float Red/Green glm::uint32 const GLI_FOURCC_A32B32G32R32F = 0x00000074; // 32-bit float RGBA glm::uint32 const GLI_DDPF_ALPHAPIXELS = 0x00000001; // The surface has alpha channel information in the pixel format. glm::uint32 const GLI_DDPF_ALPHA = 0x00000002; // The pixel format contains alpha only information glm::uint32 const GLI_DDPF_FOURCC = 0x00000004; // The FourCC code is valid. glm::uint32 const GLI_DDPF_RGB = 0x00000040; // The RGB data in the pixel format structure is valid. //glm::uint32 const GLI_DDPF_COMPRESSED = 0x00000080; // The surface will accept pixel data in the format specified and compress it during the write. //glm::uint32 const GLI_DDPF_RGBTOYUV = 0x00000100; // The surface will accept RGB data and translate it during the write to YUV data. glm::uint32 const GLI_DDPF_YUV = 0x00000200; // Pixel format is YUV - YUV data in pixel format struct is valid. //glm::uint32 const GLI_DDPF_ZBUFFER = 0x00000400; // Pixel format is a z buffer only surface //glm::uint32 const GLI_DDPF_ZPIXELS = 0x00002000; // The surface contains Z information in the pixels //glm::uint32 const GLI_DDPF_STENCILBUFFER = 0x00004000; // The surface contains stencil information along with Z //glm::uint32 const GLI_DDPF_ALPHAPREMULT = 0x00008000; // Premultiplied alpha format -- the color components have been premultiplied by the alpha component. glm::uint32 const GLI_DDPF_LUMINANCE = 0x00020000; // Luminance data in the pixel format is valid. //glm::uint32 const GLI_DDPF_BUMPLUMINANCE = 0x00040000; // Use this flag for luminance-only or luminance+alpha surfaces, the bit depth is then ddpf.dwLuminanceBitCount. //glm::uint32 const GLI_DDPF_BUMPDUDV = 0x00080000; // Bump map dUdV data in the pixel format is valid. glm::uint32 const GLI_DDSD_CAPS = 0x00000001; glm::uint32 const GLI_DDSD_HEIGHT = 0x00000002; glm::uint32 const GLI_DDSD_WIDTH = 0x00000004; glm::uint32 const GLI_DDSD_PITCH = 0x00000008; glm::uint32 const GLI_DDSD_PIXELFORMAT = 0x00001000; glm::uint32 const GLI_DDSD_MIPMAPCOUNT = 0x00020000; glm::uint32 const GLI_DDSD_LINEARSIZE = 0x00080000; glm::uint32 const GLI_DDSD_DEPTH = 0x00800000; struct DDLoader { glm::uint32 BlockSize; glm::uint32 BPP; gli::format Format; }; enum format_type { FORMAT_TYPE_NULL, FORMAT_RGBA, FORMAT_FOURCC }; inline glm::uint32 getFormatFourCC(gli::texture2D const & Image) { switch(Image.format()) { default: return 0; case DXT1: return GLI_FOURCC_DXT1; case DXT3: return GLI_FOURCC_DXT3; case DXT5: return GLI_FOURCC_DXT5; case ATI1N_UNORM: case ATI1N_SNORM: case ATI2N_UNORM: case ATI2N_SNORM: case BP_UF16: case BP_SF16: case BP: return GLI_FOURCC_DX10; case R16F: return GLI_FOURCC_R16F; case RG16F: return GLI_FOURCC_G16R16F; case RGBA16F: return GLI_FOURCC_A16B16G16R16F; case R32F: return GLI_FOURCC_R32F; case RG32F: return GLI_FOURCC_G32R32F; case RGBA32F: return GLI_FOURCC_A32B32G32R32F; } } inline glm::uint32 getFormatBlockSize(gli::texture2D const & Image) { switch(Image.format()) { default: return 0; case DXT1: return 8; case DXT3: return 16; case DXT5: return 16; case ATI1N_UNORM: case ATI1N_SNORM: return 16; case ATI2N_UNORM: case ATI2N_SNORM: return 32; case BP_UF16: case BP_SF16: return 32; case BP: return 32; case R16F: return 2; case RG16F: return 4; case RGBA16F: return 8; case R32F: return 4; case RG32F: return 8; case RGBA32F: return 16; } } inline glm::uint32 getFormatFlags(gli::texture2D const & Image) { glm::uint32 Result = 0; switch(Image.format()) { default: break; case R8U: case RG8U: case RGB8U: case RGBA8U: case R16U: case RG16U: case RGB16U: case RGBA16U: case R32U: case RG32U: case RGB32U: case RGBA32U: case R8I: case RG8I: case RGB8I: case RGBA8I: case R16I: case RG16I: case RGB16I: case RGBA16I: case R32I: case RG32I: case RGB32I: case RGBA32I: Result |= GLI_DDPF_RGB; break; case R16F: case RG16F: case RGB16F: case RGBA16F: case R32F: case RG32F: case RGB32F: case RGBA32F: case RGBE8: case RGB9E5: case RG11B10F: case R5G6B5: case RGBA4: case RGB10A2: case D16: case D24X8: case D24S8: case D32F: case D32FS8X24: case DXT1: case DXT3: case DXT5: case ATI1N_UNORM: case ATI1N_SNORM: case ATI2N_UNORM: case ATI2N_SNORM: case BP_UF16: case BP_SF16: case BP: Result |= GLI_DDPF_FOURCC; break; }; return Result; } inline glm::uint32 getFormatBPP(gli::texture2D const & Image) { switch(Image.format()) { default: return 0; case R8U: case R8I: return 8; case RG8U: case RG8I: return 16; case RGB8U: case RGB8I: return 24; case RGBA8U: case RGBA8I: return 32; case DXT1: return 4; case DXT3: return 8; case DXT5: return 8; case ATI1N_UNORM: case ATI1N_SNORM: return 4; case ATI2N_UNORM: case ATI2N_SNORM: return 8; case BP_UF16: case BP_SF16: return 8; case BP: return 8; } } inline bool isCompressed(gli::texture2D const & Image) { switch(Image.format()) { default: return false; case DXT1: case DXT3: case DXT5: case ATI1N_UNORM: case ATI1N_SNORM: case ATI2N_UNORM: case ATI2N_SNORM: case BP_UF16: case BP_SF16: case BP: return true; } return false; } }//namespace detail inline texture2D loadDDS9 ( std::string const & Filename ) { std::ifstream FileIn(Filename.c_str(), std::ios::in | std::ios::binary); if(FileIn.fail()) return texture2D(); detail::ddsHeader SurfaceDesc; char Magic[4]; //* Read magic number and check if valid .dds file FileIn.read((char*)&Magic, sizeof(Magic)); assert(strncmp(Magic, "DDS ", 4) == 0); // Get the surface descriptor FileIn.read((char*)&SurfaceDesc, sizeof(SurfaceDesc)); std::size_t Width = SurfaceDesc.width; std::size_t Height = SurfaceDesc.height; //std::size_t Levels = glm::max(glm::highestBit(Width), glm::highestBit(Height)); detail::DDLoader Loader; if(SurfaceDesc.format.flags & detail::GLI_DDPF_FOURCC) { switch(SurfaceDesc.format.fourCC) { case detail::GLI_FOURCC_DX10: assert(0); break; case detail::GLI_FOURCC_DXT1: Loader.BlockSize = 8; Loader.Format = DXT1; break; case detail::GLI_FOURCC_DXT3: Loader.BlockSize = 16; Loader.Format = DXT3; break; case detail::GLI_FOURCC_DXT5: Loader.BlockSize = 16; Loader.Format = DXT5; break; case detail::GLI_FOURCC_R16F: Loader.BlockSize = 2; Loader.Format = R16F; break; case detail::GLI_FOURCC_G16R16F: Loader.BlockSize = 4; Loader.Format = RG16F; break; case detail::GLI_FOURCC_A16B16G16R16F: Loader.BlockSize = 8; Loader.Format = RGBA16F; break; case detail::GLI_FOURCC_R32F: Loader.BlockSize = 4; Loader.Format = R32F; break; case detail::GLI_FOURCC_G32R32F: Loader.BlockSize = 8; Loader.Format = RG32F; break; case detail::GLI_FOURCC_A32B32G32R32F: Loader.BlockSize = 16; Loader.Format = RGBA32F; break; default: assert(0); return texture2D(); } } else if(SurfaceDesc.format.flags & detail::GLI_DDPF_RGB) { switch(SurfaceDesc.format.bpp) { case 8: Loader.BlockSize = 2; Loader.Format = R8U; break; case 16: Loader.BlockSize = 2; Loader.Format = RG8U; break; case 24: Loader.BlockSize = 3; Loader.Format = RGB8U; break; case 32: Loader.BlockSize = 4; Loader.Format = RGBA8U; break; } } else { } gli::format Format = Loader.Format; std::streamoff Curr = FileIn.tellg(); FileIn.seekg(0, std::ios_base::end); std::streamoff End = FileIn.tellg(); FileIn.seekg(Curr, std::ios_base::beg); std::vector<glm::byte> Data(std::size_t(End - Curr), 0); std::size_t Offset = 0; FileIn.read((char*)&Data[0], std::streamsize(Data.size())); //image Image(glm::min(MipMapCount, Levels));//SurfaceDesc.mipMapLevels); std::size_t MipMapCount = (SurfaceDesc.flags & detail::GLI_DDSD_MIPMAPCOUNT) ? SurfaceDesc.mipMapLevels : 1; //if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) // MipMapCount -= 2; texture2D Image(MipMapCount); for(std::size_t Level = 0; Level < Image.levels() && (Width || Height); ++Level) { Width = glm::max(std::size_t(Width), std::size_t(1)); Height = glm::max(std::size_t(Height), std::size_t(1)); std::size_t MipmapSize = 0; if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) MipmapSize = ((Width + 3) >> 2) * ((Height + 3) >> 2) * Loader.BlockSize; else MipmapSize = Width * Height * Loader.BlockSize; std::vector<glm::byte> MipmapData(MipmapSize, 0); memcpy(&MipmapData[0], &Data[0] + Offset, MipmapSize); image2D::dimensions_type Dimensions(Width, Height); Image[Level] = image2D(Dimensions, Format, MipmapData); Offset += MipmapSize; Width >>= 1; Height >>= 1; } return Image; } inline textureCube loadTextureCubeDDS9 ( std::string const & Filename ) { std::ifstream FileIn(Filename.c_str(), std::ios::in | std::ios::binary); if(FileIn.fail()) return textureCube(); detail::ddsHeader SurfaceDesc; char Magic[4]; //* Read magic number and check if valid .dds file FileIn.read((char*)&Magic, sizeof(Magic)); assert(strncmp(Magic, "DDS ", 4) == 0); // Get the surface descriptor FileIn.read((char*)&SurfaceDesc, sizeof(SurfaceDesc)); std::size_t Width = SurfaceDesc.width; std::size_t Height = SurfaceDesc.height; //std::size_t Levels = glm::max(glm::highestBit(Width), glm::highestBit(Height)); detail::DDLoader Loader; if(SurfaceDesc.format.flags & detail::GLI_DDPF_FOURCC) { switch(SurfaceDesc.format.fourCC) { case detail::GLI_FOURCC_DX10: assert(0); break; case detail::GLI_FOURCC_DXT1: Loader.BlockSize = 8; Loader.Format = DXT1; break; case detail::GLI_FOURCC_DXT3: Loader.BlockSize = 16; Loader.Format = DXT3; break; case detail::GLI_FOURCC_DXT5: Loader.BlockSize = 16; Loader.Format = DXT5; break; case detail::GLI_FOURCC_R16F: Loader.BlockSize = 2; Loader.Format = R16F; break; case detail::GLI_FOURCC_G16R16F: Loader.BlockSize = 4; Loader.Format = RG16F; break; case detail::GLI_FOURCC_A16B16G16R16F: Loader.BlockSize = 8; Loader.Format = RGBA16F; break; case detail::GLI_FOURCC_R32F: Loader.BlockSize = 4; Loader.Format = R32F; break; case detail::GLI_FOURCC_G32R32F: Loader.BlockSize = 8; Loader.Format = RG32F; break; case detail::GLI_FOURCC_A32B32G32R32F: Loader.BlockSize = 16; Loader.Format = RGBA32F; break; default: assert(0); return textureCube(); } } else if(SurfaceDesc.format.flags & detail::GLI_DDPF_RGB) { switch(SurfaceDesc.format.bpp) { case 8: Loader.BlockSize = 2; Loader.Format = R8U; break; case 16: Loader.BlockSize = 2; Loader.Format = RG8U; break; case 24: Loader.BlockSize = 3; Loader.Format = RGB8U; break; case 32: Loader.BlockSize = 4; Loader.Format = RGBA8U; break; } } else { } gli::format Format = Loader.Format; std::streamoff Curr = FileIn.tellg(); FileIn.seekg(0, std::ios_base::end); std::streamoff End = FileIn.tellg(); FileIn.seekg(Curr, std::ios_base::beg); std::vector<glm::byte> Data(std::size_t(End - Curr), 0); std::size_t Offset = 0; FileIn.read((char*)&Data[0], std::streamsize(Data.size())); //image Image(glm::min(MipMapCount, Levels));//SurfaceDesc.mipMapLevels); std::size_t MipMapCount = (SurfaceDesc.flags & detail::GLI_DDSD_MIPMAPCOUNT) ? SurfaceDesc.mipMapLevels : 1; //if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) // MipMapCount -= 2; textureCube Texture(MipMapCount); for(textureCube::size_type Face = 0; Face < FACE_MAX; ++Face) { Width = SurfaceDesc.width; Height = SurfaceDesc.height; for(textureCube::size_type Level = 0; Level < Texture.levels() && (Width || Height); ++Level) { Width = glm::max(std::size_t(Width), std::size_t(1)); Height = glm::max(std::size_t(Height), std::size_t(1)); std::size_t MipmapSize = 0; if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) MipmapSize = ((Width + 3) >> 2) * ((Height + 3) >> 2) * Loader.BlockSize; else MipmapSize = Width * Height * Loader.BlockSize; std::vector<glm::byte> MipmapData(MipmapSize, 0); memcpy(&MipmapData[0], &Data[0] + Offset, MipmapSize); textureCube::dimensions_type Dimensions(Width, Height); Texture[textureCube::face_type(Face)][Level] = image2D(Dimensions, Format, MipmapData); Offset += MipmapSize; Width >>= 1; Height >>= 1; } } return Texture; } inline void saveDDS9 ( texture2D const & Texture, std::string const & Filename ) { std::ofstream FileOut(Filename.c_str(), std::ios::out | std::ios::binary); if (!FileOut) return; char const * Magic = "DDS "; FileOut.write((char*)Magic, sizeof(char) * 4); glm::uint32 Caps = detail::GLI_DDSD_CAPS | detail::GLI_DDSD_HEIGHT | detail::GLI_DDSD_WIDTH | detail::GLI_DDSD_PIXELFORMAT; detail::ddsHeader SurfaceDesc; SurfaceDesc.size = sizeof(detail::ddsHeader); SurfaceDesc.flags = Caps | (detail::isCompressed(Texture) ? detail::GLI_DDSD_LINEARSIZE : detail::GLI_DDSD_PITCH) | (Texture.levels() > 1 ? detail::GLI_DDSD_MIPMAPCOUNT : 0); //659463; SurfaceDesc.width = Texture[0].dimensions().x; SurfaceDesc.height = Texture[0].dimensions().y; SurfaceDesc.pitch = loader_dds9::detail::isCompressed(Texture) ? size(Texture, LINEAR_SIZE) : 32; SurfaceDesc.depth = 0; SurfaceDesc.mipMapLevels = glm::uint32(Texture.levels()); SurfaceDesc.format.size = sizeof(detail::ddsPixelFormat); SurfaceDesc.format.flags = detail::getFormatFlags(Texture); SurfaceDesc.format.fourCC = detail::getFormatFourCC(Texture); SurfaceDesc.format.bpp = detail::getFormatBPP(Texture); SurfaceDesc.format.redMask = 0; SurfaceDesc.format.greenMask = 0; SurfaceDesc.format.blueMask = 0; SurfaceDesc.format.alphaMask = 0; SurfaceDesc.surfaceFlags = detail::GLI_DDSCAPS_TEXTURE | (Texture.levels() > 1 ? detail::GLI_DDSCAPS_MIPMAP : 0); SurfaceDesc.cubemapFlags = 0; FileOut.write((char*)&SurfaceDesc, sizeof(SurfaceDesc)); for(texture2D::level_type Level = 0; Level < Texture.levels(); ++Level) { texture2D::size_type ImageSize = size(Texture[Level], gli::LINEAR_SIZE); FileOut.write((char*)(Texture[Level].data()), ImageSize); } if(FileOut.fail() || FileOut.bad()) return; FileOut.close (); } inline void saveTextureCubeDDS9 ( textureCube const & Texture, std::string const & Filename ) { std::ofstream FileOut(Filename.c_str(), std::ios::out | std::ios::binary); if (!FileOut || Texture.empty()) return; char const * Magic = "DDS "; FileOut.write((char*)Magic, sizeof(char) * 4); glm::uint32 Caps = detail::GLI_DDSD_CAPS | detail::GLI_DDSD_HEIGHT | detail::GLI_DDSD_WIDTH | detail::GLI_DDSD_PIXELFORMAT | detail::GLI_DDSCAPS_COMPLEX; detail::ddsHeader SurfaceDesc; SurfaceDesc.size = sizeof(detail::ddsHeader); SurfaceDesc.flags = Caps | (detail::isCompressed(Texture[POSITIVE_X]) ? detail::GLI_DDSD_LINEARSIZE : detail::GLI_DDSD_PITCH) | (Texture.levels() > 1 ? detail::GLI_DDSD_MIPMAPCOUNT : 0); //659463; SurfaceDesc.width = Texture[POSITIVE_X][0].dimensions().x; SurfaceDesc.height = Texture[POSITIVE_X][0].dimensions().y; SurfaceDesc.pitch = loader_dds9::detail::isCompressed(Texture[POSITIVE_X]) ? size(Texture[POSITIVE_X], LINEAR_SIZE) : 32; SurfaceDesc.depth = 0; SurfaceDesc.mipMapLevels = glm::uint32(Texture.levels()); SurfaceDesc.format.size = sizeof(detail::ddsPixelFormat); SurfaceDesc.format.flags = detail::getFormatFlags(Texture[POSITIVE_X]); SurfaceDesc.format.fourCC = detail::getFormatFourCC(Texture[POSITIVE_X]); SurfaceDesc.format.bpp = detail::getFormatBPP(Texture[POSITIVE_X]); SurfaceDesc.format.redMask = 0; SurfaceDesc.format.greenMask = 0; SurfaceDesc.format.blueMask = 0; SurfaceDesc.format.alphaMask = 0; SurfaceDesc.surfaceFlags = detail::GLI_DDSCAPS_TEXTURE | (Texture.levels() > 1 ? detail::GLI_DDSCAPS_MIPMAP : 0); SurfaceDesc.cubemapFlags = detail::GLI_DDSCAPS2_CUBEMAP | detail::GLI_DDSCAPS2_CUBEMAP_POSITIVEX | detail::GLI_DDSCAPS2_CUBEMAP_NEGATIVEX | detail::GLI_DDSCAPS2_CUBEMAP_POSITIVEY | detail::GLI_DDSCAPS2_CUBEMAP_NEGATIVEY | detail::GLI_DDSCAPS2_CUBEMAP_POSITIVEZ | detail::GLI_DDSCAPS2_CUBEMAP_NEGATIVEZ; FileOut.write((char*)&SurfaceDesc, sizeof(SurfaceDesc)); for(textureCube::size_type Face = 0; Face < FACE_MAX; ++Face) for(texture2D::level_type Level = 0; Level < Texture.levels(); ++Level) { texture2D::size_type ImageSize = size(Texture[textureCube::face_type(Face)][Level], gli::LINEAR_SIZE); FileOut.write((char*)(Texture[textureCube::face_type(Face)][Level].data()), ImageSize); } if(FileOut.fail() || FileOut.bad()) return; FileOut.close (); } }//namespace loader_dds9 }//namespace gtx }//namespace gli
[ "alex@maps.me" ]
alex@maps.me
ffdcb9c33e9a2015b1c5e1b458c1967bcd26c350
f7e8786b1e62222bd1cedcb58383a0576c36a2a2
/src/shell/application_manager/query_util_unittest.cc
d754740fe25b7d6bbb8a8312e5f89538b04a51f1
[ "BSD-3-Clause" ]
permissive
amplab/ray-core
656915553742302915a363e42b7497037985a91e
89a278ec589d98bcbc7e57e0b80d055667cca62f
refs/heads/master
2023-07-07T20:45:40.883095
2016-08-06T23:52:23
2016-08-06T23:52:23
61,343,320
4
5
null
2016-08-06T23:52:24
2016-06-17T03:35:34
C++
UTF-8
C++
false
false
1,226
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/application_manager/query_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace shell { namespace { TEST(QueryUtil, NoQuery) { GURL url("http://www.example.com/"); std::string query; GURL base_url = GetBaseURLAndQuery(url, &query); EXPECT_EQ(base_url, url); EXPECT_EQ(query, ""); } TEST(QueryUtil, WithEmptyQuery) { GURL url("http://www.example.com/?"); std::string query; GURL base_url = GetBaseURLAndQuery(url, &query); EXPECT_EQ(base_url, GURL("http://www.example.com/")); EXPECT_EQ(query, "?"); } TEST(QueryUtil, WithFullQuery) { GURL url("http://www.example.com/?a=b&c=d"); std::string query; GURL base_url = GetBaseURLAndQuery(url, &query); EXPECT_EQ(base_url, GURL("http://www.example.com/")); EXPECT_EQ(query, "?a=b&c=d"); } TEST(QueryUtil, ForFileURL) { GURL url("file:///tmp/file?a=b&c=d"); std::string query; GURL base_url = GetBaseURLAndQuery(url, &query); EXPECT_EQ(base_url, GURL("file:///tmp/file")); EXPECT_EQ(query, "?a=b&c=d"); } } // namespace } // namespace shell
[ "pcmoritz@gmail.com" ]
pcmoritz@gmail.com
f4bd840c10a7dd9dda04d2f68bd3ffe81ac47760
9192182cfcfcf4ce9f9bbb4003106e29b37b5bd1
/mame-0.141/src/mame/includes/pooyan.h
ab68c45e2ad53ec3f3a4ab0ebd36caec6d6693d0
[]
no_license
johkelly/MAME_hi
a2b9ea9d4f089f75e57de5963af187718733fccd
ccbec44e4c82e5ca83ba80de19bfb9c100dbd349
refs/heads/master
2020-05-17T13:29:54.978078
2012-07-13T19:03:50
2012-07-13T19:03:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
h
class pooyan_state : public driver_device { public: pooyan_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT8 * videoram; UINT8 * colorram; UINT8 * spriteram; UINT8 * spriteram2; /* video-related */ tilemap_t *bg_tilemap; /* misc */ UINT8 irq_toggle, irq_enable; /* devices */ cpu_device *maincpu; }; /*----------- defined in video/pooyan.c -----------*/ WRITE8_HANDLER( pooyan_videoram_w ); WRITE8_HANDLER( pooyan_colorram_w ); WRITE8_HANDLER( pooyan_flipscreen_w ); PALETTE_INIT( pooyan ); VIDEO_START( pooyan ); VIDEO_UPDATE( pooyan );
[ "john.kelly@readytalk.com" ]
john.kelly@readytalk.com
902ab877eaeecad4e17dd496c6638178fa3e3396
f27185d32d037f6ec76bb28cfeed2e86310192fd
/MiniBase/client.cpp
38ebc5e9ba2570b53fa8bab35328dbae82dfbd46
[]
no_license
zH4x/vermilion_new
59abd84b04b4da27fef275ddfef4e5316b51f7f1
dfdda63bee2e3033bd7ddcba86a6c323b3959a77
refs/heads/master
2020-09-08T12:40:52.238211
2019-10-03T10:44:22
2019-10-03T10:44:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,595
cpp
#include "client.h" bool FirstFrame = false; bool ClearDisconnect = false; net_status_t g_nStatus; #include <wininet.h> #include <Wbemidl.h> #pragma comment(lib, "wbemuuid.lib") #pragma comment(lib, "wininet.lib") #define MYAC_PRIVATE_KEY /*5BE6D8BF8E4B8F837-*/XorStr<0xC7,19,0xA10D5352>("\xF2\x8A\x8C\xFC\x8F\xF4\x8F\x88\xF7\x95\xE5\x90\xEB\x92\xED\xE5\xE0\xF5"+0xA10D5352).s #define MYAC_CRYPT_KEY 0x79A41 #define MYAC_LICENSE_HOST /*http://csxr.ru/indigo/myac.php?hash=*/XorStr<0x92,37,0xD04FEAF6>("\xFA\xE7\xE0\xE5\xAC\xB8\xB7\xFA\xE9\xE3\xEE\xB3\xEC\xEA\x8F\xC8\xCC\xC7\xCD\xC2\xC9\x88\xC5\xD0\xCB\xC8\x82\xDD\xC6\xDF\x8F\xD9\xD3\xC0\xDC\x88"+0xD04FEAF6).s #define MYAC_LICENSE_HKEY /*http://csxr.ru/indigo/myac.php?hkey=*/XorStr<0xEB,37,0xEC6EEDA5>("\x83\x98\x99\x9E\xD5\xDF\xDE\x91\x80\x8C\x87\xD8\x85\x8D\xD6\x93\x95\x98\x94\x99\x90\x2F\x6C\x7B\x62\x67\x2B\x76\x6F\x78\x36\x62\x60\x69\x74\x33"+0xEC6EEDA5).s char* HashMD5( char* data ) { DWORD dwStatus = 0; DWORD cbHash = 16; int i = 0; HCRYPTPROV cryptProv; HCRYPTHASH cryptHash; BYTE hash[16]; char *hex = "0123456789abcdef"; char *strHash = AllocChar( 33 ); if( !CryptAcquireContextA( &cryptProv , NULL , MS_DEF_PROV , PROV_RSA_FULL , CRYPT_VERIFYCONTEXT ) ) { return NULL; } if( !CryptCreateHash( cryptProv , CALG_MD5 , 0 , 0 , &cryptHash ) ) { CryptReleaseContext( cryptProv , 0 ); return NULL; } if( !CryptHashData( cryptHash , (BYTE*)data , lstrlenA( data ) , 0 ) ) { CryptReleaseContext( cryptProv , 0 ); CryptDestroyHash( cryptHash ); return NULL; } if( !CryptGetHashParam( cryptHash , HP_HASHVAL , hash , &cbHash , 0 ) ) { CryptReleaseContext( cryptProv , 0 ); CryptDestroyHash( cryptHash ); return NULL; } for( i = 0; i < cbHash; i++ ) { strHash[i * 2] = hex[hash[i] >> 4]; strHash[( i * 2 ) + 1] = hex[hash[i] & 0xF]; } CryptReleaseContext( cryptProv , 0 ); CryptDestroyHash( cryptHash ); return strHash; } char* GetHDD() { char pcid_root_cimv2[] = { 'R','O','O','T','\\\\','C','I','M','V','2',0 }; char pcid_wql[] = { 'W','Q','L',0 }; char pcid_w32[] = { 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ', 'W','i','n','3','2','_','P','h','y','s','i','c','a','l', 'M','e','d','i','a',0 }; char pcid_prc[] = { 'S','e','r','i','a','l','N','u','m','b','e','r',0 }; HRESULT hres; char* Result = NULL; IWbemLocator *pLoc = NULL; IWbemServices *pSvc = NULL; IEnumWbemClassObject* pEnumerator = NULL; IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; hres = CoInitializeEx( 0 , COINIT_MULTITHREADED ); hres = CoInitializeSecurity( NULL , -1 , NULL , NULL , RPC_C_AUTHN_LEVEL_DEFAULT , RPC_C_IMP_LEVEL_IMPERSONATE , NULL , EOAC_NONE , NULL ); if( FAILED( hres ) ) { CoUninitialize(); } hres = CoCreateInstance( CLSID_WbemLocator , 0 , CLSCTX_INPROC_SERVER , IID_IWbemLocator , (LPVOID *)&pLoc ); if( FAILED( hres ) ) { CoUninitialize(); } hres = pLoc->ConnectServer( ConvertStringToBSTR( pcid_root_cimv2 ) , NULL , NULL , 0 , NULL , 0 , 0 , &pSvc ); if( FAILED( hres ) ) { pLoc->Release(); CoUninitialize(); } hres = CoSetProxyBlanket( pSvc , RPC_C_AUTHN_WINNT , RPC_C_AUTHZ_NONE , NULL , RPC_C_AUTHN_LEVEL_CALL , RPC_C_IMP_LEVEL_IMPERSONATE , NULL , EOAC_NONE ); if( FAILED( hres ) ) { pSvc->Release(); pLoc->Release(); CoUninitialize(); } hres = pSvc->ExecQuery( ConvertStringToBSTR( pcid_wql ) , ConvertStringToBSTR( pcid_w32 ) , WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY , NULL , &pEnumerator ); if( FAILED( hres ) ) { pSvc->Release(); pLoc->Release(); CoUninitialize(); } HRESULT hr = pEnumerator->Next( WBEM_INFINITE , 1 , &pclsObj , &uReturn ); hr = pclsObj->Get( ConvertStringToBSTR( pcid_prc ) , 0 , &vtProp , 0 , 0 ); Result = ConvertBSTRToString( vtProp.bstrVal ); VariantClear( &vtProp ); pclsObj->Release(); pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); return Result; } void reverse( char s[] ) { int i , j; char c; for( i = 0 , j = lstrlenA( s ) - 1; i<j; i++ , j-- ) { c = s[i]; s[i] = s[j]; s[j] = c; } } void nt_itoa( int n , char s[] ) { int i , sign; if( ( sign = n ) < 0 ) n = -n; i = 0; do { s[i++] = n % 10 + '0'; } while( ( n /= 10 ) > 0 ); if( sign < 0 ) s[i++] = '-'; s[i] = '\0'; reverse( s ); } void BuildLicenseQuery( char* hash ) { char* query = AllocChar( 64 ); char* hdd = GetHDD(); char* rndv = AllocChar( 3 ); nt_itoa( GetRnd( 1 , 10 ) , rndv ); lstrcpyA( query , hdd ); lstrcatA( query , "|" ); lstrcatA( query , rndv ); char* uhash = HashMD5( query ); lstrcpyA( hash , uhash ); FreeChar( uhash ); FreeChar( rndv ); FreeChar( hdd ); FreeChar( query ); } bool CheckMd5Request( char* ReciveHash ) { char* temp_value = AllocChar( 3 ); char* license_ok = AllocChar( 22 ); char* md5_license; for( int i = 1; i <= 10; i++ ) { native_memset( license_ok , 22 , 0 ); native_memset( temp_value , 3 , 0 ); lstrcpyA( license_ok , MYAC_PRIVATE_KEY ); nt_itoa( i , temp_value ); lstrcatA( license_ok , temp_value ); md5_license = HashMD5( license_ok ); if( lstrcmpA( ReciveHash , md5_license ) == 0 ) { FreeChar( md5_license ); FreeChar( license_ok ); FreeChar( temp_value ); return true; } FreeChar( md5_license ); } FreeChar( license_ok ); FreeChar( temp_value ); return false; } bool CheckLicenseRequest() { DWORD rec_timeout = 5000; DWORD NumberOfBytesRead = 0; HINTERNET hInternet = InternetOpenA( "" , INTERNET_OPEN_TYPE_PRECONFIG , NULL , NULL , 0 ); InternetSetOptionA( hInternet , INTERNET_OPTION_RECEIVE_TIMEOUT , &rec_timeout , sizeof( rec_timeout ) ); if( !hInternet ) return false; char* ReciveHash = AllocChar( 33 ); char* UrlRequst = AllocChar( 128 ); char* UserHash = AllocChar( 33 ); BuildLicenseQuery( UserHash ); lstrcpyA( UrlRequst , MYAC_LICENSE_HOST ); lstrcatA( UrlRequst , UserHash ); HINTERNET OpenAddress = InternetOpenUrlA( hInternet , UrlRequst , NULL , 0 , INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION , 0 ); if( !OpenAddress ) { InternetCloseHandle( hInternet ); return false; } if( InternetReadFile( OpenAddress , ReciveHash , 33 , &NumberOfBytesRead ) && NumberOfBytesRead ) { InternetCloseHandle( OpenAddress ); InternetCloseHandle( hInternet ); FreeChar( UserHash ); FreeChar( UrlRequst ); if( CheckMd5Request( ReciveHash ) ) { FreeChar( ReciveHash ); return true; } else { FreeChar( ReciveHash ); return false; } } return false; } bool CheckHostKeyRequest() { DWORD rec_timeout = 5000; DWORD NumberOfBytesRead = 0; HINTERNET hInternet = InternetOpenA( "" , INTERNET_OPEN_TYPE_PRECONFIG , NULL , NULL , 0 ); InternetSetOptionA( hInternet , INTERNET_OPTION_RECEIVE_TIMEOUT , &rec_timeout , sizeof( rec_timeout ) ); if( !hInternet ) return false; char* UrlRequst = AllocChar( 128 ); char* TempValue = AllocChar( 7 ); char* ReciveKey = AllocChar( 33 ); char* RValidKey = AllocChar( 33 ); int RTmpVal = ( GetRnd( 100000 , 999999 ) ); RTmpVal ^ MYAC_CRYPT_KEY; nt_itoa( RTmpVal , TempValue ); lstrcpyA( UrlRequst , MYAC_LICENSE_HKEY ); lstrcatA( UrlRequst , TempValue ); native_memset( TempValue , 7 , 0 ); nt_itoa( RTmpVal ^ MYAC_CRYPT_KEY , TempValue ); lstrcpyA( RValidKey , MYAC_PRIVATE_KEY ); lstrcatA( RValidKey , TempValue ); RValidKey = HashMD5( RValidKey ); FreeChar( TempValue ); HINTERNET OpenAddress = InternetOpenUrlA( hInternet , UrlRequst , NULL , 0 , INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_KEEP_CONNECTION , 0 ); if( !OpenAddress ) { InternetCloseHandle( hInternet ); return false; } if( InternetReadFile( OpenAddress , ReciveKey , 33 , &NumberOfBytesRead ) && NumberOfBytesRead ) { InternetCloseHandle( OpenAddress ); InternetCloseHandle( hInternet ); FreeChar( UrlRequst ); if( lstrcmpA( ReciveKey , RValidKey ) == 0 ) { FreeChar( RValidKey ); FreeChar( ReciveKey ); FreeChar( UrlRequst ); return true; } } return false; } void HookUserMessages() { pUserMsgBase = (PUserMsg)offset.FindUserMsgBase(); char reset_hud_msg[] = { 'R','e','s','e','t','H','U','D',0 }; char set_fov_msg[] = { 'S','e','t','F','O','V',0 }; char team_info_msg[] = { 'T','e','a','m','I','n','f','o',0 }; char cur_weapon_msg[] = { 'C','u','r','W','e','a','p','o','n',0 }; char death_msg_msg[] = { 'D','e','a','t','h','M','s','g',0 }; char weaponlist_msg[] = { 'W','e','a','p','o','n','L','i','s','t',0 }; char ammox_msg[] = { 'A','m','m','o','X',0 }; pResetHUD = HookUserMsg( reset_hud_msg , ResetHUD ); pSetFOV = HookUserMsg( set_fov_msg , SetFOV ); pTeamInfo = HookUserMsg( team_info_msg , TeamInfo ); pCurWeapon = HookUserMsg( cur_weapon_msg , CurWeapon ); pDeathMsg = HookUserMsg( death_msg_msg , DeathMsg ); pWeaponList = HookUserMsg( weaponlist_msg , WeaponList ); pAmmoX = HookUserMsg( ammox_msg , AmmoX ); } void HookEngineMessages() { pEngineMsgBase = (PEngineMsg)offset.FindSVCMessages(); char svc_sound_msg[] = { 's','v','c','_','s','o','u','n','d',0 }; char svc_spawnstatic_sound_msg[] = { 's','v','c','_','s','p','a','w','n','s','t','a','t','i','c','s','o','u','n','d',0 }; pSVC_sound = HookEngineMsg( svc_sound_msg , SVC_Sound ); pSVC_SpawnStaticSound = HookEngineMsg( svc_spawnstatic_sound_msg , SVC_SpawnStaticSound ); } void UnHookFunction(); void InitHack() { //if( CheckLicenseRequest() && CheckHostKeyRequest() ) //{ g_Leis.InitHack(); //} //else //{ // UnHookFunction(); //} } void HUD_Frame( double time ) { if( !FirstFrame ) { g_Screen.iSize = sizeof( SCREENINFO ); offset.HLType = g_Studio.IsHardware() + 1; HookUserMessages(); HookEngineMessages(); InitHack(); FirstFrame = true; } g_Engine.pfnGetScreenInfo( &g_Screen ); g_Engine.pNetAPI->Status( &( g_nStatus ) ); g_Client.HUD_Frame( time ); if( g_nStatus.connected && !ClearDisconnect ) { ClearDisconnect = true; } else if( !g_nStatus.connected && ClearDisconnect || !g_Engine.pfnGetServerTime() ) { g_Entity.ClearEntity(); g_Sound.ClearSound(); g_WeaponList.WeaponListClear(); g_Players.ClearPlayers(); ClearDisconnect = false; } } void HUD_Redraw( float time , int intermission ) { g_Client.HUD_Redraw( time , intermission ); if( g_nStatus.connected ) g_Leis.HUD_Redraw(); } int HUD_Key_Event( int down , int keynum , const char *pszCurrentBinding ) { if( g_nStatus.connected ) { if( down ) { g_Leis.HUD_Key_Event( keynum ); if( g_Menu.Visible || g_Menu.ExitMenu ) { if( keynum == cvar.key_NavEnter ) return 0; else if( keynum == cvar.key_TogglePanic ) return 0; else if( keynum == cvar.key_NavLeave ) return 0; else if( keynum == cvar.key_NavUp ) return 0; else if( keynum == cvar.key_NavDown ) return 0; else if( keynum == cvar.key_NavLeft ) return 0; else if( keynum == cvar.key_NavRight ) return 0; } } } return g_Client.HUD_Key_Event( down , keynum , pszCurrentBinding ); } void HUD_PlayerMove( struct playermove_s *ppmove , int server ) { g_Client.HUD_PlayerMove( ppmove , server ); if( g_nStatus.connected ) g_Leis.HUD_PlayerMove( ppmove ); } void V_CalcRefdef( struct ref_params_s *pparams ) { if( g_nStatus.connected ) g_Leis.V_CalcRefdef( pparams ); else g_Client.V_CalcRefdef( pparams ); } void StudioEntityLight( struct alight_s *plight ) { if( g_nStatus.connected ) g_Leis.StudioEntityLight( plight ); g_Studio.StudioEntityLight( plight ); } int HUD_AddEntity( int type , struct cl_entity_s *ent , const char *modelname ) { if( g_nStatus.connected ) return g_Leis.HUD_AddEntity( type , ent , modelname ); else return g_Client.HUD_AddEntity( type , ent , modelname ); } void CL_CreateMove( float frametime , usercmd_s *cmd , int active ) { g_Client.CL_CreateMove( frametime , cmd , active ); if( g_nStatus.connected ) { g_Players.UpdatePlayerInfo(); g_Leis.CL_CreateMove( frametime , cmd ); } } void HUD_PostRunCmd( struct local_state_s *from , struct local_state_s *to , struct usercmd_s *cmd , int runfuncs , double time , unsigned int random_seed ) { g_Client.HUD_PostRunCmd( from , to , cmd , runfuncs , time , random_seed ); if( g_nStatus.connected ) g_Leis.HUD_PostRunCmd( to , cmd , runfuncs , time , random_seed ); } int HUD_UpdateClientData( client_data_t *pcldata , float flTime ) { if( pcldata ) g_WeaponList.WeaponListUpdate( pcldata->iWeaponBits ); return g_Client.HUD_UpdateClientData( pcldata , flTime ); } void HookFunction() { g_pClient->HUD_Frame = HUD_Frame; g_pClient->HUD_Redraw = HUD_Redraw; g_pClient->HUD_Key_Event = HUD_Key_Event; g_pClient->HUD_PlayerMove = HUD_PlayerMove; g_pClient->V_CalcRefdef = V_CalcRefdef; g_pStudio->StudioEntityLight = StudioEntityLight; g_pClient->HUD_AddEntity = HUD_AddEntity; g_pClient->CL_CreateMove = CL_CreateMove; g_pClient->HUD_PostRunCmd = HUD_PostRunCmd; g_pClient->HUD_UpdateClientData = HUD_UpdateClientData; } void UnHookFunction() { g_pClient->HUD_Frame = g_Client.HUD_Frame; g_pClient->HUD_Redraw = g_Client.HUD_Redraw; g_pClient->HUD_Key_Event = g_Client.HUD_Key_Event; g_pClient->HUD_PlayerMove = g_Client.HUD_PlayerMove; g_pClient->V_CalcRefdef = g_Client.V_CalcRefdef; g_pStudio->StudioEntityLight = g_Studio.StudioEntityLight; g_pClient->HUD_AddEntity = g_Client.HUD_AddEntity; g_pClient->CL_CreateMove = g_Client.CL_CreateMove; g_pClient->HUD_PostRunCmd = g_Client.HUD_PostRunCmd; g_pClient->HUD_UpdateClientData = g_Client.HUD_UpdateClientData; }
[ "or.75@ya.ru" ]
or.75@ya.ru
010c43e42a866ae54e16ead55d8885590946bcd9
e39e3a4b4dc3f9abf8c9c25d247e2c43085f399e
/chapter3/practise3_5/practise3_5/practise3_5.cpp
af8f1949637ecc6997ec5dd3c4fdf84ad7c08b48
[]
no_license
dc-maggic/978-7-121-15535-2
fc52a91b3dd58ccede74f102eb31eb69a6a3583a
f3bbc221f4bc52241398bc6529c8e6e9dac2ab97
refs/heads/master
2021-10-07T09:40:53.387393
2018-12-04T14:29:04
2018-12-04T14:29:04
155,890,380
0
0
null
null
null
null
GB18030
C++
false
false
289
cpp
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; int main() { cout << "输入多个字符串并把它们连接起来输出大字符串" << endl; string line; while (cin >> line) cout << line; cout << endl; system("pause"); }
[ "dc-maggic@outlook.com" ]
dc-maggic@outlook.com
cc2b58486deadd98ba966a94d42f1462d2802864
ae50a4cd44bd13b54c28dc6e9aae8e30263153e2
/Arduino_mega_server/ping.ino
58ebb31569cf96c193c8452dfdbdd104dca09187
[]
no_license
sergiyvn/Arduino
2de6f66fda33aa8bf5ec286b6a2e58779b053177
3ee51d4361f836580cb5837c9b69098c92528463
refs/heads/master
2021-01-17T07:19:59.359734
2016-12-14T09:28:39
2016-12-14T09:28:39
38,753,923
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
ino
/* Modul Ping part of Arduino Mega Server project Response net devices Warning! Use modify ICMPPing library */ #ifdef PING_FEATURE #include <ICMPPing.h> // + 1378 bytes #define TOTAL_NET_DEVICES 10 char netDevicesNames[TOTAL_NET_DEVICES][4] = {"SWH", "HOM", "MED", "CMP", "PRN", "MGA", "UN1", "UN2", "LRN", "APC"}; byte ips[TOTAL_NET_DEVICES][4] = {{192, 168, 2, 16}, // 1 SWITCH {192, 168, 2, 8}, // 2 HOME {192, 168, 2, 28}, // 3 MEDIA {192, 168, 2, 6}, // 4 COMP {192, 168, 2, 18}, // 5 PRINTER {127, 168, 2, 37}, // 6 MEGA {192, 168, 2, 17}, // 7 UNO1 {192, 168, 2, 38}, // 8 UNO2 {192, 168, 2, 19}, // 9 LAURENT {192, 168, 2, 14}};//10 APC byte online[TOTAL_NET_DEVICES] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; byte countOnline; // for cycle SOCKET pingSocket = 0; char pingMessage[64]; // 256 original ICMPPing ping(pingSocket); void pingInit() { modulPing = MODUL_ENABLE; } void pingWorks() { for (countOnline = 0; countOnline < TOTAL_NET_DEVICES; countOnline++) { if (countOnline == 5) { // self online[countOnline] = 1; continue; } online[countOnline] = ping(1, ips[countOnline], pingMessage); /*Serial.print(netDevicesNames[countOnline]); Serial.print(": "); Serial.print(online[countOnline]); Serial.print(" "); Serial.println(pingMessage);*/ } } #endif // PING_FEATURE
[ "sergiyvn@gmail.com" ]
sergiyvn@gmail.com
ace9f4a32612b7c7b84aaa8d4ba8534f6a8d8529
be2dfc076afc556d738f116fe86015bfcc086de7
/Object_Oriented_Programming/homeworks/04-Class_Point_in_plane/Class_Point_in_plane/main.cpp
a35c1455c2f4f0a130c5a0e18a62277ddf82c391
[]
no_license
middlehuang/CSIE-HW
da35014edd8ae79bcb76568005bebbfef4bea486
db56a346fb0d76a502329ddfa0a4d68272b0fdeb
refs/heads/master
2023-03-24T12:40:02.274241
2021-03-03T11:05:55
2021-03-03T11:05:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include <iostream> #include "Point.h" using namespace std; int main(void) { Point point; point.Set(0, 5); cout << point.RetrieveVertical() << " " << point.RetrieveHorizontal() << endl; point.Move(1, 2); cout << point.RetrieveVertical() << " " << point.RetrieveHorizontal() << endl; for (int i = 0; i < 4; i++) { point.Rotate(); cout << point.RetrieveVertical() << " " << point.RetrieveHorizontal() << endl; } getchar(); return 0; }
[ "iriswu959@gmail.com" ]
iriswu959@gmail.com
05d4ec3cfd742d876389a2d4542391a7bf218ad7
541d3bca231027dfb5e85ddccd55f1d58d89820f
/util/util_skyw.h
fa689b4711278cc3a6b73579f217ab212308efbe
[]
no_license
afrendybayu/qkura
06b11ab5f5b3010c0550d365ca7c4e82470425a1
fdf753bf420efa05eb744a0a5453fe028803c31e
refs/heads/master
2016-09-05T23:15:47.634721
2014-09-23T09:08:54
2014-09-23T09:08:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
#ifndef UTIL_SKYW_H #define UTIL_SKYW_H #include <QObject> #include <QXmlStreamReader> #include <QDebug> class util_skyw : public QObject { Q_OBJECT public: explicit util_skyw(QObject *parent = 0); void baca_xml(QString skyw); signals: public slots: private: QString parsing_payload(QString skyw); }; #endif // UTIL_SKYW_H
[ "afrendy@gmail.com" ]
afrendy@gmail.com
2afc75c52f6d53f7919c8262dbe6c90e8bbfee6a
e6769524d7a8776f19df0c78e62c7357609695e8
/tags/release-v0.3.52a/rs-Qt-gui/src/gui/graphframe.h
e2c87cea3e32a15437e22ce8e0844bda32671f15
[]
no_license
autoscatto/retroshare
025020d92084f9bc1ca24da97379242886277779
e0d85c7aac0a590d5839512af8a1e3abce97ca6f
refs/heads/master
2020-04-09T11:14:01.836308
2013-06-30T13:58:17
2013-06-30T13:58:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,967
h
/**************************************************************** * RetroShare is distributed under the following license: * * Copyright (C) 2007, * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ****************************************************************/ #ifndef _GRAPHFRAME_H #define _GRAPHFRAME_H #include <QApplication> #include <QDesktopWidget> #include <QFrame> #include <QPainter> #include <QPen> #include <QList> #define HOR_SPC 2 /** Space between data points */ #define SCALE_WIDTH 75 /** Width of the scale */ #define MIN_SCALE 10 /** 10 kB/s is the minimum scale */ #define SCROLL_STEP 4 /** Horizontal change on graph update */ #define BACK_COLOR Qt::black #define SCALE_COLOR Qt::green #define GRID_COLOR Qt::darkGreen #define RECV_COLOR Qt::cyan #define SEND_COLOR Qt::yellow #define FONT_SIZE 11 class GraphFrame : public QFrame { Q_OBJECT public: /** Bandwidth graph style. */ enum GraphStyle { SolidLine = 0, /**< Plot bandwidth as solid lines. */ AreaGraph /**< Plot bandwidth as alpha blended area graphs. */ }; /** Default Constructor */ GraphFrame(QWidget *parent = 0); /** Default Destructor */ ~GraphFrame(); /** Add data points. */ void addPoints(qreal recv, qreal send); /** Clears the graph. */ void resetGraph(); /** Toggles display of data counters. */ void setShowCounters(bool showRecv, bool showSend); /** Sets the graph style used to display bandwidth data. */ void setGraphStyle(GraphStyle style) { _graphStyle = style; } protected: /** Overloaded QWidget::paintEvent() */ void paintEvent(QPaintEvent *event); private: /** Gets the width of the desktop, the max # of points. */ int getNumPoints(); /** Paints an integral and an outline of that integral for each data set * (send and/or receive) that is to be displayed. */ void paintData(); /** Paints the send/receive totals. */ void paintTotals(); /** Paints the scale in the graph. */ void paintScale(); /** Returns a formatted string representation of total. */ QString totalToStr(qreal total); /** Returns a list of points on the bandwidth graph based on the supplied set * of send or receive values. */ QVector<QPointF> pointsFromData(QList<qreal>* list); /** Paints a line with the data in <b>points</b>. */ void paintLine(QVector<QPointF> points, QColor color, Qt::PenStyle lineStyle = Qt::SolidLine); /** Paints an integral using the supplied data. */ void paintIntegral(QVector<QPointF> points, QColor color, qreal alpha = 1.0); /** Style with which the bandwidth data will be graphed. */ GraphStyle _graphStyle; /** A QPainter object that handles drawing the various graph elements. */ QPainter* _painter; /** Holds the received data points. */ QList<qreal> *_recvData; /** Holds the sent data points. */ QList<qreal> *_sendData; /** The current dimensions of the graph. */ QRect _rec; /** The maximum data value plotted. */ qreal _maxValue; /** The maximum number of points to store. */ int _maxPoints; /** The total data sent/recv. */ qreal _totalSend; qreal _totalRecv; /** Show the respective lines and counters. */ bool _showRecv; bool _showSend; }; #endif
[ "drbob7@b45a01b8-16f6-495d-af2f-9b41ad6348cc" ]
drbob7@b45a01b8-16f6-495d-af2f-9b41ad6348cc
9e0c52c584863ab9fde717601458b9b629fef1e5
64534a2cfb924e1804859797f9858b79132131b5
/src/gep/include/gep/settings.h
450621a2834cff5ea9d2cbfbbda10919bdf0f991
[]
no_license
marijnz/bouncingballs
5b098aaa4890b35d74d75feb9997971f44de2cf2
5083307b4045a3304326998d88eac147b9d927d7
refs/heads/master
2020-07-20T11:57:18.650249
2015-01-28T18:11:51
2015-01-28T18:11:51
29,972,843
1
0
null
null
null
null
UTF-8
C++
false
false
3,270
h
#pragma once #include "gep/math3d/vec2.h" #include "gep/math3d/color.h" #include "gep/interfaces/scripting.h" namespace gep { namespace settings { struct General { std::wstring applicationTitle; General() : applicationTitle(L"Gameplay Programming") { } }; struct Scripts { std::string mainScript; std::string setupScript; std::string importantScriptsRoot; std::string userScriptsRoot; Scripts() : mainScript("data/scripts/main.lua") , setupScript("data/scripts/setup.lua") , importantScriptsRoot("data/base/") , userScriptsRoot("data/scripts/") { } }; struct Video { uvec2 initialRenderWindowPosition; uvec2 screenResolution; bool vsyncEnabled; bool adaptiveVSyncEnabled; float adaptiveVSyncThreshold; float adaptiveVSyncTolerance; Color clearColor; Video() : initialRenderWindowPosition(CW_USEDEFAULT, CW_USEDEFAULT), screenResolution(1280, 720), vsyncEnabled(false), adaptiveVSyncEnabled(true), adaptiveVSyncThreshold(1.0f / 59.0f), // 59 FPS adaptiveVSyncTolerance(1), // +- 1 FPS clearColor(0.0f, 0.125f, 0.3f, 1.0f) // Blueish color { } }; struct Lua { size_t maxStackDumpLevel; bool callstackTracebackEnabled; bool stackDumpEnabled; Lua() : maxStackDumpLevel(2), #ifdef _DEBUG callstackTracebackEnabled(true), stackDumpEnabled(true) #else callstackTracebackEnabled(false), stackDumpEnabled(false) #endif // _DEBUG { } }; } // Can be set in scripts class ISettings { public: ISettings() {} virtual ~ISettings() {} virtual void setGeneralSettings(const settings::General& settings) = 0; virtual settings::General& getGeneralSettings() = 0; virtual const settings::General& getGeneralSettings() const = 0; virtual void setVideoSettings(const settings::Video& settings) = 0; virtual settings::Video& getVideoSettings() = 0; virtual const settings::Video& getVideoSettings() const = 0; virtual void setScriptsSettings(const settings::Scripts& settings) = 0; virtual settings::Scripts& getScriptsSettings() = 0; virtual const settings::Scripts& getScriptsSettings() const = 0; virtual void setLuaSettings(const settings::Lua& settings) = 0; virtual settings::Lua& getLuaSettings() = 0; virtual const settings::Lua& getLuaSettings() const = 0; virtual void loadFromScriptTable(ScriptTableWrapper table) = 0; LUA_BIND_REFERENCE_TYPE_BEGIN LUA_BIND_FUNCTION_NAMED(loadFromScriptTable, "load") LUA_BIND_REFERENCE_TYPE_END }; }
[ "me@arcomul.nl" ]
me@arcomul.nl
47b8fc7cae9f487a03c0595dd13efb33f10f6ebe
6bb033053cd606cb6d2980b1a1c65e9a2f4bc43d
/GEngine/GFileStream.h
44176f595c9bfef91ffd10ccebcb165d0c25d640
[]
no_license
Gibex51/GEngine
ac320c6da28651bbb08cb1763a295c3780da6b9d
0c7262e733fd5eafa5838f2ce1ac38da7ae82e04
refs/heads/master
2021-01-01T04:33:47.746012
2016-04-25T06:43:13
2016-04-25T06:43:13
57,017,883
0
0
null
null
null
null
UTF-8
C++
false
false
618
h
#pragma once #include "GStructs.h" #include <fstream> using namespace std; #define G_FSMODE_CREATE 0 #define G_FSMODE_READ 1 #define G_FSMODE_WRITE 2 #define G_FSMODE_READWRITE 3 class GFileStream { public: size_t Position; g_bool Create(const string &FileName, g_uint8 Mode); void Release(); size_t GetSize(); size_t Read(void *Buffer, size_t Size); size_t Write(void *Buffer, size_t Size); size_t WriteString(const string &Str); size_t ReadEntireFile(void **Buffer); GFileStream(void); ~GFileStream(void); private: fstream _fstream; g_uint8 _mode; };
[ "gibex51@mail.ru" ]
gibex51@mail.ru
4bb5b434d3e8deb2564b29488b36434909cf3448
c0b78fd512779b4cb4959e8513aa5f8b730fa59b
/src/OpenLL/Color.h
da175ce85c17c0ec4fec70faca19bc06a30084c2
[]
no_license
Kracav4ik/saturn
d267d63376031f54be2efbf1f5c9e40bff8ed1bd
835dcae3db86f0ac5d6dd40afacc2f83c7b5610d
refs/heads/master
2023-07-14T09:48:02.971155
2021-05-24T03:21:01
2021-05-24T03:45:21
338,658,311
0
0
null
null
null
null
UTF-8
C++
false
false
705
h
#pragma once namespace ll { struct Color { Color(float a, float r, float g, float b); Color(float r, float g, float b); Color(); float a; float r; float g; float b; bool isDiscard() const; static Color greyscale(float v) { return Color(v, v, v); } static const Color DISCARD; }; inline Color operator+(const Color& c1, const Color& c2) { return Color(c1.a + c2.a, c1.r + c2.r, c1.g + c2.g, c1.b + c2.b); } inline Color operator*(float f, const Color& c) { return Color(f * c.a, f * c.r, f * c.g, f * c.b); } inline Color mul(const Color& c1, const Color& c2) { return Color(c1.a * c2.a, c1.r * c2.r, c1.g * c2.g, c1.b * c2.b); } }
[ "dikama2013@ya.ru" ]
dikama2013@ya.ru
b6093a2bb835f39551709675c069fc465e509373
e64282f4dc1c44705d0d121af79db55cf2b3d69e
/bcpp3-sourcecode/ch06/worked_example_1/dice.cpp
78004a4fd45f7464d9ce05c7dbb2ec382a3a7d7b
[]
no_license
tonningp/cis201-class-examples
58af125a78403f18569b0b11903b2defe8523642
cc966e76879f6e8e4ad95be7eb72f21cb3b434ca
refs/heads/master
2020-03-28T20:15:01.626664
2019-09-02T18:57:48
2019-09-02T18:57:48
149,052,947
4
6
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
#include <iostream> using namespace std; /** Generates a sequence of die toss values for testing. @param values the array to be filled with die toss values @param size the size of the values array */ void generate_test_values(int values[], int size) { int next = 1; for (int i = 0; i < size; i++) { values[i] = next; next++; if (next == 6) { next = 1; } } } /** Counts the number of times each value occurs in a sequence of die tosses. @param values an array of die toss values. Each element is >= 1 and <= faces. @param size the size of the values array @param faces the number of faces of the die @param counters an array of counters of length faces + 1. counters[j] is filled with the count of elements of values that equal j. counters[0] is not used. */ void count_values(int values[], int size, int faces, int counters[]) { for (int i = 1; i <= faces; i++) { counters[i] = 0; } for (int j = 0; j < size; j++) { int value = values[j]; counters[value]++; } } /** Prints a table of die value counters. @param faces the number of faces of the die @param counters an array of counters of length faces + 1. counters[0] is not printed. */ void print_counters(int faces, int counters[]) { for (int i = 1; i <= faces; i++) { cout << j << ": " << counters[j] << endl; } } int main() { const int FACES = 6; int counters[FACES + 1]; const int NUMBER_OF_TOSSES = 12; int tosses[NUMBER_OF_TOSSES]; generate_test_values(tosses, NUMBER_OF_TOSSES); count_values(tosses, NUMBER_OF_TOSSES, FACES, counters); print_counters(FACES, counters); return 0; }
[ "paul.tonning@student.vvc.edu" ]
paul.tonning@student.vvc.edu
60d08c18b685cffea3033a72316e015c3d35c25b
8e78f5da3c1b3467560ab39054a71e69f280b703
/archieve/CF1100F/CF1100F.cpp
cd80cdaf389cb09da4340800a3d21484c55752e5
[]
no_license
ycsgg/oi_code
aed9922a3bd53ef5ee88450d80af9fbb79a48479
1f98dca6fb0b69da2f566276cce89817fe828edd
refs/heads/main
2023-09-03T04:55:49.611275
2021-11-19T08:31:31
2021-11-19T08:31:31
342,456,005
0
0
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
#include <algorithm> #include <array> #include <iostream> #include <vector> #include <cstdio> using namespace std; const int N = 5e5 + 5; namespace XorBasis { const int LIM = 20; array<int, LIM> basis, pos; void insert(int x, int id) { for (int i = LIM; ~i; i--) { if ((x >> i) & 1) { if (!basis[i]) { basis[i] = x; pos[i] = id; return; } if (pos[i] < id) { swap(pos[i], id); swap(x, basis[i]); } x ^= basis[i]; } } } int query(int l, int r) { int res = 0; for (int i = LIM; ~i; i--) { if (pos[i] >= l) { res = max(res, res ^ basis[i]); } } return res; } } // namespace XorBasis int n, q; struct Query { int id, l, r; }; vector<Query> c; int main() { cin >> n; vector<int> a(n); for (auto &v : a) { cin >> v; } cin >> q; c.resize(q); for (int i = 0; i < q; i++) { cin >> c[i].l >> c[i].r; c[i].r--; c[i].l--; c[i].id = i; } sort(c.begin(), c.end(), [&](const Query &A, const Query &B) -> bool { if (A.r == B.r) { return A.l < B.l; } return A.r < B.r; }); int nowr = -1; vector<int> ans(q); for (auto qr : c) { while (nowr < qr.r) { nowr++; XorBasis::insert(a[nowr], nowr); } ans[qr.id] = XorBasis::query(qr.l, qr.r); } for (auto p : ans) { printf("%d\n", p); } return 0; } // Asusetic eru quionours
[ "ycs2495472711@outlook.com" ]
ycs2495472711@outlook.com
0139536751422d649acec1e992c0444cf71cc34d
67f988dedfd8ae049d982d1a8213bb83233d90de
/external/chromium/ui/aura/test/aura_test_helper.h
5f47255fa39dca7cc199fc1a903f48d802254e64
[ "BSD-3-Clause" ]
permissive
opensourceyouthprogramming/h5vcc
94a668a9384cc3096a365396b5e4d1d3e02aacc4
d55d074539ba4555e69e9b9a41e5deb9b9d26c5b
refs/heads/master
2020-04-20T04:57:47.419922
2019-02-12T00:56:14
2019-02-12T00:56:14
168,643,719
1
1
null
2019-02-12T00:49:49
2019-02-01T04:47:32
C++
UTF-8
C++
false
false
1,818
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_AURA_TEST_AURA_TEST_HELPER_H_ #define UI_AURA_TEST_AURA_TEST_HELPER_H_ #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" class MessageLoopForUI; namespace ui { class InputMethod; } namespace aura { class RootWindow; class TestScreen; namespace client { class DefaultCaptureClient; class FocusClient; } namespace test { class TestActivationClient; class TestStackingClient; // A helper class owned by tests that does common initialization required for // Aura use. This class creates a root window with clients and other objects // that are necessary to run test on Aura. class AuraTestHelper { public: explicit AuraTestHelper(MessageLoopForUI* message_loop); ~AuraTestHelper(); // Creates and initializes (shows and sizes) the RootWindow for use in tests. void SetUp(); // Clean up objects that are created for tests. This also deletes the Env // object. void TearDown(); // Flushes message loop. void RunAllPendingInMessageLoop(); RootWindow* root_window() { return root_window_.get(); } private: MessageLoopForUI* message_loop_; bool setup_called_; bool teardown_called_; bool owns_root_window_; scoped_ptr<RootWindow> root_window_; scoped_ptr<TestStackingClient> stacking_client_; scoped_ptr<TestActivationClient> test_activation_client_; scoped_ptr<client::DefaultCaptureClient> capture_client_; scoped_ptr<ui::InputMethod> test_input_method_; scoped_ptr<client::FocusClient> focus_client_; scoped_ptr<TestScreen> test_screen_; DISALLOW_COPY_AND_ASSIGN(AuraTestHelper); }; } // namespace test } // namespace aura #endif // UI_AURA_TEST_AURA_TEST_HELPER_H_
[ "rjogrady@google.com" ]
rjogrady@google.com
7fe10250b14627acd86a8f51152401e394ed48bc
0bd1265abbec9fa8b1ecca2b2e9bd48572ffaffc
/include/llvm/DebugInfo/PDB/Native/NativeSymbolEnumerator.h
64d4c35c0858a29cd520b379218c43464b157e40
[]
no_license
BenQuickDeNN/Kaleidoscope
2daa74aaa1ec82866d4c4e8b72c68dd5a7ce803a
573b769ecc1b78f1ad9d2fd0a68978028b528e14
refs/heads/master
2022-10-06T21:51:10.741879
2020-06-11T02:19:48
2020-06-11T02:19:48
208,954,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
h
//===- NativeSymbolEnumerator.h - info about enumerator values --*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_NATIVE_NATIVESYMBOLENUMERATOR_H #define LLVM_DEBUGINFO_PDB_NATIVE_NATIVESYMBOLENUMERATOR_H #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/PDB/Native/NativeRawSymbol.h" #include "llvm/DebugInfo/PDB/Native/NativeSession.h" namespace llvm { namespace pdb { class NativeTypeEnum; class NativeSymbolEnumerator : public NativeRawSymbol { public: NativeSymbolEnumerator(NativeSession &Session, SymIndexId Id, const NativeTypeEnum &Parent, codeview::EnumeratorRecord Record); ~NativeSymbolEnumerator() override; void dump(raw_ostream &OS, int Indent, PdbSymbolIdField ShowIdFields, PdbSymbolIdField RecurseIdFields) const override; SymIndexId getClassParentId() const override; SymIndexId getLexicalParentId() const override; std::string getName() const override; SymIndexId getTypeId() const override; PDB_DataKind getDataKind() const override; PDB_LocType getLocationType() const override; bool isConstType() const override; bool isVolatileType() const override; bool isUnalignedType() const override; Variant getValue() const override; protected: const NativeTypeEnum &Parent; codeview::EnumeratorRecord Record; }; } // namespace pdb } // namespace llvm #endif // LLVM_DEBUGINFO_PDB_NATIVE_NATIVETYPEENUM_H
[ "benquickdenn@foxmail.com" ]
benquickdenn@foxmail.com
67806d90337cc657541e50f33918f17066226887
8e036ee47867781c2950ceba7fed99eef1b2d2a6
/question-bank/0140-word-break2/solution.cpp
5d4e81e1c240d8651c3041a836996fd51a731051
[]
no_license
Suida/Leetcode
5cb3a613e902a24b148d59b7c60efe3972ad6555
32f504b60ab67c41c0a68aacbeb3a35fdf0da083
refs/heads/master
2021-04-17T19:17:18.264384
2020-04-19T11:05:10
2020-04-19T11:05:10
249,468,857
1
0
null
null
null
null
UTF-8
C++
false
false
2,397
cpp
#include <vector> #include <string> #include <iostream> #include <cstdio> using namespace std; struct Trie { bool isEnd; Trie** next; }; class Solution { public: vector<string> wordBreak(string s, vector<string>& wordDict) { int m = s.size(); Trie* root = &buildTrie(wordDict), *cur; vector<vector<string>> dp; for (int i=0; i<m+1; ++i) { dp.push_back(vector<string> {}); } dp[0].push_back(""); for (int i=0; i<m; ++i) { if (dp[i].empty()) continue; cur = root; for (int j=i; j<m+1; ++j) { if (cur->isEnd) { dp[j].push_back(s.substr(i, j-i)); } if (cur->next[s[j]-'a'] && j != m) { cur = cur->next[s[j]-'a']; continue; } break; } } return dfs(dp, m); } vector<string> dfs(vector<vector<string>> const& dp, int i) { vector<string> res; int j; for (auto& w: dp[i]) { j = i - w.size(); if (j == 0) { res.push_back(w); continue; } for (auto sfx: dfs(dp, j)) { res.push_back(sfx + " " + w); } } return res; } Trie& buildTrie(vector<string> const& words) { Trie* root = new Trie, *cur; root->isEnd = false; root->next = new Trie*[26] { nullptr }; for (auto& w: words) { cur = root; for (auto c: w) { if (cur->next[c-'a'] == nullptr) { cur->next[c-'a'] = new Trie; cur->next[c-'a']->isEnd = false; cur->next[c-'a']->next = new Trie*[26] { nullptr }; } cur = cur->next[c-'a']; } cur->isEnd = true; } return *root; } }; int main() { string s, w; cin >> s; vector<string> d; char c = getchar(); while ((c = getchar()) != '\n') { if (c == ' ') d.push_back(w), w = ""; else w.push_back(c); } d.push_back(w); cout << "String: " << s << endl << "Words:" << endl; for (auto w: d) cout << "--" << w << endl; for (auto str: Solution().wordBreak(s, d)) cout << str << endl; return 0; }
[ "suidar@foxmail.com" ]
suidar@foxmail.com
01529810ce46f25631c23426e2c7cd9232c5d28c
3b8473e406bcb897e4292883c4860d7ce662775e
/lib/Target/JSBackend/OptPasses.h
44892cf907e0bf13530a058b7b3bb12e516ddad0
[ "NCSA" ]
permissive
mcanthony/PNaCl-Dynamic-Linking
3b5bfe328f8e4a2bdbd79f98799121930ff69408
92d899e138d977589f07075dbc31b781341c2f02
refs/heads/dl
2020-04-05T18:58:29.840981
2015-09-29T16:52:51
2015-09-29T16:52:51
44,759,629
0
1
null
2015-10-22T16:50:59
2015-10-22T16:50:59
null
UTF-8
C++
false
false
520
h
//===-- JSTargetMachine.h - TargetMachine for the JS Backend ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// #ifndef OPT_PASSES_H #define OPT_PASSES_H #include "llvm/Pass.h" namespace llvm { extern FunctionPass *createEmscriptenSimplifyAllocasPass(); } // End llvm namespace #endif
[ "jfb@chromium.org" ]
jfb@chromium.org
05d72c6496a4d5886ad3e31ea35be691ca79397a
7ef00c02863538e97cd741aaf228b0a4f64da059
/CTC/1.7.cpp
c4caaa43462f3ff3c7b91aa2586edf6caba7803b
[]
no_license
E-Fung/CTC
d71eab70607a42423089a306f189f99c487da0b2
2bc28db8b75073c928f6a5f250936c3ccaea9773
refs/heads/master
2022-11-18T14:25:16.532832
2020-07-18T21:17:42
2020-07-18T21:17:42
280,741,100
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
//This program rotates an N by N matrix by 90 degrees in place #include<vector> #include<iostream> #include<string> using namespace std; void print(vector<vector<string>>& vec) { int size = vec.size(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << vec[i][j] << " "; } cout << endl; } cout << endl; } void rotate(vector<vector<string>>& vec) { int size = vec.size(); string temp; for (int i = 0; i < size / 2; i++) { for (int j = i; j < size - i-1; j++) {//this code is ugly af temp = vec[i][i + j]; vec[i][i + j] = vec[size - 1 - i - j][i]; vec[size - 1 - i - j][i] = vec[size - 1 - i][size - 1 - i - j]; vec[size - 1 - i][size - 1 - i - j] = vec[i+j][size - 1 - i]; vec[j+i][size - 1 - i] = temp; print(vec); } } } int main() { vector<vector<string>> vec; vec.push_back({ "00","01","02","03","04" }); vec.push_back({ "10","11","12","13","14" }); vec.push_back({ "20","21","22","23","24" }); vec.push_back({ "30","31","32","33","34" }); vec.push_back({ "40","41","42","43","44" }); print(vec); rotate(vec); //print(vec); string input; cin >> input; return 0; }
[ "64280043+E-Fung@users.noreply.github.com" ]
64280043+E-Fung@users.noreply.github.com
2416500b28c473370098fc6a73dd696e9b587624
5119767489dc6bfa8d3b559766c87806a7e106bf
/sources/engine.cpp
afd756f283049443b2768cb99f5b61512c309658
[]
no_license
xathanex/analiza
c6ffddf803402986651574c9bea364bac1b41854
3992767d8a716d436596cefe5146049f03d45fd9
refs/heads/master
2016-09-06T17:29:42.635674
2015-02-02T21:25:44
2015-02-02T21:25:44
26,316,612
0
0
null
null
null
null
UTF-8
C++
false
false
5,805
cpp
#include "engine.h" #include "events.h" #include <cmath> #include <vector> Engine::Engine(std::vector<const char *> shipNames) { // sets start positions for all ships // TODO: randomowe pozycje statków // TODO: wykrywanie kolizji pozycji statków /* ShipProperties shipPos1, shipPos2; shipPos1.posX = BattleSettings::battlefieldSizeX / 4; shipPos1.posY = BattleSettings::battlefieldSizeY / 2; shipPos2.posX = BattleSettings::battlefieldSizeX - (BattleSettings::battlefieldSizeX / 4); shipPos2.posY = BattleSettings::battlefieldSizeY / 2; shipPos1.shipDirection = 0.0; shipPos1.cannonDirection = 0.0; shipPos1.radarDirection = 0.0; shipPos2.shipDirection = M_PI; shipPos2.cannonDirection = M_PI; shipPos2.radarDirection = M_PI; Ship * tempShip1 = new Ship(shipPos1, shipNames[0]); ships.push_back(tempShip1); Ship * tempShip2 = new Ship(shipPos2, shipNames[1]); ships.push_back(tempShip2); scene = new Scene(); scene -> registerSceneObject(ships[0] -> getSceneObject()); scene -> registerSceneObject(ships[1] -> getSceneObject()); */ } void Engine::bulletHitBulletEvent(int i1, int i2) { BulletHitBulletEvent e1 { bullets[i1] -> getId(), bullets[i2] -> getId() }; bullets[i1] -> getShip().getRubyShip().onBulletHitBullet(e1); BulletHitBulletEvent e2 { bullets[i2] -> getId(), bullets[i1] -> getId() }; bullets[i2] -> getShip().getRubyShip().onBulletHitBullet(e2); bullets.erase(bullets.begin() + i1); bullets.erase(bullets.begin() + i2); } void Engine::shipHitShipEvents(int i1, int i2) { ShipHitEvent e1 { ships[i2] -> getName(), ships[i2] -> getDirection(), atan2(ships[i2] -> getY(), ships[i2] -> getX()) - ships[i2] -> getDirection(), ships[i2] -> getEnergy(), 0 // distance between two balls-like ships? }; ships[i1] -> getRubyShip().onShipHit(e1); ShipHitEvent e2 { ships[i1] -> getName(), ships[i1] -> getDirection(), atan2(ships[i1] -> getY(), ships[i1] -> getX()) - ships[i1] -> getDirection(), ships[i1] -> getEnergy(), 0 // distance between two balls-like ships? }; ships[i2] -> getRubyShip().onShipHit(e2); } void Engine::bulletHitShipEvent(int bulletIterator, int shipIterator) { BulletHitEvent be { bullets[bulletIterator] -> getId(), ships[shipIterator] -> getName(), ships[shipIterator] -> getEnergy() - bullets[bulletIterator] -> getWeight() }; bullets[bulletIterator] -> getShip().getRubyShip().onBulletHit(be); HitByBulletEvent se { bullets[bulletIterator] -> getId() }; ships[shipIterator] -> getRubyShip().onHitByBullet(se); } void Engine::checkBulletShipCollision(int bulletIterator, int shipIterator) { double bx, by, sx, sy; bx = bullets[bulletIterator] -> getX(); by = bullets[bulletIterator] -> getY(); sx = ships[shipIterator] -> getX(); sy = ships[shipIterator] -> getY(); if (abs(bx - sx) <= BattleSettings::shipRadius && abs(by - sy) <= BattleSettings::shipRadius) { bulletHitShipEvent(bulletIterator, shipIterator); if (ships[shipIterator] -> decrementEnergy( bullets[bulletIterator] -> getWeight())) { ships.erase(ships.begin() + shipIterator); } bullets.erase(bullets.begin() + bulletIterator); } } void Engine::moveBullets() { unsigned short it = 0; while (it < bullets.size()) { if (!bullets[it] -> goAndCheck()) { // bullet is outside the screen bullets.erase(bullets.begin() + it); continue; } for (int k = 0; k < bullets.size(); ++k) { if (bullets[it] -> getX() == bullets[k] -> getX() && bullets[it] -> getY() == bullets[k] -> getY()) { bulletHitBulletEvent(it, k); break; } } ++it; } } void Engine::moveShips() { int it = 0; while (it < ships.size()) { ships[it] -> go(); // check if moved ship does not cover another ships for (int j = 0; j < ships.size(); ++j) { if (ships[it] ->isShipCollision(ships[j] -> getX(), ships[j] -> getY())) { shipHitShipEvents(it, j); ships[it] -> undoMove(); break; } } ++it; } } void Engine::moveAndCheck() { short time, it, sh, b; for (time = 0; time < BattleSettings::bulletSpeed; ++time) { moveBullets(); moveShips(); for (sh = 0; sh < ships.size(); ++sh) { for (b = 0; b < bullets.size(); ++b) { checkBulletShipCollision(b, sh); } } } } void Engine::shoot() { for (int i = 0; i < ships.size(); ++i) { if (ships[i] -> canShoot()) { // TODO: builder do tworzenia pocisków // bullets.push_back(new Bullet(ships[i], )) } } } bool Engine::executeTurn() { /* TODO: zaimplementować wykonywanie się tury true: go to next turn false: game over */ // repaints objects on screen and prepares them to next turn // also executes ruby code int i; for (i = 0; i < ships.size(); ++i) { ships[i] -> pushPosition(); ships[i] -> decrementFireDelay(); } for (i = 0; i < bullets.size(); ++i) { bullets[i] -> pushPosition(); } // moves all visible objects and checks for collisions moveAndCheck(); if (ships.size() < 2) return false; // performs shoot shoot(); // performs scan return true; }
[ "kbigaj@uj.edu.pl" ]
kbigaj@uj.edu.pl
6490a43eb0afdcf482e08edb41437b83b98708ae
c27637bbc71c302643566ba57057406ccec1bf96
/FileHandler.h
851e871bdeba5541b4387c12ecc1bc5d1f54679c
[]
no_license
dmterkula/Hashing-File-Comparison
b2ad73667fde76c5b59793742fec8f8ae380fec6
19108c58480e55308c09d79842c626f82be1beb1
refs/heads/master
2021-06-23T23:47:06.996524
2017-09-11T02:28:56
2017-09-11T02:28:56
103,080,465
0
0
null
null
null
null
UTF-8
C++
false
false
2,703
h
// FileHandler.h /* * Creates the outline for a class that reads and writes to files. This FileHandler also * stores a Hasher object so that it can hash the strings it reads from a given file. * This FileHandler will only read files that are valid. It also stores the current * File name it is reding and writing to as an instance variable. This class will * create and store a map of the hashes for the main class to retrieve and use easily. * In addition, this class also counts the number of bytes it reads. * * David Terkula * 12/4/2016 */ #ifndef FileHandler_H #define FileHandler_H #include <iostream> #include <vector> #include <string> #include <fstream> #include "Hasher.h" #include <map> using namespace std; class FileHandler{ private: string readFrom; string writeTo; ifstream infile; Hasher hasher; static const int windowSize = 3; int byteCounter = 0; int numLines = 0; public: /* * Constructor for FileHandler, takes no arguements */ FileHandler(); /* * Sets the instance variable of readFrom to the passed string 'fileName' */ void setReadFrom(string fileName); /* * Sets the instance variable of writeTo to the passed string 'fileName' */ void setWriteTo(string fileName); /* * Reads and hashes the file window by window, sliding down the file as it goes so each line is eventually * considered as the first line of the window. will not hash the last lines in a file if it is smaller than * the window size. This method also writes to a new file the hashes and starting lines of each window */ int readAndHash(); /* * Compares two files output from the readAndHash method. Tells the user which lines arein common * between the files based on matching hash values. returns the number of bytes it reads */ int compareFiles(string file1, string file2); /* * reads the data file that was output from the readAndHash method, and parses the first part as divded by a space, * a hashval_t and the next part as the starting lines of the hash value in the file. * counts the number of bytes it reads */ map<hashval_t, vector<int>> readDataFile(map<hashval_t, vector<int>> hashMap); /* * Given a string fileName, this method returns true if the file exists in the current directory and can be opened, * and false otherwise */ bool testFileValidty(string fileName); /* * this method prints the file comparison between two data files showing which lines are the same from the two files. */ void printTable(map<hashval_t, vector<int>> hashMap, string tableName); /* * this method returns the given string without any white spaces, or */ string standardizeText(string text); }; #endif
[ "David" ]
David
dc910078468d0ed3ea03f569cc5347e059003896
7c2f76936ab69618e47a8033fa788aff573d6d24
/catkin_ws/src/cpi_compare/src/cpi/CpiBase.h
5b30c160847c988f7c7445daabcb7ae78b13b42b
[ "MIT" ]
permissive
UMich-BipedLab/cpi
1a65ee0b28e86365f91a652a9fbf50046aadd061
9207d1ff1601242041c4f7cb2829b23e8d3bd3f6
refs/heads/master
2020-03-28T01:02:13.967054
2018-09-13T09:15:13
2018-09-13T09:15:13
147,471,222
1
0
null
2018-09-05T06:34:41
2018-09-05T06:34:41
null
UTF-8
C++
false
false
5,832
h
/** * MIT License * Copyright (c) 2018 Kevin Eckenhoff * Copyright (c) 2018 Patrick Geneva * Copyright (c) 2018 Guoquan Huang * * 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 CPI_BASE_H #define CPI_BASE_H #include <Eigen/Dense> #include "utils/quat_ops.h" /** * Continuous Preintegration Theory for Graph-based Visual-Inertial Navigation * Authors: Kevin Eckenhoff, Patrick Geneva, and Guoquan Huang * http://udel.edu/~ghuang/papers/tr_cpi.pdf */ class CpiBase { public: /** * Default constructor * @param sigma_w gyroscope white noise density (rad/s/sqrt(hz)) * @param sigma_wb gyroscope random walk (rad/s^2/sqrt(hz)) * @param sigma_a accelerometer white noise density (m/s^2/sqrt(hz)) * @param sigma_ab accelerometer random walk (m/s^3/sqrt(hz)) */ CpiBase(double sigma_w, double sigma_wb, double sigma_a, double sigma_ab, bool imu_avg_= false) { // Calculate our covariance matrix Q_c.block(0,0,3,3) = std::pow(sigma_w,2)*eye3; Q_c.block(3,3,3,3) = std::pow(sigma_wb,2)*eye3; Q_c.block(6,6,3,3) = std::pow(sigma_a,2)*eye3; Q_c.block(9,9,3,3) = std::pow(sigma_ab,2)*eye3; imu_avg = imu_avg_; // Calculate our unit vectors, and their skews (used in bias jacobian calcs) e_1 << 1,0,0; e_2 << 0,1,0; e_3 << 0,0,1; e_1x = skew_x(e_1); e_2x = skew_x(e_2); e_3x = skew_x(e_3); } /** * This function sets the linearization points we are to preintegrate about * For model 2 we will also pass the q_GtoK and current gravity estimate */ void setLinearizationPoints(Eigen::Matrix<double,3,1> b_w_lin_, Eigen::Matrix<double,3,1> b_a_lin_, Eigen::Matrix<double,4,1> q_k_lin_ = Eigen::Matrix<double,4,1>::Zero(), Eigen::Matrix<double,3,1> grav_ = Eigen::Matrix<double,3,1>::Zero()) { b_w_lin = b_w_lin_; b_a_lin = b_a_lin_; q_k_lin = q_k_lin_; grav = grav_; } /** * Function that handles new IMU messages, will precompound our means, jacobians, and measurement covariance */ virtual void feed_IMU(double t_0, double t_1, Eigen::Matrix<double,3,1> w_m_0, Eigen::Matrix<double,3,1> a_m_0, Eigen::Matrix<double,3,1> w_m_1 = Eigen::Matrix<double,3,1>::Zero(), Eigen::Matrix<double,3,1> a_m_2 = Eigen::Matrix<double,3,1>::Zero()) = 0; // Flag if we should perform IMU averaging or not // For version 1 we should average the measurement // For version 2 we average the local true bool imu_avg = false; // Measurement Means double DT = 0; Eigen::Matrix<double,3,1> alpha_tau = Eigen::Matrix<double,3,1>::Zero(); Eigen::Matrix<double,3,1> beta_tau = Eigen::Matrix<double,3,1>::Zero(); Eigen::Matrix<double,4,1> q_k2tau; Eigen::Matrix<double,3,3> R_k2tau = Eigen::Matrix<double,3,3>::Identity(); // Jacobians Eigen::Matrix<double,3,3> J_q = Eigen::Matrix<double,3,3>::Zero(); //ori jacob wrt b_w Eigen::Matrix<double,3,3> J_a = Eigen::Matrix<double,3,3>::Zero(); //alpha jacob wrt b_w Eigen::Matrix<double,3,3> J_b = Eigen::Matrix<double,3,3>::Zero(); //beta jacob wrt b_w Eigen::Matrix<double,3,3> H_a = Eigen::Matrix<double,3,3>::Zero(); //alpha jacob wrt b_a Eigen::Matrix<double,3,3> H_b = Eigen::Matrix<double,3,3>::Zero(); //beta jacob wrt b_a // Linearization points Eigen::Matrix<double,3,1> b_w_lin; Eigen::Matrix<double,3,1> b_a_lin; Eigen::Matrix<double,4,1> q_k_lin; // Global gravity Eigen::Matrix<double,3,1> grav = Eigen::Matrix<double,3,1>::Zero(); // Our continous-time measurement noise matrix Eigen::Matrix<double,12,12> Q_c = Eigen::Matrix<double,12,12>::Zero(); // Our measurement covariance Eigen::Matrix<double,15,15> P_meas = Eigen::Matrix<double,15,15>::Zero(); //========================================================================== // HELPER VARIABLES //========================================================================== // 3x3 identity matrix Eigen::Matrix<double,3,3> eye3 = Eigen::Matrix<double,3,3>::Identity(); // Simple unit vectors (used in bias jacobian calculations) Eigen::Matrix<double,3,1> e_1;// = Eigen::Matrix<double,3,1>::Constant(1,0,0); Eigen::Matrix<double,3,1> e_2;// = Eigen::Matrix<double,3,1>::Constant(0,1,0); Eigen::Matrix<double,3,1> e_3;// = Eigen::Matrix<double,3,1>::Constant(0,0,1); // Calculate the skew-symetric of our unit vectors Eigen::Matrix<double,3,3> e_1x;// = skew_x(e_1); Eigen::Matrix<double,3,3> e_2x;// = skew_x(e_2); Eigen::Matrix<double,3,3> e_3x;// = skew_x(e_3); }; #endif /* CPI_BASE_H */
[ "pgeneva@udel.edu" ]
pgeneva@udel.edu
9ac6f9d64f59a96a564b067251760a11c6d49162
73c8a3179b944b63b2a798542896e4cdf0937b6e
/AtCoder/ABC-295/E.cc
f21b960244e3c0234cad2aa6a4b87f2fa6ef8443
[ "Apache-2.0" ]
permissive
aajjbb/contest-files
c151f1ab9b562ca91d2f8f4070cb0aac126a188d
71de602a798b598b0365c570dd5db539fecf5b8c
refs/heads/master
2023-07-23T19:34:12.565296
2023-07-16T00:57:55
2023-07-16T00:57:59
52,963,297
2
4
null
2017-08-03T20:12:19
2016-03-02T13:05:25
C++
UTF-8
C++
false
false
912
cc
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned long long uInt; typedef unsigned uint; int main(void) { int N, M, K; cin >> N >> M >> K; vector<int> A(N); int open_values = 0; for (int i = 0; i < N; i++) { cin >> A[i]; if (A[i] == 0) { open_values += 1; } } for (int goal = 1; goal <= M; goal++) { int se = get_smaller_or_equal(A, goal); int gt = get_greater_than(A, goal); } return 0; }
[ "jefersonlsiq@gmail.com" ]
jefersonlsiq@gmail.com
4c6a310876ed2f0a0f8115b3ee54f750558cfbb8
57b6fa831fe532cf0739135c77946f0061e3fbf5
/NWNXLib/API/Mac/API/CPlayOptions.cpp
50775d0d08cb29831b345fc7a481169310993101
[ "MIT" ]
permissive
presscad/nwnee
dfcb90767258522f2b23afd9437d3dcad74f936d
0f36b281524e0b7e9796bcf30f924792bf9b8a38
refs/heads/master
2020-08-22T05:26:11.221042
2018-11-24T16:45:45
2018-11-24T16:45:45
216,326,718
1
0
MIT
2019-10-20T07:54:45
2019-10-20T07:54:45
null
UTF-8
C++
false
false
130
cpp
#include "CPlayOptions.hpp" #include "API/Functions.hpp" #include "Platform/ASLR.hpp" namespace NWNXLib { namespace API { } }
[ "liarethnwn@gmail.com" ]
liarethnwn@gmail.com
6436e908ee9a2f5edfc7c6f14e06cb85066def56
2480ceee9f28f5e8a69fb6f5ed42fd63c22b4205
/include/Pomdog/Signals/detail/EventBody.hpp
0730146558e49ab591c1659d5e437c3aa0ee17bb
[ "MIT" ]
permissive
rokrepo/pomdog
165db7884598c74bd530a4b7a1e83bc1e315c945
b21fd4fef295aaa3e06ca15e5952109cd8e93f00
refs/heads/master
2022-10-25T04:09:09.721827
2020-06-18T05:33:25
2020-06-18T05:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,391
hpp
// Copyright (c) 2013-2020 mogemimi. Distributed under the MIT license. #pragma once #include <type_traits> #include <typeinfo> #include <utility> namespace Pomdog::Detail { template <class T> struct EventHashCode final { static_assert(!std::is_pointer<T>::value, "T is not pointer."); static_assert(std::is_object<T>::value, "T is not object type."); static const std::size_t value; }; template <class T> const std::size_t EventHashCode<T>::value = typeid(const T*).hash_code(); class EventBody { public: EventBody() = default; EventBody(const EventBody&) = delete; EventBody& operator=(const EventBody&) = delete; virtual ~EventBody() = default; virtual std::size_t HashCode() const noexcept = 0; }; template <typename T> class EventBodyOverride final : public EventBody { public: static_assert(!std::is_reference<T>::value, "reference type is not supported."); static_assert(!std::is_pointer<T>::value, "pointer type is not supported."); static_assert(std::is_object<T>::value, "T is object type."); template <typename... Arguments> explicit EventBodyOverride(Arguments&&... argument) : data(std::forward<Arguments>(argument)...) { } std::size_t HashCode() const noexcept override { return EventHashCode<T>::value; } T data; }; } // namespace Pomdog::Detail
[ "mogemimi@enginetrouble.net" ]
mogemimi@enginetrouble.net
833304b7d72a372ed2700292b6e688abf83a6ef6
d1c6d23117832c1417ac630587f21f508b92efb6
/GameOfIherience.cpp
09bf56aa466aadff84fbac33919842149ed0c9be
[]
no_license
YongLAGCC/cpp_game
515e65827d1d1b2ca1f7adc279202cf43762e092
f5e458de20a463a1d8587de039c3e2f6670114a6
refs/heads/master
2020-07-11T17:17:41.543981
2020-01-20T17:48:21
2020-01-20T17:48:21
204,603,121
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
//Yong, Zhou //Miguel Long. MAC125_7133 //#include "stdafx.h" #include "Human.h" #include<iostream> using namespace std; Human::Human() { } Human::~Human() { } Human::Human(int newStrength, int newHit) :Creature(newStrength, newHit) {} string Human::getSpecies() { return "Human "; } int Human::getDamage() { int damage = Creature::getDamage(); cout << getSpecies() << "attacks for " << damage << " points!" << endl; return damage; }
[ "1291001957.yz@gmail.com" ]
1291001957.yz@gmail.com
c3df573bf6517848578bd46fcbf90b52fe304d6d
ad5eaa9a33248f38884a5a5f0d52788afa2bc901
/chrome/browser/ui/views/plugin_vm/plugin_vm_launcher_view.h
21c69051a3ac466c5320abddb0f752f39e6d6a4c
[ "BSD-3-Clause" ]
permissive
dwb420/chromium
2cc203d9cff6d64ccb4a2cbcad0aaad0a6778b4f
6147f4cea449793bef7d5a4496a47184e2867401
refs/heads/master
2023-01-09T17:35:18.799896
2019-11-13T20:32:27
2019-11-13T20:32:27
221,362,316
0
0
BSD-3-Clause
2019-11-13T03:13:37
2019-11-13T03:13:36
null
UTF-8
C++
false
false
4,207
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_PLUGIN_VM_PLUGIN_VM_LAUNCHER_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_PLUGIN_VM_PLUGIN_VM_LAUNCHER_VIEW_H_ #include "base/callback.h" #include "base/macros.h" #include "chrome/browser/chromeos/plugin_vm/plugin_vm_image_manager.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" namespace views { class ImageView; class Label; class ProgressBar; } // namespace views class Profile; // The PluginVm launcher that is shown to user if PluginVm icon is clicked, but // PluginVm is not yet ready to be launched. This class is responsible for // triggering the steps of the PluginVm setup process and displaying progress // according to the state of this setup. class PluginVmLauncherView : public views::BubbleDialogDelegateView, public plugin_vm::PluginVmImageManager::Observer { public: explicit PluginVmLauncherView(Profile* profile); static PluginVmLauncherView* GetActiveViewForTesting(); // views::BubbleDialogDelegateView implementation. int GetDialogButtons() const override; base::string16 GetDialogButtonLabel(ui::DialogButton button) const override; bool ShouldShowWindowTitle() const override; bool Accept() override; bool Cancel() override; gfx::Size CalculatePreferredSize() const override; // plugin_vm::PluginVmImageDownloadObserver implementation. void OnDownloadStarted() override; void OnDownloadProgressUpdated(uint64_t bytes_downloaded, int64_t content_length, base::TimeDelta elapsed_time) override; void OnDownloadCompleted() override; void OnDownloadCancelled() override; void OnDownloadFailed( plugin_vm::PluginVmImageManager::FailureReason reason) override; void OnImportProgressUpdated(int percent_completed, base::TimeDelta elapsed_time) override; void OnImported() override; void OnImportCancelled() override; void OnImportFailed( plugin_vm::PluginVmImageManager::FailureReason reason) override; // Public for testing purposes. base::string16 GetBigMessage() const; base::string16 GetMessage() const; void SetFinishedCallbackForTesting( base::OnceCallback<void(bool success)> callback); private: enum class State { START_DOWNLOADING, // PluginVm image downloading should be started. DOWNLOADING, // PluginVm image downloading is in progress. IMPORTING, // Downloaded PluginVm image importing is in progress. FINISHED, // PluginVm environment setting has been finished. ERROR, // Something unexpected happened. NOT_ALLOWED, // PluginVm is disallowed on the device. }; ~PluginVmLauncherView() override; void OnStateUpdated(); // views::BubbleDialogDelegateView implementation. void AddedToWidget() override; base::string16 GetDownloadProgressMessage(uint64_t downlaoded_bytes, int64_t content_length) const; // Updates the progress bar and shows a time left message if available. void UpdateOperationProgress(double units_processed, double total_units, base::TimeDelta elapsed_time) const; void SetBigMessageLabel(); void SetMessageLabel(); void SetBigImage(); void StartPluginVmImageDownload(); Profile* profile_ = nullptr; plugin_vm::PluginVmImageManager* plugin_vm_image_manager_ = nullptr; views::Label* big_message_label_ = nullptr; views::Label* message_label_ = nullptr; views::ProgressBar* progress_bar_ = nullptr; views::Label* download_progress_message_label_ = nullptr; views::Label* time_left_message_label_ = nullptr; views::ImageView* big_image_ = nullptr; base::TimeTicks setup_start_tick_; State state_ = State::START_DOWNLOADING; base::OnceCallback<void(bool success)> finished_callback_for_testing_; DISALLOW_COPY_AND_ASSIGN(PluginVmLauncherView); }; #endif // CHROME_BROWSER_UI_VIEWS_PLUGIN_VM_PLUGIN_VM_LAUNCHER_VIEW_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2413d7a487e3bb96d14cfcc9f922975adcb8dcdb
c5d0d500897a38d7aa30299a56aa756e76072de4
/src/task.cpp
fc83d3271bb1f9e7067eb031c28b9d3e5795a642
[]
no_license
belukhin/mod-task08-shop
6b0cd8906bbf0b1bbc489eac44afc111bf353402
56ddc077ffe3b5de97c9a06ce1dd736ac9671928
refs/heads/main
2023-05-14T09:19:26.704015
2021-06-08T22:33:20
2021-06-08T22:33:20
375,062,024
0
0
null
2021-06-08T15:40:33
2021-06-08T15:40:32
null
UTF-8
C++
false
false
5,303
cpp
#include <string> #include <iostream> #include "../include/task.h" using namespace std; unsigned int Client::gen_id = 1; long Fact(long n) { if (n == 0) return 1; else return n * Fact(n - 1); } ///////////////////////// /// Shop ///////////////////////// Shop::Shop(int cashCount, int rate, double speed, int avgGoods, int maxCount) { cash = cashCount; this->rate = rate; this->speed = speed; this->avgGoods = avgGoods; maxQueue = maxCount; completedCount = 0; rejectedCount = 0; queueLength = 0; procCounter = 0; cashes = vector<Cash_reg>(); queue = deque<Client *>(); for (int i = 0; i < cash; i++) { cashes.push_back(Cash_reg()); cashes[i].thrd = thread(&Shop::Start, this, i); } } void Shop::Start(int index) { while (completedCount + rejectedCount < rate) { mu.lock(); queueLength += queue.size(); procCounter++; if (queue.size() > 0) { queue.at(0)->ExitQ(); int goods = queue.at(0)->GetGoods(); unsigned int id = queue.at(0)->GetId(); cashes[index].workStat += goods * speed; completedCount++; queue.at(0)->ExitCR(goods * speed); queue.pop_front(); mu.unlock(); while (goods > 0) { this_thread::sleep_for(chrono::milliseconds(speed)); goods -= 1; } cout << "Client with ID#" << id << " served." << endl; } else { cashes[index].waitStat += 10; mu.unlock(); this_thread::sleep_for(chrono::milliseconds(10)); } } } string Shop::Act() { srand(time(0)); string out = ""; int countClients = 0; vector<Client> clients; for (int i = 0; i < rate; i++) clients.push_back(Client(avgGoods)); double avgQLen = 0; while (countClients < rate){ int time = rand() % 1000; this_thread::sleep_for(std::chrono::milliseconds(time)); mu.lock(); avgQLen += queue.size(); if (queue.size() < maxQueue){ queue.push_back(&clients.at(countClients)); clients.at(countClients).EnterQ(); mu.unlock(); } else { mu.unlock(); rejectedCount++; cout << "Client with ID#" << clients.at(countClients).GetId() << " not served." << endl; } countClients++; } double avgWait = 0.0; double avgWork = 0.0; double avgTimeQ = 0.0; double avgTimeCashBox = 0.0; double workTime = 0.0; for (int i = 0; i < cash; i++){ cashes[i].thrd.join(); avgWait += cashes[i].waitStat; avgWork += cashes[i].workStat; } for (int i = 0; i < rate; i++){ if (clients.at(i).GetQtime() == 0 && clients.at(i).GetCRTime() == 0) continue; avgTimeQ += clients.at(i).GetQtime(); avgTimeCashBox += clients.at(i).GetCRTime(); } avgQLen /= (double)countClients; workTime = avgWork + avgWait; avgWait /= (double)cash; avgWork /= (double)cash; avgTimeQ /= (double)completedCount; avgTimeCashBox /= (double)completedCount; double lambda = rate * 1000.0 / avgWork; double m = 1000.0 / avgTimeCashBox; double r = lambda / m; double P0 = 1.0; for (int i = 1; i <= cash; i++) P0 += pow(r, i) / Fact(i); for (int i = cash + 1; i < cash + maxQueue; i++) P0 += pow(r, i) / (Fact(cash) * pow(cash, i - cash)); P0 = 1.0 / P0; double Prej = pow(r, cash + maxQueue) * P0 / (double)(pow(cash, maxQueue) * Fact(cash)); double Q = 1.0 - Prej; double A = lambda * Q; out += "\n\nStats:\n"; out += "\nServed Clients: " + to_string(completedCount); out += "\nUnserved Clients: " + to_string(rejectedCount); out += "\nAvg queue: " + to_string(avgQLen); out += "\nAvg time in queue and on CR: " + to_string(avgTimeQ) + " + " + to_string(avgTimeCashBox); out += "\nAvg CR time: " + to_string(avgWork); out += "\nAvg CR downtime: " + to_string(avgWait); out += "\nSystem failure probability: " + to_string((double)rejectedCount / (double)rate); out += "\nRelative store throughput: " + to_string((double)completedCount / (double)rate); out += "\nAbsolute bandwidth: " + to_string(lambda * (double)completedCount / (double)rate); out += "\n"; out += "\nProbability of failure: " + to_string(Prej); out += "\nRelative bandwidth: " + to_string(Q); out += "\nAbsolute bandwidth: " + to_string(A); return out; } ////////////////////////////////////////// /// Client ////////////////////////////////////////// Client::Client(int avgGoods) { Qtime = 0; CR = 0; goods = rand() % (2 * avgGoods); id = gen_id++; } unsigned int Client::GetId(){ return id; } int Client::GetQtime(){ return Qtime; } int Client::GetCRTime(){ return CR; } void Client::EnterQ(){ start_time = chrono::system_clock::now(); } void Client::ExitQ(){ Qtime = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - start_time).count(); } void Client::ExitCR(int time){ CR = time; } int Client::GetGoods(){ return goods; }
[ "79859537+belukhin@users.noreply.github.com" ]
79859537+belukhin@users.noreply.github.com
18557f498e7fe701c065c3047e5032e9e8a4a589
ef9a782df42136ec09485cbdbfa8a56512c32530
/newtrunk/src/fields/crops/cropItalRyegrass.cpp
a9c2753e8f00a21d6a07032b9829b6f0485b4c35
[]
no_license
penghuz/main
c24ca5f2bf13b8cc1f483778e72ff6432577c83b
26d9398309eeacbf24e3c5affbfb597be1cc8cd4
refs/heads/master
2020-04-22T15:59:50.432329
2017-11-23T10:30:22
2017-11-23T10:30:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
#include "../../base/common.h" #include "cropItalRyegrass.h" #include "../../products/products.h" /* * Temporary filler!! NJH May 2009 */ cropItalRyegrass::cropItalRyegrass(string aName, const int aIndex, const base * aOwner, string cropName): cropRyegrass(aName, aIndex, aOwner, cropName) { // theMessage->FatalError("cropItalRyegrass:: this class has not been fully tested. Delete this line to test"); PlantItemName = "ITALRYEG"; // These names maps to products.dat ! StrawItemName = "ITALRYEG"; // These names maps to products.dat ! WinterSeed = 0; // Is the present crop a wintercrop. } /* * Cut and return a plantItem NJH March 2001 * returns cut material in g/sq metre */ void cropItalRyegrass::Cut(plantItem * cutPlantMaterial, double cut_height) { if (GiveDryMatterVegTop() <= 0.0) { decomposable * Storage = new decomposable(); decomposable * Straw = new decomposable(); Harvest(Storage, Straw); *cutPlantMaterial + *Storage; *cutPlantMaterial + *Straw; delete Storage; delete Straw; } }
[ "sai@agro.au.dk" ]
sai@agro.au.dk
b97e19eed6d7df45f7bf37545986d59935e698c5
5e9c396ea5d81dce62ef4e6f260db21385608922
/src/chrono_models/vehicle/gator/Gator_TMeasyTire.h
ca0eea237d81bc727cdd25d9130a9519d5a63d39
[ "BSD-3-Clause" ]
permissive
gvvynplaine/chrono
357b30f896eb6c1dcabcebd0d88f10fab3faff20
a3c0c8735eb069d5c845a7b508a048b58e022ce0
refs/heads/develop
2023-01-05T08:43:13.115419
2020-07-09T08:24:34
2020-07-09T08:24:34
278,308,549
0
0
BSD-3-Clause
2020-10-30T12:17:47
2020-07-09T08:33:24
null
UTF-8
C++
false
false
2,898
h
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Gator TMeasy tire subsystem // // ============================================================================= #ifndef GATOR_TMEASY_TIRE_H #define GATOR_TMEASY_TIRE_H #include "chrono_vehicle/wheeled_vehicle/tire/ChTMeasyTire.h" #include "chrono_models/ChApiModels.h" namespace chrono { namespace vehicle { namespace gator { /// @addtogroup vehicle_models_gator /// @{ /// TMeasy tire model for the Gator (front). class CH_MODELS_API Gator_TMeasyTire_Front : public ChTMeasyTire { public: Gator_TMeasyTire_Front(const std::string& name); ~Gator_TMeasyTire_Front() {} virtual double GetVisualizationWidth() const override { return m_width; } virtual void SetTMeasyParams() override; virtual double GetMass() const override { return m_mass; } virtual ChVector<> GetInertia() const override { return m_inertia; } virtual void AddVisualizationAssets(VisualizationType vis) override; virtual void RemoveVisualizationAssets() override final; void GenerateCharacteristicPlots(const std::string& dirname); private: static const double m_mass; static const ChVector<> m_inertia; static const std::string m_meshFile_left; static const std::string m_meshFile_right; std::shared_ptr<ChTriangleMeshShape> m_trimesh_shape; }; /// TMeasy tire model for the Gator (rear). class CH_MODELS_API Gator_TMeasyTire_Rear : public ChTMeasyTire { public: Gator_TMeasyTire_Rear(const std::string& name); ~Gator_TMeasyTire_Rear() {} virtual double GetVisualizationWidth() const override { return m_width; } virtual void SetTMeasyParams() override; virtual double GetMass() const override { return m_mass; } virtual ChVector<> GetInertia() const override { return m_inertia; } virtual void AddVisualizationAssets(VisualizationType vis) override; virtual void RemoveVisualizationAssets() override final; void GenerateCharacteristicPlots(const std::string& dirname); private: static const double m_mass; static const ChVector<> m_inertia; static const std::string m_meshFile_left; static const std::string m_meshFile_right; std::shared_ptr<ChTriangleMeshShape> m_trimesh_shape; }; /// @} vehicle_models_gator } // end namespace gator } // end namespace vehicle } // end namespace chrono #endif
[ "serban@wisc.edu" ]
serban@wisc.edu
cd08436a67dffa0a89bc4520f5a6a29d18c3a4ee
66728df25e2f68e40d64fb4e4692cdfb072e8789
/Lab10/tache3/etape1.cpp
e216eed12786443edee62dc73622009320f59e2b
[]
no_license
matthieu994/INF3105
bd19947dc25dcaefa67a19660d658b4f0da93c17
49a9290f5c067325a5b972cd7868f8b4d129e80c
refs/heads/master
2021-10-30T07:50:06.755716
2019-04-25T20:49:15
2019-04-25T20:49:15
171,407,273
0
1
null
null
null
null
UTF-8
C++
false
false
4,090
cpp
/* INF3105 / Lab10 -- Exercices sur l'héritage et les conteneurs. Étape 1 : Comprendre le mécanisme d'héritage. */ #include <iostream> using namespace std; //***** Début des déclarations *************/ // Ceci irait normalement dans un ou plusieurs fichiers .h (personne.h, etudiant.h, employe.h). // En C++, une telle séparation est facultative, bien qu'elle puisse faciliter l'organisation d'un projet. // Nous le ferons plus tard (etape9). Pour l'instant, nous mettons tout dans un seul // fichier afin de minimiser le nombre de fichiers à visualiser pour chaque étape. // Déclaration d'une classe de base Personne. class Personne { public: Personne(const string& nom); void afficher() const; protected: // Le modificateur d'accès 'protected' est plus souple que 'private'. // Si 'nom' était private, les sous-classes n'auraient pas accès à 'nom'. // Pour y accéder, il faudrait ajouter des setNom() et getNom(); // En le mettant protected, on permet aux fonctions des sous-classes d'y // avoir directement accès. string nom; }; // Déclaration d'une classe Etudiant héritant de Personne. // "un Etudiant est une Personne" // "une Personne n'est pas nécessairement un Etudiant" class Etudiant : public Personne { public: Etudiant(const string& nom_, const string& programme_, float moyenne_); void afficher() const; protected: string programme; float moyenne; }; // Déclaration d'une classe Employe héritant de Personne. // "un Employe est une Personne" // "une Personne n'est pas nécessairement un Employe" class Employe : public Personne { public: Employe(const string& nom_, const string& departement_, float salaire_); void afficher() const; protected: string departement; float salaire; }; //***** Fin des déclarations *************/ //***** Début des définitions (implémentations des constructeurs et fonctions) *************/ // Ceci irait normalement dans un ou des fichiers .cpp (ou .cc, .c++) Personne::Personne(const string& nom_) : nom(nom_) // après le «:» , la partie initialisation. // nom(nom_) signifie qu'on construit nom par copie de nom_ { } void Personne::afficher() const { cout << "Personne: nom=" << nom << std::endl; } Etudiant::Etudiant(const string& nom_, const string& programme_, float moyenne_) : Personne(nom_) , programme(programme_) , moyenne(moyenne_) //Personne(nom) : comme Etudiant dérive de Personne, il faut construire la partie Personne, // donc, on appelle le constructeur Personne(const string&). { } void Etudiant::afficher() const { cout << "Etudiant: nom=" << nom << ", programme=" << programme << ", moyenne=" << moyenne << "/4.3" << std::endl; } Employe::Employe(const string& nom_, const string& departement_, float salaire_) : Personne(nom_) , departement(departement_) , salaire(salaire_) //Personne(nom) : comme Employe dérive de Personne, il faut construire la partie Personne, // donc, on appelle le constructeur Personne(const string&). { } void Employe::afficher() const { cout << "Employe: nom=" << nom << ", departement=" << departement << ", salaire=" << salaire << "$/an" << std::endl; } //***** Fin des définitions *************/ //***** Le programme principal *************/ int main() { Personne p1("jean"); p1.afficher(); Etudiant et1("marie", "medecine", 4.1f); et1.afficher(); Employe ep1("robert", "finances", 62400); ep1.afficher(); // Jusqu'ici, c'est assez simple. // Que font les 2 lignes suivantes? Personne p2 = et1; p2.afficher(); // Indice : p2 est un objet Personne. La partie Personne de l'objet et1 a été copiée dans p2. // Que font les 2 lignes suivantes? Personne* p3 = &et1; p3->afficher(); // Indice : p3 est un pointeur vers une Personne. // p3 pointe bien vers l'objet et1. // Toutefois, c'est la fonction Personne::afficher() qui est appelée. // Nous corrigerons cela dans etape2.cpp. return 0; }
[ "Matthieu-Xiaomi@Ubuntu" ]
Matthieu-Xiaomi@Ubuntu
bf814f777044b6b3c2d8f616144cd72c637bda2e
ded247e7c0d0b553308c447a9680881aaf0ef849
/PWGGA/GammaConv/AliAnalysisTaskMesonJetCorrelation.h
c51bca1d1db23278b0063fbf2173c274fdcfeb00
[]
permissive
sjaelani/AliPhysics
5898074160aea315c07e7c49b8f9c4fe0ec7478d
d7196ec9f1913dfec7d5537259826b8617bd89ef
refs/heads/master
2022-11-13T00:07:18.394588
2022-11-01T19:42:33
2022-11-01T19:42:33
227,425,721
0
0
BSD-3-Clause
2019-12-11T17:44:33
2019-12-11T17:44:32
null
UTF-8
C++
false
false
27,607
h
/************************************************************************** * Copyright(c) 1998-2020, ALICE Experiment at CERN, All rights reserved. * * * * Author: Joshua Koenig <joshua.konig@cern.ch> * * Version 1.0 * * * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ ////////////////////////////////////////////////////////////////// //---------------------------------------------------------------- // Class used to do analysis for light neutral mesons inside Jets //---------------------------------------------------------------- ////////////////////////////////////////////////////////////////// #ifndef ALIANLYSISTASKMesonJetCorrelation_cxx #define ALIANLYSISTASKMesonJetCorrelation_cxx #include "AliAnalysisManager.h" #include "AliAnalysisTaskConvJet.h" #include "AliAnalysisTaskJetOutlierRemoval.h" #include "AliAnalysisTaskSE.h" #include "AliCaloPhotonCuts.h" #include "AliConvEventCuts.h" #include "AliConversionAODBGHandlerRP.h" #include "AliConversionMesonCuts.h" #include "AliConversionPhotonCuts.h" #include "AliESDtrack.h" #include "AliGammaConversionAODBGHandler.h" #include "AliKFConversionPhoton.h" #include "AliV0ReaderV1.h" #include "TH3.h" #include "TH3F.h" #include "THnSparse.h" #include "TGenPhaseSpace.h" #include "TProfile2D.h" #include <map> #include <vector> #include "AliResponseMatrixHelper.h" #include "AliGammaConvEventMixing.h" class AliAnalysisTaskMesonJetCorrelation : public AliAnalysisTaskSE { public: AliAnalysisTaskMesonJetCorrelation(); AliAnalysisTaskMesonJetCorrelation(const char* name); virtual ~AliAnalysisTaskMesonJetCorrelation(); virtual void UserCreateOutputObjects(); virtual Bool_t Notify(); virtual void UserExec(Option_t*); virtual void Terminate(const Option_t*); // base functions for selecting photon and meson candidates void ProcessClusters(); void ProcessPhotonCandidates(); void CalculateMesonCandidates(); void CalculateBackground(); void CalculateBackgroundSwapp(); void CalculateBackgroundMix(); void UpdateEventMixData(); void FillInvMassBackHistograms(AliAODConversionMother* backgroundCandidate); std::array<std::unique_ptr<AliAODConversionPhoton>, 2> GetGammasSwapped(AliAODConversionPhoton* currentEventGoodV0Temp1, AliAODConversionPhoton* currentEventGoodV0Temp2); void FillMesonHistograms(AliAODConversionPhoton* gamma0, AliAODConversionPhoton* gamma1, int firstGammaIndex, int secondGammaIndex); void ProcessTrueBackgroundCandidatesAOD(AliAODConversionMother* Pi0Candidate, AliAODConversionPhoton* TrueGammaCandidate0, AliAODConversionPhoton* TrueGammaCandidate1, const int matchedJet, const float RJetPi0Cand); float GetFrag(AliAODConversionMother* Pi0Candidate, const int matchedJet, int isTrueJet); float GetFrag(AliAODMCParticle* Pi0Candidate, const int matchedJet, int isTrueJet); // MC functions void ProcessAODMCParticles(Int_t isCurrentEventSelected = 0); void ProcessTrueClusterCandidatesAOD(AliAODConversionPhoton* TruePhotonCandidate); void ProcessTruePhotonCandidatesAOD(AliAODConversionPhoton* TruePhotonCandidate); bool MCParticleIsSelected(AliAODMCParticle* particle1, AliAODMCParticle* particle2, bool checkConversion); bool MCParticleIsSelected(AliAODMCParticle* particle, bool isConv, bool checkConversion); int GetPhotonMotherLabel(AliAODConversionPhoton* gammaCand, int& convertedPhotonLabel, bool isCaloPhoton); void RelabelAODPhotonCandidates(Bool_t mode); void ProcessTrueMesonCandidatesAOD(AliAODConversionMother* Pi0Candidate, AliAODConversionPhoton* TrueGammaCandidate0, AliAODConversionPhoton* TrueGammaCandidate1, const int matchedJet, const float RJetPi0Cand = 0); void ProcessTrueMesonCandidatesInTrueJetsAOD(AliAODConversionMother* Pi0Candidate, AliAODConversionPhoton* TrueGammaCandidate0, AliAODConversionPhoton* TrueGammaCandidate1, const int matchedJet, const float RJetPi0Cand = 0); // void IsTrueParticle(AliAODConversionMother* Pi0Candidate, AliAODConversionPhoton* TrueGammaCandidate0, AliAODConversionPhoton* TrueGammaCandidate1, Bool_t matched); bool CheckAcceptance(AliAODMCParticle* gamma0, AliAODMCParticle* gamma1); bool IsParticleFromPartonFrag(AliAODMCParticle* particle, int idParton); // Jet functions void ProcessJets(); void InitJets(); // Helper functions void MakeBinning(); void CallSumw2ForLists(TList* l); // Setters void SetIsMC(Int_t isMC) { fIsMC = isMC; } void SetLightOutput(Int_t flag) { fDoLightOutput = flag; } void SetDoMesonQA(Int_t flag) { fDoMesonQA = flag; } void SetDoPhotonQA(Int_t flag) { fDoPhotonQA = flag; } void SetDoClusterQA(Int_t flag) { fDoClusterQA = flag; } // Function to set correction task setting void SetCorrectionTaskSetting(TString setting) { fCorrTaskSetting = setting; } void SetDoMaterialBudgetWeightingOfGammasForTrueMesons(Bool_t flag) { fDoMaterialBudgetWeightingOfGammasForTrueMesons = flag; } void SetIsCalo(bool isCalo) { fIsCalo = isCalo; } void SetIsConv(bool isConv) { fIsConv = isConv; } void SetIsConvCalo(bool isConvCalo) { fIsConvCalo = isConvCalo; } void SetIsHeavyIon(int flag) { fIsHeavyIon = flag; } void SetV0ReaderName(TString name) { fV0ReaderName = name; } void SetTrackMatcherRunningMode(Int_t mode) { fTrackMatcherRunningMode = mode; } void SetUseTHnSparseForResponse(bool tmp) { fUseThNForResponse = tmp; } void SetMesonKind(int meson) { (meson == 0) ? fMesonPDGCode = 111 : fMesonPDGCode = 221; } void SetOtherMesons(std::vector<int> vec) { fOtherMesonsPDGCodes = vec; } void SetEventCutList(Int_t nCuts, TList* CutArray) { fnCuts = nCuts; fEventCutArray = CutArray; } // Setting the cut lists for the conversion photons void SetConversionCutList(Int_t nCuts, TList* CutArray) { fnCuts = nCuts; fConvCutArray = CutArray; } // Setting the cut lists for the calo photons void SetCaloCutList(Int_t nCuts, TList* CutArray) { fnCuts = nCuts; fClusterCutArray = CutArray; } // Setting the cut lists for the meson void SetMesonCutList(Int_t nCuts, TList* CutArray) { fnCuts = nCuts; fMesonCutArray = CutArray; } protected: //------------------------------- // GLobal settings //------------------------------- AliV0ReaderV1* fV0Reader; // basic photon Selection Task TString fV0ReaderName; // name of V0Reader TClonesArray* fReaderGammas; // Array with conversion photons selected by V0Reader Cut TString fCaloTriggerHelperName; // name of trigger helper for PHOS TString fCorrTaskSetting; // Correction Task Special Name AliVEvent* fInputEvent; // current event AliMCEvent* fMCEvent; // corresponding MC event TClonesArray* fAODMCTrackArray; // pointer to track array //------------------------------- // Lists for cut folders and output containers //------------------------------- TList** fCutFolder; // Top level cut folder in which all folders belonging to this cut are stored TList** fESDList; // List for standard histograms for data+MC (Inv mass vs pt etc.) TList** fMCList; // List for MC generated histograms TList** fTrueList; // List for true meson quantities TList** fJetList; // List for jet related observables TList** fTrueJetList; // List of true jet quantities (response matrix) TList* fOutputContainer; // Top level output container TList* fEventCutArray; // Event cut output container TList* fConvCutArray; // Conversion cut output container TList* fClusterCutArray; // Cluster cut output container TList* fMesonCutArray; // Meson cut output container std::vector<AliAODConversionPhoton*> fGammaCandidates; //! current list of photon candidates std::vector<AliAODConversionPhoton*> fClusterCandidates; //! current list of cluster candidates EventMixPoolMesonJets* fEventMix; // Eventmixing class used for events with a jet axis (also works with no jet axis but has no z-vertex bins etc.) TRandom3 fRandom; //! random generator needed for the rotation background TGenPhaseSpace fGenPhaseSpace; //! For generation of decays into two gammas //------------------------------- // Jet related variables //------------------------------- AliAnalysisTaskConvJet* fConvJetReader; // JetReader TVector3 fHighestJetVector; // vector px,py,pz of jet with highest momentum in the event. Needed for jet event mixing float fMaxPtJet; // pt of jet with highest pt in the event. Needed for jet ecvent mixing AliAnalysisTaskJetOutlierRemoval* fOutlierJetReader; // Jet outlier Reader //------------------------------- // global settings and variables //------------------------------- int fMesonPDGCode; // PDG code of current meson (111 for pi0 etc.) std::vector<int> fOtherMesonsPDGCodes; // PDG code of other mesons (eta code if we are looking for a pi0) int fiCut; // index of the current cut int fIsMC; // flag for data or MC (JJ MC > 1) int fnCuts; // number of cuts double fWeightJetJetMC; //! weights if jet-jet MC is used int fDoLightOutput; // flag if light output should be used int fDoMesonQA; // flag if meson QA should be switched on int fDoPhotonQA; // flag if photon QA should be switched on int fDoClusterQA; // flag if cluster QA should be switched on int fDoJetQA; // flag if Jet QA should be switched on int fIsHeavyIon; // lag for heavy ion bool fIsCalo; // flag if current analysis is calo only bool fIsConv; // flag if current analysis is using conversions only bool fIsConvCalo; // flag if current analysis is bool fIsFromDesiredHeader; // flag if particle is from desired header bool fDoMaterialBudgetWeightingOfGammasForTrueMesons; // flag if material budget weights should be applied double fEventPlaneAngle; // event plane angle int fTrackMatcherRunningMode; // track matcher mode bool fUseThNForResponse; // flag if THnSparse or TH2 should be used for the 4d response matrices bool fEnableSortForClusMC; // flag if cluster mc labels should be sorted //------------------------------- // conversions //------------------------------- Int_t* fMCEventPos; //! Int_t* fMCEventNeg; //! Int_t* fESDArrayPos; //! Int_t* fESDArrayNeg; //! //------------------------------- // binning settings //------------------------------- std::vector<double> fVecBinsMesonInvMass; //! meson inv. mass binning std::vector<double> fVecBinsPhotonPt; //! photon/cluster pt binning std::vector<double> fVecBinsClusterPt; //! cluster binning until high pT std::vector<double> fVecBinsMesonPt; //! meson pt binning std::vector<double> fVecBinsJetPt; //! jet pt binning std::vector<double> fVecBinsFragment; //! z (fragmentation function) binning std::vector<double> vecEquidistFromMinus05; //! aequdistant binning starting from -0.5 //------------------------------- // Jet related vectors //------------------------------- vector<double> fVectorJetPt; //! Vector of JetPt vector<double> fVectorJetPx; //! Vector of JetPx vector<double> fVectorJetPy; //! Vector of JetPy vector<double> fVectorJetPz; //! Vector of JetPz vector<double> fVectorJetEta; //! Vector of JetEta vector<double> fVectorJetPhi; //! Vector of JetPhi vector<double> fVectorJetArea; //! Vector of JetArea vector<double> fTrueVectorJetPt; //! Vector of True JetPt vector<double> fTrueVectorJetPx; //! Vector of True JetPx vector<double> fTrueVectorJetPy; //! Vector of True JetPy vector<double> fTrueVectorJetPz; //! Vector of True JetPz vector<double> fTrueVectorJetEta; //! Vector of True JetEta vector<double> fTrueVectorJetPhi; //! Vector of True JetPhi vector<int> fTrueVectorJetPartonID; //! Vector of parton id matched to true jet vector<double> fTrueVectorJetPartonPt; //! Vector of parton pt matched to true jet vector<double> fVectorJetEtaPerp; //! vector of jet -eta (opposite eta to original jet) vector<double> fVectorJetPhiPerp; //! vector of jet phi + 90 degree (perpendicular to original jet) std::map<int, int> MapRecJetsTrueJets; //! Map containing the reconstructed jet index in vector and mapping it to true Jet index //------------------------------- // Response Matrix handlers //------------------------------- std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonPt; //! Response matrix for true vs. rec pt for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerFrag; //! Response matrix for meson z_rec vs z_true for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerFragTrueJets; //! Response matrix for meson z_rec_trueJets (true jet pt taken) vs z_true for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonInvMass; //! Response matrix for meson inv. mass and meson pt for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonInvMassVsZ; //! Response matrix for meson inv. mass and meson z for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonBackInvMassVsZ; //! Response matrix for meson inv. mass and meson z for background candidates (mixed evt/rotation) for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonBackInvMassVsPt; //! Response matrix for meson inv. mass and meson pT for background candidates (mixed evt/rotation) for each jet pt true vs. rec. bin std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonInvMassPerpCone; //! Same as fRespMatrixHandlerMesonInvMass but in perpendicular cone std::vector<MatrixHandler4D*> fRespMatrixHandlerMesonInvMassVsZPerpCone; //! Same as fRespMatrixHandlerMesonInvMassVsZ but in perpendicular cone //------------------------------- // basic histograms //------------------------------- std::vector<TH1F*> fHistoNEvents; //! vector of histos with event information std::vector<TH1F*> fHistoNEventsWOWeight; //! vector of histos with event information without event weights in case of JJ MC std::vector<TH1F*> fHistoNGoodESDTracks; //! vector of histos for number of tracks std::vector<TH1F*> fHistoNGoodESDTracksEvtWithJets; //! vector of histos for number of tracks in events with jets std::vector<TH1F*> fHistoVertexZ; //! vector of histos for number of events without weights //------------------------------- // Jet-Jet MC related //------------------------------- std::vector<TProfile*> fProfileJetJetXSection; //! vector of profiles for Jet-Jet x-section std::vector<TH1F*> fHistoJetJetNTrials; //! vector of histos for Jet-Jet n-trials std::vector<TH2F*> fHistoPtHardJJWeight; //! vector of histos for Jet-Jet weight //------------------------------- // cluster related histograms //------------------------------- std::vector<TH1F*> fHistoClusterPt; //! vector of histos with number of clusters as function of pt std::vector<TH1F*> fHistoClusterE; //! vector of histos with number of clusters as function of E std::vector<TH1F*> fHistoClusterPtInJet; //! vector of histos with number of clusters as function of pt inside of jets std::vector<TH1F*> fHistoClusterEInJet; //! vector of histos with number of clusters as function of E inside of jets // perpendicular cone std::vector<TH1F*> fHistoClusterPtPerpCone; //! vector of histos with number of clusters as function of pt in perpendicular cone //------------------------------- // conversion photon histograms //------------------------------- std::vector<TH1F*> fHistoConvGammaPt; //! vector of histos conversion photons vs. pt std::vector<TH1F*> fHistoConvGammaPtInJet; //! vector of histos conversion photons vs. pt inside of jet // perpendicular cone std::vector<TH1F*> fHistoConvGammaPtPerpCone; //! vector of histos conversion photons vs. pt in perpendicular cone //------------------------------- // Inv. Mass histograms //------------------------------- std::vector<TH2F*> fHistoInvMassVsPt; //! vector of histos with inv. mass vs pt std::vector<TH2F*> fHistoInvMassVsPt_Incl; //! vector of histos with inv. mass vs pt for all mesons (no in-jet criterium) std::vector<TH2F*> fHistoJetPtVsFrag; //! vector of histos for jet pt vs meson-z std::vector<TH2F*> fHistoJetPtVsFrag_SB; //! vector of histos for jet pt vs meson-z in the sideband region std::vector<TH2F*> fHistoInvMassVsPtMassCut; //! vector of histos with inv. mass vs. pT after cut std::vector<TH2F*> fHistoInvMassVsPtMassCutSB; //! vector of histos with inv. mass vs. pT after cut in Sideband std::vector<TH2F*> fHistoInvMassVsPtBack; //! vector of histos with inv. mass vs pt for background distribution std::vector<TH2F*> fHistoInvMassVsPtPerpCone; //! same as fHistoInvMassVsPt but in perpendicular cone std::vector<TH2F*> fHistoJetPtVsFragPerpCone; //! same as fHistoJetPtVsFrag but in perp cone std::vector<TH2F*> fHistoJetPtVsFragPerpCone_SB; //! same as fHistoJetPtVsFrag_SB but in perp cone //------------------------------- // Jet related histograms //------------------------------- std::vector<TH1F*> fHistoEventwJets; //! vector of histos for events with jets std::vector<TH1F*> fHistoNJets; //! vector of histos with number of jets per event std::vector<TH1F*> fHistoPtJet; //! vector of histos with pt of jets std::vector<TH1F*> fHistoJetEta; //! vector of histos with eta of jets std::vector<TH1F*> fHistoJetPhi; //! vector of histos with phi of jets std::vector<TH1F*> fHistoJetArea; //! vector of histos with jet area std::vector<TH2F*> fHistoTruevsRecJetPt; //! vector of histos response matrix for jets std::vector<TH2F*> fHistoTruevsRecJetPtForTrueJets; //! vector of histos response matrix for true jets std::vector<TH2F*> fHistoTrueJetPtVsPartonPt; //! vector of histos true jet pt vs. parton pt std::vector<TH1F*> fHistoMatchedPtJet; //! vector of histos with pt of jets for jets that got matched with a true jet std::vector<TH1F*> fHistoUnMatchedPtJet; //! vector of histos with pt of jets for jets that did not get matched with a true jet std::vector<TH1F*> fHistoTruePtJet; //! vector of histos with pt of true jets std::vector<TH1F*> fHistoTrueMatchedPtJet; //! vector of histos with pt of true jets that are matched to a rec jet std::vector<TH1F*> fHistoTrueUnMatchedPtJet; //! vector of histos with pt of jets that are not matched to a rec jet //------------------------------- // True meson histograms //------------------------------- std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueMesonInvMassVsPt; //! vector of histos inv. mass vs. pT for true mesons std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueMesonInvMassVsZ; //! vector of histos inv. mass vs. Z for true mesons std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueOtherMesonInvMassVsPt; //! vector of histos inv. mass vs. pT for true other mesons (if selected meson is pi0, other mesons are etas and eta prime etc.) std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueOtherMesonInvMassVsZ; //! vector of histos inv. mass vs. Z for true other mesons (if selected meson is pi0, other mesons are etas and eta prime etc.) std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueSecondaryMesonInvMassVsPt; //! vector of histos inv. mass vs. pT for true secondary mesons std::vector<MatrixHandler4D*> fRespMatrixHandlerTrueSecondaryMesonInvMassVsZ; //! vector of histos inv. mass vs. pT for true secondary mesons std::vector<TH2F*> fHistoTrueMesonInvMassVsTruePt; //! vector of histos inv. mass vs. true pT for true mesons std::vector<TH2F*> fHistoTruePrimaryMesonInvMassPt; //! vector of histos inv. mass vs. pT for true primary mesons std::vector<TH2F*> fHistoTrueSecondaryMesonInvMassPt; //! vector of histos inv. mass vs. pT for true secondary mesons std::vector<TH2F*> fHistoTrueMesonJetPtVsTruePt; //! vector of histos true meson pt vs true jet pt std::vector<TH2F*> fHistoTrueMesonJetPtVsTrueZ; //! vector of histos true meson z vs true jet pt std::vector<TH2F*> fHistoTrueMesonInTrueJet_JetPtVsTruePt; //! vector of histos true meson pt vs true jet pt inside true jets std::vector<TH2F*> fHistoTrueMesonInTrueJet_JetPtVsTrueZ; //! vector of histos true meson z vs true jet pt inside true jets std::vector<TH2F*> fHistoMesonResponse; //! vector of histos with meson response matrix //------------------------------- // True conversion photon histograms //------------------------------- std::vector<TH1F*> fHistoTrueConvGammaPt; //! vector of histos true conversion pt std::vector<TH1F*> fHistoTruePrimaryConvGammaPt; //! vector of histos true primary conversion pt std::vector<TH2F*> fHistoTruePrimaryConvGammaESDPtMCPt; //! vector of histos true vs. rec. for conversions //------------------------------- // True cluster histograms //------------------------------- std::vector<TH1F*> fHistoTrueClusGammaPt; //! vector of histos true EM clusters //------------------------------- // mc generated histograms //------------------------------- std::vector<TH1F*> fHistoMCGammaPtNotTriggered; //! vector of histos with photons in events which are not triggered vs pT std::vector<TH1F*> fHistoMCGammaPtNoVertex; //! vector of histos with photons in events which have no vertex vs pT std::vector<TH1F*> fHistoMCAllGammaPt; //! vector of histos with all photons vs pT std::vector<TH1F*> fHistoMCDecayGammaPi0Pt; //! vector of histos gammas pt from pi0s std::vector<TH1F*> fHistoMCDecayGammaRhoPt; //! vector of histos gammas pt from rho std::vector<TH1F*> fHistoMCDecayGammaEtaPt; //! vector of histos gammas pt from eta std::vector<TH1F*> fHistoMCDecayGammaOmegaPt; //! vector of histos gammas pt from omega std::vector<TH1F*> fHistoMCDecayGammaEtapPt; //! vector of histos gammas pt from eta prime std::vector<TH1F*> fHistoMCDecayGammaPhiPt; //! vector of histos gammas pt from phi std::vector<TH1F*> fHistoMCDecayGammaSigmaPt; //! vector of histos gammas pt from sigma std::vector<TH2F*> fHistoMCPrimaryPtvsSource; //! vector of histos primary gammas for different particles std::vector<TH1F*> fHistoMCMesonPtNotTriggered; //! vector of histos mesons which are in events that are not triggered std::vector<TH1F*> fHistoMCMesonPtNoVertex; //! vector of histos mesons which are in events that have no vertex std::vector<TH1F*> fHistoMCMesonPt; //! vector of histos meson pt std::vector<TH1F*> fHistoMCMesonWOEvtWeightPt; //! vector of histos meson pt without event weights std::vector<TH1F*> fHistoMCMesonInAccPt; //! vector of histos mesons in acceptance std::vector<TH1F*> fHistoMCMesonInAccPtNotTriggered; //! vector of histos mesons in acceptance which are in events that are not triggered std::vector<TH1F*> fHistoMCMesonWOWeightInAccPt; //! vector of histos mesons in acceptance without event weight std::vector<TH1F*> fHistoMCMesonWOEvtWeightInAccPt; //! vector of histos mesons in acceptance without event weight std::vector<TH2F*> fHistoMCSecMesonPtvsSource; //! vector of histos secondary mesons from different sources vs. pt std::vector<TH1F*> fHistoMCSecMesonSource; //! vector of histos secondary mesons from different sources std::vector<TH2F*> fHistoMCSecMesonInAccPtvsSource; //! vector of histos accepted secondary mesons from different sources vs. pt //------------------------------- // mc generated histograms jet-meson corr //------------------------------- std::vector<TH2F*> fHistoMCJetPtVsMesonPt; //! vector of histos True Jet pT vs. true Meson Pt (mc particle based distribution) std::vector<TH2F*> fHistoMCJetPtVsMesonPtInAcc; //! vector of histos True Jet pT vs. true Meson Pt (for mesons in detector acceptance) std::vector<TH2F*> fHistoMCJetPtVsFrag; //! vector of histos True Jet pT vs. true Frag (mc particle based distribution) std::vector<TH2F*> fHistoMCJetPtVsFragInAcc; //! vector of histos True Jet pT vs. true Frag (for mesons in detector acceptance) std::vector<TH2F*> fHistoMCJetPtVsFrag_Sec; //! vector of histos True Jet pT vs. true Frag (mc particle based distribution for secondaries) std::vector<TH2F*> fHistoMCJetPtVsMesonPt_Sec; //! vector of histos True Jet pT vs. true meson pt (mc particle based distribution for secondaries) std::vector<TH2F*> fHistoMCPartonPtVsFrag; //! vector of histos True parton pT vs. true Frag (mc particle based distribution) std::vector<TH2F*> fHistoMCJetPtVsFragTrueParton; //! vector of histos True Jet pT vs. true Frag (mc particle based distribution) for particles originating from hard parton from Jet std::vector<TH2F*> fHistoMCPartonPtVsFragTrueParton; //! vector of histos True parton pT vs. true Frag (mc particle based distribution) for particles originating from hard parton from Jet private: AliAnalysisTaskMesonJetCorrelation(const AliAnalysisTaskMesonJetCorrelation&); // Prevent copy-construction AliAnalysisTaskMesonJetCorrelation& operator=(const AliAnalysisTaskMesonJetCorrelation&); // Prevent assignment ClassDef(AliAnalysisTaskMesonJetCorrelation, 8); }; #endif
[ "joshua.konig@cern.ch" ]
joshua.konig@cern.ch
9967b319012bd4fd9620fefae81470c12438c98d
214dbcc732e0f6a49336164c793bd4af4754a6f7
/Algorithmics/Problems from various contests/bete1.cpp
b9dca226d2baa24aaf8a50dc70289d9637bc03c7
[]
no_license
IrinaMBejan/Personal-work-contests
f878c25507a8bfdab3f7af8d55b780d7632efecb
4ab2841244a55d074d25e721aefa56431e508c43
refs/heads/master
2021-01-20T08:24:47.492233
2017-05-03T12:22:26
2017-05-03T12:22:26
90,142,452
1
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
#include <fstream> using namespace std; ifstream fin("bete1.in"); ofstream fout("bete1.out"); int n,l,k,a,b,i,j,s,ma,mb,na,nb; int main() { fin>>n; fin>>a; ma=a;na=1;s=a; for(i=2;i<=n;i++) { fin>>a; if(ma<a){ma=a;na=1;} else if(ma==a)na++; s+=a; } fin>>b; mb=b;nb=1;s+=b; for(i=2;i<=n;i++) { fin>>b; if(mb<b){mb=b;nb=1;} else if(mb==b)nb++; s+=b; } l=s/n; fout<<l<<'\n'<<ma+mb<<'\n'<<min(na,nb)<<'\n'; fout.close(); return 0; }
[ "irinam.bejan@gmail.com" ]
irinam.bejan@gmail.com
8b0957cf5cd6adfbe73484bfd933ce224776d9dc
ce666f2d46e07fe15f77fa4ba00635f527f731c9
/MajnkraftLikeGame/source/Graphic/Vertex.cpp
8c76c0df86d5621f7a41ae0f4905c48207bd102a
[]
no_license
ProjektHra-FRI/MajnKraft
7a21f227366143fbc9866fa5fc29f156d1323e28
27eee57fd1064c8211fd182100955f1bb57174c7
refs/heads/master
2021-01-15T14:17:56.325722
2015-07-20T09:28:00
2015-07-20T09:28:00
25,922,017
0
3
null
2015-07-20T09:28:00
2014-10-29T13:25:33
C++
UTF-8
C++
false
false
2,088
cpp
/* * File: Vertex.cpp * Author: Lukas * * Created on Streda, 2015, júl 15, 22:23 */ #include <glm/detail/type_vec.hpp> #include "Vertex.h" Vertex::Vertex() { } Vertex::Vertex(glm::vec3 position) : position(position) { } Vertex::Vertex(glm::vec3 position, glm::vec2 texturePosition) : position(position), texturePosition(texturePosition) { } Vertex::Vertex(glm::vec3 position, glm::vec3 normal) : position(position), normal(normal) { } Vertex::Vertex(glm::vec3 position, glm::vec2 texturePosition, glm::vec3 normal) : position(position), texturePosition(texturePosition), normal(normal) { } //----------------------------------------------------------------------------------- Vertex::Vertex(float posX, float posY, float posZ) : position(glm::vec3(posX,posY,posZ)){ } Vertex::Vertex(float posX, float posY, float posZ, float textureX, float textureY) : position(glm::vec3(posX,posY,posZ)), texturePosition(glm::vec2(textureX,textureY)) { } Vertex::Vertex(float posX, float posY, float posZ, float normalX, float normalY, float normalZ) : position(glm::vec3(posX,posY,posZ)), normal(glm::vec3(normalX,normalY,normalZ)) { } Vertex::Vertex(float posX, float posY, float posZ, float textureX, float textureY, float normalX, float normalY, float normalZ) : position(glm::vec3(posX,posY,posZ)), texturePosition(glm::vec2(textureX,textureY)), normal(glm::vec3(normalX,normalY,normalZ)) { } //----------------------------------------------------------------------------------- glm::vec3 Vertex::GetPosition() const { return position; } glm::vec2 Vertex::GetTexturePosition() const { return texturePosition; } glm::vec3 Vertex::GetNormal() const { return normal; } void Vertex::SetNormal(glm::vec3 normal) { this->normal = normal; } void Vertex::SetPosition(glm::vec3 position) { this->position = position; } void Vertex::SetTexturePosition(glm::vec2 texturePosition) { this->texturePosition = texturePosition; } Vertex::~Vertex() { }
[ "lukiluk5000@windowslive.com" ]
lukiluk5000@windowslive.com
ec8cc8c2fa1958b9fa94f2da32c9f7aa54d94cd6
bdd6458bc1dfb60fdd9b4bfd4afeec20e740794b
/OOP Week 2/Polynomial/Polynomial.cpp
326e174ec8de242d133dd2f5be9d01ae3099a15d
[]
no_license
NearHuscarl/C-Exercise
876954746ab9a3fdd9c198d1188ef28829e109cc
e95bfaae8da3933d0adb895917eefd4d5bee1044
refs/heads/master
2021-01-17T14:05:33.070837
2017-05-31T13:15:30
2017-05-31T13:15:30
83,463,305
3
1
null
2017-03-17T13:10:33
2017-02-28T17:59:10
C++
UTF-8
C++
false
false
3,125
cpp
#include <iostream> #include "Monomial.h" #include "Polynomial.h" using namespace std; Polynomial::Polynomial(int m): mMaxIndex(m), mpMonomial(nullptr) { } Polynomial::Polynomial(const Polynomial &x) { mMaxIndex = x.mMaxIndex; mpMonomial = new Monomial[mMaxIndex]; for(int i = 0; i < x.mMaxIndex; i++) { mpMonomial[i].SetMonomial(x.mpMonomial[i].GetCoefficient(), i); } } Polynomial::~Polynomial() { delete [] mpMonomial; } Polynomial& Polynomial::operator=(const Polynomial &x) { mMaxIndex = x.mMaxIndex; delete [] mpMonomial; mpMonomial = new Monomial[mMaxIndex]; for(int i = 0; i < mMaxIndex; i++) { mpMonomial[i].SetMonomial(x.mpMonomial[i].GetCoefficient(), i); } return *this; } void Polynomial::Input(void) { cout << "Enter the maximum index: "; cin >> mMaxIndex; mpMonomial = new Monomial[mMaxIndex]; for(int i = 0; i < mMaxIndex; i++) { int k; cout << "Coefficient Input: "; cin >> k; mpMonomial[i].SetCoefficient(k); mpMonomial[i].SetIndex(i); } } void Polynomial::Output(void) { mpMonomial[0].Output(); for(int i = 1; i < mMaxIndex; i++) { cout << " + "; mpMonomial[i].Output(); } cout << endl; } Polynomial Polynomial::Inverse(void) { Polynomial pInvert; pInvert.mMaxIndex = mMaxIndex; pInvert.mpMonomial = new Monomial[pInvert.mMaxIndex]; for(int i = 0; i < mMaxIndex; i++) { int coInvert = mpMonomial[i].GetCoefficient() * (-1); pInvert.mpMonomial[i].SetMonomial(coInvert, i); } return pInvert; } Polynomial Polynomial::Add(Polynomial &x) { int flag = 0; int bigIndex; int smallIndex; if(mMaxIndex > x.mMaxIndex) { bigIndex = mMaxIndex; smallIndex = x.mMaxIndex; flag = 1; } else { bigIndex = x.mMaxIndex; smallIndex = mMaxIndex; } Polynomial sum; sum.mMaxIndex = bigIndex; sum.mpMonomial = new Monomial[bigIndex]; for(int i = 0; i < smallIndex; i++) { int coSum = x.mpMonomial[i].GetCoefficient() + mpMonomial[i].GetCoefficient(); sum.mpMonomial[i].SetMonomial(coSum, i); } for(int i = smallIndex; i < bigIndex; i++) { if(flag) { int coSum = mpMonomial[i].GetCoefficient(); sum.mpMonomial[i].SetMonomial(coSum, i); } else { int coSum = x.mpMonomial[i].GetCoefficient(); sum.mpMonomial[i].SetMonomial(coSum, i); } } return sum; } Polynomial Polynomial::Subtract(Polynomial &x) { Polynomial diff = (*this).Add(x.Inverse()); return diff; } Polynomial Polynomial::Multiply(Polynomial &x) { Polynomial product; product.mMaxIndex = mMaxIndex * x.mMaxIndex; product.mpMonomial = new Monomial[product.mMaxIndex]; for(int i = 0; i < product.mMaxIndex; i++) { product.mpMonomial[i].SetMonomial(0, i); } for(int i = 0; i < mMaxIndex; i++) { for(int j = 0; j < x.mMaxIndex; j++) { product.mpMonomial[i+j] = product.mpMonomial[i+j].Add(mpMonomial[i].Multiply(x.mpMonomial[j])); } } return product; }
[ "16520846@gm.uit.edu.vn" ]
16520846@gm.uit.edu.vn
eacabdbc1a16f2de9c87c2554fee5e1c9053ee28
47ea71af72277f587908e26ad202eac5761aa166
/Game/Player.h
b356f33c2d0d030036bb5fdd04018a6d3844da87
[]
no_license
Polarist05/Game
1de51a3b4cee77ed19fbd0bd6c308d67694701e1
11b1fa4760e9b5e51b116c5c5ee33e0892372156
refs/heads/9/1/64
2023-07-20T07:49:48.623818
2021-08-31T20:30:12
2021-08-31T20:30:12
394,599,921
0
0
null
2023-08-20T06:36:47
2021-08-10T09:42:28
C++
UTF-8
C++
false
false
435
h
#pragma once #include "SFML.h" #include "GameBaseClass.h" #include "WorldControl.h" class Player:public GameBaseClass { public: RectangleShape& Sprite(); void Start() override { Sprite().setSize(Vector2f(50,50)); Sprite().setOrigin(Sprite().getSize().x/2, Sprite().getSize().y/2); Sprite().setFillColor(Color::Green); Sprite().setPosition(-460,0); } void Update() override { WorldControl::window().draw(Sprite()); } };
[ "princeofpirate1@gmail.com" ]
princeofpirate1@gmail.com
e715e32a400b25a09df9062f001a1443e9fdbbcf
09fc85cd58c0ed10e8ad780a5b19e3c0fcde667d
/test/mocks/thread/scoped_lock_test.cpp
4d02fd0435b522fd4f2193d8c0e821671e41c1ab
[ "MIT" ]
permissive
Watch-Later/centurion
40edb7c359c7bb1f4f8f7f819180166a2e033923
cc71543b6a07b4fb1f9cb24e1f39ac852bc66a3b
refs/heads/main
2023-06-04T07:45:48.814126
2021-05-26T09:47:15
2021-05-26T09:47:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
484
cpp
#include "thread/scoped_lock.hpp" #include <gtest/gtest.h> #include "core_mocks.hpp" #include "thread_mocks.hpp" class ScopedLockTest : public testing::Test { public: void SetUp() override { mocks::reset_core(); mocks::reset_thread(); } }; TEST_F(ScopedLockTest, ConstructorFailsToLockMutex) { cen::mutex mutex{0}; // Dummy parameter for mock-friendly constructor SDL_LockMutex_fake.return_val = -1; ASSERT_THROW(cen::scoped_lock{mutex}, cen::sdl_error); }
[ "albinoscar99@hotmail.com" ]
albinoscar99@hotmail.com
7720359104484955da9656c558fef315ca28f77b
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/AssociatedCacheMemory/UNIX_AssociatedCacheMemory_SOLARIS.hxx
5d6773af86f2d8adaf8930949c094cde59705cc8
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
140
hxx
#ifdef PEGASUS_OS_SOLARIS #ifndef __UNIX_ASSOCIATEDCACHEMEMORY_PRIVATE_H #define __UNIX_ASSOCIATEDCACHEMEMORY_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
f36cac28295e10384b710c22eafb9b1a6b2e1841
2b45998c5472e30ea7058603bca3a77700b86b70
/구글코드잼/codejamB.cpp
21372863e665f440cb5fce8a1b22c1c5aa3b7589
[]
no_license
forybm/CodeMountain
c6b5e404bc5947f2a41df76331bb1ba078dcbe41
7a3c8bc76db7f57ad68638f800513d0ea0a7c5a2
refs/heads/master
2021-06-21T15:05:30.653346
2017-07-27T06:03:55
2017-07-27T06:03:55
98,499,311
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
#include <stdio.h> void func(int a) { char pancake[111]; for(int i = 0 ; i < 111; i++) pancake[i]=0; for(int k = 1 ; k <= a ; k++){ int count =0; scanf("%s",pancake); for(int i=0;;i++) { if(pancake[i+1] == 0 ){ if(pancake[i] == '-') count++; break;} if(pancake[i]!=pancake[i+1]) count++; } printf("Case #%d: %d\n",k,count);} } int main() { int testcase; scanf("%d",&testcase); while(testcase--) func(testcase); }
[ "forybm1@naver.com" ]
forybm1@naver.com
9e829babef0288f76818561e55933fb22cc7e5e6
492976adfdf031252c85de91a185bfd625738a0c
/lib/hkStubs/Havok/Physics/Constraint/Atom/hkpConstraintAtom.h
a97ac13725ccec25c7c27327b75b62ca214113a0
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
2,341
h
#pragma once #include <Havok/Common/Base/hkBase.h> struct hkpConstraintAtom { public: enum AtomType { TYPE_INVALID = 0, TYPE_BRIDGE, // 1 TYPE_SET_LOCAL_TRANSFORMS, // 2 TYPE_SET_LOCAL_TRANSLATIONS, // 3 TYPE_SET_LOCAL_ROTATIONS, // 4 TYPE_BALL_SOCKET, // 5 TYPE_STIFF_SPRING, // 6 TYPE_LIN, // 7 TYPE_LIN_SOFT, // 8 TYPE_LIN_LIMIT, // 9 TYPE_LIN_FRICTION, // 10 TYPE_LIN_MOTOR, // 11 TYPE_2D_ANG, // 12 TYPE_ANG, // 13 TYPE_ANG_LIMIT, // 14 TYPE_TWIST_LIMIT, // 15 TYPE_CONE_LIMIT, // 16 TYPE_ANG_FRICTION, // 17 TYPE_ANG_MOTOR, // 18 TYPE_RAGDOLL_MOTOR, // 19 TYPE_PULLEY, // 20 TYPE_RACK_AND_PINION, // 21 TYPE_COG_WHEEL, // 22 TYPE_SETUP_STABILIZATION, // 23 TYPE_3D_ANG, // 24 TYPE_DEFORMABLE_3D_LIN, // 25 TYPE_DEFORMABLE_3D_ANG, // 26 TYPE_OVERWRITE_PIVOT, TYPE_WHEEL_FRICTION, // 28 TYPE_CONTACT, FIRST_MODIFIER_TYPE, TYPE_MODIFIER_SOFT_CONTACT = FIRST_MODIFIER_TYPE, TYPE_MODIFIER_MASS_CHANGER, TYPE_MODIFIER_VISCOUS_SURFACE, TYPE_MODIFIER_MOVING_SURFACE, TYPE_MODIFIER_IGNORE_CONSTRAINT, TYPE_MODIFIER_CENTER_OF_MASS_CHANGER, LAST_MODIFIER_TYPE = TYPE_MODIFIER_CENTER_OF_MASS_CHANGER, TYPE_MAX }; enum CallbackRequest { CALLBACK_REQUEST_NONE = 0, CALLBACK_REQUEST_NEW_CONTACT_POINT = 1, CALLBACK_REQUEST_SETUP_PPU_ONLY = 2, CALLBACK_REQUEST_SETUP_CALLBACK = 4, CALLBACK_REQUEST_CONTACT_POINT_CALLBACK = 8 }; enum SolvingMethod { METHOD_STABILIZED = 0, METHOD_OLD = 1, }; HK_DECLARE_CLASS_ALLOCATOR(hkpConstraintAtom) HK_DECLARE_REFLECTION() hkpConstraintAtom() = delete; explicit hkpConstraintAtom(hkFinishLoadedObjectFlag f) {} HK_FORCE_INLINE AtomType getType() const { return m_type; } HK_FORCE_INLINE int isModifierType() const { return m_type >= FIRST_MODIFIER_TYPE; } protected: hkpConstraintAtom(AtomType type) : m_type(type) {} public: hkEnum<AtomType, hkUint16> m_type; };
[ "leo@leolam.fr" ]
leo@leolam.fr
c1a2273c0168ffbe9a39896baab045dab7b795b4
26f9034e57216b3ad4b09ffcd831025fe1d78ea9
/code/SimpleFactory/Factory.cpp
e0864736a7ca18cd88e01ee13372664f6c1dba9f
[]
no_license
jasonblog/design_patterns
217e3f9a987abb6c7ed604d33f50143782f140c3
35bf13d6382d6040244c91bf21f70fb0e08344a1
refs/heads/master
2020-05-19T03:27:10.446568
2015-09-06T04:38:15
2015-09-06T04:38:15
41,972,269
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
/////////////////////////////////////////////////////////// // Factory.cpp // Implementation of the Class Factory // Created on: 01-十月-2014 18:41:33 // Original author: colin /////////////////////////////////////////////////////////// #include "Factory.h" #include "ConcreteProductA.h" #include "ConcreteProductB.h" Factory::Factory() { } Factory::~Factory() { } Product* Factory::createProduct(string proname) { if ("A" == proname) { return new ConcreteProductA(); } else if ("B" == proname) { return new ConcreteProductB(); } return NULL; }
[ "gigigigi" ]
gigigigi
ce948225c1717edbfbf09346dd49bab0b41d9a64
13d7ed402bcf152b922095c2433824ed0188f387
/src/flock_simulation/boid.hpp
f88f79012d3771e69ae199111ec3e306d7562cb2
[ "MIT" ]
permissive
wangtaoyijiu/flockingbird
550260a81ddbc2bdc11626d667b8be153017bede
eed3e7cead4a37635625d1055fb0a830e6152d1b
refs/heads/master
2023-05-31T20:04:05.519880
2021-06-03T09:00:21
2021-06-03T09:00:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
553
hpp
#pragma once #include "../utility/vector_operations.hpp" #include <ostream> namespace flockingbird { class Boid { public: Boid(Vector2D positionIn, Vector2D velocity) : position(positionIn) , velocity(velocity) {} Vector2D position; Vector2D velocity; friend std::ostream& operator<<(std::ostream& outputStream, const Boid& p); }; inline std::ostream& operator<<(std::ostream& outputStream, const Boid& p) { outputStream << "(pos" << p.position << ") (dir: " << p.velocity << ")"; return outputStream; } }
[ "falcowinkler@icloud.com" ]
falcowinkler@icloud.com
d946c89bbe660e4a1b6e674902ba558b6c7004b3
e35dd506083ad5119d035f517f8487bd0d0090bb
/OBOZY/2010 - Październik/kkdigits.cpp
ce0e0a61652d84c2a11604f72e8016b606c22dd5
[]
no_license
Neverous/xivlo08-11
95088ded4aa7aeebc28da7c22b255446e4a43bda
7daa4f5125aece228fc2f067a455e24ff20eb3f4
refs/heads/master
2016-08-12T15:59:21.258466
2016-03-22T14:41:25
2016-03-22T14:41:25
54,478,420
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
cpp
/* 2010 * Maciej Szeptuch * XIV LO Wrocław */ #include<cstdio> //#define DEBUG(args...) fprintf(stderr, args) #define DEBUG(args...) int number; char numbers[10][5][3] = { { {'x', 'x', 'x'}, {'x', ' ', 'x'}, {'x', ' ', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, }, // 0 { {' ', ' ', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, }, // 1 { {'x', 'x', 'x'}, {' ', ' ', 'x'}, {'x', 'x', 'x'}, {'x', ' ', ' '}, {'x', 'x', 'x'}, }, // 2 { {'x', 'x', 'x'}, {' ', ' ', 'x'}, {'x', 'x', 'x'}, {' ', ' ', 'x'}, {'x', 'x', 'x'}, }, // 3 { {'x', ' ', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, }, // 4 { {'x', 'x', 'x'}, {'x', ' ', ' '}, {'x', 'x', 'x'}, {' ', ' ', 'x'}, {'x', 'x', 'x'}, }, // 5 { {'x', 'x', 'x'}, {'x', ' ', ' '}, {'x', 'x', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, }, // 6 { {'x', 'x', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, {' ', ' ', 'x'}, }, // 7 { {'x', 'x', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, }, // 8 { {'x', 'x', 'x'}, {'x', ' ', 'x'}, {'x', 'x', 'x'}, {' ', ' ', 'x'}, {'x', 'x', 'x'}, }, // 9 }; inline static void printXNumber(int num); int main(void) { while(scanf("%d", &number) != -1 && number != -1) printXNumber(number); return 0; } inline static void printXNumber(int num) { for(int i = 0; i < 5; ++ i) { for(int n = 0; n < 3; ++ n) putchar(numbers[num / 10][i][n]); putchar(' '); for(int n = 0; n < 3; ++ n) putchar(numbers[num % 10][i][n]); putchar('\n'); } return; }
[ "neverous@neverous.info" ]
neverous@neverous.info
6ea16724e870e16b3e73454fa7c2fd6decd4a283
c694da160d4365eb2d5aad404334c6ed1d41a75c
/src/usr/initservice/plugins/initsvcudparserfactory.H
7d73aaad2c72ba55eec5175ae63df1d94c4de84d
[ "Apache-2.0" ]
permissive
3mdeb/talos-hostboot
b00e00fa4613731c01338a73dcf39dededae971f
8d49baa2180fc3cff78c393b19e39816dfa8606f
refs/heads/master
2022-12-18T01:04:50.303567
2018-04-25T02:13:30
2018-05-20T06:31:19
299,345,985
1
0
NOASSERTION
2020-09-28T15:40:46
2020-09-28T15:06:58
C++
UTF-8
C++
false
false
2,599
h
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/initservice/plugins/initsvcudparserfactory.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* COPYRIGHT International Business Machines Corp. 2012,2014 */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef INITSVC_UDPARSERFACTORY_H #define INITSVC_UDPARSERFACTORY_H /** * @file initsvcudparserfactory.H * * Defines the InitSvcUserDetailsParserFactory.H class */ #include "errludparserfactory.H" #include "initsvcudistep.H" namespace INITSERVICE { /** * @class InitSvcUserDetailsParserFactory * * This factory produces ErrlUserDetailsParser objects to parse the specified * InitService user detail data. */ class InitSvcUserDetailsParserFactory : public ERRORLOG::ErrlUserDetailsParserFactory { public: /** * @brief Constructor */ InitSvcUserDetailsParserFactory() { registerParser<InitSvcUserDetailsParserIstep>(INIT_SVC_UDT_ISTEP); } private: // Disabled InitSvcUserDetailsParserFactory(const InitSvcUserDetailsParserFactory &); InitSvcUserDetailsParserFactory & operator=( const InitSvcUserDetailsParserFactory &); }; } #endif
[ "iawillia@us.ibm.com" ]
iawillia@us.ibm.com
c6b9197bebe9dae4ce00d7af1c80e4883e3ca9fd
db019496ccdec20ad159feec1f4d7e97d469cf11
/http-standalone-esp8266/http-standalone-esp8266.ino
b4a339ab2ab859cf6a4c7233688829dc36fd0365
[ "MIT" ]
permissive
ArGJolan/arduino-sketches
8a2f3882fdec45abe41a941d179c7d9048a48670
25b7c4b4309faa76388f8e0ac5b563a12e8e8828
refs/heads/master
2023-04-04T07:41:44.430970
2021-04-17T09:24:04
2021-04-17T09:24:04
333,207,793
1
0
null
null
null
null
UTF-8
C++
false
false
243
ino
#include "http.h" void setup() { setupWifi(); } void loop() { if (wifiReady()) { Serial.print(get("http://worldtimeapi.org/api/ip.txt")); } else { Serial.println("Error in WiFi connection"); } delay(30000); }
[ "argjolan@gmail.com" ]
argjolan@gmail.com
7f896605171bea64e9383cca49a521695b05319c
c06207424322bbfc54ec82e8a6b172da681803c7
/N-Queens/N-Queens_3.cpp
2ad97676411358b042fbd946cf7ac09d86798f98
[ "MIT" ]
permissive
yergen/leetcode
4e5c6ee218695ddc99852a04032f9ebdc99880aa
a40e99d511a76a6a18dbe9a30567190847e821f1
refs/heads/master
2023-03-15T14:45:16.495176
2023-03-05T14:11:19
2023-03-05T14:11:19
180,911,779
0
0
null
null
null
null
GB18030
C++
false
false
1,709
cpp
#include<iostream> #include<vector> #include<string> using namespace::std; class Solution { private: vector<vector<string> > res; int upperlim; public: vector<vector<string> > solveNQueens(int n) { upperlim = (1 << n) - 1;//低n位全部置1 vector<string> cur(n, string(n, '.')); helper(0, 0, 0, cur, 0); return res; } void helper(const int row, const int ld, const int rd, vector<string>&cur, const int index) { int pos, p; if (row != upperlim) { pos = upperlim & (~(row | ld | rd));//pos中二进制为1的位,表示可以在当前行的对应列放皇后 //和upperlim与运算,主要是ld在上一层是通过左移位得到的,它的高位可能有无效的1存在,这样会清除ld高位无效的1 while (pos) { p = pos & (~pos + 1);//获取pos最右边的1,例如pos = 010110,则p = 000010 pos = pos - p;//pos最右边的1清0 setQueen(cur, index, p, 'Q');//在当前行,p中1对应的列放置皇后 helper(row | p, (ld | p) << 1, (rd | p) >> 1, cur, index + 1);//设置下一行 setQueen(cur, index, p, '.'); } } else//找到一个解 res.push_back(cur); } //第row行,第loc1(p)列的位置放置一个queen或者清空queen,loc1(p)表示p中二进制1的位置 void setQueen(vector<string>&cur, const int row, int p, char val) { int col = 0; while (!(p & 1)) { p >>= 1; col++; } cur[row][col] = val; } }; int main() { Solution sol; int sum = 0; vector<vector<string>> res; res = sol.solveNQueens(8); for (auto Vstring : res) { for (auto str : Vstring) { cout << str << endl; } cout << endl; sum++; if (sum == 1) break; } cout << "sum : " << sum << endl; return 0; }
[ "15010908626@163.com" ]
15010908626@163.com
7eb2037ec462942182a56567bae528f37c605105
469e80e06f9f55e1089b3e4ef7e36a4bcae17ca9
/example/src/ofApp.h
75adb0fb84f4f33e1d0220ba34aeccd70a75bdcb
[ "MIT" ]
permissive
leozimmerman/ofxAudioDecoder
6da98e0c9dd8e09ee5c1105853c906895e11bb26
70e27952b7133151f6475c8f0f9fb26ae368fa8b
refs/heads/master
2021-01-13T08:56:54.623306
2016-09-29T19:36:04
2016-09-29T19:36:04
69,600,465
1
1
null
2016-09-29T19:26:37
2016-09-29T19:26:37
null
UTF-8
C++
false
false
272
h
#pragma once #include "ofMain.h" #include "ofxAudioDecoder.h" class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); void dragEvent(ofDragInfo dragInfo); void loadFile(string filename); ofxAudioDecoder audio; ofMesh left, right; };
[ "kyle@kylemcdonald.net" ]
kyle@kylemcdonald.net
8647f337216316dc1f767e741230f897ebed476b
7391feeb5b8e31f982422bdd74517e954d8c955e
/Crypto/testsuite/src/CryptoTest.h
37a01f5588050a1a8f9c1d2896388ace789c9cc3
[ "BSL-1.0" ]
permissive
AppAnywhere/agent-sdk
62d762d0424fc2e8d4a98b79fb150e635adedd4d
c5495c4a1d892f2d3bca5b82a7436db7d8adff71
refs/heads/master
2021-01-11T15:22:01.406793
2016-09-01T16:36:20
2016-09-01T16:36:20
80,341,203
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
// // CryptoTest.h // // $Id: //poco/1.7/Crypto/testsuite/src/CryptoTest.h#1 $ // // Definition of the CryptoTest class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef CryptoTest_INCLUDED #define CryptoTest_INCLUDED #include "Poco/Crypto/Crypto.h" #include "CppUnit/TestCase.h" class CryptoTest: public CppUnit::TestCase { public: enum { MAX_DATA_SIZE = 10000 }; CryptoTest(const std::string& name); ~CryptoTest(); void testEncryptDecrypt(); void testEncryptDecryptWithSalt(); void testEncryptDecryptDESECB(); void testStreams(); void testPassword(); void testEncryptInterop(); void testDecryptInterop(); void testCertificate(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: }; #endif // CryptoTest_INCLUDED
[ "guenter.obiltschnig@appinf.com" ]
guenter.obiltschnig@appinf.com
730855bb297bb68fd89f456b252c1bd23a37d35e
ddcadc460cd2ced213396de76fcc53f61866998b
/Tutorial Projects/02 2019 Ultimate Unreal C++ Guide/Ultimate/Source/Ultimate/UltimateGameMode.cpp
08598fe85503ea7bb37658ef4c5d876aef4c395e
[ "MIT" ]
permissive
mukobi/Unreal-Engine-Learning
8ae3f35567cf2ddb6f8bbfd2ce94d5a243768ed1
90048cd46342ffb8e9c5b9e80c022fafbe547ae8
refs/heads/master
2022-11-01T13:18:01.291717
2020-06-15T00:53:06
2020-06-15T00:53:06
271,365,476
0
0
null
null
null
null
UTF-8
C++
false
false
996
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "UltimateGameMode.h" #include "UltimateCharacter.h" #include "UObject/ConstructorHelpers.h" #include "UltimateGameState.h" AUltimateGameMode::AUltimateGameMode() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } PointsToWin = 5; } void AUltimateGameMode::OnTargetHit() { if (AUltimateGameState* gameState = Cast<AUltimateGameState>(GameState)) { gameState->Points++; if (gameState->Points >= PointsToWin) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Cyan, FString::Printf(TEXT("You wont in %f second!"), GetWorld()->GetTimeSeconds())); } else { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Cyan, FString::Printf(TEXT("You have %d points."), gameState->Points)); } } }
[ "gabrielmukobi@gmail.com" ]
gabrielmukobi@gmail.com
5e5a77c52ab0a61894171433c8f6845cec11d2eb
aedb5d78cbe6acaf9becea0ea7b43c46a9584f5e
/src_client/related/databasemanage/pages/systemmainpage/filedeal/uploadingdatafile.h
d01db8a149059a8f7d996fa0dc2e9b1fb2201850
[]
no_license
wey580231/Framewrok
60a922d4cc868b0d0b7f87a529eab2724ca3c18f
1050b079997a975dcc7b64e1bfa5eb8acb72d8c4
refs/heads/develop
2023-03-15T04:36:18.608430
2021-03-23T14:30:51
2021-03-23T14:30:51
326,935,482
0
1
null
2021-03-23T14:30:52
2021-01-05T08:31:30
C++
GB18030
C++
false
false
1,502
h
/*! * @brief 发送文件 * @details * @author yzg * @version 1.0 * @date 2021.03.15 16:31:25 * @warning * @copyright NanJing RenGu. * @note */ #pragma once #include <QObject> #include <QThread> #include <QFileInfo> #include <QFile> #include <base/util/rutil.h> #include <commondefines/protocol.h> #include "../../datastruct.h" #define SEND_FILE_LENGTH 63*1024 namespace Related { class UploadingDataFile : public QObject { Q_OBJECT public: UploadingDataFile(QObject *parent = nullptr); ~UploadingDataFile(); void setFileDescription(FileDescriptionData description); void startUploading(); void pauseSendFile(); void continueSendFile(); signals: void signalSendFileProgressStataus(qint64 totalLen, qint64 currentLen); void signalSendFileStataus(bool status); private slots: void processTaskDataFileCeateResponse(const Datastruct::TaskDataFileCreateResponse & response); void slotSendFileStatus(Datastruct::ConnectionType type); private: void initConnect(); void sendCreateTaskDataFileInfo(Datastruct::TaskDataFileCreateRequest request); bool openFile(); void dealFile(); void closeFile(); private: FileDescriptionData m_fileDescription; /*!< 文件描述 */ QString m_fileId; /*!< 文件Id */ qint64 m_currentLength; /*!< 当时发送长度 */ QFile * m_file; /*!< 文件句柄指针 */ bool m_b_sendFile; /*!< 发送文件 */ bool m_pause; }; }//namespace Related
[ "45348493+YZG030455@users.noreply.github.com" ]
45348493+YZG030455@users.noreply.github.com
2a4828e9a5f6fc848e24dc1feeb6f63ea66eebb8
3c188593997cc06eab489328d81a661de16eb9fe
/src/qt/test/test_main.cpp
c8405a17e7fbcac036c396d184d2f59bfbb99417
[ "MIT" ]
permissive
yangchigi/BitHao-Source
304fc1ec94e985090ccced61a008defd61a523dc
76f330020a917d6680d3d15867773afc6887d541
refs/heads/master
2020-05-05T12:49:45.934520
2019-02-28T05:32:44
2019-02-28T05:32:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,542
cpp
// Copyright (c) 2009-2018 The Bitcoin Core developers // Copyright (c) 2014-2018 The Dash Core developers // Copyright (c) 2017-2018 The BitHao Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bithao-config.h" #endif #include "util.h" #include "uritests.h" #include "compattests.h" #include "trafficgraphdatatests.h" #ifdef ENABLE_WALLET #include "paymentservertests.h" #endif #include <QCoreApplication> #include <QObject> #include <QTest> #include <openssl/ssl.h> #if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000 #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) #endif // This is all you need to run all the tests int main(int argc, char *argv[]) { SetupEnvironment(); bool fInvalid = false; // Don't remove this, it's needed to access // QCoreApplication:: in the tests QCoreApplication app(argc, argv); app.setApplicationName("BitHao-Qt-test"); SSL_library_init(); URITests test1; if (QTest::qExec(&test1) != 0) fInvalid = true; #ifdef ENABLE_WALLET PaymentServerTests test2; if (QTest::qExec(&test2) != 0) fInvalid = true; #endif CompatTests test4; if (QTest::qExec(&test4) != 0) fInvalid = true; TrafficGraphDataTests test5; if (QTest::qExec(&test5) != 0) fInvalid = true; return fInvalid; }
[ "48000899+cqcrypto@users.noreply.github.com" ]
48000899+cqcrypto@users.noreply.github.com
1b11a86801ec39f8aa545b4b0bf4359dd2644630
04b1803adb6653ecb7cb827c4f4aa616afacf629
/components/spellcheck/common/spellcheck_struct_traits.cc
2f0c4efc3732b805f1b8a69262166bba6f61042e
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,672
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/spellcheck/common/spellcheck_struct_traits.h" #include "mojo/public/cpp/base/string16_mojom_traits.h" namespace mojo { spellcheck::mojom::Decoration EnumTraits<spellcheck::mojom::Decoration, SpellCheckResult::Decoration>:: ToMojom(SpellCheckResult::Decoration decoration) { switch (decoration) { case SpellCheckResult::SPELLING: return spellcheck::mojom::Decoration::kSpelling; case SpellCheckResult::GRAMMAR: return spellcheck::mojom::Decoration::kGrammar; } NOTREACHED(); return spellcheck::mojom::Decoration::kSpelling; } bool EnumTraits<spellcheck::mojom::Decoration, SpellCheckResult::Decoration>:: FromMojom(spellcheck::mojom::Decoration input, SpellCheckResult::Decoration* output) { switch (input) { case spellcheck::mojom::Decoration::kSpelling: *output = SpellCheckResult::SPELLING; return true; case spellcheck::mojom::Decoration::kGrammar: *output = SpellCheckResult::GRAMMAR; return true; } NOTREACHED(); return false; } bool StructTraits< spellcheck::mojom::SpellCheckResultDataView, SpellCheckResult>::Read(spellcheck::mojom::SpellCheckResultDataView input, SpellCheckResult* output) { if (!input.ReadDecoration(&output->decoration)) return false; output->location = input.location(); output->length = input.length(); if (!input.ReadReplacements(&output->replacements)) return false; return true; } } // namespace mojo
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
165a2b396066b738ac6a78fe5a92445728505644
903767e9e1bd7ae4c273621f2787e8e93ed38553
/Codeforces/ECR/97/E.cpp
8146890cefdac3316c05cd717677383bbfd9f41f
[]
no_license
itohdak/Competitive_Programming
609e6a9e17a4fa21b8f3f7fc9bbc13204d7f7ac4
e14ab7a92813755d97a85be4ead68620753a6d4b
refs/heads/master
2023-08-04T08:57:55.546063
2023-08-01T21:09:28
2023-08-01T21:09:28
304,704,923
0
0
null
null
null
null
UTF-8
C++
false
false
2,073
cpp
#include <bits/stdc++.h> #include <print.hpp> using namespace std; #define ll long long #define ld long double #define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++) #define rep(i,n) REP(i,0,n) #define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--) #define rrep(i,n) RREP(i,(n)-1,0) #define all(v) v.begin(), v.end() #define endk '\n' const int inf = 1e9+7; const ll longinf = 1LL<<60; const ll mod = 1e9+7; const ld eps = 1e-10; template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;} template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;} // 最長増加部分列の長さを求める int LIS(const vector<ll> &a) { int N = (int)a.size(); vector<ll> dp(N, longinf+5); for (int i = 0; i < N; ++i) { // dp[k] >= a[i] となる最小のイテレータを見つける auto it = lower_bound(dp.begin(), dp.end(), a[i]); // そこを a[i] で書き換える *it = a[i]; } // dp[k] < longinf+5 となる最大の k に対して k+1 が答え // それは dp[k] >= longinf+5 となる最小の k に一致する return lower_bound(dp.begin(), dp.end(), longinf+5) - dp.begin(); } void solve() { int n, k; cin >> n >> k; vector<ll> A(n); rep(i, n) cin >> A[i]; vector<int> B(k); rep(i, k) { cin >> B[i]; B[i]--; } rep(i, k-1) { if(A[B[i]] >= A[B[i+1]]) { cout << -1 << endk; return; } } vector<vector<ll>> C(k+1); rep(i, k+1) { REP(j, (i==0 ? 0 : B[i-1]+1), (i == k ? n : B[i])) C[i].push_back(A[j]); } cout << C << endk; auto DP = [&](ll l, ll r, vector<ll>& v) { vector<ll> w; w.push_back(l); for(ll a: v) if(l < a && a < r) w.push_back(a); w.push_back(r); int ret = LIS(w); return v.size() + 2 - ret; }; int ans = 0; rep(i, k+1) { ans += DP((i==0 ? -longinf : A[B[i-1]]), (i==k ? longinf : A[B[i]]), C[i]); } cout << ans << endk; } int main() { cin.tie(0); ios::sync_with_stdio(false); int T = 1; while(T--) solve(); return 0; }
[ "itohdak@gmail.com" ]
itohdak@gmail.com
2bddf932a0ea76290b0d19ee699b69a25ee8301f
babf1a2d4a38f6d0dd952907a2d6f732a93c0814
/Program/Practice/ThiCK.cpp
129d3a764afa898edd1c63aca4a308f73ef02e62
[]
no_license
binhkio123/Coding
059601abb0faac7fa8683420efd9f2887d8b3404
002820431bbafe9818f6008ec7c2efe99c29819f
refs/heads/main
2023-08-03T10:07:26.426582
2021-09-24T05:49:45
2021-09-24T05:49:45
409,506,796
0
0
null
null
null
null
UTF-8
C++
false
false
7,147
cpp
#include<stdio.h> #include<string.h> #include<windows.h> struct Olympic { int ID; char Nation[4]; char Name[30]; float R[3]; //so thuc >0 <20 va =0 neu pham quy float FR; }; Olympic VDV[1]; void showMenu(){ system("cls"); printf("\n-----------CHUONG TRINH OLYMPIC MON NHAY XA-----------"); printf("\n 1. Nhap thong tin truoc thi dau"); printf("\n 2. In thong tin"); printf("\n 3. Thi dau"); printf("\n 4. Tim kiem"); printf("\n 5. In ket qua"); printf("\n 6. Ket thuc"); printf("\n>> "); } void nhap(Olympic &p, int n){ p.ID = n+1;int i,j; printf("\n< Van dong vien thu %d >\n", p.ID); printf("Nhap quoc gia cua van dong vien: "); fflush(stdin); fgets(p.Nation,4,stdin); for(i=0;i<3;i++){ if(p.Nation[i]>96){ p.Nation[i]-=32; } } printf("Nhap ten van dong vien: "); fflush(stdin); gets(p.Name); // kiemTraTenp---------- int X=strlen(p.Name); while(p.Name[0]==32){ //loai bo khoang trang dau ten for(i=0;i<X-1;i++){ p.Name[i]=p.Name[i+1]; } X--; } if(p.Name[0]>90){ //viet hoa dau dong p.Name[0]-=32; } i=0; while(i!=X-1){ //loai bo DoubleSpace if(p.Name[i]==32 && p.Name[i+1]==32){ for(j=i;j<X-1;j++){ p.Name[j]=p.Name[j+1]; } X--; } else{i++;} } for(i=X-1;i>0;i--){ //loai bo khoang trang cuoi ten if(p.Name[i]==32){ p.Name[i]=p.Name[i+1]; }else{break;} } for(i=1;i<X;i++){ //viet hoa ten if(p.Name[i]!=32 && p.Name[i-1]==32){ if(p.Name[i]>90){ p.Name[i]-=32; } } } //----------------------- printf("----------------------------------"); } void nhapN(Olympic p[], int N){ system("cls"); printf("\n-----NHAP THONG TIN VAN DONG VIEN-----\n"); int i; for(i=0;i<N;i++){ nhap(p[i],i); } } void xuatN(int N){ system("cls"); printf("\n-----THONG TIN VAN DONG VIEN-----"); printf("\n ID Nation Name R1 R2 R3 FR"); int i; for(i=0;i<N;i++){ printf("\n %-3d%-8s%-30s%-6.2f%-6.2f%-6.2f%-6.2f",VDV[i].ID,VDV[i].Nation,VDV[i].Name,VDV[i].R[0],VDV[i].R[1],VDV[i].R[2],VDV[i].FR); } } void sapXep(int N){ int i,j; float fr[N]; for(i=0;i<N;i++){ for(j=0;j<3;j++){ if(fr[i]<VDV[i].R[j]){ fr[i]=VDV[i].R[j]; } } } for(i=0;i<N;i++){ for(j=i;j<N;j++){ if(fr[i]<fr[j]){ float t=fr[i]; fr[i]=fr[j]; fr[j]=t; Olympic T=VDV[i]; VDV[i]=VDV[j]; VDV[j]=T; } } } } void search_name(int N){ printf("\nNhap ten can tim:"); char name_input[3]; fflush(stdin); gets(name_input); for (int i = 0; i < N; i++) { if (strstr(VDV[i].Name, name_input) != NULL) { printf("\n-----THONG TIN VAN DONG VIEN-----"); printf("\n ID Nation Name R1 R2 R3 FR"); printf("\n %-3d%-8s%-30s%-6.2f%-6.2f%-6.2f%-6.2f",VDV[i].ID,VDV[i].Nation,VDV[i].Name,VDV[i].R[0],VDV[i].R[1],VDV[i].R[2],VDV[i].FR); } } } void tinhfr(int N){ int i,j; for(i=0;i<N;i++){ VDV[i].FR=0; for(j=0;j<3;j++){ if(VDV[i].FR<VDV[i].R[j]){ VDV[i].FR=VDV[i].R[j]; } } } } int main(){ bool cn1=false,cn3=false,cn4=true; int N,i,choice; while(choice!=6){ begin: showMenu(); scanf("%d", &choice); switch (choice) { case 1:{ if(cn1==true){ printf("Vui long nhap lai"); break;} sl: printf("Nhap so luong van dong vien (1~20): "); scanf("%d",&N); if(N<1||N>20){ printf("Vui long nhap lai!\n"); fflush(stdin); goto sl; } (Olympic*)malloc(N*sizeof(Olympic)); nhapN(VDV,N); cn1=true; printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); break; } case 2:{ xuatN(N); printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); break; } case 3:{ if(cn3==true){ printf("Vui long nhap lai"); break;} int i,j; for(i=0;i<3;i++){ system("cls"); printf("---KET QUA THI DAU LAN %d---\n", i+1); for(j=0;j<N;j++){ kq: printf("Ket qua thi cua van dong vien thu %d: ",j+1); scanf("%f",&VDV[j].R[i]); if(VDV[j].R[i]<0||VDV[j].R[i]>20){ printf("Vui long nhap lai!\n"); fflush(stdin); goto kq; } } xuatN(N); printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); } tinhfr(N); cn3=true; cn4=false; break; } case 4:{ if(cn4==true){ printf("Vui long nhap lai"); break;} system("cls"); int x; printf("----TIM KIEM VAN DONG VIEN----"); while(x!=1 && x!=2){ printf("\n 1. Tim kiem theo ten quoc gia"); printf("\n 2. Tim kiem theo ten"); printf("\n>> "); scanf("%d",&x); } switch (x) { case 1:{ x=0; char arr[4]; printf("Nhap ten quoc gia: "); fflush(stdin); fgets(arr,4,stdin); printf("\nDanh sach:"); int i; printf("\n ID Nation Name R1 R2 R3 FR"); for(i=0;i<N;i++){ if(strcmp(arr,VDV[i].Nation)==0){ printf("\n %-3d%-8s%-30s%-6.2f%-6.2f%-6.2f%-6.2f",VDV[i].ID,VDV[i].Nation,VDV[i].Name,VDV[i].R[0],VDV[i].R[1],VDV[i].R[2],VDV[i].FR); } } printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); break; } case 2:{ x=0; search_name(N); printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); break; } } } case 5:{ if(cn4==true){ printf("Vui long nhap lai"); break;} sapXep(N); xuatN(N); printf("\nNhan Enter de tiep tuc..."); fflush(stdin); getchar(); break; } case 6: break; default: goto begin; } } return 0; }
[ "vuanhquan01@gmail.com" ]
vuanhquan01@gmail.com
256210df1536bbc17038c288876c816ee7bd5497
0ecb5f6911965c08b8a4d4297a10584b2e720310
/Libraries/MDStudio-SDK/Source/MDStudio/PortableCore/UI/image.h
4da578cdd8ca5f60c7b43d6710d01349041df241
[ "Apache-2.0" ]
permissive
danodus/studioengine
01c368835f8f8503b9ced298ec5da927621be67c
1a18d373b26575b040d014ae2650a1aaeb208a89
refs/heads/main
2023-05-26T11:13:11.355483
2021-05-27T15:17:06
2021-05-27T15:17:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,268
h
// // image.h // MDStudio // // Created by Daniel Cliche on 2014-07-15. // Copyright (c) 2014-2020 Daniel Cliche. All rights reserved. // #ifndef IMAGE_H #define IMAGE_H #include <memory> #include <string> #include "size.h" namespace MDStudio { class Image { bool _textureLoaded = false; unsigned char* _data; int _width, _height; int _textureWidth, _textureHeight; uint32_t _textureID; float _scale; bool loadPNGImage(const char* name); public: Image(const std::string& path, bool isExternal = false); ~Image(); Size size() { return makeSize(static_cast<float>(_width / _scale), static_cast<float>(_height / _scale)); } Size internalSize() { return makeSize(static_cast<float>(_width), static_cast<float>(_height)); } Size internalTextureSize() { return makeSize(static_cast<float>(_textureWidth), static_cast<float>(_textureHeight)); } void bindTexture(); }; class SystemImages { std::shared_ptr<Image> _starEmptyImage; std::shared_ptr<Image> _starFilledImage; std::shared_ptr<Image> _upArrowImage; std::shared_ptr<Image> _downArrowImage; std::shared_ptr<Image> _leftArrowImage; std::shared_ptr<Image> _rightArrowImage; std::shared_ptr<Image> _sliderThumbImage; std::shared_ptr<Image> _checkMarkImage; std::shared_ptr<Image> _radioButtonImage; std::shared_ptr<Image> _crossCircleImage; public: SystemImages(); static SystemImages* sharedInstance(); std::shared_ptr<Image> starEmptyImage() { return _starEmptyImage; } std::shared_ptr<Image> starFilledImage() { return _starFilledImage; } std::shared_ptr<Image> upArrowImage() { return _upArrowImage; } std::shared_ptr<Image> downArrowImage() { return _downArrowImage; } std::shared_ptr<Image> leftArrowImage() { return _leftArrowImage; } std::shared_ptr<Image> rightArrowImage() { return _rightArrowImage; } std::shared_ptr<Image> sliderThumbImage() { return _sliderThumbImage; } std::shared_ptr<Image> checkMarkImage() { return _checkMarkImage; } std::shared_ptr<Image> radioButtonImage() { return _radioButtonImage; } std::shared_ptr<Image> crossCircleImage() { return _crossCircleImage; } }; } // namespace MDStudio #endif // IMAGE_H
[ "dcliche@meldora.com" ]
dcliche@meldora.com
21c2ed4a2d4071359d8844a56ce78a557b10934f
835b5664e703a224b598afd373286e7bd711efbb
/tri_engine/include/core/kernel/io/tri_file.hpp
b53722d0c52e2f65a50c668eb480b2c0e015bf12
[]
no_license
doscoy/tri_engine
a4f70b7331b4ad0a1dc2a735dc59e7aabbdd9a82
429508946355563ff4fa0d09abde331517021137
refs/heads/master
2021-01-17T08:53:20.657417
2016-01-13T12:13:30
2016-01-13T12:13:30
4,419,828
0
0
null
null
null
null
UTF-8
C++
false
false
2,251
hpp
//////////////////////////////////////////////////////////////////////// // Tri ENGINE // copyright 2012... Tri ENGINE project team. // // Website: http://tri-engine.aquariuscode.com/ // License: https://github.com/doscoy/tri_engine/wiki/License //////////////////////////////////////////////////////////////////////// /** @file tri_file.hpp ファイル. */ #ifndef TRI_FILE_HPP_INCLUDED #define TRI_FILE_HPP_INCLUDED // include #include "cross/cross_std.hpp" #include "core/core_config.hpp" #include "core/utility/tri_uncopyable.hpp" #include "core/base/tri_types.hpp" #include "tri_filepath.hpp" TRI_CORE_NS_BEGIN /// /// ファイルクラス class File : private Uncopyable { public: enum class IOMode { IN, OUT }; enum class IOType { TEXT, BINARY }; public: /// /// コンストラクタ File(); /// /// コンストラクタ File( const String& name, size_t size ); /// /// コンストラクタ File( const String& name, size_t size, uint8_t* data ); /// /// デストラクタ ~File(); public: /// /// ファイル読み込み bool loadFile( const FilePath& filepath, IOMode mode = IOMode::IN, IOType type = IOType::BINARY ); /// /// ファイル読み込み bool loadFile( const char* const filepath, IOMode mode = IOMode::IN, IOType type = IOType::BINARY ); /// /// データ取得 const uint8_t* data() const { return data_; } /// /// データサイズ取得 std::size_t size() const { return size_; } /// /// 正当性チェック bool isVaild() const { return data_ != nullptr; } /// /// 名前 const String& name() const { return name_; } private: String name_; ///< 名前 std::uint8_t* data_; ///< データ std::size_t size_; ///< データサイズ bool auto_free_; ///< バッファの自動解放フラグ }; using FilePtr = SharedPtr<File>; TRI_CORE_NS_END #endif // TRI_FILE_HPP_INCLUDED
[ "doscoy.t@gmail.com" ]
doscoy.t@gmail.com
c8a43c505d0117633f46e8c939807e5542669197
9d917ee288f3071c0c2dfd7a9d192a0d1a3ca87a
/AMGLib/AMG_Thread.cpp
a0575592d50cd8c136130df2d250a19290e834f2
[ "Zlib" ]
permissive
PSP-Archive/AMGLib-Plus
ce7cf9ebda7ccceb703244b7834f4f7cbe7b1d3d
c9ced0ed88c766a0eea7e8c357fe13b88bd069bb
refs/heads/main
2023-07-19T03:41:14.642301
2021-09-18T15:51:24
2021-09-18T15:51:24
407,902,298
4
0
null
null
null
null
UTF-8
C++
false
false
2,895
cpp
// Includes #include <pspkernel.h> #include <pspctrl.h> #include <pspmoduleinfo.h> #include <pspthreadman.h> #include <psppower.h> #include <pspdisplay.h> #include <pspgu.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "AMG_Thread.h" #include "AMG_3D.h" #ifndef AMG_COMPILE_ONELUA // Variables AMG_Power_ AMG_Power; // Callback de salida int AMG_ExitCallback(int arg1, int arg2, void *common){ AMG.Exit = 1; return 0; } // Callback de funciones POWER int AMG_PowerCallback(int unknown, int pwrflags, void *common){ AMG_Power.Suspended = (pwrflags &PSP_POWER_CB_POWER_SWITCH || pwrflags &PSP_POWER_CB_SUSPENDING); AMG_Power.Resuming = (pwrflags & PSP_POWER_CB_RESUMING); AMG_Power.Resumed = (pwrflags & PSP_POWER_CB_RESUME_COMPLETE); AMG_Power.StandBy = (pwrflags & PSP_POWER_CB_STANDBY); sceDisplayWaitVblankStart(); return 0; } // main() de los callbacks int callbackThread(SceSize args, void *argp){ AMG.CBID = sceKernelCreateCallback("AMG_ExitCallback", AMG_ExitCallback, NULL); sceKernelRegisterExitCallback(AMG.CBID); AMG.CBID = sceKernelCreateCallback("AMG_PowerCallback", AMG_PowerCallback, NULL); scePowerRegisterCallback(0, AMG.CBID); sceKernelSleepThreadCB(); return 0; } // Inicializa los callbacks void AMG_SetupCallbacks(void){ // Crea el thread principal AMG.MainThreadID = sceKernelCreateThread("AMG_HomeThread", callbackThread, 0x11, 0xFA0, 0, 0); if(AMG.MainThreadID >= 0) sceKernelStartThread(AMG.MainThreadID, 0, 0); else{ AMG_Error(AMG_THREAD_SETUP, AMG.MainThreadID, "AMG_HomeThread"); return; } // Inicializa los perifericos sceCtrlSetSamplingCycle(0); sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG); } // Devuelve al XMB int AMG_ReturnXMB(void){ sceKernelExitGame(); return 0; } // Actualiza el modulo POWER void AMG_UpdatePower(void){ AMG_Power.BatteryExists = scePowerIsBatteryExist(); AMG_Power.ExternalPower = scePowerIsPowerOnline(); AMG_Power.LowBattery = scePowerIsLowBattery(); AMG_Power.BatteryCharging = scePowerIsBatteryCharging(); AMG_Power.BatteryLifeTime = scePowerGetBatteryLifeTime(); AMG_Power.BatteryLife = scePowerGetBatteryLifePercent(); AMG_Power.BatteryVolt = scePowerGetBatteryVolt(); AMG_Power.BatteryTemp = scePowerGetBatteryTemp(); AMG_Power.CPUFreq = scePowerGetCpuClockFrequency(); AMG_Power.BUSFreq = scePowerGetBusClockFrequency(); } // Cambia la velocidad de CPU void AMG_SetCpuSpeed(int mhz){ scePowerSetClockFrequency(mhz, mhz, (mhz >> 1)); } // Crea un Thread void AMG_CreateThread(AMG_Thread *th){ th->ThreadID = sceKernelCreateThread(th->Name, th->EntryPoint, th->Priority, th->StackSize, 0, NULL); if(th->ThreadID >= 0) sceKernelStartThread(th->ThreadID, 0, 0); else{ AMG_Error(AMG_THREAD_SETUP, th->ThreadID, th->Name); return; } } // Elimina un Thread void AMG_DeleteThread(AMG_Thread *th){ sceKernelTerminateDeleteThread(th->ThreadID); } #endif
[ "pierluigiortenzi@gmail.com" ]
pierluigiortenzi@gmail.com
8c957a09b258b927a3f6c69efda8c96dfc659205
502983baddff63bbf87f8e25fcd8681d8257b6f5
/src/ESP32-devcam.cpp
c79d7a700523550771a22dcacb2298b46ea9937b
[ "MIT" ]
permissive
jelinj8/TenDollarWebcam
d3d1a3532dab90e7c7b19103da6affabbecfdb0e
7854a6d592c1e5beca73298ecc764f32c9baf79a
refs/heads/master
2023-04-14T13:59:58.739456
2023-03-26T19:21:42
2023-03-26T19:21:42
259,108,087
0
0
null
2020-04-26T18:49:27
2020-04-26T18:49:27
null
UTF-8
C++
false
false
9,719
cpp
#include <Arduino.h> // #define USEBOARD_TTGO_T // #define USEBOARD_AITHINKER // #define USEBOARD_ESP_CAM // #define ENABLE_OLED //if want use oled, turn on this macro // #define ENABLE_WEBSERVER // #define ENABLE_RTSPSERVER // when pulled low, forces config (AP) mode. #define FACTORYRESET_BUTTON 12 #define FLASH_LED 4 #define FLASH_LED_CH 0 #define TICKER_LED 33 #define TICKER_LED_ON LOW #define HOSTNAME "ESP32-Camera-" // delay to allow WiFi AP come up before attempting to connect, comment out to disable #define BOOT_DELAY 2 #include "OV2640.h" #include <AutoConnect.h> #ifdef ENABLE_WEBSERVER #include <WebServer.h> #endif #ifdef ENABLE_RTSPSERVER #include "SimStreamer.h" #include "OV2640Streamer.h" #include "CRtspSession.h" #endif #ifdef ENABLE_OLED #include "SSD1306.h" #define OLED_ADDRESS 0x3c #ifdef USEBOARD_TTGO_T #define I2C_SDA 21 #define I2C_SCL 22 #else #define I2C_SDA 14 #define I2C_SCL 13 #endif SSD1306Wire display(OLED_ADDRESS, I2C_SDA, I2C_SCL, GEOMETRY_128_32); bool hasDisplay; // we probe for the device at runtime #endif OV2640 cam; #ifdef FLASH_LED uint16_t ledLevel = 0; #endif AutoConnectConfig Config("ESP32-CamCfg", "12345678"); #ifdef ENABLE_RTSPSERVER WiFiServer rtspServer(554); #endif #ifdef ENABLE_WEBSERVER WebServer server(80); AutoConnect Portal(server); #else AutoConnect Portal; #endif #ifdef ENABLE_WEBSERVER void handle_jpg_stream(void) { Serial.println("stream"); WiFiClient client = server.client(); String response = "HTTP/1.1 200 OK\r\n"; response += "Content-Type: multipart/x-mixed-replace; boundary=frame\r\n\r\n"; server.sendContent(response); while (1) { cam.run(); if (!client.connected()) break; response = "--frame\r\n"; response += "Content-Type: image/jpeg\r\n\r\n"; server.sendContent(response); client.write((char *)cam.getfb(), cam.getSize()); Serial.printf("%lu JPG frame\n", millis()); server.sendContent("\r\n"); if (!client.connected()) break; } } void handle_jpg(void) { Serial.printf("%lu jpg\n", millis()); WiFiClient client = server.client(); #ifdef FLASH_LED String led = server.arg("led"); if (led == ""){ //Parameter not found cam.run(); }else{ //Parameter found uint16_t arg = led.toInt(); if(arg != ledLevel){ ledcWrite(FLASH_LED_CH, arg); delay(400); cam.run(); delay(100); ledcWrite(FLASH_LED_CH, ledLevel); } else { cam.run(); } } #else cam.run(); #endif if (!client.connected()) { return; } String response = "HTTP/1.1 200 OK\r\n"; response += "Content-disposition: inline; filename=capture.jpg\r\n"; response += "Content-type: image/jpeg\r\n\r\n"; server.sendContent(response); client.write((char *)cam.getfb(), cam.getSize()); } void handle_root(void) { Serial.printf("%lu root\n", millis()); WiFiClient client = server.client(); #ifdef FLASH_LED String led = server.arg("led"); if (led == ""){ //Parameter not found Serial.printf(" %lu LED unspecified\n", millis()); }else{ //Parameter found uint16_t arg = led.toInt(); if(arg != ledLevel){ Serial.printf(" %lu LED %lu\n", millis(), arg); ledLevel = arg; ledcWrite(FLASH_LED_CH, ledLevel); delay(100); } } #endif String response = "HTTP/1.1 200 OK\r\n"; response += "Content-disposition: inline; filename=index.htm\r\n"; response += "Content-type: text/html\r\n\r\n<html><body><H1>ESP32 camera "; response += HOSTNAME; response += String((uint32_t)(ESP.getEfuseMac() >> 32), HEX); response += "</H1>"; #ifdef FLASH_LED response += "LED: "\ "<a href=\"/?led=255\">255</a> "\ "<a href=\"/?led=128\">128</a> "\ "<a href=\"/?led=64\">64</a> "\ "<a href=\"/?led=32\">32</a> "\ "<a href=\"/?led=8\">8</a> "\ "<a href=\"/?led=0\">OFF</a>"; #endif response += " <a href=\"/jpg\">/jpg</a> for single image, <a href=\"/stream\">/stream</a> for MJPEG stream.<br>For RTSP use rtsp://"; response += HOSTNAME; response += String((uint32_t)(ESP.getEfuseMac() >> 32), HEX); response += ":554/mjpeg/1<br><img src=\"/jpg\" /></body></html>\r\n"; server.sendContent(response); } void handleNotFound() { Serial.printf("%lu Not found: ", millis()); Serial.println(server.uri()); String message = "Server is running!\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; server.send(200, "text/plain", message); } #endif #ifdef ENABLE_OLED void lcdMessage(String msg) { if (hasDisplay) { display.clear(); display.drawString(128 / 2, 32 / 2, msg); display.display(); } } #endif void setup() { #ifdef ENABLE_OLED hasDisplay = display.init(); if (hasDisplay) { display.flipScreenVertically(); display.setFont(ArialMT_Plain_16); display.setTextAlignment(TEXT_ALIGN_CENTER); } lcdMessage("booting"); #endif Serial.begin(115200); while (!Serial) { ; } #ifdef FLASH_LED ledcSetup(FLASH_LED_CH, 5000, 8); ledcAttachPin(FLASH_LED, FLASH_LED_CH); ledcWrite(FLASH_LED_CH, 0); #endif #ifdef FACTORYRESET_BUTTON pinMode(FACTORYRESET_BUTTON, INPUT_PULLUP); bool forceAP = !digitalRead(FACTORYRESET_BUTTON); if(forceAP) Serial.println("Force AP mode"); #endif Serial.print("ESP32-TenDollarWebcam + jelinj8 changes"); #ifdef BOOT_DELAY Serial.print(", boot delay "); Serial.print(BOOT_DELAY); Serial.println("s"); delay(BOOT_DELAY * 1000l); #else Serial.println(); #endif #if defined(USEBOARD_TTGO_T) camera_config_t cconfig = esp32cam_ttgo_t_config; #elif defined(USEBOARD_AITHINKER) camera_config_t cconfig = esp32cam_aithinker_config; #elif defined(USEBOARD_ESP_CAM) camera_config_t cconfig = esp32cam_config; #else #error "BOARD NOT DEFINED" #endif if (psramFound()) { Serial.println("PSRAM found."); //cconfig.frame_size = FRAMESIZE_SVGA; //cconfig.frame_size = FRAMESIZE_HD; cconfig.frame_size = FRAMESIZE_SXGA; //cconfig.frame_size = FRAMESIZE_UXGA; cconfig.jpeg_quality = 5; // cconfig.fb_count = 2; cconfig.fb_count = 1; } else { cconfig.frame_size = FRAMESIZE_SVGA; cconfig.jpeg_quality = 12; cconfig.fb_count = 1; } int camInit = cam.init(cconfig); Serial.printf("Camera init returned %d\n", camInit); #ifdef ENABLE_OLED lcdMessage(ip.toString()); #endif #ifdef ENABLE_WEBSERVER server.on("/", HTTP_GET, handle_root); server.on("/stream", HTTP_GET, handle_jpg_stream); server.on("/jpg", HTTP_GET, handle_jpg); server.onNotFound(handleNotFound); #endif Config.autoReconnect = true; Config.autoRise = false; Config.title = "Camera config"; #ifdef TICKER_LED Config.ticker = true; Config.tickerPort = TICKER_LED; Config.tickerOn = TICKER_LED_ON; #endif Config.hostName = HOSTNAME + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX); #ifdef FACTORYRESET_BUTTON if (forceAP) { // 1 means not pressed Config.immediateStart = true; Config.autoRise = true; } #endif Portal.config(Config); if (Portal.begin()) { Serial.println("WiFi connected: " + WiFi.localIP().toString()); } else Serial.println("Failed to connect WiFi"); #ifdef ENABLE_RTSPSERVER rtspServer.begin(); Serial.println("RTSP server started."); #endif } #ifdef ENABLE_RTSPSERVER CStreamer *streamer; CRtspSession *session; WiFiClient client; // FIXME, support multiple clients #endif void loop() { Portal.handleClient(); #ifdef ENABLE_RTSPSERVER uint32_t msecPerFrame = 500; static uint32_t lastimage = millis(); static float fps; // If we have an active client connection, just service that until gone // (FIXME - support multiple simultaneous clients) if (session) { session->handleRequests(0); // we don't use a timeout here, // instead we send only if we have new enough frames uint32_t now = millis(); if (now > lastimage + msecPerFrame || now < lastimage) { // handle clock rollover session->broadcastCurrentFrame(now); fps = 1000.0 / (now - lastimage); lastimage = now; now = millis(); printf("%d RTSP frame %.2f FPS\n", lastimage, fps); // check if we are overrunning our max frame rate if (now > lastimage + msecPerFrame) printf("warning exceeding max frame rate of %d ms\n", now - lastimage); } if (session->m_stopped) { delete session; delete streamer; session = NULL; streamer = NULL; printf("%lu Closed RTSP session\n", millis()); } } else { client = rtspServer.accept(); if (client) { //streamer = new SimStreamer(&client, true); // our streamer for UDP/TCP based RTP transport streamer = new OV2640Streamer(&client, cam); // our streamer for UDP/TCP based RTP transport session = new CRtspSession(&client, streamer); // our threads RTSP session and state printf("%lu Started RTSP session\n", millis()); } } #endif }
[ "jakub.jelinek@gmail.com" ]
jakub.jelinek@gmail.com
ef4f8126f4fd2419a75ec54013eab9d5bdca5e56
aa54d7be40f06d93a6fe2bdc7ccbe530a126d8c4
/cli/src/demo/ui_test_sequence.cpp
9a01fb2b680941b650fa98c574b5e899093c2b11
[]
no_license
shipduck/cham-cham-cham
1365a97ef565cc036bd3e2f8321c15799aa84fff
d6ddebea7fd7e385820b97693c1fd9ea643ae2a5
refs/heads/master
2016-09-06T03:19:41.333661
2013-08-28T13:15:20
2013-08-28T13:15:20
10,620,263
1
0
null
null
null
null
UTF-8
C++
false
false
1,129
cpp
// Ŭnicode please #include "stdafx.h" #include "ui_test_sequence.h" #include "base/lib.h" #include "irr/hmd_gui.h" using namespace irr; using namespace core; using namespace video; using namespace scene; scene::ISceneNode *test = nullptr; scene::ICameraSceneNode* fpsCamera = nullptr; hmd_ui::Manager uiMgr; UiTestSequence::UiTestSequence() { auto comp = new hmd_ui::TestComp(); uiMgr.add(comp); // add fps camera auto camNode = Lib::smgr->addCameraSceneNodeFPS(); { // create test cube test = Lib::smgr->addCubeSceneNode(60); // let the cube rotate and set some light settings scene::ISceneNodeAnimator* anim = Lib::smgr->createRotationAnimator(core::vector3df(0.3f, 0.3f,0)); test->setPosition(core::vector3df(-30, 0, 100)); test->setMaterialFlag(video::EMF_LIGHTING, false); // disable dynamic lighting test->addAnimator(anim); anim->drop(); test->setMaterialTexture(0, comp->getTexture()); // set material of cube to render target } } UiTestSequence::~UiTestSequence() { uiMgr.shutDown(); } void UiTestSequence::update(int ms) { } void UiTestSequence::preDraw() { uiMgr.drawAll(); }
[ "libsora25@gmail.com" ]
libsora25@gmail.com
c93e513083fda526b54b15d90476f00bb9a05bd1
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5648941810974720_1/C++/shishirt22/codejam.cpp
aac7379388f2d2975e8842ea57d08b13d193b6e5
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,388
cpp
#include <bits/stdc++.h> using namespace std; #define mod 1000000007 #define ll long long int #define pb push_back #define mp make_pair #define lf long double #define VI vector<ll> #define ppl pair<ll,ll> #define ppi pair<int,int> #define F first #define S Second #define ML map<ll,ll> #define itm map<ll,ll>::iterator #define f_inp ios_base::sync_with_stdio(false) int Z[10000],C[20]; int main() { f_inp; ll n,m,a,b,c,d,i,j; freopen("1.in","r",stdin); freopen("2.out","w",stdout); cin>>n; string str; int test=1; string str1[]={"ZERO", "ONE", "TWO","THREE","FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"}; while(n>0) { cin>>str; n--; int pos; memset(Z,0,sizeof(Z)); memset(C,0,sizeof(C)); for(i=0;i<str.length();i++) Z[str[i]-'A']++; C[4]=Z['U'-'A']; Z['F'-'A']-=Z['U'-'A']; Z['O'-'A']-=Z['U'-'A']; Z['R'-'A']-=Z['U'-'A']; Z['U'-'A']-=Z['U'-'A'];; C[5]=Z['F'-'A']; Z['I'-'A']-=Z['F'-'A']; Z['V'-'A']-=Z['F'-'A']; Z['E'-'A']-=Z['F'-'A']; Z['F'-'A']-=Z['F'-'A'];; C[6]=Z['X'-'A']; Z['I'-'A']-=Z['X'-'A']; Z['S'-'A']-=Z['S'-'A']; C[7]=Z['V'-'A']; Z['S'-'A']-=Z['V'-'A']; Z['E'-'A']-=2*Z['V'-'A']; Z['N'-'A']-=Z['V'-'A']; Z['V'-'A']-=Z['V'-'A']; C[8]=Z['G'-'A']; Z['I'-'A']-=Z['G'-'A']; Z['E'-'A']-=Z['G'-'A']; Z['H'-'A']-=Z['G'-'A']; Z['T'-'A']-=Z['G'-'A']; Z['G'-'A']-=Z['G'-'A']; C[2]=Z['W'-'A']; Z['T'-'A']-=Z['W'-'A']; Z['O'-'A']-=Z['W'-'A']; Z['W'-'A']-=Z['W'-'A']; C[3]=Z['H'-'A']; Z['T'-'A']-=Z['H'-'A']; Z['R'-'A']-=Z['H'-'A']; Z['E'-'A']-=2*Z['H'-'A']; Z['H'-'A']-=Z['H'-'A']; C[0]=Z['Z'-'A']; Z['O'-'A']-=Z['Z'-'A']; C[1]=Z['O'-'A']; Z['N'-'A']-=Z['O'-'A']; Z['E'-'A']-=Z['O'-'A']; Z['O'-'A']-=Z['O'-'A']; C[9]=Z['I'-'A']; //cout<<C[9]<<" "; cout<<"Case #"<<test<<": "; for(i=0;i<10;i++) { while(C[i]>0){ cout<<i; C[i]--; } } cout<<endl; test++; } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
e8e1f4494f9231b529c8b17de76ceb6e04a9b759
a9a9d4d58e1f2e9e043c9e4253604b8c6325811b
/src/qt/bitcoinaddressvalidator.cpp
c711d5c7087636f6ea959df6a91604580285df53
[ "MIT" ]
permissive
26rahulsingh/funbyte
d193d9989bdd177fd6a7548e66d4b85838771f4a
b3f7cc83157538b3f030ea34a6930e66c5c3da56
refs/heads/master
2021-04-06T08:14:38.933092
2018-03-12T10:00:43
2018-03-12T10:00:43
124,378,018
0
0
null
null
null
null
UTF-8
C++
false
false
2,709
cpp
// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The FunByte Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject *parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch(ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch<='9') || (ch >= 'a' && ch<='z') || (ch >= 'A' && ch<='Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject *parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Validate the passed FunByte address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
[ "singh.rahul26@hotmail.com" ]
singh.rahul26@hotmail.com
22db2bd3853ff7a9d6b2add7035ba632fe8bdbe8
9176cec35f7e4242c5600ec20f9df86d4f0623b3
/USpeak/servertcp.cpp
21db6c99f0b13560e3cc76ec3117773c060dfa48
[]
no_license
krdcl/USpeak
48220716daf64ad7b3747c9d0d9ea09a7c414c05
0b1910bff510962b9cee73ae693f0f0ca8cecd28
refs/heads/master
2021-01-10T08:34:20.726530
2018-09-26T07:23:29
2018-09-26T07:23:29
45,999,762
1
0
null
null
null
null
UTF-8
C++
false
false
2,375
cpp
#include "servertcp.h" ServerTCP::ServerTCP(QObject *parent) : QTcpServer(parent) { connect(this, SIGNAL(newConnection()), this, SLOT(newClient())); host_adress = QHostAddress::Any; port = 9999; time_out_wait = 300; } ServerTCP::~ServerTCP() { foreach(QTcpSocket * cliento,clients) delete cliento; } void ServerTCP::newClient() { // need to grab the socket QTcpSocket *socket = nextPendingConnection(); clients.append(socket); connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconected())); connect(socket, SIGNAL(readyRead()), this, SLOT(readMessage())); socket->write("Hello client\r\n"); //socket->flush(); socket->waitForBytesWritten(time_out_wait); } bool ServerTCP::sendMessageToAllClients(QByteArray message) { bool rezult = true; emit sendedMessage(message); int i=0; // foreach(QTcpSocket * cliento,clients) for (int i=0; i< clients.size(); i++) { QTcpSocket * cliento = clients[i]; cliento->write(message); //cliento->flush(); qDebug() << "sendMessageToAllClients " << i++ << "successfull: " << cliento->waitForBytesWritten(time_out_wait); /* if (!cliento->flush()) rezult = false; if (!cliento->waitForBytesWritten(time_out_wait)) rezult = false;*/ } return rezult; } void ServerTCP::clientDisconected() { QTcpSocket *client = (QTcpSocket*)sender(); //qDebug() << "Client disconnected:" << client->peerAddress().toString(); //clients.remove(client); foreach(QTcpSocket *client, clients) client->write(QString("Server: has left.\n").toUtf8()); } void ServerTCP::readMessage() { QTcpSocket *client = (QTcpSocket*)sender(); //if (client->) QByteArray message = client->readAll(); emit receivedMessage(message); } bool ServerTCP::listenHostPort() { if (!listen(host_adress,port)) return false; return true; if (!this->waitForNewConnection(time_out_wait)) { this->close(); return false; } return true; } quint16 ServerTCP::getPort() const { return port; } void ServerTCP::setPort(const quint16 &value) { port = value; } QHostAddress ServerTCP::getHostAdress() const { return host_adress; } void ServerTCP::setHostAdress(const QHostAddress &value) { host_adress = value; }
[ "krdcl@mail.ru" ]
krdcl@mail.ru
1bc9816da2aaeddbf334d9388f3091c8403ee8d2
609fa5bdce507d6613e62bb71838909a3d5b7cb7
/WorldofWombats/HabitatWombat/worker.cpp
7444f02d90cfe2aaeb50017be99057c93aab3f48
[]
no_license
great-communication/worldofwombats
5e3c907b11289b57c8d7477ead86d821e669a259
0b47699b481f8f2e579e7706be114ff46b4d8439
refs/heads/master
2020-03-21T21:42:06.423006
2018-06-28T23:54:06
2018-06-28T23:54:06
139,078,762
0
0
null
null
null
null
UTF-8
C++
false
false
14,730
cpp
#include "worker.h" #include "herdmember.h" #include "registry.h" #include "herder.h" #include "imagepainter.h" void Worker::setup(QString levelName, QSize backgroundSize) { global = new Global(this); // Is it safe to have "this" as parent!? global->setup(); worldBuilder = new WorldBuilder(this); worldBuilder->worker = this; worldBuilder->global = global; worldBuilder->setup(levelName, backgroundSize); consolePrint("Setup done"); //QTimer *hej = new QTimer(this); //connect(hej, SIGNAL(timeout()), this, SLOT(test())); //hej->start(500); } //Signals sent to controller void Worker::toController() { emit s_toController(); } void Worker::consolePrint(const QString &output) { emit s_consolePrint(output); } void Worker::playSoundFX(SoundFX sound){ emit s_playSoundFX(sound); } //From WorldBuilder void Worker::updateTexture(QPoint positionsChanged, const QImage &backgroundImage, bool underground) { emit s_updateTexture(positionsChanged, backgroundImage, underground); } void Worker::updateNeighboursArray(const QVector<MoveStruct> &neighbours) { emit s_updateNeighboursArray(neighbours); } //From Registry void Worker::addWombatToDisplay(int wombatId, QPoint tilePos, QPoint startingOffsetPx, qreal rotation, bool underground, int age, WombatAITask currentTask){ emit s_addWombatToDisplay(wombatId, tilePos, startingOffsetPx, rotation, underground, age, currentTask); } void Worker::addPosToWombatPosBuffer(int wombatId, QPoint pxChange, qreal rotation, bool underground, int age){ emit s_addPosToWombatPosBuffer(wombatId, pxChange, rotation, underground, age); } void Worker::setLockMovement(bool b){ emit s_setLockMovement(b); } void Worker::setLockInput(bool b){ emit s_setLockInput(b); } void Worker::setSelectedWombatVisibility(bool b){ emit s_setSelectedWombatVisibility(b); } void Worker::displayWombatInfo(QVector<QString> strings, int wombatId, bool setPossessButtonVisible){ emit s_displayWombatInfo(strings, wombatId, setPossessButtonVisible); } void Worker::displayTileInfo(QVector<QString> strings){ emit s_displayTileInfo(strings); } void Worker::setUnderground(bool b){ emit s_setUnderground(b); } void Worker::setViewPosition(QPoint pos){ emit s_setViewPosition(pos); } void Worker::setXYMoved(QPoint moved){ emit s_setXYMoved(moved); } void Worker::setSelectedWombatId(int wombatId){ emit s_setSelectedWombatId(wombatId); } void Worker::setSelectedWombatRotation(qreal rotation){ emit s_setSelectedWombatRotation(rotation); } void Worker::setScrollTarget(int wombatId){ emit s_setScrollTarget(wombatId); } void Worker::setUpdatingTiles(bool b){ emit s_setUpdatingTiles(b); } void Worker::displayBurrowList(QVector<QString> strings, QVector<int> burrowIds, QVector<int> selectedBurrowWombatIds){ emit s_displayBurrowList(strings, burrowIds, selectedBurrowWombatIds); } void Worker::showDeathNotice(QString wombatName, int wombatAge, int wombatCount, bool gameOver, CauseOfDeath causeOfDeath){ emit s_showDeathNotice(wombatName, wombatAge, wombatCount, gameOver, causeOfDeath); } void Worker::setLocationText(QString string){ emit s_setLocationText(string); } void Worker::displayOutOfRangeMessage(QPoint pos){ emit s_displayOutOfRangeMessage(pos); } void Worker::returnStorageInfoForShowStorageWidget(int burrowId, int storageId, QVector<bool> acceptedResources){ emit s_returnStorageInfoForShowStorageWidget(burrowId, storageId, acceptedResources); } void Worker::setAcceptedResourcesInStorage(int burrowId, int storageId, QVector<bool> acceptedResources){ worldBuilder->registry->setAcceptedResourcesInStorage(burrowId,storageId,acceptedResources); } void Worker::stopCollectResource(){ emit s_stopCollectResource(); } //From Herder void Worker::removeWombatFromDisplay(int wombatId){ emit s_removeWombatFromDisplay(wombatId); } //From HerdMember void Worker::updateWombatSize(int index, int age){ emit s_updateWombatSize(index, age); } void Worker::setWombatTask(int index, WombatAITask currentTask){ emit s_setWombatTask(index,currentTask); } void Worker::setWombatEmoticon(int index, WombatEmoticon emoticon){ emit s_setWombatEmoticon(index, emoticon); } //Slots called from controller void Worker::fromController() { //For debugging //QFile file("yourFile.png"); //file.open(QIODevice::WriteOnly); //worldBuilder->croppedPaths[6].save(&file, "PNG"); //consolePrint("wombats in registry: "+QString::number(worldBuilder->registry->wombats.length())); //consolePrint("wombatherd: "+QString::number(worldBuilder->herder->wombatHerd.length())); /* QVector<int> killList; QVector<CauseOfDeath> causeOfDeath; killList.append(0); causeOfDeath.append(CauseOfDeath_OldAge); worldBuilder->registry->killWombats(killList,causeOfDeath); */ //consolePrint("entrancelenght: "+QString::number(worldBuilder->registry->burrows.value(0).entrancePos.length())); //consolePrint("entrances: "+QString::number(worldBuilder->registry->burrows.value(0).entrances)); /* consolePrint("wombatlength: "+QString::number(worldBuilder->registry->wombats.length())); consolePrint("herdlength: "+QString::number(worldBuilder->herder->wombatHerd.length())); for (int i=0;i<worldBuilder->herder->wombatHerd.length();i++){ consolePrint("id in herd: "+QString::number(worldBuilder->herder->wombatHerd.value(i)->wombatId)); } */ /* consolePrint("herdlength: "+QString::number(worldBuilder->herder->wombatHerd.length())); worldBuilder->herder->removeWombatFromHerd(13); consolePrint("herdlength2: "+QString::number(worldBuilder->herder->wombatHerd.length())); worldBuilder->herder->removeWombatFromHerd(19); consolePrint("herdlength2: "+QString::number(worldBuilder->herder->wombatHerd.length()));*/ /* consolePrint("path empty: "+QString::number(worldBuilder->herder->wombatHerd[0]->currentPath.isEmpty())); consolePrint("pathlength: "+QString::number(worldBuilder->herder->wombatHerd[0]->currentPath.length())); if(worldBuilder->herder->wombatHerd[0]->currentPath.length()>0){ consolePrint("firstpos: "+QString::number(worldBuilder->herder->wombatHerd[0]->currentPath.value(0).pos.x())+","+QString::number(worldBuilder->herder->wombatHerd[0]->currentPath.value(0).pos.y())); }*/ //Put wombat to sleep // int wombatIdd = worldBuilder->herder->wombatHerd[0]->wombatId; //int wombatIndex = worldBuilder->registry->getWombatIndex(wombatIdd); // worldBuilder->registry->wombats[wombatIndex].rested = 10; //worldBuilder->registry->displayStorageBuffer(0); //int hej = worldBuilder->getTileType(QPoint(-2,-2),false); // consolePrint("tileType: "+QString::number(hej)); //worldBuilder->herder->removeAllWombatsFromHerd(); } void Worker::fromControllerWithParameters(QPoint pos) { //For debugging //worldBuilder->world->getTile(pos); consolePrint("tile position: "+QString::number(pos.x())+","+QString::number(pos.y())); QPoint chunkPosition = worldBuilder->qPointDivisionWithFloor(pos,QPoint(32,32)); consolePrint("chunk position: "+QString::number(chunkPosition.x())+","+QString::number(chunkPosition.y())); } //To WorldBuilder void Worker::startUpdate(QPoint viewPosition, bool underground) { worldBuilder->prepareToUpdateTiles(viewPosition, underground); } void Worker::updateBackgroundSize(QSize backgroundSize, bool underground) { worldBuilder->imagePainter->updateBackgroundSize(backgroundSize, underground); } void Worker::changeTerrain(QPoint pos, Terrain terrain, int burrowId, bool update) { worldBuilder->changeTerrain(pos, terrain, burrowId, update); } void Worker::addOverlay(QPoint pos, Overlay overlay, int variation){ worldBuilder->addOverlayToTile(pos, overlay, variation); } void Worker::quitGame(QPoint viewPosition){ worldBuilder->quitGame(viewPosition); } //To Registry void Worker::prepareWombatInfoForDisplay(int wombatId){ worldBuilder->registry->prepareWombatInfoForDisplay(wombatId); } void Worker::prepareTileInfoForDisplay(QPoint pos){ worldBuilder->registry->prepareTileInfoForDisplay(pos); } void Worker::possess(int wombatId, QPoint viewPosition, QPoint moved, bool underground, qreal rotation){ worldBuilder->registry->possess(wombatId, viewPosition, moved, underground, rotation); } void Worker::scrollToTargetPosDone(){ worldBuilder->registry->scrollToTargetPosDone(); } void Worker::setSelectedWombatInRegistryUnderground(bool b){ worldBuilder->registry->setSelectedWombatInRegistryUnderground(b); } void Worker::getRandomBurrowName(){ QString burrowName = worldBuilder->registry->getRandomBurrowName(); emit s_returnRandomBurrowName(burrowName); } void Worker::createBurrow(QPoint pos, QString burrowName){ worldBuilder->registry->createBurrow(pos, burrowName); } void Worker::prepareBurrowListForDisplay(int selectedBurrowId){ worldBuilder->registry->prepareBurrowListForDisplay(selectedBurrowId); } void Worker::changeHomeBurrow(QPoint pos){ worldBuilder->registry->changeHomeBurrow(pos); } void Worker::getBurrowName(QPoint pos){ QString burrowName = worldBuilder->registry->getBurrowName(pos); setLocationText(burrowName); } void Worker::addPosToBurrow(QPoint posBurrow, QPoint newPos){ worldBuilder->registry->addPosToBurrow(posBurrow,newPos); } void Worker::getRandomWombatIdForPossess(){ int wombatId = worldBuilder->registry->getRandomWombatIdForPossess(); emit s_returnRandomWombatIdForPossess(wombatId); } void Worker::claimResource(QPoint pos, TileType tileType){ worldBuilder->registry->claimResource(pos,tileType); } void Worker::getWombatInventory(int wombatId){ const QVector<InventoryItem> &inventory = worldBuilder->registry->getWombatInventory(wombatId); int selectedWombat = worldBuilder->registry->selectedWombat; emit s_returnWombatInventory(inventory,selectedWombat); } void Worker::getStorageInventory(int burrowId, int storageId){ int burrowIndex = worldBuilder->registry->getBurrowIndex(burrowId); int storageIndex = worldBuilder->registry->getStorageIndex(burrowIndex,storageId); const QVector<InventoryItem> &inventory = worldBuilder->registry->getStorageInventory(burrowIndex,storageIndex); //Calculate how full the storage is int tilesCount = worldBuilder->registry->burrows[burrowIndex].storages[storageIndex].allTiles.length(); int totalSize = gStorageSize*tilesCount; int usedSize = 0; for (int j=0;j<tilesCount;j++){ for (int k=0;k<worldBuilder->registry->burrows[burrowIndex].storages[storageIndex].allTiles[j].inventory.length();k++){ usedSize += global->getItemSize(worldBuilder->registry->burrows[burrowIndex].storages[storageIndex].allTiles[j].inventory.value(k)); } } int percentageFull = ((double)usedSize/(double)totalSize)*100; emit s_returnStorageInventory(inventory,percentageFull); } void Worker::addBuilding(QPoint pos,TileType buildingType,int variation){ //Temp fix Overlay building; if (buildingType == Storage){ building = Overlay_Storage; }else if(buildingType == Nest){ building = Overlay_Nest; } // worldBuilder->registry->addBuilding(pos,building,variation); } void Worker::moveItemFromWombat(InventoryItem item, int wombatId, int burrowId, int storageId, QPoint draggedLabelPos){ worldBuilder->registry->moveItemFromWombatToStorage(item, wombatId, burrowId, storageId, draggedLabelPos); } void Worker::moveItemFromStorage(InventoryItem item, int wombatId, int burrowId, int storageId, QPoint draggedLabelPos){ worldBuilder->registry->moveItemFromStorageToWombat(item, wombatId, burrowId, storageId, draggedLabelPos); } void Worker::setWInventoryWidgetData(bool wInventoryWidgetOpen, int wombatId){ worldBuilder->registry->setWInventoryWidgetData(wInventoryWidgetOpen, wombatId); } void Worker::setStorageWidgetData(bool storageWidgetOpen, int storageId){ worldBuilder->registry->setStorageWidgetData(storageWidgetOpen,storageId); } void Worker::prepareStorageInfoForShowStorageWidget(QPoint pos){ worldBuilder->registry->prepareStorageInfoForShowStorageWidget(pos); } void Worker::setInfoBoxOpen(bool b){ worldBuilder->registry->setInfoBoxOpen(b); } void Worker::findPathDebug(PathPoint startPos, PathPoint endPos){ //Print path for (int i=0;i<worldBuilder->registry->visited.length();i++){ if(worldBuilder->registry->visited.value(i).underground){ worldBuilder->removeOverlayFromTileUnderground(worldBuilder->registry->visited.value(i).pos,Overlay_Cross,1); }else{ worldBuilder->removeOverlayFromTile(worldBuilder->registry->visited.value(i).pos,Overlay_Cross,1); } } consolePrint("hej"); worldBuilder->registry->findPath(startPos,endPos); } void Worker::removeItemFromWombatInventory(int wombatId, InventoryItem item){ worldBuilder->registry->addItemToWombatInventory(wombatId, item.resource, -item.amount); } void Worker::removeItemFromStorage(int burrowId, int storageId, InventoryItem item){ worldBuilder->registry->removeItemFromStorageOverload(burrowId, storageId, item); } void Worker::addTunnelsToBurrow(int burrowId, QVector<QPoint> startPos){ worldBuilder->registry->addTunnelsToBurrow(burrowId, startPos); } void Worker::showOwner(int burrowId){ worldBuilder->registry->showOwner(burrowId); } void Worker::hideOwner(int burrowId){ worldBuilder->registry->hideOwner(burrowId); } void Worker::getNameWombatId(int wombatId){ QString name = "None found"; for (int i=0;i<worldBuilder->registry->wombats.length();i++){ if(wombatId = worldBuilder->registry->wombats.value(i).id){ name = worldBuilder->registry->wombats.value(i).name; break; } } consolePrint("wombatId "+QString::number(wombatId)+"= name:"+name); } void Worker::printAllWombatsToConsole(){ worldBuilder->registry->printAllWombatsToConsole(); } void Worker::collectResource(QPoint pos, TileType tileType){ worldBuilder->registry->collectResource(pos,tileType); } //To Herder void Worker::taunt(){ worldBuilder->herder->taunt(); } //To Herdmember void Worker::setMovingInOpenGl(int wombatId, bool b){ int index = None; for (int i=0;i<worldBuilder->herder->wombatHerd.length();i++){ if(worldBuilder->herder->wombatHerd.value(i)->wombatId == wombatId){ index = i; break; } } if(index!=None){ worldBuilder->herder->wombatHerd[index]->setMovingInOpenGl(b); } }
[ "tjiitjo@yahoo.com" ]
tjiitjo@yahoo.com
0d8d3ecb45b9710a637907b2590b68bf7b3e0092
1596b3e365d5169e6b0590a4904fb5f3a71ca2fc
/VideoServer/libs/unimrcp/platforms/umc/src/umcconsole.cpp
3165854082ea863275fefd530c7d4c05dc412247
[ "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-public-domain", "FSFUL", "MIT" ]
permissive
zengfanmao/mpds
7be4bc35be28b37b475ee0250236cb7450327ba6
c2bba464eaddc9ec70604a8614d84c5334461e8e
refs/heads/master
2022-12-11T08:29:52.181440
2020-01-16T08:49:09
2020-01-16T08:49:09
234,209,365
0
0
MIT
2022-12-08T02:39:45
2020-01-16T01:36:39
C
UTF-8
C++
false
false
8,229
cpp
/* * Copyright 2008-2014 Arsen Chaloyan * * 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. * * $Id: umcconsole.cpp 2204 2014-10-31 01:01:42Z achaloyan@gmail.com $ */ #include <stdio.h> #include <stdlib.h> #include <apr_getopt.h> #include "umcconsole.h" #include "umcframework.h" #include "apt_pool.h" #include "uni_version.h" UmcConsole::UmcConsole() : m_pFramework(NULL) { m_pFramework = new UmcFramework; } UmcConsole::~UmcConsole() { delete m_pFramework; } bool UmcConsole::Run(int argc, const char * const *argv) { apr_pool_t* pool = NULL; apt_dir_layout_t* pDirLayout = NULL; const char *logConfPath; /* APR global initialization */ if(apr_initialize() != APR_SUCCESS) { apr_terminate(); return false; } /* create APR pool */ pool = apt_pool_create(); if(!pool) { apr_terminate(); return false; } /* load options */ if(!LoadOptions(argc,argv,pool)) { apr_pool_destroy(pool); apr_terminate(); return false; } if(m_Options.m_DirLayoutConf) { /* create and load directories layout from the configuration file */ pDirLayout = apt_dir_layout_create(pool); if(pDirLayout) apt_dir_layout_load(pDirLayout,m_Options.m_DirLayoutConf,pool); } else { /* create default directories layout */ pDirLayout = apt_default_dir_layout_create(m_Options.m_RootDirPath,pool); } if(!pDirLayout) { printf("Failed to Create Directories Layout\n"); apr_pool_destroy(pool); apr_terminate(); return false; } /* get path to logger configuration file */ logConfPath = apt_confdir_filepath_get(pDirLayout,"logger.xml",pool); /* create and load singleton logger */ apt_log_instance_load(logConfPath,pool); if(m_Options.m_LogPriority) { /* override the log priority, if specified in command line */ apt_log_priority_set((apt_log_priority_e)atoi(m_Options.m_LogPriority)); } if(m_Options.m_LogOutput) { /* override the log output mode, if specified in command line */ apt_log_output_mode_set((apt_log_output_e)atoi(m_Options.m_LogOutput)); } if(apt_log_output_mode_check(APT_LOG_OUTPUT_FILE) == TRUE) { /* open the log file */ const char *logDirPath = apt_dir_layout_path_get(pDirLayout,APT_LAYOUT_LOG_DIR); apt_log_file_open(logDirPath,"unimrcpclient",MAX_LOG_FILE_SIZE,MAX_LOG_FILE_COUNT,FALSE,pool); } /* create demo framework */ if(m_pFramework->Create(pDirLayout,pool)) { /* run command line */ RunCmdLine(); /* destroy demo framework */ m_pFramework->Destroy(); } /* destroy singleton logger */ apt_log_instance_destroy(); /* destroy APR pool */ apr_pool_destroy(pool); /* APR global termination */ apr_terminate(); return true; } bool UmcConsole::ProcessCmdLine(char* pCmdLine) { bool running = true; char *name; char *last; name = apr_strtok(pCmdLine, " ", &last); if(strcasecmp(name,"run") == 0) { char* pScenarioName = apr_strtok(NULL, " ", &last); if(pScenarioName) { const char* pProfileName = apr_strtok(NULL, " ", &last); if(!pProfileName) { pProfileName = "uni2"; } m_pFramework->RunSession(pScenarioName,pProfileName); } } else if(strcasecmp(name,"kill") == 0) { char* pID = apr_strtok(NULL, " ", &last); if(pID) { m_pFramework->KillSession(pID); } } else if(strcasecmp(name,"stop") == 0) { char* pID = apr_strtok(NULL, " ", &last); if(pID) { m_pFramework->StopSession(pID); } } else if(strcasecmp(name,"show") == 0) { char* pWhat = apr_strtok(NULL, " ", &last); if(pWhat) { if(strcasecmp(pWhat,"sessions") == 0) m_pFramework->ShowSessions(); else if(strcasecmp(pWhat,"scenarios") == 0) m_pFramework->ShowScenarios(); } } else if(strcasecmp(name,"loglevel") == 0) { char* pPriority = apr_strtok(NULL, " ", &last); if(pPriority) { apt_log_priority_set((apt_log_priority_e)atol(pPriority)); } } else if(strcasecmp(name,"exit") == 0 || strcmp(name,"quit") == 0) { running = false; } else if(strcasecmp(name,"help") == 0) { printf("usage:\n" "\n- run [scenario] [profile] (run new session)\n" " scenario is one of 'synth', 'recog', ... (use 'show scenarios')\n" " profile is one of 'uni2', 'uni1', ... (see unimrcpclient.xml)\n" "\n examples: \n" " run synth\n" " run recog\n" " run synth uni1\n" " run recog uni1\n" "\n- kill [id] (kill session)\n" " id is a session identifier: 1, 2, ... (use 'show sessions')\n" "\n example: \n" " kill 1\n" "\n- show [what] (show either available scenarios or in-progress sessions)\n" "\n examples: \n" " show scenarios\n" " show sessions\n" "\n- loglevel [level] (set loglevel, one of 0,1...7)\n" "\n- quit, exit\n"); } else { printf("unknown command: %s (input help for usage)\n",name); } return running; } bool UmcConsole::RunCmdLine() { apt_bool_t running = true; char cmdline[1024]; apr_size_t i; do { printf(">"); memset(&cmdline, 0, sizeof(cmdline)); for(i = 0; i < sizeof(cmdline); i++) { cmdline[i] = (char) getchar(); if(cmdline[i] == '\n') { cmdline[i] = '\0'; break; } } if(*cmdline) { running = ProcessCmdLine(cmdline); } } while(running != 0); return true; } void UmcConsole::Usage() { printf( "\n" " * "UNI_COPYRIGHT"\n" " *\n" UNI_LICENSE"\n" "\n" "Usage:\n" "\n" " umc [options]\n" "\n" " Available options:\n" "\n" " -r [--root-dir] path : Set the path to the project root directory.\n" "\n" " -c [--dir-layout] path : Set the path to the dir layout config file.\n" " (takes the precedence over --root-dir option)\n" "\n" " -l [--log-prio] priority : Set the log priority.\n" " (0-emergency, ..., 7-debug)\n" "\n" " -o [--log-output] mode : Set the log output mode.\n" " (0-none, 1-console only, 2-file only, 3-both)\n" "\n" " -v [--version] : Show the version.\n" "\n" " -h [--help] : Show the help.\n" "\n"); } bool UmcConsole::LoadOptions(int argc, const char * const *argv, apr_pool_t *pool) { apr_status_t rv; apr_getopt_t* opt = NULL; int optch; const char* optarg; const apr_getopt_option_t opt_option[] = { /* long-option, short-option, has-arg flag, description */ { "root-dir", 'r', TRUE, "path to root dir" }, /* -r arg or --root-dir arg */ { "dir-layout", 'c', TRUE, "path to dir layout conf" }, /* -c arg or --dir-layout arg */ { "log-prio", 'l', TRUE, "log priority" }, /* -l arg or --log-prio arg */ { "log-output", 'o', TRUE, "log output mode" }, /* -o arg or --log-output arg */ { "version", 'v', FALSE, "show version" }, /* -v or --version */ { "help", 'h', FALSE, "show help" }, /* -h or --help */ { NULL, 0, 0, NULL }, /* end */ }; rv = apr_getopt_init(&opt, pool , argc, argv); if(rv != APR_SUCCESS) return false; while((rv = apr_getopt_long(opt, opt_option, &optch, &optarg)) == APR_SUCCESS) { switch(optch) { case 'r': m_Options.m_RootDirPath = optarg; break; case 'c': m_Options.m_DirLayoutConf = optarg; break; case 'l': if(optarg) m_Options.m_LogPriority = optarg; break; case 'o': if(optarg) m_Options.m_LogOutput = optarg; break; case 'v': printf(UNI_VERSION_STRING); return FALSE; case 'h': Usage(); return FALSE; } } if(rv != APR_EOF) { Usage(); return false; } return true; }
[ "zengfan007@126.com" ]
zengfan007@126.com
4b41e25211f3f3a10f428e50d706f21e73befb70
b18bb35192ba2e93685f754763872350fe2afbd5
/9_2(线性群体)/9_4(Array).cpp
affd027a7f9d5fbea2eef35e3a8be4bb5fe9aa51
[]
no_license
Shawn070/CPP
4c890a5882af6aa190f6f30e42ccfa17c5109fb9
942096a9c78820987384df9ec0048b6fc552c06e
refs/heads/master
2021-01-20T00:15:57.332018
2019-04-04T06:48:52
2019-04-04T06:48:52
101,275,015
0
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
// 9_4.cpp #include<iostream> #include<iomanip> #include "Array.h" using namespace std; int main(){ Array<int>a(10); // 用来存放质数的数组,初始状态有10个元素 int count=0; int n; cout<<"Enter a value>=2 as upper limit for prime numbers: "; cin>>n; for(int i=2; i<=n; i++){ // 检查i是否能被比它小的质数整除 bool isPrime=true; for(int j=0; j<count; j++) if(i%a[j]==0){ isPrime=false; break; } // 把i写入质数表中 if(isPrime){ // 如果质数表满了,将其空间加倍 if(count==a.getSize()) a.resize(count * 2); a[count++]=i; } } for(int i=0; i<count; i++) // 输出质数 cout<<setw(8)<<a[i]; cout<<endl; return 0; } /* ouput: Enter a value>=2 as upper limit for prime numbers: 9 2 3 5 7 */
[ "307882919@qq.com" ]
307882919@qq.com
bf03c52ee9fdcb59d16c035ace9c2fad2efc3aa7
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/xray/input/gamepad.h
ba2784871a791827764176f6ce150d57fff70ace
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
1,731
h
//////////////////////////////////////////////////////////////////////////// // Created : 21.11.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #ifndef XRAY_INPUT_CONTROLLER_H_INCLUDED #define XRAY_INPUT_CONTROLLER_H_INCLUDED namespace xray { namespace input { enum enum_gamepad_action{ gp_key_down, gp_key_up, gp_key_hold }; enum gamepad_button { gamepad_dpad_up = u16( 0x0001 ), gamepad_dpad_down = u16( 0x0002 ), gamepad_dpad_left = u16( 0x0004 ), gamepad_dpad_right = u16( 0x0008 ), gamepad_start = u16( 0x0010 ), gamepad_back = u16( 0x0020 ), gamepad_left_thumb = u16( 0x0040 ), gamepad_right_thumb = u16( 0x0080 ), gamepad_left_shoulder = u16( 0x0100 ), gamepad_right_shoulder = u16( 0x0200 ), gamepad_bigbutton = u16( 0x0800 ), gamepad_a = u16( 0x1000 ), gamepad_b = u16( 0x2000 ), gamepad_x = u16( 0x4000 ), gamepad_y = u16( 0x8000 ), }; // enum gamepad_buttons enum gamepad_vibrators { gamepad_vibrator_left, gamepad_vibrator_right, }; // enum gamepad_vibrators struct XRAY_NOVTABLE gamepad { public: struct state { math::float2 left_thumb_stick; math::float2 right_thumb_stick; float left_trigger; float right_trigger; gamepad_button buttons; }; // struct state public: virtual state const& get_state ( ) const = 0; virtual float get_vibration ( gamepad_vibrators vibrator ) const = 0; virtual void set_vibration ( gamepad_vibrators vibrator, float value ) = 0; protected: XRAY_DECLARE_PURE_VIRTUAL_DESTRUCTOR( gamepad ) }; // class handler } // namespace input } // namespace xray #endif // #ifndef XRAY_INPUT_CONTROLLER_H_INCLUDED
[ "youalexandrov@icloud.com" ]
youalexandrov@icloud.com
23ada58cfe1bc59ff54786b7541f6a2269e71522
ddc7ed6ca7e543f5887b800ca297768652e96e82
/protected.cpp
edc846ae48f38f7d1d716c6829c4faf3f8f22733
[]
no_license
iversongit/20160315
416a7ba8e4dee718fbd3f170cec3202e4b9b40ce
337bd4cf1f22cda81f2f49d8a11adc0ad4872d6c
refs/heads/master
2021-01-10T10:27:24.962179
2016-03-15T16:21:55
2016-03-15T16:21:55
53,936,779
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
/// /// @file protected.cpp /// @iverson (1564329410@qq.com) /// @date 2016-03-15 04:33:07 /// #include <iostream> using std::cout; using std::endl; class Base{ public: void display(){ cout<<"_x --> "<<_x<<endl; } protected: //这是另一种形式的抽象类 Base(int x) : _x(x) { cout<<"Base(int)"<<endl; } private: int _x; }; class Child : public Base{ public: Child(int ix) :Base(ix) { cout<<"Child(int)"<<endl; } }; int main(void){ //无法直接创建Base的实例,只能通过派生类去创建实例 Child c(99); c.display(); return 0; }
[ "1564329410@qq.com" ]
1564329410@qq.com
4966e4e2475b3826005a4f07e493b053c9ec0a6b
f36ad3bcb527ae00973fbb93a98f8b51e54d0277
/UVa/Volume 1/146 - ID Codes.cpp
2fee399de95a5f80bd6ca5c8194c8125dac4441d
[]
no_license
ianyong/competitive-programming
739a1a6e3c353707caa23697c580e601c72f8686
d0dd5d126cdf424715b51442332ce141a1e3a264
refs/heads/master
2022-08-27T06:37:38.822045
2022-08-19T09:16:32
2022-08-19T09:16:32
175,630,952
0
0
null
null
null
null
UTF-8
C++
false
false
333
cpp
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; char code[51]; int main() { while (true) { scanf("%s", code); if (strcmp(code, "#") == 0) { break; } next_permutation(code, code + strlen(code)) ? printf("%s\n", code) : printf("No Successor\n"); } }
[ "ianyongyc@gmail.com" ]
ianyongyc@gmail.com
6941ecea0b4d5b64f8ec7085a7b8659e0114c479
f4e17640afef6d1b4d4a85f583a90e37f705dbd5
/B2G/gecko/content/html/content/src/nsHTMLTableSectionElement.cpp
e42cae49bfafb05407ba3acf421f33b9999a30d8
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
wilebeast/FireFox-OS
d370362916f0c5a5408fa08285dbf4779f8b5eb3
43067f28711d78c429a1d6d58c77130f6899135f
refs/heads/master
2016-09-05T22:06:54.838558
2013-09-03T13:49:21
2013-09-03T13:49:21
12,572,236
4
3
null
null
null
null
UTF-8
C++
false
false
9,297
cpp
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "mozilla/Util.h" #include "nsIDOMHTMLTableSectionElem.h" #include "nsIDOMEventTarget.h" #include "nsMappedAttributes.h" #include "nsGenericHTMLElement.h" #include "nsAttrValueInlines.h" #include "nsGkAtoms.h" #include "nsHTMLParts.h" #include "nsStyleConsts.h" #include "nsContentList.h" #include "nsRuleData.h" #include "nsError.h" #include "nsContentUtils.h" using namespace mozilla; // you will see the phrases "rowgroup" and "section" used interchangably class nsHTMLTableSectionElement : public nsGenericHTMLElement, public nsIDOMHTMLTableSectionElement { public: nsHTMLTableSectionElement(already_AddRefed<nsINodeInfo> aNodeInfo); // nsISupports NS_DECL_ISUPPORTS_INHERITED // nsIDOMNode NS_FORWARD_NSIDOMNODE(nsGenericHTMLElement::) // nsIDOMElement NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLElement::) // nsIDOMHTMLElement NS_FORWARD_NSIDOMHTMLELEMENT(nsGenericHTMLElement::) // nsIDOMHTMLTableSectionElement NS_DECL_NSIDOMHTMLTABLESECTIONELEMENT virtual bool ParseAttribute(int32_t aNamespaceID, nsIAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult); virtual nsMapRuleToAttributesFunc GetAttributeMappingFunction() const; NS_IMETHOD_(bool) IsAttributeMapped(const nsIAtom* aAttribute) const; virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const; NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED_NO_UNLINK(nsHTMLTableSectionElement, nsGenericHTMLElement) virtual nsXPCClassInfo* GetClassInfo(); virtual nsIDOMNode* AsDOMNode() { return this; } protected: nsRefPtr<nsContentList> mRows; }; NS_IMPL_NS_NEW_HTML_ELEMENT(TableSection) nsHTMLTableSectionElement::nsHTMLTableSectionElement(already_AddRefed<nsINodeInfo> aNodeInfo) : nsGenericHTMLElement(aNodeInfo) { } NS_IMPL_CYCLE_COLLECTION_CLASS(nsHTMLTableSectionElement) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsHTMLTableSectionElement, nsGenericHTMLElement) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mRows, nsIDOMNodeList) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_ADDREF_INHERITED(nsHTMLTableSectionElement, nsGenericElement) NS_IMPL_RELEASE_INHERITED(nsHTMLTableSectionElement, nsGenericElement) DOMCI_NODE_DATA(HTMLTableSectionElement, nsHTMLTableSectionElement) // QueryInterface implementation for nsHTMLTableSectionElement NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(nsHTMLTableSectionElement) NS_HTML_CONTENT_INTERFACE_TABLE1(nsHTMLTableSectionElement, nsIDOMHTMLTableSectionElement) NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLTableSectionElement, nsGenericHTMLElement) NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLTableSectionElement) NS_IMPL_ELEMENT_CLONE(nsHTMLTableSectionElement) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, Align, align) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, VAlign, valign) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, Ch, _char) NS_IMPL_STRING_ATTR(nsHTMLTableSectionElement, ChOff, charoff) NS_IMETHODIMP nsHTMLTableSectionElement::GetRows(nsIDOMHTMLCollection** aValue) { if (!mRows) { mRows = new nsContentList(this, mNodeInfo->NamespaceID(), nsGkAtoms::tr, nsGkAtoms::tr, false); } NS_ADDREF(*aValue = mRows); return NS_OK; } NS_IMETHODIMP nsHTMLTableSectionElement::InsertRow(int32_t aIndex, nsIDOMHTMLElement** aValue) { *aValue = nullptr; if (aIndex < -1) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } nsCOMPtr<nsIDOMHTMLCollection> rows; GetRows(getter_AddRefs(rows)); uint32_t rowCount; rows->GetLength(&rowCount); if (aIndex > (int32_t)rowCount) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } bool doInsert = (aIndex < int32_t(rowCount)) && (aIndex != -1); // create the row nsCOMPtr<nsINodeInfo> nodeInfo; nsContentUtils::NameChanged(mNodeInfo, nsGkAtoms::tr, getter_AddRefs(nodeInfo)); nsCOMPtr<nsIContent> rowContent = NS_NewHTMLTableRowElement(nodeInfo.forget()); if (!rowContent) { return NS_ERROR_OUT_OF_MEMORY; } nsCOMPtr<nsIDOMNode> rowNode(do_QueryInterface(rowContent)); NS_ASSERTION(rowNode, "Should implement nsIDOMNode!"); nsCOMPtr<nsIDOMNode> retChild; nsresult rv; if (doInsert) { nsCOMPtr<nsIDOMNode> refRow; rows->Item(aIndex, getter_AddRefs(refRow)); rv = InsertBefore(rowNode, refRow, getter_AddRefs(retChild)); NS_ENSURE_SUCCESS(rv, rv); } else { rv = AppendChild(rowNode, getter_AddRefs(retChild)); NS_ENSURE_SUCCESS(rv, rv); } if (retChild) { CallQueryInterface(retChild, aValue); } return NS_OK; } NS_IMETHODIMP nsHTMLTableSectionElement::DeleteRow(int32_t aValue) { if (aValue < -1) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } nsCOMPtr<nsIDOMHTMLCollection> rows; GetRows(getter_AddRefs(rows)); nsresult rv; uint32_t refIndex; if (aValue == -1) { rv = rows->GetLength(&refIndex); NS_ENSURE_SUCCESS(rv, rv); if (refIndex == 0) { return NS_OK; } --refIndex; } else { refIndex = (uint32_t)aValue; } nsCOMPtr<nsIDOMNode> row; rv = rows->Item(refIndex, getter_AddRefs(row)); NS_ENSURE_SUCCESS(rv, rv); if (!row) { return NS_ERROR_DOM_INDEX_SIZE_ERR; } nsCOMPtr<nsIDOMNode> retChild; return RemoveChild(row, getter_AddRefs(retChild)); } bool nsHTMLTableSectionElement::ParseAttribute(int32_t aNamespaceID, nsIAtom* aAttribute, const nsAString& aValue, nsAttrValue& aResult) { if (aNamespaceID == kNameSpaceID_None) { /* ignore these attributes, stored simply as strings ch */ if (aAttribute == nsGkAtoms::charoff) { return aResult.ParseIntWithBounds(aValue, 0); } if (aAttribute == nsGkAtoms::height) { return aResult.ParseSpecialIntValue(aValue); } if (aAttribute == nsGkAtoms::align) { return ParseTableCellHAlignValue(aValue, aResult); } if (aAttribute == nsGkAtoms::bgcolor) { return aResult.ParseColor(aValue); } if (aAttribute == nsGkAtoms::valign) { return ParseTableVAlignValue(aValue, aResult); } } return nsGenericHTMLElement::ParseBackgroundAttribute(aNamespaceID, aAttribute, aValue, aResult) || nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue, aResult); } static void MapAttributesIntoRule(const nsMappedAttributes* aAttributes, nsRuleData* aData) { if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Position)) { // height: value nsCSSValue* height = aData->ValueForHeight(); if (height->GetUnit() == eCSSUnit_Null) { const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::height); if (value && value->Type() == nsAttrValue::eInteger) height->SetFloatValue((float)value->GetIntegerValue(), eCSSUnit_Pixel); } } if (aData->mSIDs & NS_STYLE_INHERIT_BIT(Text)) { nsCSSValue* textAlign = aData->ValueForTextAlign(); if (textAlign->GetUnit() == eCSSUnit_Null) { // align: enum const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::align); if (value && value->Type() == nsAttrValue::eEnum) textAlign->SetIntValue(value->GetEnumValue(), eCSSUnit_Enumerated); } } if (aData->mSIDs & NS_STYLE_INHERIT_BIT(TextReset)) { nsCSSValue* verticalAlign = aData->ValueForVerticalAlign(); if (verticalAlign->GetUnit() == eCSSUnit_Null) { // valign: enum const nsAttrValue* value = aAttributes->GetAttr(nsGkAtoms::valign); if (value && value->Type() == nsAttrValue::eEnum) verticalAlign->SetIntValue(value->GetEnumValue(), eCSSUnit_Enumerated); } } nsGenericHTMLElement::MapBackgroundAttributesInto(aAttributes, aData); nsGenericHTMLElement::MapCommonAttributesInto(aAttributes, aData); } NS_IMETHODIMP_(bool) nsHTMLTableSectionElement::IsAttributeMapped(const nsIAtom* aAttribute) const { static const MappedAttributeEntry attributes[] = { { &nsGkAtoms::align }, { &nsGkAtoms::valign }, { &nsGkAtoms::height }, { nullptr } }; static const MappedAttributeEntry* const map[] = { attributes, sCommonAttributeMap, sBackgroundAttributeMap, }; return FindAttributeDependence(aAttribute, map); } nsMapRuleToAttributesFunc nsHTMLTableSectionElement::GetAttributeMappingFunction() const { return &MapAttributesIntoRule; }
[ "info@hadrons.me" ]
info@hadrons.me
e6193e9daffca76d38ff5867a3f476eb73173ae4
7c7924348498b1183ed9d1a7a3b4682d4bd0aa1a
/sort algorithms/internal sort/selection/c++/selection.h
28b3040e8b3f3095a9238f15f7f9820d23cfeb41
[ "MIT" ]
permissive
rafaelcn/algorithms
c2877aebe66b3094a59091f7f4fa306453c1346d
feaa976317be7bb32849b528de768dc9ed8b4001
refs/heads/master
2023-07-31T14:18:37.987969
2023-07-11T04:20:33
2023-07-11T04:20:33
102,994,259
0
0
MIT
2018-10-19T00:57:33
2017-09-10T01:00:21
C
UTF-8
C++
false
false
1,460
h
/** MIT License * * Copyright (c) 2017-2018 Rafael C. Nunes * * 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 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 SELECTION_H #define SELECTION_H #include <vector> template <typename T> void selection_sort(std::vector<T> &instance) { T min; for (std::size_t i = 0; i < instance.size()-1; i++) { min = i; for (std::size_t j = i+1; j < instance.size(); j++) { if (instance[min] > instance[j]) { min = j; } } std::swap(instance[min], instance[i]); } } #endif // SELECTION_H
[ "rafaelnunes@engineer.com" ]
rafaelnunes@engineer.com
7428cc4c77807397b73eb2c66a8d09bb067500fc
4210a2eb943c89e1e3339466d72dd45cc333bdde
/lib/src/DJI_API.cpp
8f44c140ea8fd21a04045ad1d0579e1ed346bf2f
[]
no_license
ZKRT/MainBoardHardwareTest
0ff9d01bb09895ce5022114d0d177162031a1911
e32c5f899de409f26f3110d8343e74caa04c337b
refs/heads/master
2021-01-12T05:45:31.823767
2017-03-31T09:17:03
2017-03-31T09:17:04
77,188,312
0
0
null
null
null
null
UTF-8
C++
false
false
23,376
cpp
/** @file DJI_API.cpp * @version 3.1.7 * @date July 1st, 2016 * * @brief * Core API for DJI onboardSDK library * * @copyright 2016 DJI. All right reserved. * */ #include "DJI_API.h" #include <string.h> #include <stdio.h> using namespace DJI; using namespace DJI::onboardSDK; #ifdef USE_ENCRYPT uint8_t DJI::onboardSDK::encrypt = 1; #else uint8_t DJI::onboardSDK::encrypt = 0; #endif // USE_ENCRYPT CoreAPI::CoreAPI(HardDriver *sDevice, Version SDKVersion, bool userCallbackThread, CallBack userRecvCallback, UserData userData) { CallBackHandler handler; handler.callback = userRecvCallback; handler.userData = userData; init(sDevice, handler, userCallbackThread, SDKVersion); } void CoreAPI::init(HardDriver *sDevice, CallBackHandler userRecvCallback, bool userCallbackThread, Version SDKVersion) { serialDevice = sDevice; // serialDevice->init(); seq_num = 0; ackFrameStatus = 11; broadcastFrameStatus = false; filter.recvIndex = 0; filter.reuseCount = 0; filter.reuseIndex = 0; filter.encode = 0; broadcastCallback.callback = 0; broadcastCallback.userData = 0; fromMobileCallback.callback = 0;//ldl 2016 09 28 fromMobileCallback.userData = 0; hotPointCallback.callback = 0; wayPointCallback.callback = 0; hotPointCallback.userData = 0; wayPointEventCallback.callback = 0; wayPointEventCallback.userData = 0; wayPointCallback.userData = 0; followCallback.callback = 0; followCallback.userData = 0; missionCallback.callback = 0; missionCallback.userData = 0; recvCallback.callback = userRecvCallback.callback; recvCallback.userData = userRecvCallback.userData; callbackThread = false; hotPointData = false; followData = false; wayPointData = false; callbackThread = userCallbackThread; ack_data = 99; versionData.version = SDKVersion; //! @todo simplify code above memset((unsigned char *)&broadcastData, 0, sizeof(broadcastData)); setup(); } CoreAPI::CoreAPI(HardDriver *sDevice, Version SDKVersion, CallBackHandler userRecvCallback, bool userCallbackThread) { init(sDevice, userRecvCallback, userCallbackThread, SDKVersion); getSDKVersion(); } void CoreAPI::send(unsigned char session, unsigned char is_enc, CMD_SET cmdSet, unsigned char cmdID, void *pdata, int len, CallBack ackCallback, int timeout, int retry) { Command param; unsigned char *ptemp = (unsigned char *)encodeSendData; *ptemp++ = cmdSet; *ptemp++ = cmdID; memcpy(encodeSendData + SET_CMD_SIZE, pdata, len); param.handler = ackCallback; param.sessionMode = session; param.length = len + SET_CMD_SIZE; param.buf = encodeSendData; param.retry = retry; param.timeout = timeout; param.encrypt = is_enc; param.userData = 0; sendInterface(&param); } void CoreAPI::send(unsigned char session_mode, bool is_enc, CMD_SET cmd_set, unsigned char cmd_id, void *pdata, size_t len, int timeout, int retry_time, CallBack ack_handler, UserData userData) { Command param; unsigned char *ptemp = (unsigned char *)encodeSendData; *ptemp++ = cmd_set; *ptemp++ = cmd_id; memcpy(encodeSendData + SET_CMD_SIZE, pdata, len); param.handler = ack_handler; param.sessionMode = session_mode; param.length = len + SET_CMD_SIZE; param.buf = encodeSendData; param.retry = retry_time; param.timeout = timeout; param.encrypt = is_enc ? 1 : 0; param.userData = userData; sendInterface(&param); } void CoreAPI::send(Command *parameter) { sendInterface(parameter); } void CoreAPI::ack(req_id_t req_id, unsigned char *ackdata, int len) { Ack param; memcpy(encodeACK, ackdata, len); param.sessionID = req_id.session_id; param.seqNum = req_id.sequence_number; param.encrypt = req_id.need_encrypt; param.buf = encodeACK; param.length = len; this->ackInterface(&param); } void CoreAPI::getDroneVersion(CallBack callback, UserData userData) { versionData.version_ack = ACK_COMMON_NO_RESPONSE; versionData.version_crc = 0x0; versionData.version_name[0] = 0; unsigned cmd_timeout = 100; // unit is ms unsigned retry_time = 3; unsigned char cmd_data = 0; send(2, 0, SET_ACTIVATION, CODE_GETVERSION, (unsigned char *)&cmd_data, 1, cmd_timeout, retry_time, callback ? callback : CoreAPI::getDroneVersionCallback, userData); } VersionData CoreAPI::getDroneVersion(int timeout) { versionData.version_ack = ACK_COMMON_NO_RESPONSE; versionData.version_crc = 0x0; versionData.version_name[0] = 0; unsigned cmd_timeout = 100; // unit is ms unsigned retry_time = 3; unsigned char cmd_data = 0; send(2, 0, SET_ACTIVATION, CODE_GETVERSION, (unsigned char *)&cmd_data, 1, cmd_timeout, retry_time, 0, 0); // Wait for end of ACK frame to arrive serialDevice->lockACK(); serialDevice->wait(timeout); serialDevice->freeACK(); // Parse return value versionData.version_ack = version_ack_data[0] + (version_ack_data[1] << 8); version_ack_data += 2; versionData.version_crc = version_ack_data[0] + (version_ack_data[1] << 8) + (version_ack_data[2] << 16) + (version_ack_data[3] << 24); ack_data += 4; if (versionData.version != versionM100_23) { memcpy(versionData.version_ID, version_ack_data, 11); ack_data += 11; } memcpy(versionData.version_name, version_ack_data, 32); return versionData; } void CoreAPI::activate(ActivateData *data, CallBack callback, UserData userData) { data->version = versionData.version; accountData = *data; accountData.reserved = 2; for (int i = 0; i < 32; ++i) accountData.iosID[i] = '0'; //! @note for ios verification API_LOG(serialDevice, DEBUG_LOG, "version 0x%X/n", versionData.version); API_LOG(serialDevice, DEBUG_LOG, "%.32s", accountData.iosID); send(2, 0, SET_ACTIVATION, CODE_ACTIVATE, (unsigned char *)&accountData, sizeof(accountData) - sizeof(char *), 1000, 3, callback ? callback : CoreAPI::activateCallback, userData); } unsigned short CoreAPI::activate(ActivateData *data, int timeout) { data->version = versionData.version; accountData = *data; accountData.reserved = 2; for (int i = 0; i < 32; ++i) accountData.iosID[i] = '0'; //! @note for ios verification API_LOG(serialDevice, DEBUG_LOG, "version 0x%X/n", versionData.version); API_LOG(serialDevice, DEBUG_LOG, "%.32s", accountData.iosID); send(2, 0, SET_ACTIVATION, CODE_ACTIVATE, (unsigned char *)&accountData, sizeof(accountData) - sizeof(char *), 1000, 3, 0, 0); // Wait for end of ACK frame to arrive serialDevice->lockACK(); serialDevice->wait(timeout); serialDevice->freeACK(); ack_data = missionACKUnion.simpleACK; if(ack_data == ACK_ACTIVE_SUCCESS && accountData.encKey) setKey(accountData.encKey); return ack_data; } void CoreAPI::sendToMobile(uint8_t *data, uint8_t len, CallBack callback, UserData userData) { if (len > 100) { API_LOG(serialDevice, ERROR_LOG, "Too much data to send"); return; } // printf("sendToMobile!\r\n"); send(0, 0, SET_ACTIVATION, CODE_TOMOBILE, data, len, 500, 1, callback ? callback : CoreAPI::sendToMobileCallback, userData); } void CoreAPI::setBroadcastFreq(uint8_t *dataLenIs16, CallBack callback, UserData userData) { //! @note see also enum BROADCAST_FREQ in DJI_API.h for (int i = 0; i < 16; ++i) { if (versionData.version == versionM100_31) if (i < 12) { dataLenIs16[i] = (dataLenIs16[i] > 5 ? 5 : dataLenIs16[i]); } else dataLenIs16[i] = 0; else { if (i < 14) { dataLenIs16[i] = (dataLenIs16[i] > 5 ? 5 : dataLenIs16[i]); } else dataLenIs16[i] = 0; } } send(2, 0, SET_ACTIVATION, CODE_FREQUENCY, dataLenIs16, 16, 100, 1, callback ? callback : CoreAPI::setFrequencyCallback, userData); } unsigned short CoreAPI::setBroadcastFreq(uint8_t *dataLenIs16, int timeout) { //! @note see also enum BROADCAST_FREQ in DJI_API.h for (int i = 0; i < 16; ++i) { if (versionData.version == versionM100_31) if (i < 12) { dataLenIs16[i] = (dataLenIs16[i] > 5 ? 5 : dataLenIs16[i]); } else dataLenIs16[i] = 0; else { if (i < 14) { dataLenIs16[i] = (dataLenIs16[i] > 5 ? 5 : dataLenIs16[i]); } else dataLenIs16[i] = 0; } } send(2, 0, SET_ACTIVATION, CODE_FREQUENCY, dataLenIs16, 16, 100, 1, 0, 0); // Wait for end of ACK frame to arrive serialDevice->lockACK(); serialDevice->wait(timeout); serialDevice->freeACK(); return missionACKUnion.simpleACK; } void CoreAPI::setBroadcastFreqDefaults() { uint8_t freq[16]; /* Channels definition: * 0 - Timestamp * 1 - Attitude Quaterniouns * 2 - Acceleration * 3 - Velocity (Ground Frame) * 4 - Angular Velocity (Body Frame) * 5 - Position * 6 - Magnetometer * 7 - RC Channels Data * 8 - Gimbal Data * 9 - Flight Status * 10 - Battery Level * 11 - Control Information */ freq[0] = BROADCAST_FREQ_1HZ; freq[1] = BROADCAST_FREQ_10HZ; freq[2] = BROADCAST_FREQ_50HZ; freq[3] = BROADCAST_FREQ_100HZ; freq[4] = BROADCAST_FREQ_50HZ; freq[5] = BROADCAST_FREQ_10HZ; freq[6] = BROADCAST_FREQ_1HZ; freq[7] = BROADCAST_FREQ_10HZ; freq[8] = BROADCAST_FREQ_50HZ; freq[9] = BROADCAST_FREQ_100HZ; freq[10] = BROADCAST_FREQ_50HZ; freq[11] = BROADCAST_FREQ_10HZ; setBroadcastFreq(freq); } void CoreAPI::setBroadcastFreqToZero() { uint8_t freq[16]; /* Channels definition: * 0 - Timestamp * 1 - Attitude Quaterniouns * 2 - Acceleration * 3 - Velocity (Ground Frame) * 4 - Angular Velocity (Body Frame) * 5 - Position * 6 - Magnetometer * 7 - RC Channels Data * 8 - Gimbal Data * 9 - Flight Status * 10 - Battery Level * 11 - Control Information */ freq[0] = BROADCAST_FREQ_1HZ; freq[1] = BROADCAST_FREQ_10HZ; freq[2] = BROADCAST_FREQ_50HZ; freq[3] = BROADCAST_FREQ_100HZ; freq[4] = BROADCAST_FREQ_50HZ; freq[5] = BROADCAST_FREQ_10HZ; freq[6] = BROADCAST_FREQ_1HZ; freq[7] = BROADCAST_FREQ_10HZ; freq[8] = BROADCAST_FREQ_50HZ; freq[9] = BROADCAST_FREQ_100HZ; freq[10] = BROADCAST_FREQ_50HZ; freq[11] = BROADCAST_FREQ_10HZ; setBroadcastFreq(freq); } unsigned short CoreAPI::setBroadcastFreqDefaults(int timeout) { uint8_t freq[16]; /* Channels definition: * 0 - Timestamp * 1 - Attitude Quaterniouns * 2 - Acceleration * 3 - Velocity (Ground Frame) * 4 - Angular Velocity (Body Frame) * 5 - Position * 6 - Magnetometer * 7 - RC Channels Data * 8 - Gimbal Data * 9 - Flight Status * 10 - Battery Level * 11 - Control Information */ freq[0] = BROADCAST_FREQ_1HZ; freq[1] = BROADCAST_FREQ_10HZ; freq[2] = BROADCAST_FREQ_50HZ; freq[3] = BROADCAST_FREQ_100HZ; freq[4] = BROADCAST_FREQ_50HZ; freq[5] = BROADCAST_FREQ_10HZ; freq[6] = BROADCAST_FREQ_1HZ; freq[7] = BROADCAST_FREQ_10HZ; freq[8] = BROADCAST_FREQ_50HZ; freq[9] = BROADCAST_FREQ_100HZ; freq[10] = BROADCAST_FREQ_50HZ; freq[11] = BROADCAST_FREQ_10HZ; return setBroadcastFreq(freq, timeout); } TimeStampData CoreAPI::getTime() const { return broadcastData.timeStamp; } FlightStatus CoreAPI::getFlightStatus() const { return broadcastData.status; } void CoreAPI::setFromMobileCallback(CallBackHandler FromMobileEntrance) { fromMobileCallback = FromMobileEntrance; } ActivateData CoreAPI::getAccountData() const { return accountData; } void CoreAPI::setAccountData(const ActivateData &value) { accountData = value; } void CoreAPI::setHotPointData(bool value) { hotPointData = value; } void CoreAPI::setWayPointData(bool value) { wayPointData = value; } void CoreAPI::setFollowData(bool value) { followData = value; } bool CoreAPI::getHotPointData() const { return hotPointData; } bool CoreAPI::getWayPointData() const { return wayPointData; } bool CoreAPI::getFollowData() const { return followData; } void CoreAPI::setControl(bool enable, CallBack callback, UserData userData) { unsigned char data = enable ? 1 : 0; send(2, DJI::onboardSDK::encrypt, SET_CONTROL, CODE_SETCONTROL, &data, 1, 500, 2, callback ? callback : CoreAPI::setControlCallback, userData); } unsigned short CoreAPI::setControl(bool enable, int timeout) { unsigned char data = enable ? 1 : 0; send(2, DJI::onboardSDK::encrypt, SET_CONTROL, CODE_SETCONTROL, &data, 1, 500, 2, 0, 0); // Wait for end of ACK frame to arrive serialDevice->lockACK(); serialDevice->wait(timeout); serialDevice->freeACK(); return missionACKUnion.simpleACK; } HardDriver *CoreAPI::getDriver() const { return serialDevice; } SimpleACK CoreAPI::getSimpleACK () const { return missionACKUnion.simpleACK; } void CoreAPI::setDriver(HardDriver *sDevice) { serialDevice = sDevice; } void CoreAPI::getDroneVersionCallback(CoreAPI *api, Header *protocolHeader, UserData userData __UNUSED) { unsigned char *ptemp = ((unsigned char *)protocolHeader) + sizeof(Header); api->versionData.version_ack = ptemp[0] + (ptemp[1] << 8); ptemp += 2; api->versionData.version_crc = ptemp[0] + (ptemp[1] << 8) + (ptemp[2] << 16) + (ptemp[3] << 24); ptemp += 4; if (api->versionData.version != versionM100_23) { memcpy(api->versionData.version_ID, ptemp, 11); ptemp += 11; } memcpy(api->versionData.version_name, ptemp, 32); API_LOG(api->serialDevice, STATUS_LOG, "version ack = %d\n", api->versionData.version_ack); API_LOG(api->serialDevice, STATUS_LOG, "version crc = 0x%X\n", api->versionData.version_crc); if (api->versionData.version != versionM100_23) API_LOG(api->serialDevice, STATUS_LOG, "version ID = %.11s\n", api->versionData.version_ID); API_LOG(api->serialDevice, STATUS_LOG, "version name = %.32s\n", api->versionData.version_name); } void CoreAPI::activateCallback(CoreAPI *api, Header *protocolHeader, UserData userData __UNUSED) { unsigned short ack_data; if (protocolHeader->length - EXC_DATA_SIZE <= 2) { memcpy((unsigned char *)&ack_data, ((unsigned char *)protocolHeader) + sizeof(Header), (protocolHeader->length - EXC_DATA_SIZE)); switch (ack_data) { case ACK_ACTIVE_SUCCESS: API_LOG(api->serialDevice, STATUS_LOG, "Activated successfully\n"); if (api->accountData.encKey) api->setKey(api->accountData.encKey); return; case ACK_ACTIVE_NEW_DEVICE: API_LOG(api->serialDevice, STATUS_LOG, "New device, please link DJIGO to your " "remote controller and try again\n"); break; case ACK_ACTIVE_PARAMETER_ERROR: API_LOG(api->serialDevice, ERROR_LOG, "Wrong parameter\n"); break; case ACK_ACTIVE_ENCODE_ERROR: API_LOG(api->serialDevice, ERROR_LOG, "Encode error\n"); break; case ACK_ACTIVE_APP_NOT_CONNECTED: API_LOG(api->serialDevice, ERROR_LOG, "DJIGO not connected\n"); break; case ACK_ACTIVE_NO_INTERNET: API_LOG(api->serialDevice, ERROR_LOG, "DJIGO not " "connected to the internet\n"); break; case ACK_ACTIVE_SERVER_REFUSED: API_LOG(api->serialDevice, ERROR_LOG, "DJI server rejected " "your request, please use your SDK ID\n"); break; case ACK_ACTIVE_ACCESS_LEVEL_ERROR: API_LOG(api->serialDevice, ERROR_LOG, "Wrong SDK permission\n"); break; case ACK_ACTIVE_VERSION_ERROR: API_LOG(api->serialDevice, ERROR_LOG, "SDK version did not match\n"); api->getDroneVersion(); break; default: if (!api->decodeACKStatus(ack_data)) { API_LOG(api->serialDevice, ERROR_LOG, "While calling this function"); } break; } } else { API_LOG(api->serialDevice, ERROR_LOG, "ACK is exception, session id %d,sequence %d\n", protocolHeader->sessionID, protocolHeader->sequenceNumber); } } void CoreAPI::sendToMobileCallback(CoreAPI *api, Header *protocolHeader, UserData userData __UNUSED) { unsigned short ack_data = ACK_COMMON_NO_RESPONSE; if (protocolHeader->length - EXC_DATA_SIZE <= 2) { memcpy((unsigned char *)&ack_data, ((unsigned char *)protocolHeader) + sizeof(Header), (protocolHeader->length - EXC_DATA_SIZE)); if (!api->decodeACKStatus(ack_data)) { API_LOG(api->serialDevice, ERROR_LOG, "While calling this function"); } } else { API_LOG(api->serialDevice, ERROR_LOG, "ACK is exception, session id %d,sequence %d\n", protocolHeader->sessionID, protocolHeader->sequenceNumber); } } //! Mobile Data Transparent Transmission Input Servicing void CoreAPI::parseFromMobileCallback(CoreAPI *api, Header *protocolHeader, UserData userData __UNUSED) { uint16_t mobile_data_id; printf("protocolHeader->length= 0x%x!\r\n",protocolHeader->length); if (protocolHeader->length - EXC_DATA_SIZE <= 4) { printf("RRRRRRRRRRRR!\r\n"); mobile_data_id = *((unsigned char*)protocolHeader + sizeof(Header) + 2); printf("0x %x ",mobile_data_id); switch (mobile_data_id) { case 2: if (obtainControlMobileCallback.callback) { obtainControlMobileCallback.callback(api, protocolHeader, obtainControlMobileCallback.userData); } else { obtainControlMobileCMD = true; } break; case 3: if (releaseControlMobileCallback.callback) { releaseControlMobileCallback.callback(api, protocolHeader, releaseControlMobileCallback.userData); } else { releaseControlMobileCMD = true; } break; case 4: if (activateMobileCallback.callback) { activateMobileCallback.callback(api, protocolHeader, activateMobileCallback.userData); } else { activateMobileCMD = true; } break; case 5: if (armMobileCallback.callback) { armMobileCallback.callback(api, protocolHeader, armMobileCallback.userData); } else { armMobileCMD = true; } break; case 6: if (disArmMobileCallback.callback) { disArmMobileCallback.callback(api, protocolHeader, disArmMobileCallback.userData); } else { disArmMobileCMD = true; } break; case 7: if (takeOffMobileCallback.callback) { takeOffMobileCallback.callback(api, protocolHeader, takeOffMobileCallback.userData); } else { takeOffMobileCMD = true; } break; case 8: if (landingMobileCallback.callback) { landingMobileCallback.callback(api, protocolHeader, landingMobileCallback.userData); } else { landingMobileCMD = true; } break; case 9: if (goHomeMobileCallback.callback) { goHomeMobileCallback.callback(api, protocolHeader, goHomeMobileCallback.userData); } else { goHomeMobileCMD = true; } break; case 10: if (takePhotoMobileCallback.callback) { takePhotoMobileCallback.callback(api, protocolHeader, takePhotoMobileCallback.userData); } else { takePhotoMobileCMD = true; } break; case 11: if (startVideoMobileCallback.callback) { startVideoMobileCallback.callback(api, protocolHeader, startVideoMobileCallback.userData); } else { startVideoMobileCMD = true; } break; case 13: if (stopVideoMobileCallback.callback) { stopVideoMobileCallback.callback(api, protocolHeader, stopVideoMobileCallback.userData); } else { stopVideoMobileCMD = true; } break; //! The next few are only polling based and do not use callbacks. See usage in Linux Sample. case 61: drawCirMobileCMD = true; break; case 62: drawSqrMobileCMD = true; break; case 63: attiCtrlMobileCMD = true; break; case 64: gimbalCtrlMobileCMD = true; break; case 65: wayPointTestMobileCMD = true; break; case 66: localNavTestMobileCMD = true; break; case 67: globalNavTestMobileCMD = true; break; case 68: VRCTestMobileCMD = true; break; } } } void CoreAPI::setFrequencyCallback(CoreAPI *api __UNUSED, Header *protocolHeader, UserData userData __UNUSED) { unsigned short ack_data = ACK_COMMON_NO_RESPONSE; if (protocolHeader->length - EXC_DATA_SIZE <= 2) { memcpy((unsigned char *)&ack_data, ((unsigned char *)protocolHeader) + sizeof(Header), (protocolHeader->length - EXC_DATA_SIZE)); } switch (ack_data) { case 0x0000: API_LOG(api->serialDevice, STATUS_LOG, "Frequency set successfully\n"); break; case 0x0001: API_LOG(api->serialDevice, ERROR_LOG, "Frequency parameter error\n"); break; default: if (!api->decodeACKStatus(ack_data)) { API_LOG(api->serialDevice, ERROR_LOG, "While calling this function\n"); } break; } } Version CoreAPI::getSDKVersion() const { return versionData.version; } SDKFilter CoreAPI::getFilter() const { return filter; } void CoreAPI::setVersion(const Version &value) { versionData.version = value; } void CoreAPI::setControlCallback(CoreAPI *api, Header *protocolHeader, UserData userData __UNUSED) { unsigned short ack_data = ACK_COMMON_NO_RESPONSE; unsigned char data = 0x1; if (protocolHeader->length - EXC_DATA_SIZE <= sizeof(ack_data)) { memcpy((unsigned char *)&ack_data, ((unsigned char *)protocolHeader) + sizeof(Header), (protocolHeader->length - EXC_DATA_SIZE)); } else { API_LOG(api->serialDevice, ERROR_LOG, "ACK is exception, session id %d,sequence %d\n", protocolHeader->sessionID, protocolHeader->sequenceNumber); } switch (ack_data) { case ACK_SETCONTROL_NEED_MODE_F: API_LOG(api->serialDevice, STATUS_LOG, "Obtain control failed, conditions did not " "satisfied"); break; case ACK_SETCONTROL_RELEASE_SUCCESS: API_LOG(api->serialDevice, STATUS_LOG, "Released control successfully\n"); break; case ACK_SETCONTROL_OBTAIN_SUCCESS: API_LOG(api->serialDevice, STATUS_LOG, "Obtained control successfully\n"); break; case ACK_SETCONTROL_OBTAIN_RUNNING: API_LOG(api->serialDevice, STATUS_LOG, "Obtain control running\n"); api->send(2, DJI::onboardSDK::encrypt, SET_CONTROL, CODE_SETCONTROL, &data, 1, 500, 2, CoreAPI::setControlCallback); break; case ACK_SETCONTROL_RELEASE_RUNNING: API_LOG(api->serialDevice, STATUS_LOG, "Release control running\n"); data = 0; api->send(2, DJI::onboardSDK::encrypt, SET_CONTROL, CODE_SETCONTROL, &data, 1, 500, 2, CoreAPI::setControlCallback); break; case ACK_SETCONTROL_IOC: API_LOG(api->serialDevice, STATUS_LOG, "IOC mode opening can not obtain control\n"); break; default: if (!api->decodeACKStatus(ack_data)) { API_LOG(api->serialDevice, ERROR_LOG, "While calling this function"); } break; } }
[ "413899391@qq.com" ]
413899391@qq.com
79eb77ef3565cf95d061b8ca69ad1ea99a2b0cd2
1af49694004c6fbc31deada5618dae37255ce978
/components/page_info/android/connection_info_view_android.cc
b3e1b8ced50455efa48a8a89340600c396dd017d
[ "BSD-3-Clause" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
5,978
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/page_info/android/connection_info_view_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "components/page_info/android/jni_headers/ConnectionInfoView_jni.h" #include "components/page_info/android/page_info_client.h" #include "components/page_info/page_info.h" #include "components/page_info/page_info_delegate.h" #include "components/page_info/page_info_ui_delegate.h" #include "components/security_state/core/security_state.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/ssl_status.h" #include "content/public/browser/web_contents.h" #include "net/cert/x509_certificate.h" #include "ui/base/l10n/l10n_util.h" using base::android::CheckException; using base::android::ConvertUTF16ToJavaString; using base::android::ConvertUTF8ToJavaString; using base::android::GetClass; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; using content::WebContents; // static static jlong JNI_ConnectionInfoView_Init( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& java_web_contents) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(java_web_contents); DCHECK(web_contents); return reinterpret_cast<intptr_t>( new ConnectionInfoViewAndroid(env, obj, web_contents)); } ConnectionInfoViewAndroid::ConnectionInfoViewAndroid( JNIEnv* env, jobject java_page_info_pop, WebContents* web_contents) { page_info_client_ = page_info::GetPageInfoClient(); DCHECK(page_info_client_); // Important to use GetVisibleEntry to match what's showing in the omnibox. content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == nullptr) return; popup_jobject_.Reset(env, java_page_info_pop); presenter_ = std::make_unique<PageInfo>( page_info_client_->CreatePageInfoDelegate(web_contents), web_contents, nav_entry->GetURL()); presenter_->InitializeUiState(this); } ConnectionInfoViewAndroid::~ConnectionInfoViewAndroid() {} void ConnectionInfoViewAndroid::Destroy(JNIEnv* env, const JavaParamRef<jobject>& obj) { delete this; } void ConnectionInfoViewAndroid::ResetCertDecisions( JNIEnv* env, const JavaParamRef<jobject>& obj, const JavaParamRef<jobject>& java_web_contents) { presenter_->OnRevokeSSLErrorBypassButtonPressed(); } void ConnectionInfoViewAndroid::SetIdentityInfo( const IdentityInfo& identity_info) { JNIEnv* env = base::android::AttachCurrentThread(); { int icon_id = page_info_client_->GetJavaResourceId( PageInfoUI::GetIdentityIconID(identity_info.identity_status)); int icon_color_id = page_info_client_->GetJavaResourceId( PageInfoUI::GetIdentityIconColorID(identity_info.identity_status)); // The headline and the certificate dialog link of the site's identity // section is only displayed if the site's identity was verified. If the // site's identity was verified, then the headline contains the organization // name from the provided certificate. If the organization name is not // available than the hostname of the site is used instead. std::string headline; if (identity_info.certificate) { headline = identity_info.site_identity; } ScopedJavaLocalRef<jstring> description = ConvertUTF8ToJavaString( env, identity_info.identity_status_description_android); base::string16 certificate_label; // Only show the certificate viewer link if the connection actually used a // certificate. if (identity_info.identity_status != PageInfo::SITE_IDENTITY_STATUS_NO_CERT) { certificate_label = l10n_util::GetStringUTF16(IDS_PAGE_INFO_CERT_INFO_BUTTON); } Java_ConnectionInfoView_addCertificateSection( env, popup_jobject_, icon_id, ConvertUTF8ToJavaString(env, headline), description, ConvertUTF16ToJavaString(env, certificate_label), icon_color_id); if (identity_info.show_ssl_decision_revoke_button) { base::string16 reset_button_label = l10n_util::GetStringUTF16( IDS_PAGE_INFO_RESET_INVALID_CERTIFICATE_DECISIONS_BUTTON); Java_ConnectionInfoView_addResetCertDecisionsButton( env, popup_jobject_, ConvertUTF16ToJavaString(env, reset_button_label)); } } { int icon_id = page_info_client_->GetJavaResourceId( PageInfoUI::GetConnectionIconID(identity_info.connection_status)); int icon_color_id = page_info_client_->GetJavaResourceId( PageInfoUI::GetConnectionIconColorID(identity_info.connection_status)); ScopedJavaLocalRef<jstring> description = ConvertUTF8ToJavaString( env, identity_info.connection_status_description); Java_ConnectionInfoView_addDescriptionSection( env, popup_jobject_, icon_id, nullptr, description, icon_color_id); } Java_ConnectionInfoView_addMoreInfoLink( env, popup_jobject_, ConvertUTF8ToJavaString( env, l10n_util::GetStringUTF8(IDS_PAGE_INFO_HELP_CENTER_LINK))); Java_ConnectionInfoView_onReady(env, popup_jobject_); } void ConnectionInfoViewAndroid::SetCookieInfo( const CookieInfoList& cookie_info_list) { NOTIMPLEMENTED(); } void ConnectionInfoViewAndroid::SetPageFeatureInfo( const PageFeatureInfo& info) { NOTIMPLEMENTED(); } void ConnectionInfoViewAndroid::SetPermissionInfo( const PermissionInfoList& permission_info_list, ChosenObjectInfoList chosen_object_info_list) { NOTIMPLEMENTED(); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
4137a3f7c33e7b29753042601c841c2b0fa23a2f
61c850d2a9de6468a885f671e4e298f217a90361
/cgi/graphics.cpp
b4c5480e5b499bf5b34887efb5919e1a5b1bfeac
[ "Apache-2.0" ]
permissive
Cyraphim/Console-Graphics-Interface
bdd4e1bea87333ef658696320fac4e46093c5571
783b8f04adaa820761626c964e3bba20f7bea901
refs/heads/main
2023-08-27T13:02:23.943060
2021-09-16T14:12:20
2021-09-16T14:12:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,068
cpp
#include "graphics.h" #define NOMINMAX #include <Windows.h> #include "../cgi.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <thread> #include <mutex> namespace cgi { namespace graphics { // Singleton init CConsoleBuffer* CConsoleBuffer::m_instance = NULL; void GoToXY(int x, int y) { static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); std::cout.flush(); COORD coord = { (SHORT)x, (SHORT)y }; SetConsoleCursorPosition(hOut, coord); } char GetFromXY(int x, int y) { GoToXY(x, y); CONSOLE_SCREEN_BUFFER_INFO csbiInfo; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsole, &csbiInfo); COORD pos = csbiInfo.dwCursorPosition; //set pos to current cursor location TCHAR strFromConsole[1]; //need space to only one char DWORD dwChars; ReadConsoleOutputCharacter( hConsole, strFromConsole, // Buffer where store symbols 1, // Read 1 char to strFormConsole pos, // Read from current cursor position &dwChars); // How many symbols stored return strFromConsole[0]; } void DrawImage(CSprite& sprite, size_t x, size_t y) { // As many threads as there are rows on the console std::vector<std::thread> threads; auto imgHeight = sprite.GetHeight(); auto imgWidth = sprite.GetWidth(); auto maxHeight = CConsoleBuffer::Instance()->GetHeight(); auto maxWidth = CConsoleBuffer::Instance()->GetWidth(); for (size_t imgY = 0; imgY < imgHeight && imgY < maxHeight; imgY++) { // if our row is negative then we dont need to draw it at all if (y + imgY >= 0) { // Multithreading the actual placement auto xLoop = [&sprite, &x, &y, &imgWidth, &maxWidth, imgY]() { for (size_t imgX = 0; imgX < maxWidth && imgX < imgWidth; imgX++) { // If the pixel is black then why bother copying it at all auto col = sprite.GetPixel(imgX, imgY); if (col != SColor::BLACK) { CConsoleBuffer::Instance()->PutPixel(col, x + imgX, y + imgY); } } }; // Add to our thread references threads.push_back(std::thread(xLoop)); } } // Wait for it all to end before ending the function for (auto& t : threads) { t.join(); } } void DrawImage(CSprite& sprite, SVec2 position) { DrawImage(sprite, (int) position.x, (int) position.y); } CSprite::CSprite(std::string filepath) { this->m_width = 0; this->m_height = 0; int channels; // Using STB to load image into memory regardless of extension unsigned char* data = stbi_load(filepath.c_str(), (int*)&this->m_width, (int*)&this->m_height, &channels, 3); for (int i = 0; i < this->m_width * this->m_height * 3; i += 3) { m_imageData.push_back(SColor(data[i], data[i + 1], data[i + 2])); } stbi_image_free(data); } CConsoleBuffer::CConsoleBuffer() { DWORD l_mode; HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleMode(hStdout, &l_mode); SetConsoleMode(hStdout, l_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN); SetConsoleOutputCP(65001); // Get the console width and height and create a buffer COORD size; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), {m_screenWidth, m_screenHeight}); CONSOLE_FONT_INFOEX cfi; cfi.cbSize = sizeof(cfi); cfi.nFont = 0; cfi.dwFontSize.X = 8; cfi.dwFontSize.Y = 8; cfi.FontFamily = FF_DONTCARE; cfi.FontWeight = FW_NORMAL; SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi); ::SendMessage(::GetConsoleWindow(), WM_SYSKEYDOWN, VK_RETURN, 0x20000000); m_consoleBuffer.insert(m_consoleBuffer.end(), m_screenWidth * m_screenHeight, SColor(0, 0, 0)); m_drawChar = u8"█"; } void CConsoleBuffer::ClearBuffer() { // Set everything to black for (auto& color : m_consoleBuffer) { color = SColor(0, 0, 0); } } void CConsoleBuffer::SwapBuffer() { //NOTE: // We currently use multithreading to append everything to a buffer string // Then we attach all these strings together to create a final buffer // and then we print that // // In a hypthothetical optimization I would try to get rid of the // intermediate buffer and append directly std::vector<std::thread> threads; std::vector<std::string> buffer(m_screenHeight, ""); for (size_t imgY = 0; imgY < m_screenHeight; imgY++) { auto xLoop = [&buffer, this, imgY]() { SColor col = this->GetPixel(0, imgY); buffer[imgY].append(col.toString()); SColor prevcol = col; for (size_t imgX = 0; imgX < m_screenWidth; imgX++) { col = this->GetPixel(imgX, imgY); if (col != SColor::BLACK) { if (col != prevcol) { buffer[imgY].append(col.toString()); prevcol = col; } buffer[imgY].append(m_drawChar); } else { buffer[imgY].push_back(' '); } } buffer[imgY].append("\033[0m\n"); }; threads.push_back(std::thread(xLoop)); } for (auto& t : threads) { t.join(); } std::string finalBuffer = ""; for (auto s : buffer) finalBuffer += s; GoToXY(0, 0); cgi::PrintText(finalBuffer.c_str()); } } }
[ "daserialgenius@gmail.com" ]
daserialgenius@gmail.com
534891387415c5a45c4388b01b36a5004c7a3a86
40b4b96bc62b242a887442728f36fa1b8439ddd5
/format/PascalToMdl.h
74024258f66a6b12c5a55e6e4ca394443ae7c56b
[]
no_license
javierfigueroacl/MemoriaUSM
5838373771c7f00380bbee6bd887d1d12bdb339a
44abb83fcbd1d0500adfa1cd3055e59b68f386ec
refs/heads/master
2021-01-12T06:21:38.658358
2017-08-07T02:28:53
2017-08-07T02:28:53
77,346,980
0
0
null
null
null
null
UTF-8
C++
false
false
218
h
#ifndef PascalToMdl_h #define PascalToMdl_h 1 #include <string> #include <cctype> #include <iostream> #include <vector> #include "../read_write/ReadPascal.h" #include "../read_write/WriteMdl.h" #endif
[ "javier.figueroag@alumnos.usm.cl" ]
javier.figueroag@alumnos.usm.cl
9d2a9c925aaeb5e5d914b68005d183910f61aafb
2d2e951b42cac90d480d4e250e906c0ff19e8675
/find_average/src/lib/solution.h
1abc923c6a87e3ab7b2ab93b1fd868e42d855f05
[]
no_license
YoeYang/EE599-HW1
222248f756d1ad3a7871801b1449d30e43f58ec1
8362b1e2c606b793c71b8ddcc71420ae942f901d
refs/heads/master
2020-12-12T22:45:12.390070
2020-01-23T03:17:27
2020-01-23T03:17:27
234,248,483
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
#ifndef TEMPLATE_SOLUTION_H #define TEMPLATE_SOLUTION_H #include <vector> class Solution { public: double FindAverage(std::vector<int> &inputs); }; #endif
[ "yoe@yoedeMacBook-Pro.local" ]
yoe@yoedeMacBook-Pro.local
2b0c1193924d53ba3aea6ba601a2df3c332136e5
83fa0c25184c5b7907d1c63a67c9b8d56482569a
/Maximum_Depth_of_Binary_Tree.cpp
e23edc9cc22583443c925f93aec5e872101cf741
[]
no_license
ouyangz/LeetCode
56313e3326b5da2ff1ddad25d0a6855968f80c91
0402323e978a1e76f00ab404b14cc5cd95aadfbd
refs/heads/master
2020-07-09T07:11:02.990404
2014-03-19T08:18:28
2014-03-19T08:18:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if (root == NULL) return 0; else{ int leftD = maxDepth(root->left); int rightD = maxDepth(root->right); if (leftD >= rightD) return (leftD + 1); else return (rightD + 1); } } };
[ "soph.oyzj@gmail.com" ]
soph.oyzj@gmail.com
d822a2ab5a6a624ada2edfd92a9d874b7bfe6fa3
198f071c0f3db78fc2b2209a2ab7da65f8f3b66e
/Contests/Olympiads/[KOI] Korean Olympiad of Informatics/KOI 2016/고등1-리조트.cpp
5cdfa5f7869c79a5c6558ff9f9691cbb6b88876f
[]
no_license
gratus907/Gratus_PS
a33924836f67c14c3b1f8d4eecdfea73cd5cb98f
7efdc7f37f268dccd2f8a0ec562aa7a4a67adf15
refs/heads/master
2023-07-27T03:43:17.731930
2021-08-31T17:26:54
2021-08-31T17:26:54
235,131,504
1
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #define ll long long #define eps 1e-7 #define all(x) ((x).begin()),((x).end()) #define usecppio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; using pii = pair<int, int>; int INF = 0x7f7f7f7f; int resort[150]; int n, m; int dp[150][150]; int filldp(int day, int coupon) { if (coupon<0) return INF; if (day > n) return 0; if (dp[day][coupon]!=INF) return dp[day][coupon]; if (resort[day]) { dp[day][coupon] = filldp(day+1, coupon); return dp[day][coupon]; } dp[day][coupon] = min({filldp(day+1,coupon-3),filldp(day+1,coupon)+10000,filldp(day+3,coupon+1)+25000,filldp(day+5,coupon+2)+37000}); return dp[day][coupon]; } int main() { cin >> n >> m; for (int i = 0; i<m; i++) { int x; cin >> x; resort[x] = 1; } memset(dp,0x7f,sizeof(dp)); cout << filldp(1, 0); }
[ "gratus907@naver.com" ]
gratus907@naver.com
ba6566d4a4afac256faf332b98a28b9fafdb2b6d
ea2bb9b2b70ac5854248801371a236c4ea9c03c8
/Code/Filter/vtkMimxPolyDataSingleSourceShortestPath.h
d60bfeda41d649ea1d371423d7da7bd37f3a85c1
[]
no_license
Piyusha23/IAFEMesh
557de885d80ac3575ece146cf97f1a807bfeeb4e
e91b34c9eaa9c8ecc4ebb5d16f4c13f330d75c9f
refs/heads/master
2021-10-27T03:19:25.279119
2019-04-15T17:11:46
2019-04-15T17:11:46
181,531,319
1
0
null
null
null
null
UTF-8
C++
false
false
5,323
h
/*========================================================================= Program: MIMX Meshing Toolkit Module: $RCSfile: vtkMimxPolyDataSingleSourceShortestPath.h,v $ Language: C++ Date: $Date: 2013/01/02 20:39:31 $ Version: $Revision: 1.2 $ Musculoskeletal Imaging, Modelling and Experimentation (MIMX) Center for Computer Aided Design The University of Iowa Iowa City, IA 52242 http://www.ccad.uiowa.edu/mimx/ Copyright (c) The University of Iowa. All rights reserved. See MIMXCopyright.txt or http://www.ccad.uiowa.edu/mimx/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // .NAME vtkMimxPolyDataSingleSourceShortestPath - Single source shortest path on a polygonal mesh // .SECTION Description // // vtkMimxPolyDataSingleSourceShortestPath is a filter that takes as input // a polygonal mesh and performs a single source shortest path // calculation. Most of the code is used from the work of Rasmus Paulsen // email: rrp(a)imm.dtu.dk, web: www.imm.dtu.dk/~rrp/VTK // The output of the filter is a polydata describing the shortest path. The user has to input the // polydata on which the path need to be found. the start and end vertex need to be specified. // The input polydata should be a single continuous region. #ifndef __vtkMimxPolyDataSingleSourceShortestPath_h__ #define __vtkMimxPolyDataSingleSourceShortestPath_h__ #include "vtkPolyDataAlgorithm.h" //MIMX Headers #include "vtkMimxFilterWin32Header.h" class vtkDoubleArray; class vtkIntArray; class vtkIdList; class vtkFloatArray; class vtkPolyData; class VTK_MIMXFILTER_EXPORT vtkMimxPolyDataSingleSourceShortestPath : public vtkPolyDataAlgorithm { public: vtkTypeRevisionMacro(vtkMimxPolyDataSingleSourceShortestPath,vtkPolyDataAlgorithm); static vtkMimxPolyDataSingleSourceShortestPath *New(); void PrintSelf(ostream& os, vtkIndent indent); // Description: // The vertex at the start of the shortest path vtkGetMacro(StartVertex, vtkIdType); vtkSetMacro(StartVertex, vtkIdType); // Description: // The vertex at the end of the shortest path vtkGetMacro(EndVertex, vtkIdType); vtkSetMacro(EndVertex, vtkIdType); // Description: // Stop when the end vertex is reached // or calculate shortest path to all vertices vtkSetMacro(StopWhenEndReached, int); vtkGetMacro(StopWhenEndReached, int); // Description: // To force the connection between the vertices to be constant (in this case 1.0) // else distance b/w two vertices is calculated. vtkSetMacro(EqualWeights, int); vtkGetMacro(EqualWeights, int); vtkBooleanMacro(EqualWeights, int); // Description: // Id list of points in the closest path vtkGetMacro(IdList, vtkIdList*); protected: vtkMimxPolyDataSingleSourceShortestPath(); ~vtkMimxPolyDataSingleSourceShortestPath(); virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); vtkMimxPolyDataSingleSourceShortestPath(const vtkMimxPolyDataSingleSourceShortestPath&); void operator=(const vtkMimxPolyDataSingleSourceShortestPath&); // Build a graph description of the mesh void BuildAdjacency(vtkPolyData *pd); void DeleteAdjacency(); // The cost going from vertex u to v // TODO: should be implemented as a user supplied // callback function double EdgeCost(vtkPolyData *pd, vtkIdType u, vtkIdType v); void init(vtkPolyData*); // structure the heap void Heapify(int i); // insert vertex v in heap. Weight is in d(v) void HeapInsert(int v); // extract vertex with min d(v) int HeapExtractMin(); // Update heap when key d(v) has been decreased void HeapDecreaseKey(int v); void InitSingleSource(int startv); // Calculate shortest path from vertex startv to vertex endv void ShortestPath(int startv, int endv, vtkPolyData*); // Relax edge u,v with weight w void Relax(int u, int v, double w); // Backtrace the shortest path void TraceShortestPath(vtkPolyData *inPd, vtkPolyData *outPd, vtkIdType startv, vtkIdType endv); // the number of vertices int n; // d(v) current summed weight for path to vertex v vtkFloatArray *d; // pre(v) predecessor of v vtkIntArray *pre; // f is the set of vertices wich has not a shortest path yet but has a path // ie. the front set (f(v) == 1 means that vertex v is in f) vtkIntArray *f; // s is the set of vertices with allready determined shortest path // s(v) == 1 means that vertex v is in s vtkIntArray *s; // the priority que (a binary heap) with vertex indices vtkIntArray *H; // The real number of elements in H != H.size() int Hsize; // p(v) the position of v in H (p and H are kindoff inverses) vtkIntArray *p; // The vertex ids on the shortest path vtkIdList *IdList; // The vertex at the start of the shortest path vtkIdType StartVertex; // The vertex at the end of the shortest path vtkIdType EndVertex; // Adjacency representation vtkIdList **Adj; int StopWhenEndReached; int UseScalarWeights; int EqualWeights; // Used to remember the size of the graph. If the filter is re-used. int AdjacencyGraphSize; }; #endif
[ "gadepiyusha@gmail.com" ]
gadepiyusha@gmail.com
93a68c03026f7592042bbc42d4390c9fddf31b1e
617a4f71917a92569c66d2d7789437d0cf1728d0
/src/test/uint256_tests.cpp
e5e50c453d00da14c5e9a287a2f00ece5dca8e85
[ "MIT" ]
permissive
minblock/luascoin
db251af5feda26125d436ea87a3b5cfc6d8ba5a7
499334f8d5c50dfe6c146a1cddacf2ee5c76f256
refs/heads/master
2023-08-06T03:32:34.218016
2023-07-29T00:36:56
2023-07-29T00:36:56
238,172,510
0
0
null
null
null
null
UTF-8
C++
false
false
10,670
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "arith_uint256.h" #include "uint256.h" #include "version.h" #include "test/test_luascoin.h" #include <boost/test/unit_test.hpp> #include <stdint.h> #include <sstream> #include <iomanip> #include <limits> #include <cmath> #include <string> #include <stdio.h> BOOST_FIXTURE_TEST_SUITE(uint256_tests, BasicTestingSetup) const unsigned char R1Array[] = "\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2" "\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d"; const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c"; const uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32)); const uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20)); const unsigned char R2Array[] = "\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf" "\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7"; const uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32)); const uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20)); const unsigned char ZeroArray[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32)); const uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20)); const unsigned char OneArray[] = "\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const uint256 OneL = uint256(std::vector<unsigned char>(OneArray,OneArray+32)); const uint160 OneS = uint160(std::vector<unsigned char>(OneArray,OneArray+20)); const unsigned char MaxArray[] = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; const uint256 MaxL = uint256(std::vector<unsigned char>(MaxArray,MaxArray+32)); const uint160 MaxS = uint160(std::vector<unsigned char>(MaxArray,MaxArray+20)); std::string ArrayToString(const unsigned char A[], unsigned int width) { std::stringstream Stream; Stream << std::hex; for (unsigned int i = 0; i < width; ++i) { Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1]; } return Stream.str(); } inline uint160 uint160S(const char *str) { uint160 rv; rv.SetHex(str); return rv; } inline uint160 uint160S(const std::string& str) { uint160 rv; rv.SetHex(str); return rv; } BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality { BOOST_CHECK(1 == 0+1); // constructor uint256(vector<char>): BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32)); BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20)); BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32)); BOOST_CHECK(R2S.ToString() == ArrayToString(R2Array,20)); BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32)); BOOST_CHECK(ZeroS.ToString() == ArrayToString(ZeroArray,20)); BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32)); BOOST_CHECK(OneS.ToString() == ArrayToString(OneArray,20)); BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32)); BOOST_CHECK(MaxS.ToString() == ArrayToString(MaxArray,20)); BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32)); BOOST_CHECK(OneS.ToString() != ArrayToString(ZeroArray,20)); // == and != BOOST_CHECK(R1L != R2L && R1S != R2S); BOOST_CHECK(ZeroL != OneL && ZeroS != OneS); BOOST_CHECK(OneL != ZeroL && OneS != ZeroS); BOOST_CHECK(MaxL != ZeroL && MaxS != ZeroS); // String Constructor and Copy Constructor BOOST_CHECK(uint256S("0x"+R1L.ToString()) == R1L); BOOST_CHECK(uint256S("0x"+R2L.ToString()) == R2L); BOOST_CHECK(uint256S("0x"+ZeroL.ToString()) == ZeroL); BOOST_CHECK(uint256S("0x"+OneL.ToString()) == OneL); BOOST_CHECK(uint256S("0x"+MaxL.ToString()) == MaxL); BOOST_CHECK(uint256S(R1L.ToString()) == R1L); BOOST_CHECK(uint256S(" 0x"+R1L.ToString()+" ") == R1L); BOOST_CHECK(uint256S("") == ZeroL); BOOST_CHECK(R1L == uint256S(R1ArrayHex)); BOOST_CHECK(uint256(R1L) == R1L); BOOST_CHECK(uint256(ZeroL) == ZeroL); BOOST_CHECK(uint256(OneL) == OneL); BOOST_CHECK(uint160S("0x"+R1S.ToString()) == R1S); BOOST_CHECK(uint160S("0x"+R2S.ToString()) == R2S); BOOST_CHECK(uint160S("0x"+ZeroS.ToString()) == ZeroS); BOOST_CHECK(uint160S("0x"+OneS.ToString()) == OneS); BOOST_CHECK(uint160S("0x"+MaxS.ToString()) == MaxS); BOOST_CHECK(uint160S(R1S.ToString()) == R1S); BOOST_CHECK(uint160S(" 0x"+R1S.ToString()+" ") == R1S); BOOST_CHECK(uint160S("") == ZeroS); BOOST_CHECK(R1S == uint160S(R1ArrayHex)); BOOST_CHECK(uint160(R1S) == R1S); BOOST_CHECK(uint160(ZeroS) == ZeroS); BOOST_CHECK(uint160(OneS) == OneS); } BOOST_AUTO_TEST_CASE( comparison ) // <= >= < > { uint256 LastL; for (int i = 255; i >= 0; --i) { uint256 TmpL; *(TmpL.begin() + (i>>3)) |= 1<<(7-(i&7)); BOOST_CHECK( LastL < TmpL ); LastL = TmpL; } BOOST_CHECK( ZeroL < R1L ); BOOST_CHECK( R2L < R1L ); BOOST_CHECK( ZeroL < OneL ); BOOST_CHECK( OneL < MaxL ); BOOST_CHECK( R1L < MaxL ); BOOST_CHECK( R2L < MaxL ); uint160 LastS; for (int i = 159; i >= 0; --i) { uint160 TmpS; *(TmpS.begin() + (i>>3)) |= 1<<(7-(i&7)); BOOST_CHECK( LastS < TmpS ); LastS = TmpS; } BOOST_CHECK( ZeroS < R1S ); BOOST_CHECK( R2S < R1S ); BOOST_CHECK( ZeroS < OneS ); BOOST_CHECK( OneS < MaxS ); BOOST_CHECK( R1S < MaxS ); BOOST_CHECK( R2S < MaxS ); } BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex begin() end() size() GetLow64 GetSerializeSize, Serialize, Unserialize { BOOST_CHECK(R1L.GetHex() == R1L.ToString()); BOOST_CHECK(R2L.GetHex() == R2L.ToString()); BOOST_CHECK(OneL.GetHex() == OneL.ToString()); BOOST_CHECK(MaxL.GetHex() == MaxL.ToString()); uint256 TmpL(R1L); BOOST_CHECK(TmpL == R1L); TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L); TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == uint256()); TmpL.SetHex(R1L.ToString()); BOOST_CHECK(memcmp(R1L.begin(), R1Array, 32)==0); BOOST_CHECK(memcmp(TmpL.begin(), R1Array, 32)==0); BOOST_CHECK(memcmp(R2L.begin(), R2Array, 32)==0); BOOST_CHECK(memcmp(ZeroL.begin(), ZeroArray, 32)==0); BOOST_CHECK(memcmp(OneL.begin(), OneArray, 32)==0); BOOST_CHECK(R1L.size() == sizeof(R1L)); BOOST_CHECK(sizeof(R1L) == 32); BOOST_CHECK(R1L.size() == 32); BOOST_CHECK(R2L.size() == 32); BOOST_CHECK(ZeroL.size() == 32); BOOST_CHECK(MaxL.size() == 32); BOOST_CHECK(R1L.begin() + 32 == R1L.end()); BOOST_CHECK(R2L.begin() + 32 == R2L.end()); BOOST_CHECK(OneL.begin() + 32 == OneL.end()); BOOST_CHECK(MaxL.begin() + 32 == MaxL.end()); BOOST_CHECK(TmpL.begin() + 32 == TmpL.end()); BOOST_CHECK(R1L.GetSerializeSize(0,PROTOCOL_VERSION) == 32); BOOST_CHECK(ZeroL.GetSerializeSize(0,PROTOCOL_VERSION) == 32); std::stringstream ss; R1L.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(R1L == TmpL); ss.str(""); ZeroL.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ZeroL == TmpL); ss.str(""); MaxL.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+32)); TmpL.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(MaxL == TmpL); ss.str(""); BOOST_CHECK(R1S.GetHex() == R1S.ToString()); BOOST_CHECK(R2S.GetHex() == R2S.ToString()); BOOST_CHECK(OneS.GetHex() == OneS.ToString()); BOOST_CHECK(MaxS.GetHex() == MaxS.ToString()); uint160 TmpS(R1S); BOOST_CHECK(TmpS == R1S); TmpS.SetHex(R2S.ToString()); BOOST_CHECK(TmpS == R2S); TmpS.SetHex(ZeroS.ToString()); BOOST_CHECK(TmpS == uint160()); TmpS.SetHex(R1S.ToString()); BOOST_CHECK(memcmp(R1S.begin(), R1Array, 20)==0); BOOST_CHECK(memcmp(TmpS.begin(), R1Array, 20)==0); BOOST_CHECK(memcmp(R2S.begin(), R2Array, 20)==0); BOOST_CHECK(memcmp(ZeroS.begin(), ZeroArray, 20)==0); BOOST_CHECK(memcmp(OneS.begin(), OneArray, 20)==0); BOOST_CHECK(R1S.size() == sizeof(R1S)); BOOST_CHECK(sizeof(R1S) == 20); BOOST_CHECK(R1S.size() == 20); BOOST_CHECK(R2S.size() == 20); BOOST_CHECK(ZeroS.size() == 20); BOOST_CHECK(MaxS.size() == 20); BOOST_CHECK(R1S.begin() + 20 == R1S.end()); BOOST_CHECK(R2S.begin() + 20 == R2S.end()); BOOST_CHECK(OneS.begin() + 20 == OneS.end()); BOOST_CHECK(MaxS.begin() + 20 == MaxS.end()); BOOST_CHECK(TmpS.begin() + 20 == TmpS.end()); BOOST_CHECK(R1S.GetSerializeSize(0,PROTOCOL_VERSION) == 20); BOOST_CHECK(ZeroS.GetSerializeSize(0,PROTOCOL_VERSION) == 20); R1S.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(R1S == TmpS); ss.str(""); ZeroS.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ZeroS == TmpS); ss.str(""); MaxS.Serialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+20)); TmpS.Unserialize(ss,0,PROTOCOL_VERSION); BOOST_CHECK(MaxS == TmpS); ss.str(""); } BOOST_AUTO_TEST_CASE( conversion ) { BOOST_CHECK(ArithToUint256(UintToArith256(ZeroL)) == ZeroL); BOOST_CHECK(ArithToUint256(UintToArith256(OneL)) == OneL); BOOST_CHECK(ArithToUint256(UintToArith256(R1L)) == R1L); BOOST_CHECK(ArithToUint256(UintToArith256(R2L)) == R2L); BOOST_CHECK(UintToArith256(ZeroL) == 0); BOOST_CHECK(UintToArith256(OneL) == 1); BOOST_CHECK(ArithToUint256(0) == ZeroL); BOOST_CHECK(ArithToUint256(1) == OneL); BOOST_CHECK(arith_uint256(R1L.GetHex()) == UintToArith256(R1L)); BOOST_CHECK(arith_uint256(R2L.GetHex()) == UintToArith256(R2L)); BOOST_CHECK(R1L.GetHex() == UintToArith256(R1L).GetHex()); BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex()); } BOOST_AUTO_TEST_SUITE_END()
[ "38344452+minblock@users.noreply.github.com" ]
38344452+minblock@users.noreply.github.com
3d7f76720b2a81f05aa686f4efbde8225ed6539a
9c2b4dfe2ccdcb5cce1a6a9ed93361660252df5e
/nei_result.h
8627471be527f24adc9638972937dd3f808a1836
[]
no_license
crazytyt/neitianfa
980c9b67865477b30cbd16c0a53e2cd24dece7b0
a5bc1fa627bffa992085be0df22e01e9da53d922
refs/heads/master
2021-01-13T08:44:51.632658
2017-03-09T02:04:22
2017-03-09T02:04:22
71,974,242
0
0
null
null
null
null
UTF-8
C++
false
false
618
h
#ifndef NEI_RESULT_H #define NEI_RESULT_H #include <QWidget> namespace Ui { class nei_result; } class nei_result : public QWidget { Q_OBJECT public: explicit nei_result(QWidget *parent = 0); ~nei_result(); int X1[15], X2[15]; int mErr, mCorr; double mErrRate; double X1max, X1min, X2max, X2min, R1, R2; double M1, M2, S1, S2, V, V1, V2, N, T; double uM1, uM2, uR1, uR2, uS1, uS2, uV, uN, uT; double calP[2][9], calS[2][9], calC[2][9], calSP[2][9]; double P, S, C, SP; QString mType; void cal_para(void); private: Ui::nei_result *ui; }; #endif // NEI_RESULT_H
[ "tforjob@163.com" ]
tforjob@163.com
8999168a40ad0c143090d3d2aba478c895919a42
737bd9818fb712801371d3552a6ee41d92bbd33e
/src/engine_core/wme_base/SXArray.cpp
139ded8b31a06f6f5309d82a49d2c14076c79f78
[ "MIT" ]
permissive
segafan/wme1_jankavan_tlc_edition-repo
9bf8afb542d3a4a3949bf61c881927df4942410e
72163931f348d5a2132577930362d297cc375a26
refs/heads/master
2020-12-24T17:54:12.910112
2015-04-26T23:03:42
2015-04-26T23:03:42
38,780,832
1
0
null
null
null
null
UTF-8
C++
false
false
5,697
cpp
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme #include "dcgf.h" #include "SXArray.h" IMPLEMENT_PERSISTENT(CSXArray, false); ////////////////////////////////////////////////////////////////////////// CSXArray::CSXArray(CBGame* inGame, CScStack* Stack):CBScriptable(inGame) { m_Length = 0; m_Values = new CScValue(Game); int NumParams = Stack->Pop()->GetInt(0); if(NumParams==1) m_Length = Stack->Pop()->GetInt(0); else if(NumParams>1){ m_Length = NumParams; char ParamName[20]; for(int i=0; i<NumParams; i++){ sprintf(ParamName, "%d", i); m_Values->SetProp(ParamName, Stack->Pop()); } } } ////////////////////////////////////////////////////////////////////////// CSXArray::CSXArray(CBGame* inGame):CBScriptable(inGame) { m_Length = 0; m_Values = new CScValue(Game); } ////////////////////////////////////////////////////////////////////////// CSXArray::~CSXArray() { SAFE_DELETE(m_Values); } ////////////////////////////////////////////////////////////////////////// char* CSXArray::ScToString() { static char Dummy[32768]; strcpy(Dummy, ""); char PropName[20]; for(int i=0; i<m_Length; i++){ sprintf(PropName, "%d", i); CScValue* val = m_Values->GetProp(PropName); if(val){ if(strlen(Dummy) + strlen(val->GetString()) < 32768){ strcat(Dummy, val->GetString()); } } if(i<m_Length-1 && strlen(Dummy)+1 < 32768) strcat(Dummy, ","); } return Dummy; } ////////////////////////////////////////////////////////////////////////// HRESULT CSXArray::ScCallMethod(CScScript* Script, CScStack *Stack, CScStack *ThisStack, char *Name) { ////////////////////////////////////////////////////////////////////////// // Push ////////////////////////////////////////////////////////////////////////// if(strcmp(Name, "Push")==0){ int NumParams = Stack->Pop()->GetInt(0); char ParamName[20]; for(int i=0; i<NumParams; i++){ m_Length++; sprintf(ParamName, "%d", m_Length-1); m_Values->SetProp(ParamName, Stack->Pop(), true); } Stack->PushInt(m_Length); return S_OK; } ////////////////////////////////////////////////////////////////////////// // Pop ////////////////////////////////////////////////////////////////////////// if(strcmp(Name, "Pop")==0){ Stack->CorrectParams(0); if(m_Length>0){ char ParamName[20]; sprintf(ParamName, "%d", m_Length-1); Stack->Push(m_Values->GetProp(ParamName)); m_Values->DeleteProp(ParamName); m_Length--; } else Stack->PushNULL(); return S_OK; } else return E_FAIL; } ////////////////////////////////////////////////////////////////////////// CScValue* CSXArray::ScGetProperty(char *Name) { m_ScValue->SetNULL(); ////////////////////////////////////////////////////////////////////////// // Type ////////////////////////////////////////////////////////////////////////// if(strcmp(Name, "Type")==0){ m_ScValue->SetString("array"); return m_ScValue; } ////////////////////////////////////////////////////////////////////////// // Length ////////////////////////////////////////////////////////////////////////// else if(strcmp(Name, "Length")==0){ m_ScValue->SetInt(m_Length); return m_ScValue; } ////////////////////////////////////////////////////////////////////////// // [number] ////////////////////////////////////////////////////////////////////////// else{ char ParamName[20]; if(ValidNumber(Name, ParamName)){ return m_Values->GetProp(ParamName); } else return m_ScValue; } } ////////////////////////////////////////////////////////////////////////// HRESULT CSXArray::ScSetProperty(char *Name, CScValue *Value) { ////////////////////////////////////////////////////////////////////////// // Length ////////////////////////////////////////////////////////////////////////// if(strcmp(Name, "Length")==0){ int OrigLength = m_Length; m_Length = max(Value->GetInt(0), 0); char PropName[20]; if(m_Length < OrigLength){ for(int i=m_Length; i<OrigLength; i++){ sprintf(PropName, "%d", i); m_Values->DeleteProp(PropName); } } return S_OK; } ////////////////////////////////////////////////////////////////////////// // [number] ////////////////////////////////////////////////////////////////////////// else{ char ParamName[20]; if(ValidNumber(Name, ParamName)){ int Index = atoi(ParamName); if(Index>=m_Length) m_Length = Index + 1; return m_Values->SetProp(ParamName, Value); } else return E_FAIL; } } ////////////////////////////////////////////////////////////////////////// HRESULT CSXArray::Persist(CBPersistMgr* PersistMgr) { CBScriptable::Persist(PersistMgr); PersistMgr->Transfer(TMEMBER(m_Length)); PersistMgr->Transfer(TMEMBER(m_Values)); return S_OK; } ////////////////////////////////////////////////////////////////////////// bool CSXArray::ValidNumber(const char *OrigStr, char *OutStr) { bool IsNumber = true; for(int i=0; i<strlen(OrigStr); i++){ if(!isdigit(OrigStr[i])){ IsNumber = false; break; } } if(IsNumber){ int Index = atoi(OrigStr); sprintf(OutStr, "%d", Index); return true; } else return false; } ////////////////////////////////////////////////////////////////////////// HRESULT CSXArray::Push(CScValue* Val) { char ParamName[20]; m_Length++; sprintf(ParamName, "%d", m_Length-1); m_Values->SetProp(ParamName, Val, true); return S_OK; }
[ "Jan Kavan@localhost" ]
Jan Kavan@localhost
a90432779f18b115e669cb6d2ec9269e673d5761
4dc8131cda9ef4e3c6d0a5d1555ffa58d791c63a
/work/work/src/XF_amad/xf/core/behavior.cpp
86b81d121313870c8c2bf84d076ad50c5b2fda84
[]
no_license
BorgeatRemy/XF_PTR
806cc2166a4cfb9cc267c9eb9c7164aa121ddc99
3877e6197b344eb4077ff4a008fbed234e2b437a
refs/heads/master
2021-02-10T12:04:31.888615
2020-03-03T11:27:29
2020-03-03T11:27:29
244,379,950
0
0
null
null
null
null
UTF-8
C++
false
false
2,510
cpp
#include <assert.h> #include "xf/xf.h" #include "xf/interface/resourcefactory.h" #include "xf/interface/dispatcher.h" #include "xf/timeout.h" #include "xf/initialevent.h" #include "xf/behavior.h" #include "trace/trace.h" using interface::XFResourceFactory; XFBehavior::XFBehavior(bool ownDispatcher) { this->_hasOwnDispatcher = ownDispatcher; // Create or get default dispatcher if(this->_hasOwnDispatcher) this->_pDispatcher = XFResourceFactory::getInstance()->createDispatcher(); else this->_pDispatcher = XFResourceFactory::getInstance()->getDefaultDispatcher(); this->deleteOnTerminate_ = true; this->_pCurrentEvent = nullptr; } XFBehavior::~XFBehavior() { // Destroy only if own dispatcher created //if(_hasOwnDispatcher) //delete this->_pDispatcher; if(_hasOwnDispatcher) this->_pDispatcher->stop(); } void XFBehavior::startBehavior() { // start dispatcher (no problem with multiple start call) this->_pDispatcher->start(); // push an initial event this->pushEvent(new XFInitialEvent()); } void XFBehavior::pushEvent(XFEvent *pEvent) { // set this behavior for callback if none is set if(!pEvent->getBehavior()) pEvent->setBehavior(this); // push an event this->_pDispatcher->pushEvent(pEvent); } bool XFBehavior::deleteOnTerminate() const { //return this->deleteOnTerminate_; /*if(this->deleteOnTerminate_) { delete this; return true; }*/ return this->deleteOnTerminate_; } void XFBehavior::setDeleteOnTerminate(bool deleteBehaviour) { this->deleteOnTerminate_ = deleteBehaviour; } const XFEvent *XFBehavior::getCurrentEvent() const { return this->_pCurrentEvent; } interface::XFDispatcher *XFBehavior::getDispatcher() { return this->_pDispatcher; } const XFTimeout *XFBehavior::getCurrentTimeout() { if(this->_pCurrentEvent->getEventType() == XFEvent::Timeout) { return (XFTimeout*)this->_pCurrentEvent; } return nullptr; } void XFBehavior::setCurrentEvent(const XFEvent *pEvent) { this->_pCurrentEvent = pEvent; } interface::XFReactive::TerminateBehavior XFBehavior::process(const XFEvent *pEvent) { // register and process event this->setCurrentEvent(pEvent); XFEventStatus stat = this->processEvent(); // if needs to termintae this if(stat == XFEventStatus::Terminate) { this->deleteOnTerminate(); return true; } return stat==XFEventStatus::Terminate; }
[ "48057941+BorgeatRemy@users.noreply.github.com" ]
48057941+BorgeatRemy@users.noreply.github.com