hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e128842e9679a7a9f120e9cc06a7996beb353e27
1,175
hh
C++
config/example/GenerateEmissionProfiles/WCSimEmissionProfileGenerator.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
config/example/GenerateEmissionProfiles/WCSimEmissionProfileGenerator.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
config/example/GenerateEmissionProfiles/WCSimEmissionProfileGenerator.hh
chipsneutrino/chips-reco
0d9e7e8a1dd749a2b0b0d64eabf0b32d895f19ba
[ "MIT" ]
null
null
null
/* * WCSimEmissionProfileGenerator.hh * * Created on: 28 Mar 2014 * Author: andy */ #ifndef WCSIMEMISSIONPROFILEGENERATOR_HH_ #define WCSIMEMISSIONPROFILEGENERATOR_HH_ #include "TChain.h" #include "TString.h" #include <map> class WCSimEmissionProfileGenerator { public: WCSimEmissionProfileGenerator( const char * treeName, Int_t particleType ); virtual ~WCSimEmissionProfileGenerator(); void AddFile(Double_t energy, Int_t particleType, const char * filename); void SetSaveName( const char * savename); std::map<Double_t, TChain *> GetChain(); TString GetChainSaveName(); void BuildSaveName(); void Concatenate(); void ResetEnergy(); void MakeFluxHistogram(); TChain * Next(); private: const char * fTreeName; const char * fSaveName; std::map<Double_t, TString> fNameMap; Int_t fParticle; TString fName; std::map<Double_t, TChain *> fChain; std::map<Double_t, TChain *>::const_iterator fChainItr; Double_t fEnergy; Int_t fType; Bool_t fIsFirstCall; UInt_t fUNKNOWN; ClassDef(WCSimEmissionProfileGenerator,1) }; #endif /* WCSIMEMISSIONPROFILEGENERATOR_HH_ */
21.759259
79
0.710638
chipsneutrino
e12d58f5e7382a2786a0d000523d164e428a914b
575
cpp
C++
src/linear/tests/testNormalize.cpp
moddyz/LinearAlgebra
ca44a8aef1c1ef3abba33b3fd8ebd83c000e4b60
[ "MIT" ]
1
2020-06-29T00:25:37.000Z
2020-06-29T00:25:37.000Z
src/linear/tests/testNormalize.cpp
moddyz/LinearAlgebra
ca44a8aef1c1ef3abba33b3fd8ebd83c000e4b60
[ "MIT" ]
null
null
null
src/linear/tests/testNormalize.cpp
moddyz/LinearAlgebra
ca44a8aef1c1ef3abba33b3fd8ebd83c000e4b60
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <linear/normalize.h> #include <iostream> TEST_CASE( "Matrix_Normalize" ) { CHECK( linear::Normalize( linear::Matrix< 3, 1 >( 1.0f, 0.0f, 0.0f ) ) == linear::Matrix< 3, 1 >( 1.0f, 0.0f, 0.0f ) ); CHECK( linear::Normalize( linear::Matrix< 3, 1 >( 3.0f, 4.0f, 5.0f ) ) == linear::Matrix< 3, 1 >( 0.424264f, 0.565685f, 0.707107f ) ); }
17.424242
53
0.401739
moddyz
e130a89fd7897cf1688ff2e25323d8d3dee58d20
37,499
cpp
C++
ROBIT_vision2/src/vision.cpp
zang09/turtlebot3_autorace_ROBIT2_src
adc7225b7e0e5f822e62746beba16cd5a0b20214
[ "Apache-2.0" ]
null
null
null
ROBIT_vision2/src/vision.cpp
zang09/turtlebot3_autorace_ROBIT2_src
adc7225b7e0e5f822e62746beba16cd5a0b20214
[ "Apache-2.0" ]
null
null
null
ROBIT_vision2/src/vision.cpp
zang09/turtlebot3_autorace_ROBIT2_src
adc7225b7e0e5f822e62746beba16cd5a0b20214
[ "Apache-2.0" ]
null
null
null
#include "../include/ROBIT_vision2/vision.hpp" using namespace cv; using namespace std; using namespace cv::xfeatures2d; int sign_state; string sign_value; int vision_line::r_line_xpos = 0; int vision_line::l_line_xpos = 0; bool vision_line::r_line_detect = false; bool vision_line::l_line_detect = false; bool vision_line::v_line_detect = false; bool vision_line::y_line_detect = false; bool vision_line::w_line_detect = false; double vision_line::white_line_deg = 0.0; double vision_line::yellow_line_deg = 0.0; double vision_line::vertical_line_deg = 0.0; int vision::parking_condition = 0; int vision::cross_condition = 0; int vision::construct_condition = 0; bool vision::direction = false; void detect_mat(Mat frame_detect, float* detections_output, int* num_output_class, float thresh, float hier_thresh, vector<cv::Rect>& objBoxes) { double time = what_is_the_time_now(); // do detect in an unsigned char* data buffer getted from Mat::data or IplImage.imageData unsigned char* data = (unsigned char*)frame_detect.data; int w = frame_detect.cols; int h = frame_detect.rows; int c = frame_detect.channels(); float* detections = test_detector_uchar(data, w, h, c, thresh, hier_thresh, num_output_class); for(int i = 0; i < *num_output_class; i++) { sign_state = (int)detections[i*6+0]; detections_output[i*6+0] = detections[i*6+0]; // ith detection's category detections_output[i*6+1] = detections[i*6+1]; // ith detection's confidence score detections_output[i*6+2] = detections[i*6+2]; // ith detection's top-left x-coordinate of bbox detections_output[i*6+3] = detections[i*6+3]; // ith detection's top-left y-coordinate of bbox detections_output[i*6+4] = detections[i*6+4]; // ith detection's width of bbox detections_output[i*6+5] = detections[i*6+5]; // ith detection's height of bbox objBoxes.push_back(cv::Rect(detections_output[i*6+2], detections_output[i*6+3], detections_output[i*6+4], detections_output[i*6+5])); } } void vision::START(Mat &input_img) { Raw_image = input_img.clone(); Perspective_View(input_img, Perspective_img); Perspective_View2(input_img, Perspective_img2); Find_Sign_Img(Raw_image,input_img); Find_Gatebar(input_img); Traffic_Process(Raw_image, input_img); Construct_Process(); vision_line line(Perspective_img, Perspective_img2); Update_Message(); Q_EMIT white_line_callback(line.yellow_line); Q_EMIT yellow_line_callback(Perspective_img); Q_EMIT perspective_callback(Perspective_img2); Q_EMIT mission_callback(); } void vision::Update_Message() { Vision_msg.gatebar_detect = gatebar_detect; Vision_msg.r_angle = (int)(vision_line::white_line_deg); Vision_msg.l_angle = (int)(vision_line::yellow_line_deg); Vision_msg.r_line_info = vision_line::r_line_detect; Vision_msg.l_line_info = vision_line::l_line_detect; Vision_msg.r_diff_pixel = vision_line::r_line_xpos; Vision_msg.l_diff_pixel = vision_line::l_line_xpos; Vision_msg.cross_detect = cross_detect; Vision_msg.cross_info = cross_condition; Vision_msg.traffic = traffic_action; Vision_msg.parking_detect = parking_detect; Vision_msg.parking_info = parking_condition; Vision_msg.construct_detect = construct_detect2; Vision_msg.construct_info = construct_condition; if(cross_pixel > -160 && cross_pixel < 160) Vision_msg.cross_pixel = cross_pixel; } void vision::Change_to_Binary(Mat &input_img, Mat &output_img, int value[], bool flag) { Mat mask1 = getStructuringElement(MORPH_RECT, Size(3, 3), Point(1, 1)); Mat mask2 = getStructuringElement(MORPH_RECT, Size(15, 15), Point(1, 1)); output_img = input_img.clone(); medianBlur(output_img , output_img , 9); GaussianBlur(output_img , output_img , Size(15,15) , 2.0); cvtColor(output_img , output_img , CV_RGB2HSV); inRange(output_img, Scalar(value[3],value[4],value[5]),Scalar(value[0],value[1],value[2]), output_img); if(!flag){ erode(output_img, output_img, mask1, Point(-1, -1), 2); dilate(output_img, output_img, mask1, Point(-1, -1), 2); } else{ erode(output_img, output_img, mask1, Point(-1, -1), 2); dilate(output_img, output_img, mask2, Point(-1, -1), 2); } } void vision::Perspective_View(Mat &input_img, Mat &output_img) { Point2f inputQuad[4], outputQuad[4]; Mat lambda = Mat::zeros(input_img.rows, input_img.cols, input_img.type()); inputQuad[0] = Point2f(50,155); inputQuad[1] = Point2f(270,155); inputQuad[2] = Point2f(300, 185); inputQuad[3] = Point2f(20, 185); outputQuad[0] = Point2f(0,0); outputQuad[1] = Point2f(RAW_X,0); outputQuad[2] = Point2f(RAW_X,RAW_Y); outputQuad[3] = Point2f(0,RAW_Y); lambda = getPerspectiveTransform(inputQuad, outputQuad); warpPerspective(input_img.clone(), output_img, lambda, output_img.size()); circle(input_img,Point(50,155),3,Scalar(255,204,51),-1); circle(input_img,Point(270,155),3,Scalar(255,204,51),-1); circle(input_img,Point(20,185),3,Scalar(255,204,51),-1); circle(input_img,Point(300,185),3,Scalar(255,204,51),-1); } void vision::Perspective_View2(Mat &input_img, Mat &output_img) { Point2f inputQuad[4], outputQuad[4]; Mat lambda = Mat::zeros(input_img.rows, input_img.cols, input_img.type()); inputQuad[0] = Point2f(20,115); inputQuad[1] = Point2f(300,115); inputQuad[2] = Point2f(300, 155); inputQuad[3] = Point2f(20, 155); outputQuad[0] = Point2f(0,0); outputQuad[1] = Point2f(RAW_X,0); outputQuad[2] = Point2f(RAW_X,RAW_Y); outputQuad[3] = Point2f(0,RAW_Y); lambda = getPerspectiveTransform(inputQuad, outputQuad); warpPerspective(input_img.clone(), output_img, lambda, output_img.size()); circle(input_img,Point(50,155),3,Scalar(255,204,51),-1); circle(input_img,Point(270,155),3,Scalar(255,204,51),-1); circle(input_img,Point(20,185),3,Scalar(255,204,51),-1); circle(input_img,Point(300,185),3,Scalar(255,204,51),-1); } void vision::Find_Sign_Img(Mat &input_img, Mat &draw_image) { Scalar color; Mat darknet = input_img(Rect(0, 0, 320, 120)).clone(); cvtColor(darknet, darknet, CV_BGR2RGB); float* detections = (float*)calloc(255 * 6, sizeof(float)); int num_of_outputs = 0; double thresh = 0.8; double hier_thresh = 0.0; vector<Rect> results; if(!process_flag[2]) detect_mat(darknet, detections, &num_of_outputs, thresh, hier_thresh, results); if(!results.empty()) { switch (sign_state) { case 0: sign_count[0]++; sign_value = "left"; color = Scalar(0, 255, 0); if((direction_angle >= 168 && direction_angle <= 180) && !process_flag[0] && sign_count[0] > 1){ sign_condition[left] = true; process_flag[0] = true; cross_detect = true; cross_condition = turn_l1; direction = true; }break; case 1: color = Scalar(255, 255, 0); sign_count[1]++; sign_value = "right"; color = Scalar(0, 255, 0); if((direction_angle >= 170 && direction_angle <= 180) && !process_flag[0] && sign_count[1] > 2){ sign_condition[right] = true; process_flag[0] = true; cross_detect = true; cross_condition = turn_r1; direction = false; }break; case 2: sign_count[2]++; sign_value = "parking"; color = Scalar(255, 0, 0); if((direction_angle >= 170 && direction_angle <= 190) && !construct_detect2 && sign_count[2] > 3){ process_flag[2] = true; parking_detect = true; }break; default: break; } } else sign_value = "NONE"; for(int i = 0; i < results.size(); i++) rectangle(draw_image, results[i], color, 4); Sign_Process(Raw_image, input_img); Parking_Process(); free(detections); } void vision::Find_Gatebar(Mat &input_img) { Gatebar_img = input_img(Rect(0,0,320,150)).clone(); Change_to_Binary(Gatebar_img, Gatebar_img, gatebar_value, 0); Q_EMIT gatebar_callback(Gatebar_img); vision_labeling Gatebar_labeling(Gatebar_img, 1300); Gatebar_labeling.do_labeling(); if(Gatebar_labeling.blobs.size() > 0) { int max_x, min_x, max_num = 0, min_num = 0 , y_gap; max_x = Gatebar_labeling.blobs[0].x; min_x = Gatebar_labeling.blobs[0].x; for(int i = 0; i < Gatebar_labeling.blobs.size() ; i++) { if(Gatebar_labeling.blobs[i].x > max_x) max_num = i; if(Gatebar_labeling.blobs[i].x < min_x) min_num = i; } for(int i = 0 ; i < Gatebar_labeling.blobs.size() ; i++) rectangle(input_img, Gatebar_labeling.blobs[i], Red, 2); y_gap = Gatebar_labeling.blobs[max_num].y - Gatebar_labeling.blobs[min_num].y; if(Gatebar_labeling.blobs.size() >= 2 && sensor_data[0] > 380) { y_gap = Gatebar_labeling.blobs[max_num].y - Gatebar_labeling.blobs[min_num].y; if(abs(y_gap) < 50){ gatebar_count++; if (gatebar_count > 0) gatebar_detect = true; else gatebar_detect = false; } } else gatebar_detect = false; } else { gatebar_detect = false; gatebar_count = 0; } } void vision::Traffic_Process(Mat &raw_image, Mat &draw_image) { Mat Traffic_Sign_img = raw_image(Rect(200,80,100,70)).clone(); rectangle(draw_image, Rect(200,80,100,70),Yellow, 3, 8, 0); Change_to_Binary(Traffic_Sign_img, Traffic_Sign_img, traffic_value, 0); Q_EMIT traffic_callback(Traffic_Sign_img); vision_labeling Traffic_labeling(Traffic_Sign_img, 300); Traffic_labeling.do_labeling(); Traffic_labeling.draw_maximum_label_rect(draw_image); if(Traffic_labeling.blobs.size() > 0) { int x = Traffic_labeling.blobs[Traffic_labeling.max_num].x + (int)(Traffic_labeling.blobs[Traffic_labeling.max_num].width / 2) + 200; int y = Traffic_labeling.blobs[Traffic_labeling.max_num].y + (int)(Traffic_labeling.blobs[Traffic_labeling.max_num].height / 2) + 80; int radius = (int)(Traffic_labeling.blobs[Traffic_labeling.max_num].width / 2); circle(draw_image,Point(x, y), radius, Scalar(51,153,51), 3, 8, 0); traffic_action = 1; } } void vision::Construct_Process() { if(!construct_detect1 && sensor_data[1] > 250 && (direction_angle < 10 || direction_angle > 350)) //30, 50 { construct_detect1 = true; } if(construct_detect1 && sensor_data[1] > 250 && (direction_angle > 30 && direction_angle < 50)) //30, 50 { timer_ctrl = true; construct_detect2 = true; } if(construct_detect1 && construct_detect2 && (timer_cnt < 45 && sensor_data[1] > 200 && sensor_data[0] > 80) && (direction_angle > 85 && direction_angle < 110)) { process_flag[1] = true; construct_detect1 = false; timer_ctrl = false; construct_condition = left_c1; } else if(construct_detect2 && timer_cnt >= 45) { construct_detect1 = false; construct_detect2 = false; timer_ctrl = false; } if(construct_condition >= left_c1) { switch(construct_condition) { case left_c1: if(direction_angle >= 130 && direction_angle <= 140) construct_condition = front_c1; break; case front_c1: if((direction_angle >= 30 && direction_angle <= 80 && vision_line::w_line_detect)) { construct_detect2 = false; construct_condition = 0; } break; } } } void vision::Sign_Process(Mat &raw_image, Mat &draw_image) { Mat Blue_Sign_img = raw_image(Rect(0,0,320,120)).clone(); Change_to_Binary(Blue_Sign_img, Blue_Sign_img, parking_value, 0); Q_EMIT parking_sign_callback(Blue_Sign_img); if(cross_condition >= wait && cross_detect) { if(sign_condition[right]) Cross_Process(1); else if(sign_condition[left]) Cross_Process(0); } } void vision::Cross_Process(bool direction) { if(direction){ if(cross_condition > wait) //right { if(direction_angle >= 120 && direction_angle <= 130) cross_condition = drive; else if(cross_condition == drive){ timer_ctrl = true; if(timer_cnt > 30 && vision_line::y_line_detect){ cross_condition = turn_r2; timer_ctrl = false; } } else if(cross_condition == turn_r2){ if(direction_angle >= 170 && direction_angle <= 190){ sign_condition[right] = false; cross_detect = false; cross_condition = 0; sign_count[0] = 0; sign_count[1] = 0; } } } } else{ if(cross_condition > wait) //left { if(direction_angle >= 225 && direction_angle <= 235) cross_condition = drive; else if(cross_condition == drive) { timer_ctrl = true; if(timer_cnt > 30 && vision_line::w_line_detect && (direction_angle >= 50 && direction_angle <= 130)) { vision::direction = true; cross_condition = turn_l2; timer_ctrl = false; } } else if(cross_condition == turn_l2){ if(direction_angle >= 150 && direction_angle <= 170){ sign_condition[left] = false; cross_detect = false; cross_condition = 0; sign_count[0] = 0; sign_count[1] = 0; } } } } } void vision::Parking_Process() { if(parking_detect && parking_condition >= mark) { switch (parking_condition) { case mark: if(vision_line::l_line_detect) parking_condition = line1; break; case line1: if(!vision_line::l_line_detect) parking_condition = go; break; case go: if(vision_line::y_line_detect){ parking_condition = turn1; } break; case turn1: if(direction_angle <= 265 && direction_angle >= 255) parking_condition = line2; break; case line2: timer_ctrl = true; if(timer_cnt > 68 && sensor_data[2] > 350) { parking_condition = detect; rotate = 1; timer_ctrl = false; } else if(timer_cnt > 68 && sensor_data[1] > 350) { parking_condition = detect; rotate = 0; timer_ctrl = false; } break; case detect: if(vision_line::v_line_detect && rotate == 1) parking_condition = turn2l; else if(vision_line::v_line_detect && rotate == 0) parking_condition = turn2r; break; case turn2l: if(direction_angle <= 190 && direction_angle >= 170) // target parking_condition = back; break; case turn2r: if(direction_angle <= 10 || direction_angle >= 355) // target /*direction_angle <= 185 && direction_angle >=175*/ parking_condition = back; break; case back: timer_ctrl = true; if(timer_cnt > 4){ parking_condition = front; timer_ctrl = false; }break; case front: timer_ctrl = true; if(timer_cnt > 6){ if(rotate) parking_condition = turn3l; else parking_condition = turn3r; timer_ctrl = false; }break; case turn3r: if(direction_angle >= 75 && direction_angle <= 90) parking_condition = line3; break; case turn3l: if(direction_angle >= 90 && direction_angle <= 105) parking_condition = line3; break; case line3: if(!vision_line::r_line_detect && !vision_line::l_line_detect) parking_condition = front2; break; case front2: timer_ctrl = true; if(timer_cnt > 15){ parking_condition = turn4; timer_ctrl = false; }break; case turn4: if(direction_angle >= 165 && direction_angle <= 175){ parking_condition = 0; parking_detect = false; timer_ctrl = false; sign_count[2] = 0; }break; } } } vision_line:: vision_line(Mat &line_img, Mat &line_img2) { line_color = line_img.clone(); line_color2 = line_img2.clone(); vision::Change_to_Binary(line_img, line_binary, yellow_value, 0); vision::Change_to_Binary(line_img2, line_binary2, yellow_value, 0); vision::Change_to_Binary(line_img, line_binary3, white_value, 0);\ vision::Change_to_Binary(line_img2, line_binary4, white_value, 0); medianBlur(line_color, line_color , 9); GaussianBlur(line_color, line_color , Size(15,15) , 2.0); Canny(line_color, edge_img, Canny_value[0], Canny_value[1], 3); medianBlur(line_color2, line_color2 , 9); GaussianBlur(line_color2, line_color2 , Size(15,15) , 2.0); Canny(line_color2, edge_img2, Canny_value[0], Canny_value[1], 3); Reinforce_Line(edge_img, reinforce_line); if(vision::parking_condition >= 2) Reinforce_Vertical_Line(edge_img, V_reinforce_line); if(vision::cross_condition >= 4 || vision::construct_condition >= 1 || vision::parking_condition >= 1) Reinforce_Color_Line(edge_img2); Line_Color_Analyze(); RANSAC_LINE(line_img, line_img2); } void vision_line::Reinforce_Line(Mat &input_img, Mat &output_img) { output_img = Mat::zeros(RAW_Y , RAW_X , CV_8U); int pos_average = 0; for(int y = 0; y < input_img.rows - 1; y++) { uchar* pointer_input_img = input_img.ptr<uchar>(y); uchar* pointer_output_img = output_img.ptr<uchar>(y); for(int x = 0; x < input_img.cols - 1; x++) { if(pointer_input_img[x] == 255) { vector<int> stack; stack.push_back(0); for(int dx = 0 ; dx < LINE_MAXIMUM_WIDTH && (x + dx) < (RAW_X - 1) ; dx++) { if(pointer_input_img[x + dx] == 255) stack.push_back(x + dx); } if(stack.size() > 0) { if(stack[stack.size() - 1] - x > LINE_MINIMUM_WIDTH) { for(int i = 1 ; i < stack.size() ; i++) pos_average += stack[i]; pos_average = (int)(pos_average / (stack.size() - 1)); pointer_output_img[pos_average] = 255; if(pos_average + 1 < 320) pointer_output_img[pos_average + 1] = 255; if(pos_average - 1 > 0) pointer_output_img[pos_average - 1] = 255; pos_average = 0; } } } } } } void vision_line::Reinforce_Color_Line(Mat &input_img) { Y_reinforce_line = Mat::zeros(RAW_Y, RAW_X, CV_8U); W_reinforce_line = Mat::zeros(RAW_Y, RAW_X, CV_8U); int pos_average = 0; for(int y = 90; y < 180; y++) { for(int x = 40; x < 280 ; x++) { uchar *pointer_input_img = input_img.ptr<uchar>(y); uchar *pointer_line_binary_img = line_binary2.ptr<uchar>(y); //yellow if(pointer_input_img[x] == 255) { vector<int> stack; stack.push_back(0); for(int dy = 0 ; dy < LINE_MAXIMUM_WIDTH && (y + dy) < (180 - 1) ; dy++) { uchar* pointer_input_check = input_img.ptr<uchar>(y + dy); if(pointer_input_check[x] == 255) stack.push_back(y + dy); } if(stack.size() > 0) { if(stack[stack.size() - 1] - y > LINE_MINIMUM_WIDTH) { for(int i = 1 ; i < stack.size() ; i++) pos_average += stack[i]; pos_average = (int)(pos_average / (stack.size() - 1)); if(pointer_line_binary_img[x] == 255) { for(int i = -1 ; i < 2 ; i++) { uchar* pointer_output_img = Y_reinforce_line.ptr<uchar>(y + i); for(int i = -1 ; i < 2 ; i++) { if(x + i < 320 && x + i > 0) pointer_output_img[x + i] = 255; } } } pos_average = 0; } } } } } pos_average = 0; for(int y = 60; y < 150; y++) { uchar* pointer_input_img = input_img.ptr<uchar>(y); uchar *pointer_line_binary_img2 = line_binary4.ptr<uchar>(y); //white for(int x = 40; x < 280 ; x++) { if(pointer_input_img[x] == 255) { vector<int> stack; stack.push_back(0); for(int dx = 0 ; dx < LINE_MAXIMUM_WIDTH2 && (x + dx) < (280 - 1) ; dx++) { if(pointer_input_img[x + dx] == 255) stack.push_back(x + dx); } if(stack.size() > 0) { if(stack[stack.size() - 1] - x > LINE_MINIMUM_WIDTH) { for(int i = 1 ; i < stack.size() ; i++) pos_average += stack[i]; pos_average = (int)(pos_average / (stack.size() - 1)); if(pointer_line_binary_img2[pos_average] == 255) { for(int i = -1 ; i < 2 ; i++) { uchar* pointer_output_img = W_reinforce_line.ptr<uchar>(y + i); for(int j = -1 ; j < 2 ; j++) { if(x + j < 320 && x + j > 0) pointer_output_img[x + j] = 255; } } } pos_average = 0; } } } } } } void vision_line::Reinforce_Vertical_Line(Mat &input_img, Mat &output_img) { output_img = Mat::zeros(RAW_Y, RAW_X, CV_8U); int pos_average = 0; int y_gap; if(vision::parking_condition > 2) { y_gap = 0; } else { y_gap = 100; } for(int y = y_gap; y < input_img.rows - 1; y++) { for(int x = 100; x < 220 ; x++) { uchar* pointer_input_img = input_img.ptr<uchar>(y); if(pointer_input_img[x] == 255) { vector<int> stack; stack.push_back(0); for(int dy = 0 ; dy < LINE_MAXIMUM_WIDTH && (y + dy) < (RAW_Y - 1) ; dy++) { uchar* pointer_input_check = input_img.ptr<uchar>(y + dy); if(pointer_input_check[x] == 255) stack.push_back(y + dy); } if(stack.size() > 0) { if(stack[stack.size() - 1] - y > LINE_MINIMUM_WIDTH) { for(int i = 1 ; i < stack.size() ; i++) pos_average += stack[i]; pos_average = (int)(pos_average / (stack.size() - 1)); if(pos_average + 1 < 320 && pos_average - 1 > 0) { if(vision::parking_condition >= 3) { uchar *pointer_line_binary_img = line_binary.ptr<uchar>(pos_average); if(pointer_line_binary_img[x] == 255) { for(int i = -1 ; i < 2 ; i++) { uchar* pointer_output_img = output_img.ptr<uchar>(pos_average + i); for(int i = -1 ; i < 2; i++) pointer_output_img[x + i] = 255; } } } else { for(int i = -1 ; i < 2 ; i++) { uchar* pointer_output_img = output_img.ptr<uchar>(pos_average + i); for(int i = -1 ; i < 2; i++) pointer_output_img[x + i] = 255; } } } pos_average = 0; } } } } } } void vision_line::Line_Color_Analyze() { yellow_line = Mat::zeros(RAW_Y / 2 , RAW_X , CV_8U); white_line = Mat::zeros(RAW_Y / 2 , RAW_X , CV_8U); if(vision::parking_condition < 4) { for(int y = Y_POS_GAP ; y < reinforce_line.rows ; y++) { uchar *pointer_line_img = reinforce_line.ptr<uchar>(y); uchar *pointer_line_binary_img = line_binary.ptr<uchar>(y); uchar *pointer_line_binary_img2 = line_binary3.ptr<uchar>(y); uchar *pointer_yellow_img = yellow_line.ptr<uchar>(y - Y_POS_GAP); uchar *pointer_white_img = white_line.ptr<uchar>(y - Y_POS_GAP); for(int x = 0 ; x < reinforce_line.cols ; x++) { if(pointer_line_img[x] == 255) { if(pointer_line_binary_img[x] == 255) { for(int i = -1 ; i < 2 ; i++) pointer_yellow_img[x + i] = 255; } else if(pointer_line_binary_img2[x] == 255) { for(int i = -1 ; i < 2 ; i++) pointer_white_img[x] = 255; } } } } } else { for(int y = Y_POS_GAP ; y < reinforce_line.rows ; y++) { uchar *pointer_line_img = reinforce_line.ptr<uchar>(y); uchar *pointer_yellow_img = yellow_line.ptr<uchar>(y - Y_POS_GAP); uchar *pointer_white_img = white_line.ptr<uchar>(y - Y_POS_GAP); for(int x = 0 ; x < reinforce_line.cols; x++) { if(pointer_line_img[x] == 255) { if(x < 160) pointer_yellow_img[x] = 255; else pointer_white_img[x] = 255; } } } } if(vision::parking_condition < 4) { for(int y = 0; y < white_line.rows ; y++) { uchar *pointer_white_img = white_line.ptr<uchar>(y); for(int x = 0 ; x < 100 ; x++) pointer_white_img[x] = 0; } for(int y = 0; y < white_line.rows ; y++) { uchar *pointer_yellow_img = yellow_line.ptr<uchar>(y); for(int x = 220 ; x < 320 ; x++) pointer_yellow_img[x] = 0; } } } void vision_line::RANSAC_LINE(Mat &perspective_img, Mat &perspective_img2) { vision_RANSAC Yellow_RANSAC(yellow_line); vision_RANSAC White_RANSAC(white_line); vision_RANSAC Vertical_RANSAC(V_reinforce_line); vision_RANSAC Y_Vertical_RANSAC(Y_reinforce_line); vision_RANSAC W_Vertical_RANSAC(W_reinforce_line); Yellow_RANSAC.runRansac(); White_RANSAC.runRansac(); Vertical_RANSAC.runRansac(); Y_Vertical_RANSAC.runRansac(); W_Vertical_RANSAC.runRansac(); if(!Yellow_RANSAC.m_noSamples) { Point yellow_point_a = Yellow_RANSAC.getPointLineA(); yellow_point_a = Point(yellow_point_a.x,yellow_point_a.y + Y_POS_GAP); Point yellow_point_b = Yellow_RANSAC.getPointLineB(); yellow_point_b = Point(yellow_point_b.x,yellow_point_b.y + Y_POS_GAP); l_line_detect = true; l_line_xpos = (int)((yellow_point_a.x + yellow_point_b.x) / 2); yellow_line_deg = Yellow_RANSAC.getDegree(); line(perspective_img, yellow_point_a, yellow_point_b, Blue, 2, CV_AA); } else l_line_detect = false; if(!White_RANSAC.m_noSamples) { Point white_point_a = White_RANSAC.getPointLineA(); white_point_a = Point(white_point_a.x,white_point_a.y + Y_POS_GAP); Point white_point_b = White_RANSAC.getPointLineB(); white_point_b = Point(white_point_b.x,white_point_b.y + Y_POS_GAP); if(vision::cross_condition >= 2 && vision::direction) { r_line_detect = false; } else { r_line_detect = true; r_line_xpos = (int)((white_point_a.x + white_point_b.x) / 2); white_line_deg = White_RANSAC.getDegree(); line(perspective_img, white_point_a, white_point_b, Red, 2, CV_AA); } } else r_line_detect = false; if(!Vertical_RANSAC.m_noSamples) { Point vertical_point_a = Vertical_RANSAC.getPointLineA(); Point vertical_point_b = Vertical_RANSAC.getPointLineB(); v_line_detect = true; vertical_line_deg = Vertical_RANSAC.getDegree(); line(perspective_img, vertical_point_a, vertical_point_b, Green, 2, CV_AA); } else v_line_detect = false; if(!Y_Vertical_RANSAC.m_noSamples) { Point y_vertical_point_a = Y_Vertical_RANSAC.getPointLineA(); Point y_vertical_point_b = Y_Vertical_RANSAC.getPointLineB(); y_line_detect = true; line(perspective_img2, y_vertical_point_a, y_vertical_point_b, Purple, 2, CV_AA); } else y_line_detect = false; if(!W_Vertical_RANSAC.m_noSamples) { Point w_vertical_point_a = W_Vertical_RANSAC.getPointLineA(); Point w_vertical_point_b = W_Vertical_RANSAC.getPointLineB(); w_line_detect = true; line(perspective_img2, w_vertical_point_a, w_vertical_point_b, Skyblue, 2, CV_AA); } else w_line_detect = false; } vision_labeling::vision_labeling(Mat &binary_img, int threshold) { img_binary = binary_img.clone(); pixel_threshold = threshold; } void vision_labeling::do_labeling() { pixel_num = 0; num_of_labels = connectedComponentsWithStats(img_binary, img_labels,stats,centroids,8,CV_32S); for(int i = 1 ; i < num_of_labels ; i++) { int area = stats.at<int>(i,CC_STAT_AREA); int left = stats.at<int>(i,CC_STAT_LEFT); int top = stats.at<int>(i,CC_STAT_TOP); int width = stats.at<int>(i,CC_STAT_WIDTH); int height = stats.at<int>(i,CC_STAT_HEIGHT); for(int y = top ; y < top + height ; y++) { uchar *pointer_binary_img = img_binary.ptr<uchar>(y); for(int x = left ; x < left + width ; x++) { if(pointer_binary_img[x] == 255) pixel_num++; } } if(pixel_num > pixel_threshold) blobs.push_back(cv::Rect(left,top,width,height)); } } void vision_labeling::draw_maximum_label_rect(Mat &raw_img) { max_num = 0; max_pixel = 0; if(blobs.size() > 0) { int *num_of_pixel = new int[blobs.size()]; for(int i = 0 ; i < blobs.size() ; i++) num_of_pixel[i] = 0; for(int i = 0 ; i < blobs.size() ; i++) { for(int y = blobs[i].y ; y < blobs[i].y + blobs[i].height ; y++) { uchar *pointer_binary_img = img_binary.ptr<uchar>(y); for(int x = blobs[i].x ; x < blobs[i].x + blobs[i].width ; x++) { if(pointer_binary_img[x] == 255) num_of_pixel[i]++; } } if(num_of_pixel[i] > max_pixel) { max_pixel = num_of_pixel[i]; max_num = i; } } delete num_of_pixel; } } void vision_record::prepare_Record() { if(button_clicked && count == 0) { count++; output_video = string("left.avi"); outputVideo.open(output_video, cv::VideoWriter::fourcc('M','J','P','G'), 13.0, cv::Size(320,240), true); } } void vision_record::do_Record(Mat &input_img) { if(button_clicked){ outputVideo << input_img; } } vision_RANSAC::vision_RANSAC(const Mat& img) { m_ImgData = (unsigned char *)img.data; m_width = img.cols; m_height = img.rows; m_lineThreshold = 10; m_pos.clear(); m_noSamples = true; m_degree = 0.0; } void vision_RANSAC::getSamples() { const unsigned int threshold_nSamples = (m_width + m_height) / 4; Point Pt_temp; for(int i = 0 ,idxY = 0 ; i < m_height ; i++, idxY += m_width) { for(int j = 0; j < m_width; j++) { if(m_ImgData[idxY + j] != 0) { Pt_temp.x = j; Pt_temp.y = i; m_pos.push_back(Pt_temp); } } } if(m_pos.size() >= threshold_nSamples) m_noSamples = false; } void vision_RANSAC::compute_model_parameter(const vector<Point>& vInlierPoint, sLine &model) { double sx = 0, sy = 0; double sxx = 0, syy = 0; double sxy = 0; for(size_t i = 0; i < vInlierPoint.size() ; ++i) { const double x = (double)vInlierPoint.at(i).x; const double y = (double)vInlierPoint.at(i).y; sx += x; sy += y; sxx += x*x; sxy += x*y; syy += y*y; } const double sw= vInlierPoint.size(); const double vxx = (sxx - sx * sx / sw) / sw; const double vxy = (sxy - sx * sy / sw) / sw; const double vyy = (syy - sy * sy / sw) / sw; const double theta = atan2(2.0 * vxy, vxx - vyy) / 2.0; model.mx = cos(theta); model.my = sin(theta); model.sx = sx / sw; model.sy = sy / sw; } double vision_RANSAC::compute_distance(sLine &line, Point &x)const { return fabs((double)((double)(x.x - line.sx)*line.my - ((double)x.y - line.sy)*line.mx))/sqrt(line.mx*line.mx + line.my*line.my); } void vision_RANSAC::runRansac() { getSamples(); if(m_noSamples == true) return; srand(time(NULL)); unsigned int nSamples = 0; nSamples=(m_pos.size() * 4) / 10; const double distance_threshold = 1.0; double max_cost = 0.0; sLine estimated_model; for(int i = 0 ; i < nSamples ; i++) { const int n = rand() % m_pos.size(); const int m = rand() % m_pos.size(); if(n == m)continue; if(norm(m_pos[n] - m_pos[m]) < m_lineThreshold)continue; vector<Point> SamplePt; SamplePt.push_back(m_pos[n]); SamplePt.push_back(m_pos[m]); compute_model_parameter(SamplePt,estimated_model); double cost = 0.; const double sqrtmmyy = sqrt(estimated_model.mx * estimated_model.mx + estimated_model.my * estimated_model.my); const double mysx = estimated_model.sx * estimated_model.my; const double mxsy = estimated_model.sy * estimated_model.mx; const double sub_ms = mxsy - mysx; for(size_t i = 0; i < m_pos.size(); i++) { const double distance = fabs((((double)m_pos[i].x*estimated_model.my) - ((double)m_pos[i].y * estimated_model.mx)) + sub_ms) / sqrtmmyy; if (distance < distance_threshold) cost += 1.0; } const double CostThresHold = norm(SamplePt[0] - SamplePt[1]) / 3.0; if(cost < CostThresHold)continue; if(cost > max_cost) { m_line_A = m_pos[n]; m_line_B = m_pos[m]; max_cost = cost; } } if(m_line_A.x < m_line_B.x) { Point tempP = m_line_A; m_line_A = m_line_B; m_line_B = tempP; } m_degree = -(atan2(m_line_A.y - m_line_B.y, m_line_A.x - m_line_B.x) * 180.0) / CV_PI; if(m_degree < 0.0) m_degree += 180.0; }
35.343073
164
0.537694
zang09
e1330234abe6a638ba2cd7650bd6a42b47176f81
1,478
cpp
C++
Library/Sources/Stroika/Foundation/Time/Realtime.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Time/Realtime.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Time/Realtime.cpp
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../StroikaPreComp.h" #include "../Debug/Assertions.h" #include "Realtime.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Time; namespace { template <class Clock, class Duration> inline DurationSecondsType cvt_ (const time_point<Clock, Duration>& tp) { return chrono::duration<DurationSecondsType>{tp.time_since_epoch ()}.count (); } } namespace Stroika::Foundation::Time::Private_ { /* ******************************************************************************** *********************** Time::Private::GetClockTickountOffset_ ***************** ******************************************************************************** */ template <> DurationSecondsType GetClockTickountOffset_<chrono::steady_clock> () { // in CPP file, so that we can guarantee kFirstTC_ done exactly once, and have value not depend on which module compiled against/in what order etc. // And must be done in function - not file scope - cuz must be done first time referenced, and nearly always before main () static const DurationSecondsType kFirstTC_ = cvt_ (chrono::steady_clock::now ()); Stroika_Foundation_Debug_ValgrindDisableHelgrind (kFirstTC_); // ignore warning because C++ guarantees magic statics -- LGP 2017-09-14 return kFirstTC_; } }
38.894737
155
0.609608
SophistSolutions
e1365dfa5d5aa5062db84d5a24d165de96db1604
2,572
cpp
C++
tests/tx_edit_multisig_test.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
7
2019-06-26T11:37:49.000Z
2020-11-04T21:47:19.000Z
tests/tx_edit_multisig_test.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
1
2020-02-29T10:41:58.000Z
2020-03-02T16:21:40.000Z
tests/tx_edit_multisig_test.cpp
MinterTeam/cpp-minter
af657bb21d4b68429948f8d34fd642f874fe412e
[ "MIT" ]
5
2019-08-22T16:24:18.000Z
2020-03-01T15:34:08.000Z
/*! * minter_tx. * tx_edit_multisig_owners_data_test.cpp * * \date 2020 * \author Eduard Maximovich (edward.vstock@gmail.com) * \link https://github.com/edwardstock */ #include <gtest/gtest.h> #include <minter/tx/tx.h> #include <minter/tx/tx_builder.h> #include <minter/tx/tx_edit_multisig.h> TEST(TxEditMultisigOwnersData, TestEncode) { const char* expected = "f8800801018012b0ef03c20102ea9467691076548b20234461ff6fd2bc9c64393eb8fc94c26dbd06984949a0efce1517925ca57a8d7a2c06808001b845f8431ca02da06551a97e23cefd1f0aecdbbb4ae5a40bf412a817a38c59d89ff18c33520ca06a758b304bb363e34746284db3df1809c6f17506726eab8378d59063ddd93764"; minter::privkey_t pk = "4daf02f92bf760b53d3c725d6bcc0da8e55d27ba5350c78d3a88f873e502bd6e"; //addAddress("Mx67691076548b20234461ff6fd2bc9c64393eb8fc", 1) // .addAddress("Mxc26dbd06984949a0efce1517925ca57a8d7a2c06", 2) // .setThreshold(3) auto tx = minter::new_tx() ->set_gas_coin_id(dev::bigint("0")) .set_nonce(dev::bigint("8")) .set_gas_price("1") .set_chain_id(minter::mainnet) .tx_edit_multisig() ->add_address(minter::address_t("Mx67691076548b20234461ff6fd2bc9c64393eb8fc"), 1) .add_address(minter::address_t("Mxc26dbd06984949a0efce1517925ca57a8d7a2c06"), 2) .set_threshold(3) .build(); auto signature = tx->sign_single(pk); ASSERT_STREQ(expected, signature.to_hex().c_str()); } TEST(TxEditMultisigOwnersData, TestDecode) { const char* encoded = "f8800801018012b0ef03c20102ea9467691076548b20234461ff6fd2bc9c64393eb8fc94c26dbd06984949a0efce1517925ca57a8d7a2c06808001b845f8431ca02da06551a97e23cefd1f0aecdbbb4ae5a40bf412a817a38c59d89ff18c33520ca06a758b304bb363e34746284db3df1809c6f17506726eab8378d59063ddd93764"; auto decoded = minter::tx::decode(encoded); auto data = decoded->get_data<minter::tx_edit_multisig>(); ASSERT_EQ(2, data->get_addresses().size()); ASSERT_EQ(2, data->get_weights().size()); ASSERT_EQ(3, data->get_threshold()); minter::address_t a1 = data->get_addresses()[0]; minter::address_t a2 = data->get_addresses()[1]; ASSERT_EQ(minter::address_t("Mx67691076548b20234461ff6fd2bc9c64393eb8fc"), a1); ASSERT_EQ(minter::address_t("Mxc26dbd06984949a0efce1517925ca57a8d7a2c06"), a2); dev::bigint w1 = data->get_weights()[0]; dev::bigint w2 = data->get_weights()[1]; ASSERT_EQ(dev::bigint("1"), w1); ASSERT_EQ(dev::bigint("2"), w2); }
44.344828
290
0.721229
MinterTeam
e137ffb45f24d9ae917b0deee733482d3830e316
3,121
cpp
C++
project/race3d/src/WorldLoader/CStatic.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
5
2015-01-05T17:03:00.000Z
2016-04-07T07:43:32.000Z
project/race3d/src/WorldLoader/CStatic.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
null
null
null
project/race3d/src/WorldLoader/CStatic.cpp
maximbilan/cpp_marmalade_sdk_the_pursuit_3d
b0e42bae7ba5c47c5bf2f9db22d973f3319cdb06
[ "MIT" ]
null
null
null
#include "CStatic.h" #include "WorldLoader.h" #include "IwSerialise.h" #include "IwTextParserITX.h" //---------------------------------------------------------------------------------------------- IW_MANAGED_IMPLEMENT_FACTORY( CStatic ); //---------------------------------------------------------------------------------------------- CStatic::CStatic() { IW_CALLSTACK( "CStatic::CStatic" ); } //---------------------------------------------------------------------------------------------- CStatic::~CStatic() { IW_CALLSTACK( "CStatic::~CStatic" ); } //---------------------------------------------------------------------------------------------- bool CStatic::ParseAttribute( CIwTextParserITX* apParser, const char* apAttribute ) { IW_CALLSTACK( "CStatic::ParseAttribute" ); if( !stricmp( apAttribute, "name" ) ) { apParser->ReadString( m_name ); } else if( !stricmp( apAttribute, "model" ) ) { apParser->ReadString( m_modelName ); } else if( !stricmp( apAttribute, "groupName" ) ) { apParser->ReadString( m_groupName ); } else if( !stricmp( apAttribute, "pos" ) ) { float f[3]; apParser->ReadFloatArray( f, 3 ); m_position.x = f[0]; m_position.y = f[1]; m_position.z = f[2]; } else if( !stricmp( apAttribute, "rot" ) ) { float f[4]; apParser->ReadFloatArray( f, 4 ); m_rotation.s = static_cast<float>( f[0] ); m_rotation.x = static_cast<float>( f[1] ); m_rotation.y = static_cast<float>( f[2] ); m_rotation.z = static_cast<float>( f[3] ); } else if( !stricmp( apAttribute, "entityType" ) ) { apParser->ReadString( m_entityType ); } else if( !stricmp( apAttribute, "collisionType" ) ) { apParser->ReadString( m_collisionType ); } else if( !stricmp( apAttribute, "mass" ) ) { apParser->ReadFloat( &m_mass ); } else if( !stricmp( apAttribute, "scale" ) ) { apParser->ReadFloat( &m_scale ); } else if( !stricmp( apAttribute, "onEnterScript" ) ) { apParser->ReadString( m_onEnterScript ); } else if( !stricmp( apAttribute, "onLeaveScript" ) ) { apParser->ReadString( m_onLeaveScript ); } else { return CIwManaged::ParseAttribute( apParser, apAttribute ); } return true; } //---------------------------------------------------------------------------------------------- void CStatic::ParseClose( CIwTextParserITX* apParser ) { IW_CALLSTACK( "CStatic::ParseClose" ); WorldLoader::AddObject( this ); } //---------------------------------------------------------------------------------------------- void CStatic::Serialise() { IW_CALLSTACK( "CStatic::Serialise" ); CIwManaged::Serialise(); m_name.Serialise(); m_modelName.Serialise(); m_groupName.Serialise(); m_entityType.Serialise(); m_collisionType.Serialise(); m_position.Serialise(); m_rotation.Serialise(); IwSerialiseBool( m_isVisible ); IwSerialiseBool( m_isEnabled ); IwSerialiseFloat( m_mass ); IwSerialiseFloat( m_scale ); m_onEnterScript.Serialise(); m_onLeaveScript.Serialise(); } //---------------------------------------------------------------------------------------------- void CStatic::Resolve() { IW_CALLSTACK( "CStatic::Resolve" ); }
24.007692
96
0.533483
maximbilan
e13b96f6a90ddd763b9221f52f19a1dbdf8ff558
7,141
cpp
C++
cpp/open3d/ml/tensorflow/misc/InvertNeighborsListOps.cpp
zhengminxu/Open3D
e17648468030018155de1e225a86dbb56fed1dec
[ "MIT" ]
1
2021-08-06T06:16:08.000Z
2021-08-06T06:16:08.000Z
cpp/open3d/ml/tensorflow/misc/InvertNeighborsListOps.cpp
zhengminxu/Open3D
e17648468030018155de1e225a86dbb56fed1dec
[ "MIT" ]
null
null
null
cpp/open3d/ml/tensorflow/misc/InvertNeighborsListOps.cpp
zhengminxu/Open3D
e17648468030018155de1e225a86dbb56fed1dec
[ "MIT" ]
1
2021-08-05T13:51:10.000Z
2021-08-05T13:51:10.000Z
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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. // ---------------------------------------------------------------------------- #include "open3d/ml/tensorflow/TensorFlowHelper.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/core/errors.h" using namespace tensorflow; REGISTER_OP("Open3DInvertNeighborsList") .Attr("TIndex: {int32}") .Attr("TAttr: {int32, int64, float, double}") .Input("num_points: int64") .Input("inp_neighbors_index: TIndex") .Input("inp_neighbors_row_splits: int64") .Input("inp_neighbors_attributes: TAttr") .Output("neighbors_index: TIndex") .Output("neighbors_row_splits: int64") .Output("neighbors_attributes: TAttr") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { using namespace ::tensorflow::shape_inference; ShapeHandle num_points, inp_neighbors_index, inp_neighbors_row_splits, inp_neighbors_attributes, neighbors_index, neighbors_row_splits; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &num_points)); TF_RETURN_IF_ERROR( c->WithRank(c->input(1), 1, &inp_neighbors_index)); TF_RETURN_IF_ERROR( c->WithRank(c->input(2), 1, &inp_neighbors_row_splits)); TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(3), 1, &inp_neighbors_attributes)); // check input shapes { using namespace open3d::ml::op_util; Dim num_neighbors("num_neighbors"); CHECK_SHAPE_HANDLE(c, inp_neighbors_index, num_neighbors); CHECK_SHAPE_HANDLE_IGNORE_LAST_DIMS(c, inp_neighbors_attributes, num_neighbors || 0); CHECK_SHAPE_HANDLE(c, inp_neighbors_row_splits, Dim()); } // output will have the same shape c->set_output(0, inp_neighbors_index); // The length of the prefix sum vector will change to num_points // which we do not know here neighbors_row_splits = c->MakeShape({c->UnknownDim()}); c->set_output(1, neighbors_row_splits); // the attributes will have the same shape c->set_output(2, inp_neighbors_attributes); return Status::OK(); }) .Doc(R"doc( Inverts a neighbors list made of neighbors_index and neighbors_row_splits. This op inverts the neighbors list as returned from the neighbor search ops. The role of query points and input points is reversed in the returned list. The following example illustrates this:: import open3d.ml.tf as ml3d # in this example we have 4 points and 3 query points with 3, 1, and 2 neighbors # the mapping is 0->(0,1,2), 1->(2), 2->(1,3) neighbors_index = [0, 1, 2, 2, 1, 3] neighbors_row_splits = [0, 3, 4, 6] # optional attributes for each pair neighbors_attributes = [10, 20, 30, 40, 50, 60] ans = ml3d.ops.invert_neighbors_list(4, neighbors_index, neighbors_row_splits, neighbors_attributes) # returns ans.neighbors_index = [0, 0, 2, 0, 1, 2] # ans.neighbors_row_splits = [0, 1, 3, 5, 6] # ans.neighbors_attributes = [10, 20, 50, 30, 40, 60] # which is the mapping 0->(0), 1->(0,2), 2->(0,1), 3->(2) # note that the order of the neighbors can be permuted # or with pytorch import torch import open3d.ml.torch as ml3d # in this example we have 4 points and 3 query points with 3, 1, and 2 neighbors # the mapping is 0->(0,1,2), 1->(2), 2->(1,3) neighbors_index = torch.IntTensor([0, 1, 2, 2, 1, 3]) neighbors_row_splits = torch.LongTensor([0, 3, 4, 6]) # optional attributes for each pair neighbors_attributes = torch.Tensor([10, 20, 30, 40, 50, 60]) ans = ml3d.ops.invert_neighbors_list(4, neighbors_index, neighbors_row_splits, neighbors_attributes) # returns ans.neighbors_index = [0, 0, 2, 0, 1, 2] # ans.neighbors_row_splits = [0, 1, 3, 5, 6] # ans.neighbors_attributes = [10, 20, 50, 30, 40, 60] # which is the mapping 0->(0), 1->(0,2), 2->(0,1), 3->(2) # note that the order of the neighbors can be permuted num_points: Scalar integer with the number of points that have been tested in a neighbor search. This is the number of the points in the second point cloud (not the query point cloud) in a neighbor search. The size of the output **neighbors_row_splits** will be **num_points** +1. inp_neighbors_index: The input neighbor indices stored linearly. inp_neighbors_row_splits: The number of neighbors for the input queries as exclusive prefix sum. The prefix sum includes the total number as last element. inp_neighbors_attributes: Array that stores an attribute for each neighbor. The size of the first dim must match the first dim of inp_neighbors_index. To ignore attributes pass a 1D Tensor with zero size. neighbors_index: The output neighbor indices stored linearly. neighbors_row_splits: Stores the number of neighbors for the new queries, previously the input points, as exclusive prefix sum including the total number in the last element. neighbors_attributes: Array that stores an attribute for each neighbor. If the inp_neighbors_attributes Tensor is a zero length vector then the output will be a zero length vector as well. )doc");
45.775641
88
0.631984
zhengminxu
e13e00709b3260668c2d30ae071b6bc79fc39bbc
234
cpp
C++
test/algos/is_valid_parentheses.cpp
paulpan05/algodts-cpp
db02a8d18668afb004bc63a1814fcc6fe32729ef
[ "Apache-2.0" ]
null
null
null
test/algos/is_valid_parentheses.cpp
paulpan05/algodts-cpp
db02a8d18668afb004bc63a1814fcc6fe32729ef
[ "Apache-2.0" ]
null
null
null
test/algos/is_valid_parentheses.cpp
paulpan05/algodts-cpp
db02a8d18668afb004bc63a1814fcc6fe32729ef
[ "Apache-2.0" ]
null
null
null
#include <algodts/algos/is_valid_parentheses.hpp> #include <testing/catch.hh> using namespace std; TEST_CASE("Testing parentheses validity", "[parentheses]") { string input = "{}[]]"; REQUIRE_FALSE(isValidParentheses(input)); }
23.4
60
0.739316
paulpan05
e1410dac1ae4ebe9b007f4433f27dfab64cf3582
283
hpp
C++
MainGUI.hpp
erurami/connect4-game
e6e1a695e92acc1aa074573e302a1f4324882bfd
[ "MIT" ]
null
null
null
MainGUI.hpp
erurami/connect4-game
e6e1a695e92acc1aa074573e302a1f4324882bfd
[ "MIT" ]
null
null
null
MainGUI.hpp
erurami/connect4-game
e6e1a695e92acc1aa074573e302a1f4324882bfd
[ "MIT" ]
null
null
null
#pragma once // (C)onnect(4) (G)UI (W)indow (M)essage #define _C4GWM_REDRAW (WM_APP + 1) #define CONNECT4_CELL_GAP (cell_width / 15) #define CONNECT4_CELL_ROUNDNESS (cell_width / 10) int _Connect4GuiRegisterMainGuiWndClass(LPTSTR strWndClassName); #include "MainGUI.ipp"
20.214286
64
0.749117
erurami
e1418434cc43ae7aee933c4b6651a4a029920691
1,629
cc
C++
components/dom_distiller/webui/dom_distiller_ui.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
components/dom_distiller/webui/dom_distiller_ui.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
components/dom_distiller/webui/dom_distiller_ui.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/dom_distiller/webui/dom_distiller_ui.h" #include "components/dom_distiller/core/dom_distiller_constants.h" #include "components/dom_distiller/webui/dom_distiller_handler.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "grit/component_strings.h" #include "grit/dom_distiller_resources.h" namespace dom_distiller { DomDistillerUI::DomDistillerUI(content::WebUI* web_ui) : content::WebUIController(web_ui) { // Set up WebUIDataSource. content::WebUIDataSource* source = content::WebUIDataSource::Create(kChromeUIDomDistillerHost); source->SetDefaultResource(IDR_ABOUT_DOM_DISTILLER_HTML); source->AddResourcePath("about_dom_distiller.css", IDR_ABOUT_DOM_DISTILLER_CSS); source->AddResourcePath("about_dom_distiller.js", IDR_ABOUT_DOM_DISTILLER_JS); source->SetUseJsonJSFormatV2(); source->AddLocalizedString("domDistillerTitle", IDS_DOM_DISTILLER_TITLE); content::BrowserContext* browser_context = web_ui->GetWebContents()->GetBrowserContext(); content::WebUIDataSource::Add(browser_context, source); source->SetJsonPath("strings.js"); // Add message handler. web_ui->AddMessageHandler(new DomDistillerHandler()); } DomDistillerUI::~DomDistillerUI() {} } // namespace dom_distiller
37.883721
75
0.769184
nagineni
e141e6945513770a9978fc6411ff503e774761ee
787
cpp
C++
Operators.Test/DomainBinaryOperatorTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Operators.Test/DomainBinaryOperatorTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Operators.Test/DomainBinaryOperatorTests.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include <gtest/gtest.h> #include "Operators\BinaryOperators.h" #include "TestDomain.h" using namespace DNVS::MoFa::Operators; TEST(DomainBinaryOperatorTests, CreateDomainAndDoMultiply) { Base a; BinaryResult<Tags::Multiplies,Base,int> result=a*5; EXPECT_EQ(typeid(BinaryResult<Tags::Multiplies,Base,int>), typeid(a*5)); BinaryResult<Tags::Multiplies,int,Base> result2=5*a; EXPECT_EQ(typeid(BinaryResult<Tags::Multiplies,int,Base>), typeid(5*a)); BinaryResult<Tags::Multiplies,Base,Base> result3=a*a; EXPECT_EQ(typeid(BinaryResult<Tags::Multiplies,Base,Base>), typeid(a*a)); }
37.47619
74
0.749682
dnv-opensource
e1439f9a06f47e3a8cc6c01075d92a708525107f
9,705
cpp
C++
src/veil/proofofstake/stakeinput.cpp
jskitty-repos/veil
075f51693a5ac39e4c8bf22a9f12cd851fb29a1c
[ "MIT" ]
1
2020-07-08T18:01:12.000Z
2020-07-08T18:01:12.000Z
src/veil/proofofstake/stakeinput.cpp
MatWaller/veil
072cc3a63bda5f0c47c09cdc74635ee3bc68e160
[ "MIT" ]
1
2019-09-25T12:58:45.000Z
2019-09-25T12:58:45.000Z
src/veil/proofofstake/stakeinput.cpp
MatWaller/veil
072cc3a63bda5f0c47c09cdc74635ee3bc68e160
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2019 The PIVX developers // Copyright (c) 2019 The Veil developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <tinyformat.h> #include "veil/zerocoin/accumulators.h" #include "veil/zerocoin/mintmeta.h" #include "chain.h" #include "chainparams.h" #include "wallet/deterministicmint.h" #include "validation.h" #include "stakeinput.h" #include "veil/proofofstake/kernel.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif typedef std::vector<unsigned char> valtype; ZerocoinStake::ZerocoinStake(const libzerocoin::CoinSpend& spend) { this->nChecksum = spend.getAccumulatorChecksum(); this->denom = spend.getDenomination(); uint256 nSerial = spend.getCoinSerialNumber().getuint256(); this->hashSerial = Hash(nSerial.begin(), nSerial.end()); this->pindexFrom = nullptr; fMint = false; } int ZerocoinStake::GetChecksumHeightFromMint() { int nNewBlockHeight = chainActive.Height() + 1; int nHeightChecksum = 0; if (nNewBlockHeight >= Params().HeightLightZerocoin()) { nHeightChecksum = nNewBlockHeight - Params().Zerocoin_RequiredStakeDepthV2(); } else { nHeightChecksum = chainActive.Height() + 1 - Params().Zerocoin_RequiredStakeDepth(); } //Need to return the first occurance of this checksum in order for the validation process to identify a specific //block height uint256 nChecksum; nChecksum = chainActive[nHeightChecksum]->mapAccumulatorHashes[denom]; return GetChecksumHeight(nChecksum, denom); } int ZerocoinStake::GetChecksumHeightFromSpend() { return GetChecksumHeight(nChecksum, denom); } uint256 ZerocoinStake::GetChecksum() { return nChecksum; } // The Zerocoin block index is the first appearance of the accumulator checksum that was used in the spend // note that this also means when staking that this checksum should be from a block that is beyond 60 minutes old and // 100 blocks deep. CBlockIndex* ZerocoinStake::GetIndexFrom() { if (pindexFrom) return pindexFrom; int nHeightChecksum = 0; if (fMint) nHeightChecksum = GetChecksumHeightFromMint(); else nHeightChecksum = GetChecksumHeightFromSpend(); if (nHeightChecksum > chainActive.Height()) { pindexFrom = nullptr; } else { //note that this will be a nullptr if the height DNE pindexFrom = chainActive[nHeightChecksum]; } return pindexFrom; } CAmount ZerocoinStake::GetValue() { return denom * COIN; } int ZerocoinStake::HeightToModifierHeight(int nHeight) { //Nearest multiple of KernelModulus that is over KernelModulus bocks deep in the chain return (nHeight - Params().KernelModulus()) - (nHeight % Params().KernelModulus()) ; } // Use the PoW hash or the PoS hash uint256 GetHashFromIndex(const CBlockIndex* pindexSample) { if (pindexSample->IsProofOfWork()) return pindexSample->GetBlockPoWHash(); uint256 hashProof = pindexSample->GetBlockPoSHash(); return hashProof; } // As the sampling gets further back into the chain, use more bits of entropy. This prevents the ability to significantly // impact the modifier if you create one of the most recent blocks used. For example, the contribution from the first sample // (which is 101 blocks from the coin tip) will only be 2 bits, thus only able to modify the end result of the modifier // 4 different ways. As the sampling gets further back into the chain (take previous sample height - nSampleCount*6 for the height // it will be) it has more entropy that is assigned to that specific sampling. The further back in the chain, the less // ability there is to have any influence at all over the modifier calculations going forward from that specific block. // The bits taper down as it gets deeper into the chain so that the precomputability is less significant. int GetSampleBits(int nSampleCount) { switch(nSampleCount) { case 0: return 2; case 1: return 4; case 2: return 8; case 3: return 16; case 4: return 32; case 5: return 64; case 6: return 128; case 7: return 64; case 8: return 32; case 9: return 16; default: return 0; } } //Use the first accumulator checkpoint that occurs 60 minutes after the block being staked from bool ZerocoinStake::GetModifier(uint64_t& nStakeModifier, const CBlockIndex* pindexChainPrev) { CBlockIndex* pindex = GetIndexFrom(); if (!pindex || !pindexChainPrev) return false; uint256 hashModifier; if (pindexChainPrev->nHeight >= Params().HeightLightZerocoin()) { //Use a new modifier that is less able to be "grinded" int nHeightChain = pindexChainPrev->nHeight; int nHeightPrevious = nHeightChain - 100; for (int i = 0; i < 10; i++) { int nHeightSample = nHeightPrevious - (6*i); nHeightPrevious = nHeightSample; auto pindexSample = pindexChainPrev->GetAncestor(nHeightSample); //Get a sampling of entropy from this block. Rehash the sample, since PoW hashes may have lots of 0's uint256 hashSample = GetHashFromIndex(pindexSample); hashSample = Hash(hashSample.begin(), hashSample.end()); //Reduce the size of the sampling int nBitsToUse = GetSampleBits(i); auto arith = UintToArith256(hashSample); arith >>= (256-nBitsToUse); hashSample = ArithToUint256(arith); hashModifier = Hash(hashModifier.begin(), hashModifier.end(), hashSample.begin(), hashSample.end()); } nStakeModifier = UintToArith256(hashModifier).GetLow64(); return true; } int nNearest100Block = ZerocoinStake::HeightToModifierHeight(pindex->nHeight); //Rare case block index < 100, we don't use proof of stake for these blocks if (nNearest100Block < 1) { nStakeModifier = 1; return false; } while (nNearest100Block != pindex->nHeight) { pindex = pindex->pprev; } nStakeModifier = UintToArith256(pindex->mapAccumulatorHashes[denom]).GetLow64(); return true; } CDataStream ZerocoinStake::GetUniqueness() { //The unique identifier for a Zerocoin VEIL is a hash of the serial CDataStream ss(SER_GETHASH, 0); ss << hashSerial; return ss; } bool ZerocoinStake::CreateTxIn(CWallet* pwallet, CTxIn& txIn, uint256 hashTxOut) { #ifdef ENABLE_WALLET if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { #endif return error("%s: wallet disabled", __func__); #ifdef ENABLE_WALLET } CBlockIndex* pindexCheckpoint = GetIndexFrom(); if (!pindexCheckpoint) return error("%s: failed to find checkpoint block index", __func__); CZerocoinMint mint; if (!pwallet->GetMintFromStakeHash(hashSerial, mint)) return error("%s: failed to fetch mint associated with serial hash %s", __func__, hashSerial.GetHex()); if (libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < 2) return error("%s: serial extract is less than v2", __func__); int nSecurityLevel = 100; CZerocoinSpendReceipt receipt; if (!pwallet->MintToTxIn(mint, nSecurityLevel, hashTxOut, txIn, receipt, libzerocoin::SpendType::STAKE, GetIndexFrom())) return error("%s\n", receipt.GetStatusMessage()); return true; #endif } bool ZerocoinStake::CreateTxOuts(CWallet* pwallet, vector<CTxOut>& vout, CAmount nTotal) { #ifdef ENABLE_WALLET if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { #endif return error("%s: wallet disabled", __func__); #ifdef ENABLE_WALLET } //Create an output returning the Zerocoin VEIL that was staked CTxOut outReward; libzerocoin::CoinDenomination denomStaked = libzerocoin::AmountToZerocoinDenomination(this->GetValue()); CDeterministicMint dMint; if (!pwallet->CreateZOutPut(denomStaked, outReward, dMint)) return error("%s: failed to create zerocoin output", __func__); vout.emplace_back(outReward); //Add new staked denom to our wallet if (!pwallet->DatabaseMint(dMint)) return error("%s: failed to database the staked Zerocoin", __func__); CAmount nRewardOut = 0; while (nRewardOut < nTotal) { CTxOut out; CDeterministicMint dMintReward; auto denomReward = libzerocoin::CoinDenomination::ZQ_TEN; if (!pwallet->CreateZOutPut(denomReward, out, dMintReward)) return error("%s: failed to create Zerocoin output", __func__); vout.emplace_back(out); if (!pwallet->DatabaseMint(dMintReward)) return error("%s: failed to database mint reward", __func__); nRewardOut += libzerocoin::ZerocoinDenominationToAmount(denomReward); } return true; #endif } bool ZerocoinStake::GetTxFrom(CTransaction& tx) { return false; } bool ZerocoinStake::MarkSpent(CWallet *pwallet, const uint256& txid) { #ifdef ENABLE_WALLET if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { #endif return error("%s: wallet disabled", __func__); #ifdef ENABLE_WALLET } CzTracker* zTracker = pwallet->GetZTrackerPointer(); CMintMeta meta; if (!zTracker->GetMetaFromStakeHash(hashSerial, meta)) return error("%s: tracker does not have serialhash", __func__); zTracker->SetPubcoinUsed(meta.hashPubcoin, txid); return true; #endif } uint256 ZerocoinStake::GetSerialStakeHash() { return hashSerial; }
33.350515
130
0.691705
jskitty-repos
e14a49912aaf687d395cdc6f2e90f54df0eca2c9
147
hpp
C++
src/eepp/helper/haikuttf/haikuttf.hpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/helper/haikuttf/haikuttf.hpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
src/eepp/helper/haikuttf/haikuttf.hpp
weimingtom/eepp
dd672ff0e108ae1e08449ca918dc144018fb4ba4
[ "MIT" ]
null
null
null
#ifndef HAIKUTTF_HPP #define HAIKUTTF_HPP #include "hkbase.hpp" #include "hkglyph.hpp" #include "hkfont.hpp" #include "hkfontmanager.hpp" #endif
14.7
28
0.768707
weimingtom
e14d22ace951c3fdd281459a7eb1c8bf9af37ed7
4,719
cpp
C++
Source/Beezer/CommentWindow.cpp
Teknomancer/beezer
37dc9029aff5bd42bd38d01c7059ccbea4bb95a7
[ "BSD-3-Clause" ]
3
2020-08-20T18:57:52.000Z
2021-12-13T03:11:19.000Z
Source/Beezer/CommentWindow.cpp
Teknomancer/beezer
37dc9029aff5bd42bd38d01c7059ccbea4bb95a7
[ "BSD-3-Clause" ]
22
2020-02-24T21:40:44.000Z
2021-04-18T15:07:15.000Z
Source/Beezer/CommentWindow.cpp
Teknomancer/beezer
37dc9029aff5bd42bd38d01c7059ccbea4bb95a7
[ "BSD-3-Clause" ]
null
null
null
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2002 Ramshankar (aka Teknomancer). // Copyright (c) 2011 Chris Roberts. // All rights reserved. #include "CommentWindow.h" #include "BitmapPool.h" #include "CommonStrings.h" #include "MsgConstants.h" #include "Preferences.h" #include "PrefsFields.h" #include "StaticBitmapView.h" #include "UIConstants.h" #include <Bitmap.h> #include <Button.h> #include <GroupLayoutBuilder.h> #include <ScrollView.h> #include <StringView.h> #include <TextView.h> #ifdef HAIKU_ENABLE_I18N #include <Catalog.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "CommentWindow" #else #define B_TRANSLATE(x) x #endif #include <cstring> CommentWindow::CommentWindow(BWindow* callerWindow, const char* archiveName, const char* commentText, BFont* displayFont) : BWindow(BRect(0, 0, 590, 290), BZ_TR(kCommentString), B_FLOATING_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), m_callerWindow(callerWindow), m_textView(NULL) { if (m_callerWindow) { SetFeel(B_MODAL_SUBSET_WINDOW_FEEL); AddToSubset(m_callerWindow); } SetLayout(new BGroupLayout(B_VERTICAL, 0)); // Get comment icon from resource, construct comment holding view etc. BBitmap* commentBmp = BitmapPool::LoadAppVector("Img:Comment", 32, 32); // Add icon view, make it hold the picture StaticBitmapView* commentBmpView = new StaticBitmapView(BRect(0, 0, commentBmp->Bounds().Width(), commentBmp->Bounds().Height()), "CommentWindow:commentBmpView", commentBmp); // Add the file name string view (align it vertically with the icon view) BStringView* fileNameStr = new BStringView("CommentWindow:FileNameView", archiveName); fileNameStr->SetFont(be_bold_font); AddChild(BGroupLayoutBuilder(B_HORIZONTAL) .AddStrut(30) .Add(commentBmpView, 0.0f) .Add(fileNameStr, 1.0f) .AddGlue() .SetInsets(K_MARGIN, K_MARGIN, K_MARGIN, K_MARGIN) ); m_textView = new BTextView("CommentWindow:TextView", displayFont, NULL, B_WILL_DRAW); BScrollView* scrollView = new BScrollView("CommentWindow:ScrollView", m_textView, B_WILL_DRAW, true, true, B_PLAIN_BORDER); m_textView->SetWordWrap(false); m_textView->SetText(commentText); m_textView->DisallowChar(B_INSERT); m_textView->DisallowChar(B_ESCAPE); m_textView->DisallowChar(B_DELETE); m_textView->DisallowChar(B_TAB); m_textView->DisallowChar(B_FUNCTION_KEY); m_textView->DisallowChar(B_PAGE_UP); m_textView->DisallowChar(B_PAGE_DOWN); m_textView->DisallowChar(B_HOME); m_textView->DisallowChar(B_END); m_textView->SetMaxBytes(32768L); AddChild(scrollView); BButton* saveButton = new BButton("CommentWindow:SaveButton", BZ_TR(kSaveString), new BMessage(M_SAVE_COMMENT)); BButton* closeButton = new BButton("CommentWindow:CloseButton", BZ_TR(kCloseWindowString), new BMessage(B_QUIT_REQUESTED)); AddChild(BGroupLayoutBuilder(B_HORIZONTAL) .AddGlue() .Add(closeButton, 0.0f) .Add(saveButton, 0.0f) .SetInsets(K_MARGIN, K_MARGIN, K_MARGIN, K_MARGIN) ); // Center our window on screen CenterOnScreen(); m_textView->MakeFocus(true); // Load from prefs the window dimensions BRect frame; if (_prefs_windows.FindBoolDef(kPfCommentWnd, true)) if (_prefs_windows.FindRect(kPfCommentWndFrame, &frame) == B_OK) { MoveTo(frame.LeftTop()); ResizeTo(frame.Width(), frame.Height()); } Show(); } bool CommentWindow::QuitRequested() { if (_prefs_windows.FindBoolDef(kPfCommentWnd, true)) _prefs_windows.SetRect(kPfCommentWndFrame, Frame()); return BWindow::QuitRequested(); } void CommentWindow::MessageReceived(BMessage* message) { switch (message->what) { case M_SAVE_COMMENT: { // Let the main window handle talking with the archiver to write the comments // We will just pass it the comment (if any) as a field in a BMessage const char* commentStr = m_textView->Text(); if (commentStr && strlen(commentStr) > 0L) message->AddString(kCommentContent, commentStr); m_callerWindow->PostMessage(message); PostMessage(B_QUIT_REQUESTED); break; } default: BWindow::MessageReceived(message); break; } }
31.671141
133
0.661369
Teknomancer
e14e08a93b37e05b93563f1fb300c9a6b6fb6bf4
2,483
cpp
C++
libs/interprocess/example/comp_doc_anonymous_conditionA.cpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
libs/interprocess/example/comp_doc_anonymous_conditionA.cpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
libs/interprocess/example/comp_doc_anonymous_conditionA.cpp
Ron2014/boost_1_48_0
19673f69677ffcba7c7bd6e08ec07ee3962f161c
[ "BSL-1.0" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> //[doc_anonymous_conditionA #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <iostream> #include <cstdio> #include "doc_anonymous_condition_shared_data.hpp" using namespace boost::interprocess; int main () { //Erase previous shared memory and schedule erasure on exit struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Create a shared memory object. shared_memory_object shm (create_only //only create ,"MySharedMemory" //name ,read_write //read-write mode ); try{ //Set size shm.truncate(sizeof(trace_queue)); //Map the whole shared memory in this process mapped_region region (shm //What to map ,read_write //Map it as read-write ); //Get the address of the mapped region void * addr = region.get_address(); //Construct the shared structure in memory trace_queue * data = new (addr) trace_queue; const int NumMsg = 100; for(int i = 0; i < NumMsg; ++i){ scoped_lock<interprocess_mutex> lock(data->mutex); if(data->message_in){ data->cond_full.wait(lock); } if(i == (NumMsg-1)) std::sprintf(data->items, "%s", "last message"); else std::sprintf(data->items, "%s_%d", "my_trace", i); //Notify to the other process that there is a message data->cond_empty.notify_one(); //Mark message buffer as full data->message_in = true; } } catch(interprocess_exception &ex){ std::cout << ex.what() << std::endl; return 1; } return 0; } //]
31.0375
79
0.564237
Ron2014
e14f4e7cc46dadd7951fa61d84800e2094febbde
1,560
cpp
C++
libs/ebpfnetsh/links.cpp
fengjixuchui/ebpf-for-windows
4553bfff39ccd4c0cfb9a18560dbeeff04cf3084
[ "MIT" ]
null
null
null
libs/ebpfnetsh/links.cpp
fengjixuchui/ebpf-for-windows
4553bfff39ccd4c0cfb9a18560dbeeff04cf3084
[ "MIT" ]
1
2022-03-26T16:17:41.000Z
2022-03-26T16:17:41.000Z
libs/ebpfnetsh/links.cpp
fengjixuchui/ebpf-for-windows
4553bfff39ccd4c0cfb9a18560dbeeff04cf3084
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation // SPDX-License-Identifier: MIT #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <iostream> #include <iomanip> #include <netsh.h> #include <string> #include <vector> #include "bpf/bpf.h" #include "ebpf_api.h" #include "ebpf_windows.h" #include "platform.h" #include "links.h" #include "tokens.h" DWORD handle_ebpf_show_links( LPCWSTR machine, LPWSTR* argv, DWORD current_index, DWORD argc, DWORD flags, LPCVOID data, BOOL* done) { UNREFERENCED_PARAMETER(argv); UNREFERENCED_PARAMETER(current_index); UNREFERENCED_PARAMETER(argc); UNREFERENCED_PARAMETER(machine); UNREFERENCED_PARAMETER(flags); UNREFERENCED_PARAMETER(data); UNREFERENCED_PARAMETER(done); std::cout << "\n"; std::cout << " Link Program Attach\n"; std::cout << " ID ID Type\n"; std::cout << "======= ======= =============\n"; uint32_t link_id = 0; for (;;) { if (bpf_link_get_next_id(link_id, &link_id) < 0) { break; } fd_t link_fd = bpf_link_get_fd_by_id(link_id); if (link_fd < 0) { break; } struct bpf_link_info info; uint32_t info_size = (uint32_t)sizeof(info); if (bpf_obj_get_info_by_fd(link_fd, &info, &info_size) == 0) { const char* attach_type_name = ebpf_get_attach_type_name(&info.attach_type_uuid); printf("%7u%9u %s\n", info.id, info.prog_id, attach_type_name); } Platform::_close(link_fd); } return EBPF_SUCCESS; }
26.440678
106
0.632051
fengjixuchui
e14fd80d0b948e439e79726700ab30ccc69c46ba
4,823
cpp
C++
datastore/common/objects/Interface.test.cpp
cmwill/netmeld
bf72a2b2954609b9767575fd2a25bf2ac81338e3
[ "MIT" ]
27
2017-11-04T23:58:54.000Z
2022-03-28T14:21:50.000Z
datastore/common/objects/Interface.test.cpp
cmwill/netmeld
bf72a2b2954609b9767575fd2a25bf2ac81338e3
[ "MIT" ]
64
2020-03-16T19:59:43.000Z
2022-03-18T14:49:18.000Z
datastore/common/objects/Interface.test.cpp
cmwill/netmeld
bf72a2b2954609b9767575fd2a25bf2ac81338e3
[ "MIT" ]
13
2019-12-01T21:32:33.000Z
2022-03-28T15:40:02.000Z
// ============================================================================= // Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // 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. // ============================================================================= // Maintained by Sandia National Laboratories <Netmeld@sandia.gov> // ============================================================================= #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <netmeld/datastore/objects/Interface.hpp> namespace nmdo = netmeld::datastore::objects; class TestInterface : public nmdo::Interface { public: TestInterface() : Interface() {}; explicit TestInterface(const std::string& _name) : Interface(_name) {}; public: std::string getMediaType() const { return mediaType; } bool getIsUp() const { return isUp; } std::string getFlags() const { return flags; } uint32_t getMtu() const { return mtu; } }; BOOST_AUTO_TEST_CASE(testConstructors) { nmdo::MacAddress macAddr; { TestInterface interface; BOOST_CHECK(interface.getName().empty()); BOOST_CHECK_EQUAL("ethernet", interface.getMediaType()); BOOST_CHECK(!interface.getIsUp()); BOOST_CHECK_EQUAL(macAddr, interface.getMacAddress()); BOOST_CHECK(interface.getFlags().empty()); BOOST_CHECK_EQUAL(0, interface.getMtu()); } { TestInterface interface {"Name"}; BOOST_CHECK_EQUAL("name", interface.getName()); BOOST_CHECK_EQUAL("ethernet", interface.getMediaType()); BOOST_CHECK(!interface.getIsUp()); BOOST_CHECK_EQUAL(macAddr, interface.getMacAddress()); BOOST_CHECK(interface.getFlags().empty()); BOOST_CHECK_EQUAL(0, interface.getMtu()); } } BOOST_AUTO_TEST_CASE(testSetters) { { TestInterface interface; nmdo::IpAddress ipAddr {"1.2.3.4/24"}; interface.addIpAddress(ipAddr); auto ipAddrs = interface.getIpAddresses(); BOOST_CHECK_EQUAL(1, ipAddrs.size()); BOOST_CHECK_EQUAL(ipAddr, ipAddrs[0]); } { TestInterface interface; interface.setName("Name"); BOOST_CHECK_EQUAL("name", interface.getName()); } { TestInterface interface; interface.setMediaType("MediaType"); BOOST_CHECK_EQUAL("mediatype", interface.getMediaType()); } { TestInterface interface; nmdo::MacAddress macAddr {"00:11:22:33:44:55"}; interface.setMacAddress(macAddr); BOOST_CHECK_EQUAL(macAddr, interface.getMacAddress()); } { TestInterface interface; BOOST_CHECK(!interface.getIsUp()); interface.setUp(); BOOST_CHECK(interface.getIsUp()); } { TestInterface interface; BOOST_CHECK(!interface.getIsUp()); interface.setDown(); BOOST_CHECK(!interface.getIsUp()); } { TestInterface interface; interface.setFlags("some flags up here"); BOOST_CHECK_EQUAL("some flags up here", interface.getFlags()); BOOST_CHECK(!interface.getIsUp()); interface.setDown(); interface.setFlags("flag,UP"); BOOST_CHECK(interface.getIsUp()); interface.setDown(); interface.setFlags("flag<UP"); BOOST_CHECK(interface.getIsUp()); } { TestInterface interface; interface.setMtu(0); BOOST_CHECK_EQUAL(0, interface.getMtu()); interface.setMtu(UINT32_MAX); BOOST_CHECK_EQUAL(UINT32_MAX, interface.getMtu()); } } BOOST_AUTO_TEST_CASE(testValidity) { { TestInterface interface; BOOST_CHECK(!interface.isValid()); interface.setName("name"); BOOST_CHECK(interface.isValid()); interface.setMediaType("loopback"); BOOST_CHECK(!interface.isValid()); } }
28.370588
80
0.676135
cmwill
e155b496354b2ac8bad5b7216ef85e6567991486
3,776
cpp
C++
src/WAM/choice.cpp
ThermalSpan/russWAM
c237bb782a83f7f6e2ccfa50800a55523ca22f67
[ "MIT" ]
null
null
null
src/WAM/choice.cpp
ThermalSpan/russWAM
c237bb782a83f7f6e2ccfa50800a55523ca22f67
[ "MIT" ]
null
null
null
src/WAM/choice.cpp
ThermalSpan/russWAM
c237bb782a83f7f6e2ccfa50800a55523ca22f67
[ "MIT" ]
null
null
null
// // choice.cpp // russWAM // // Created by Russell Wilhelm Bentley on 12/3/15. // Copyright (c) 2015 Russell Wilhelm Bentley. // Distributed under the MIT License // #include "WAM.h" void WAM::try_me_else (int labelId) { // Allocate a new choice frame m_B = new ChoiceFrame (m_arity, m_B); // Save the global registers for (int i = 0; i < m_arity; i++) { m_B->GlobalRegs[i] = *getGlobalReg (i); } // Get the next clause label m_B->L = m_functorTable->getLabel (m_functorId, labelId); // Save the current state m_B->E = m_E; m_B->CP = m_CP; m_B->TR = m_TR; m_B->H = m_H; m_B->B0 = m_B0; m_B->functorId = m_functorId; m_B->arity = m_arity; // Set the new backtracking point m_HB = m_H; m_P = m_P + 1; } void WAM::retry_me_else (int labelId) { // Undo any bindings of unbound cells unwind_trail (m_B->TR, m_TR); // Restore state m_E = m_B->E; m_CP = m_B->CP; m_TR = m_B->TR; m_H = m_B->H; m_functorId = m_B->functorId; m_arity = m_B->arity; // Restore the global registers for (int i = 0; i < m_arity; i++) { *getGlobalReg (i) = m_B->GlobalRegs[i]; } // Get label for next clause m_B->L = m_functorTable->getLabel (m_functorId, labelId); m_HB = m_H; m_P = m_P + 1; } void WAM::trust_me_else_fail () { // Undo any bindings of unbound cells unwind_trail (m_B->TR, m_TR); // Restore state m_E = m_B->E; m_CP = m_B->CP; m_TR = m_B->TR; m_H = m_B->H; m_functorId = m_B->functorId; m_arity = m_B->arity; // Restore the global registers for (int i = 0; i < m_arity; i++) { *getGlobalReg (i) = m_B->GlobalRegs[i]; } // Reset Choice point to previous one ChoiceFrame* temp = m_B; m_B = m_B->prevChoice; delete (temp); m_HB = m_H; m_P = m_P + 1; } void WAM::try_ (int labelId) { // Allocate a new choice frame m_B = new ChoiceFrame (m_arity, m_B); // Save the global registers for (int i = 0; i < m_arity; i++) { m_B->GlobalRegs[i] = *getGlobalReg (i); } // Save next instruction as the next clause m_B->L = m_P + 1; // Save the current state m_B->E = m_E; m_B->CP = m_CP; m_B->TR = m_TR; m_B->H = m_H; m_B->B0 = m_B0; m_B->functorId = m_functorId; m_B->arity = m_arity; // Set the new backtracking point m_HB = m_H; // The next instruction is the label passed in m_P = m_functorTable->getLabel (m_functorId, labelId); } void WAM::retry (int labelId) { // Undo any bindings of unbound cells unwind_trail (m_B->TR, m_TR); // Restore state m_E = m_B->E; m_CP = m_B->CP; m_TR = m_B->TR; m_H = m_B->H; m_functorId = m_B->functorId; m_arity = m_B->arity; // Restore the global registers for (int i = 0; i < m_arity; i++) { *getGlobalReg (i) = m_B->GlobalRegs[i]; } // Set next instruction as next clause m_B->L = m_P + 1; m_HB = m_H; // The next instruction is the label passed in m_P = m_functorTable->getLabel (m_functorId, labelId); } void WAM::trust (int labelId) { // Undo any bindings of unbound cells unwind_trail (m_B->TR, m_TR); // Restore state m_E = m_B->E; m_CP = m_B->CP; m_TR = m_B->TR; m_H = m_B->H; m_functorId = m_B->functorId; m_arity = m_B->arity; // Restore the global registers for (int i = 0; i < m_arity; i++) { *getGlobalReg (i) = m_B->GlobalRegs[i]; } // Reset Choice point to previous one ChoiceFrame* temp = m_B; m_B = m_B->prevChoice; delete (temp); m_HB = m_H; // Continue with label passed in m_P = m_functorTable->getLabel (m_functorId, labelId); }
22.746988
61
0.583951
ThermalSpan
e155c88f619ea2ec117f7c08b25e42ba57240981
307
cpp
C++
Good Bye 2018/Codeforces 1091A.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Good Bye 2018/Codeforces 1091A.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Good Bye 2018/Codeforces 1091A.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int y, b, r, mini; scanf("%d %d %d", &y, &b, &r); mini = min(y, min(b, r)); if(mini == r || (mini == y && r - y == 1)) printf("%d", 3*r - 3); else if(mini == b) printf("%d", 3*b); else printf("%d", 3*y + 3); return 0; }
23.615385
69
0.456026
Jvillegasd
e1578efdc91db357ddbe4f27aec066d8ded4a18c
3,330
hpp
C++
src/RealTimeClock.hpp
PhilPalmer/REAL
c56b9d96f6028295556a6e8bf73a56df8975f189
[ "MIT" ]
2
2017-02-18T18:54:28.000Z
2017-06-30T11:17:28.000Z
src/RealTimeClock.hpp
PhilPalmer/REAL
c56b9d96f6028295556a6e8bf73a56df8975f189
[ "MIT" ]
1
2018-11-23T17:17:06.000Z
2018-11-23T19:47:20.000Z
src/RealTimeClock.hpp
PhilPalmer/REAL
c56b9d96f6028295556a6e8bf73a56df8975f189
[ "MIT" ]
2
2015-11-26T08:40:09.000Z
2016-04-01T07:01:54.000Z
/** REAL: An efficient REad ALigner for next generation sequencing reads. Copyright (C) 2010 German Tischler, Solon Pissis This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **/ #if ! defined(REALTIMECLOCK_HPP) #define REALTIMECLOCK_HPP #include "types.hpp" #if defined(HAVE_WINDOWS_H) #include <windows.h> #endif #if defined(HAVE_SYS_TIME_H) #include <sys/time.h> #endif namespace toollib { #if defined(__linux) || defined(__FreeBSD__) || defined(__APPLE__) typedef u_int64_t rtc_u_int64_t; struct RealTimeClock { private: struct timeval started; mutable struct timezone tz; public: RealTimeClock() { tz.tz_minuteswest = 0; tz.tz_dsttime = 0; } ~RealTimeClock() throw() {} bool start() throw() { return gettimeofday(&started,&tz) == 0; } //! elapsed time in u-secs rtc_u_int64_t getElapsed() const { struct timeval stopped; gettimeofday(&stopped,&tz); struct timeval dif; timersub(&stopped,&started,&dif); return static_cast<rtc_u_int64_t>(dif.tv_usec) + ( static_cast<rtc_u_int64_t>(dif.tv_sec) * static_cast<rtc_u_int64_t>(1000000ul) ); } double getElapsedSeconds() const { rtc_u_int64_t const t = getElapsed(); rtc_u_int64_t const s = t / 1000000; rtc_u_int64_t const u = t % 1000000; double ds = static_cast<double>(s); double du = static_cast<double>(u)/1000000.0; return (ds+du); } }; #else typedef unsigned __int64 rtc_u_int64_t; struct RealTimeClock { private: LARGE_INTEGER freq; LARGE_INTEGER started; static __int64 ltd(LARGE_INTEGER const & l) { __int64 result = l.HighPart; result <<= 32; result |= l.LowPart; return result; } public: RealTimeClock() { QueryPerformanceFrequency(&freq); } ~RealTimeClock() throw() {} bool start() throw() { if ( ltd(freq) == 0 ) return false; else { return QueryPerformanceCounter(&started) > 0; } } rtc_u_int64_t getElapsed() const { if ( ! ltd(freq) ) return 0; else { LARGE_INTEGER now; QueryPerformanceCounter(&now); return ( static_cast<rtc_u_int64_t>(ltd(now)-ltd(started)) * static_cast<rtc_u_int64_t>(1000000ul) ) / static_cast<rtc_u_int64_t>(ltd(freq)); } } double getElapsedSeconds() const { rtc_u_int64_t const t = getElapsed(); rtc_u_int64_t const s = t / 1000000; rtc_u_int64_t const u = t % 1000000; double ds = static_cast<double>(s); double du = static_cast<double>(u)/1000000.0; return (ds+du); } }; #endif } #endif
26.015625
73
0.645045
PhilPalmer
e1594cd3ddb25606a9a6b52147463f6e2be92738
1,584
hh
C++
graphs/SubwordGraph.hh
aalto-speech/wdecoder
096225714558d1f97a5d3f4814408ad4efaa3788
[ "BSD-2-Clause" ]
null
null
null
graphs/SubwordGraph.hh
aalto-speech/wdecoder
096225714558d1f97a5d3f4814408ad4efaa3788
[ "BSD-2-Clause" ]
null
null
null
graphs/SubwordGraph.hh
aalto-speech/wdecoder
096225714558d1f97a5d3f4814408ad4efaa3788
[ "BSD-2-Clause" ]
null
null
null
#ifndef SUBWORD_GRAPH_HH #define SUBWORD_GRAPH_HH #include <map> #include <fstream> #include <vector> #include <set> #include "defs.hh" #include "Hmm.hh" #include "DecoderGraph.hh" class SubwordGraph : public DecoderGraph { public: SubwordGraph(); SubwordGraph(const std::set<std::string> &subwords, bool verbose=false); virtual ~SubwordGraph() { }; void create_graph(const std::set<std::string> &subwords, bool verbose=false); void create_crossword_network(const std::set<std::string> &subwords, std::vector<DecoderGraph::Node> &nodes, std::map<std::string, int> &fanout, std::map<std::string, int> &fanin); void connect_one_phone_subwords_from_start_to_cw(const std::set<std::string> &subwords, std::vector<DecoderGraph::Node> &nodes, std::map<std::string, int> &fanout); void connect_one_phone_subwords_from_cw_to_end(const std::set<std::string> &subwords, std::vector<DecoderGraph::Node> &nodes, std::map<std::string, int> &fanin); virtual void create_forced_path(std::vector<DecoderGraph::Node> &nodes, std::vector<std::string> &sentence, std::map<int, std::string> &node_labels); }; #endif /* SUBWORD_GRAPH_HH */
35.2
92
0.535354
aalto-speech
e15b5953533d93576e70364f8069de38dbd17aed
4,736
cpp
C++
accelerators/vmxc/src/transcoders/cout_live_reg.cpp
vmware/vmaccel
a5be7b3c650db203febb331c18bc9c4870671f27
[ "BSD-2-Clause" ]
3
2019-06-20T18:45:16.000Z
2022-03-11T19:09:50.000Z
accelerators/vmxc/src/transcoders/cout_live_reg.cpp
ConnectionMaster/vmaccel
70c4cc7b302a4f490926f98cee7bbcb8022e3488
[ "BSD-2-Clause" ]
2
2019-12-19T02:52:43.000Z
2020-04-14T06:33:36.000Z
accelerators/vmxc/src/transcoders/cout_live_reg.cpp
ConnectionMaster/vmaccel
70c4cc7b302a4f490926f98cee7bbcb8022e3488
[ "BSD-2-Clause" ]
3
2019-04-23T11:59:45.000Z
2022-03-11T19:09:49.000Z
/****************************************************************************** Copyright (c) 2016-2019 VMware, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /* * cout_live_reg.cpp * * Output SPIR-V live registers to the console using cout. This * demonstrates analyzing live registers within the SPIRV-Tools-opt * infrastructure. */ #include <iostream> #include "cout_live_reg.h" #include "reg_analysis_pass.h" #include "opt/ir_context.h" #include "opt/register_pressure.h" using namespace spvtools; using namespace spvtools::opt; using namespace std; namespace vmxc { namespace xcode { bool CoutLiveReg::ProcessFn(Function *func) { cout << "==== Begin Function ====" << endl; RegisterLiveness liveness(context(), func); std::map<uint32_t, uint32_t> resultIDs; std::map<uint32_t, uint32_t> uniqueIDs; std::map<uint32_t, uint32_t> variableIDs; for (auto &block : *func) { RegisterLiveness::RegionRegisterLiveness *blockLiveness; RegAnalysisPass regAnalysis; blockLiveness = liveness.Get(block.id()); regAnalysis.GetIDUsage(block.begin(), block.end(), resultIDs, uniqueIDs, variableIDs); cout << "Block[" << block.id() << "] number of live registers used: " << blockLiveness->used_registers_ << endl; cout << " Input registers" << endl; for (auto inst : blockLiveness->live_in_) { cout << " " << *inst << endl; } cout << " Output registers" << endl; for (auto inst : blockLiveness->live_out_) { cout << " " << *inst << endl; } } if (!resultIDs.empty()) { cout << " Result IDs = ["; for (auto &id : resultIDs) { cout << id.first << ","; } cout << "]" << endl; } if (!uniqueIDs.empty()) { cout << " Unique IDs = ["; for (auto &id : uniqueIDs) { cout << id.first << ","; } cout << "]" << endl; } if (!variableIDs.empty()) { cout << " Variable IDs = ["; for (auto &id : variableIDs) { cout << id.first << ","; } cout << "]" << endl; } cout << "==== End Function ====" << endl; return true; } Pass::Status CoutLiveReg::Process() { cout << "=== Begin CoutLiveReg ===" << endl; std::map<uint32_t, uint32_t> resultIDs; std::map<uint32_t, uint32_t> uniqueIDs; std::map<uint32_t, uint32_t> variableIDs; RegAnalysisPass regAnalysis; bool modified = false; // Global pass to process forward declarations and block instructions context()->module()->ForEachInst( [&regAnalysis, &resultIDs, &uniqueIDs, &variableIDs](Instruction *inst) { regAnalysis.HandleInstruction(inst, resultIDs, uniqueIDs, variableIDs); }, true); if (!resultIDs.empty()) { cout << " Global Result IDs = ["; for (auto &id : resultIDs) { cout << id.first << ","; } cout << "]" << endl; } if (!uniqueIDs.empty()) { cout << " Global Unique IDs = ["; for (auto &id : uniqueIDs) { cout << id.first << ","; } cout << "]" << endl; } ProcessFunction pfn = [this](Function *fp) { return ProcessFn(fp); }; modified |= context()->ProcessReachableCallTree(pfn); cout << "=== End CoutLiveReg ===" << endl; return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange; } } // namespace xcode } // namespace vmxc
34.318841
80
0.622889
vmware
e15df9eca5583c72174b0326a963b1fd05dd8f3c
693
cpp
C++
src/ast/VariableExpression.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
1
2019-06-17T07:16:01.000Z
2019-06-17T07:16:01.000Z
src/ast/VariableExpression.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
src/ast/VariableExpression.cpp
denisw/soyac
2531e16e8dfbfa966931b774f9d79af528d16ff9
[ "MIT" ]
null
null
null
/* * soyac - Soya Programming Language compiler * Copyright (c) 2009 Denis Washington <dwashington@gmx.net> * * This file is distributed under the terms of the MIT license. * See LICENSE.txt for details. */ #include <cassert> #include "VariableExpression.hpp" #include "Visitor.hpp" namespace soyac { namespace ast { VariableExpression::VariableExpression(Variable* target) : mTarget(target) { assert (target != NULL); } void* VariableExpression::visit(Visitor* v) { return v->visitVariableExpression(this); } Type* VariableExpression::type() const { return target()->type(); } Variable* VariableExpression::target() const { return mTarget.target(); } }}
14.744681
63
0.707071
denisw
ff168f1878a068b6883257ca38f442fca39e1cbf
240
cpp
C++
kernel/sched.cpp
mrtska/StarRing
b9a0d7aa043f23c8b789b23983ce74ee0d4bbdcc
[ "MIT" ]
6
2015-02-01T21:12:17.000Z
2016-07-31T14:32:11.000Z
kernel/sched.cpp
mrtska/StarRing
b9a0d7aa043f23c8b789b23983ce74ee0d4bbdcc
[ "MIT" ]
null
null
null
kernel/sched.cpp
mrtska/StarRing
b9a0d7aa043f23c8b789b23983ce74ee0d4bbdcc
[ "MIT" ]
null
null
null
#include <sched.h> #include <slaballocator.h> void schedule::sched_init() { struct process *init = new struct process; init->pid = 0; } void schedule::scheduling() { }
3.037975
43
0.495833
mrtska
ff16be60f949d4fe78eaa50dd87b4357a8d38a5f
839
cc
C++
15_ImportantLibs/CmdParser/main.cc
ultrazongo/UdemyCpp
729d7f8a1b3fbd4fe16612ecd638340cfc3847a7
[ "MIT" ]
null
null
null
15_ImportantLibs/CmdParser/main.cc
ultrazongo/UdemyCpp
729d7f8a1b3fbd4fe16612ecd638340cfc3847a7
[ "MIT" ]
null
null
null
15_ImportantLibs/CmdParser/main.cc
ultrazongo/UdemyCpp
729d7f8a1b3fbd4fe16612ecd638340cfc3847a7
[ "MIT" ]
null
null
null
#include <iostream> #include "cxxopts.hpp" constexpr int MAJOR_VERSION = 1; constexpr int MINOR_VERSION = 0; constexpr int PATCH_VERSION = 0; int main(int argc, char **argv) { cxxopts::Options options("Name", "Description"); options.add_options()("v,version", "Print version"); options.add_options()("h,help", "Print all commands"); options.add_options()("n,name", "Your name", cxxopts::value<std::string>()->default_value("Jan")); auto result = options.parse(argc, argv); if (result.count("version")) { std::cout << MAJOR_VERSION << "." << MINOR_VERSION << "." << PATCH_VERSION << std::endl; } if (result.count("help")) { std::cout << options.help() << std::endl; } auto name = result["name"].as<std::string>(); std::cout << name << std::endl; return 0; }
23.971429
102
0.61025
ultrazongo
ff17778b96206c9b82bd06c2f6822ba8506e1bc4
424
cpp
C++
USTCOJ/USTC1003.cpp
Sunrisepeak/AC-Online-Judge
5b5ea2eefa2ba48d718957720158fb79134a8fa7
[ "Apache-2.0" ]
3
2019-03-17T11:47:05.000Z
2021-12-10T03:41:42.000Z
USTCOJ/USTC1003.cpp
Sunrisepeak/AC-Online-Judge
5b5ea2eefa2ba48d718957720158fb79134a8fa7
[ "Apache-2.0" ]
null
null
null
USTCOJ/USTC1003.cpp
Sunrisepeak/AC-Online-Judge
5b5ea2eefa2ba48d718957720158fb79134a8fa7
[ "Apache-2.0" ]
null
null
null
#include<iostream> int main() { int n,s,a,b,i; while(std::cin>>n) { s=0; a=1; b=1; if(n>2){ for(i=3;i<=n;i++) { s=a+b; a=b; b=s; } std::cout<<"The Fibonacci number for "<<n<<" is "<<s<<std::endl; } else{ if(n==0) std::cout<<"The Fibonacci number for "<<n<<" is "<<0<<std::endl; else std::cout<<"The Fibonacci number for "<<n<<" is "<<1<<std::endl; } } return 0; }
15.142857
68
0.478774
Sunrisepeak
ff19d6bbbe62b9934664a03a3ae937786930bb72
2,575
cpp
C++
RType.Common/Sources/Components/Drawable.cpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
RType.Common/Sources/Components/Drawable.cpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
RType.Common/Sources/Components/Drawable.cpp
Mikyan0207/RType
ae3d0e4b3192577eccfb3ba55ac86bd7238e9451
[ "MIT", "Unlicense" ]
null
null
null
#include <Components/Drawable.hpp> #include "Logger.hpp" Drawable::Drawable(const DrawableType& type, const std::string& file, const sf::IntRect& spriteRect, const sf::IntRect& textureRect) { // TODO: Check result. m_Texture.loadFromFile(file, textureRect); m_SpriteRect = spriteRect; m_Type = type; m_Sprite.setTextureRect(spriteRect); m_Sprite.setTexture(m_Texture); } void Drawable::Animate(const double& deltaTime) { if (m_Animated == false) return; m_AnimTimeRate.first += deltaTime; if (m_AnimTimeRate.first < m_AnimTimeRate.second) return; m_AnimTimeRate.first = 0.0; m_SpriteRect.left += m_SpriteRect.width * m_AnimWay; if (m_SpriteRect.left > static_cast<int>((m_AnimFrameNb - 1) * m_SpriteRect.width) || m_SpriteRect.left < 0) { m_AnimWay *= (-1); m_SpriteRect.left += m_SpriteRect.width * m_AnimWay; } m_Sprite.setTextureRect(m_SpriteRect); } void Drawable::SetPosition(const sf::Vector2f& position) { m_Sprite.setPosition(position); } void Drawable::SetRotation(const float& rotation) { m_Sprite.setRotation(rotation); } void Drawable::SetScale(const sf::Vector2f& scale) { m_Sprite.setScale(scale); } void Drawable::SetAnimated(const bool& animated, const size_t& frameNb, const double& timeRate) { m_Animated = animated; m_AnimFrameNb = frameNb; m_AnimTimeRate = {0.0, timeRate * 1000.0}; } void Drawable::SetAnimationFrame(const size_t& frame, const double& deltaTime) { m_AnimTimeRate.first += deltaTime; if (m_AnimTimeRate.first < m_AnimTimeRate.second) return; m_AnimTimeRate.first = 0.0; if (frame < m_AnimFrameNb) { m_SpriteRect.left = static_cast<int>(frame * m_SpriteRect.width); m_Sprite.setTextureRect(m_SpriteRect); } } const sf::Vector2f& Drawable::GetPosition() const { return m_Sprite.getPosition(); } float Drawable::GetRotation() const { return m_Sprite.getRotation(); } sf::FloatRect Drawable::GetGlobalBounds() const { return m_Sprite.getGlobalBounds(); } const sf::Sprite& Drawable::GetSprite() const { return m_Sprite; } sf::IntRect Drawable::GetSpriteRect() const { return m_SpriteRect; } const Drawable::DrawableType& Drawable::GetType() const { return m_Type; } size_t Drawable::GetCurrentAnimationFrame() const { return static_cast<size_t>(m_SpriteRect.left / m_SpriteRect.width); } size_t Drawable::GetAnimationFrameNb() const { return m_AnimFrameNb; } const sf::Vector2f& Drawable::GetScale() const { return m_Sprite.getScale(); } void Drawable::ResetAnimation() { m_AnimTimeRate.first = 0.0; m_SpriteRect.left = 0; m_Sprite.setTextureRect(m_SpriteRect); }
20.766129
132
0.747961
Mikyan0207
ff23ce8af8fb037f7dc8ba4f270f69f985612cb1
280
cpp
C++
CodeForces/835/B - The number on the board.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeForces/835/B - The number on the board.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeForces/835/B - The number on the board.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; int sum,k,l,ans; char s[1123456]; int main(){ cin>>k>>s; l=strlen(s); for(int i=0;i<l;i++) sum+=(s[i]-'0'); if(sum<k){ sort(s,s+l); int i=0; while(sum<k&&i<l) sum+=9-(s[i++]-'0'),ans++; } cout<<ans<<endl; return 0; }
15.555556
29
0.535714
QAQrz
ff27ecda8831c0319c4209ed60ad9655faf96af9
1,257
cpp
C++
host/MidiUart/MidiUartHost.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
host/MidiUart/MidiUartHost.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
host/MidiUart/MidiUartHost.cpp
anupam19/mididuino
27c30f586a8d61381309434ed05b4958c7727402
[ "BSD-3-Clause" ]
null
null
null
#include <unistd.h> #include "WProgram.h" #include "MidiUartHost.h" MidiClass Midi, Midi2; MidiUartHostClass MidiUart; void MidiUartHostSysexListener::end() { // printf("send sysex of %d bytes\n", sysex->len); uint8_t buf[sysex->len +2]; buf[0] = 0xF0; m_memcpy(buf + 1, sysex->data, sysex->len); buf[sysex->len + 1] = 0xF7; uart->midiSendLong(buf, sysex->len + 2); } void handleIncomingMidi() { MidiUart.runLoop(); while (MidiUart.avail()) { Midi.handleByte(MidiUart.getc()); } usleep(1000); } void MidiUartHostParent::onOutputMessage(uint8_t *msg, uint8_t len) { // printf("output message %d bytes\n", len); if (len > 3) { midiSendLong(msg, len); } else { switch (len) { case 0: return; case 1: midiSendShort(msg[0], 0, 0); break; case 2: midiSendShort(msg[0], msg[1], 0); break; case 3: midiSendShort(msg[0], msg[1], msg[2]); break; default: return; } } } void MidiUartHostParent::init(int _inputDevice, int _outputDevice) { inputDevice = _inputDevice; outputDevice = _outputDevice; outputMidi.init(); outputMidi.addOnMessageCallback(this, (midi_callback_ptr2_t)&MidiUartHostParent::onOutputMessage); outputMidi.midiSysex.addSysexListener(&sysexListener); }
20.606557
77
0.672235
anupam19
ff2b230465ab648c9a9854158832d8bd9fac4b5c
6,908
cpp
C++
libraries/plugins/blockchain_history/account_history_api.cpp
scorum/scorum
1da00651f2fa14bcf8292da34e1cbee06250ae78
[ "MIT" ]
53
2017-10-28T22:10:35.000Z
2022-02-18T02:20:48.000Z
libraries/plugins/blockchain_history/account_history_api.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
38
2017-11-25T09:06:51.000Z
2018-10-31T09:17:22.000Z
libraries/plugins/blockchain_history/account_history_api.cpp
Scorum/Scorum
fb4aa0b0960119b97828865d7a5b4d0409af7876
[ "MIT" ]
27
2018-01-08T19:43:35.000Z
2022-01-14T10:50:42.000Z
#include <scorum/blockchain_history/account_history_api.hpp> #include <scorum/blockchain_history/blockchain_history_plugin.hpp> #include <scorum/blockchain_history/schema/history_object.hpp> #include <scorum/app/api_context.hpp> #include <scorum/app/application.hpp> #include <scorum/blockchain_history/schema/operation_objects.hpp> #include <scorum/common_api/config_api.hpp> #include <scorum/protocol/operations.hpp> #include <map> namespace scorum { namespace blockchain_history { namespace detail { class account_history_api_impl { public: scorum::app::application& _app; public: account_history_api_impl(scorum::app::application& app) : _app(app) { } template <typename history_object_type, typename fill_result_functor> void get_history(const std::string& account, uint64_t from, uint32_t limit, fill_result_functor& funct) const { const auto db = _app.chain_database(); FC_ASSERT(limit > 0, "Limit must be greater than zero"); FC_ASSERT(limit <= get_api_config(API_ACCOUNT_HISTORY).max_blockchain_history_depth, "Limit of ${l} is greater than maxmimum allowed ${2}", ("l", limit)("2", get_api_config(API_ACCOUNT_HISTORY).max_blockchain_history_depth)); FC_ASSERT(from >= limit, "From must be greater than limit"); const auto& idx = db->get_index<account_history_index<history_object_type>, by_account>(); auto itr = idx.lower_bound(boost::make_tuple(account, from)); if (itr != idx.end()) { auto end = idx.upper_bound(boost::make_tuple(account, int64_t(0))); int64_t pos = int64_t(itr->sequence) - limit; if (pos > 0) { end = idx.lower_bound(boost::make_tuple(account, pos)); } while (itr != end) { funct(*itr); ++itr; } } } template <typename history_object_type> std::map<uint32_t, applied_operation> get_history(const std::string& account, uint64_t from, uint32_t limit) const { std::map<uint32_t, applied_operation> result; const auto db = _app.chain_database(); auto fill_funct = [&](const history_object_type& hobj) { result[hobj.sequence] = db->get(hobj.op); }; this->template get_history<history_object_type>(account, from, limit, fill_funct); return result; } }; } // namespace detail account_history_api::account_history_api(const scorum::app::api_context& ctx) : _impl(new detail::account_history_api_impl(ctx.app)) { } account_history_api::~account_history_api() { } void account_history_api::on_api_startup() { } std::map<uint32_t, applied_operation> account_history_api::get_account_scr_to_scr_transfers(const std::string& account, uint64_t from, uint32_t limit) const { const auto db = _impl->_app.chain_database(); return db->with_read_lock( [&]() { return _impl->get_history<account_transfers_to_scr_history_object>(account, from, limit); }); } std::map<uint32_t, applied_operation> account_history_api::get_account_scr_to_sp_transfers(const std::string& account, uint64_t from, uint32_t limit) const { const auto db = _impl->_app.chain_database(); return db->with_read_lock( [&]() { return _impl->get_history<account_transfers_to_sp_history_object>(account, from, limit); }); } std::map<uint32_t, applied_operation> account_history_api::get_account_history(const std::string& account, uint64_t from, uint32_t limit) const { const auto db = _impl->_app.chain_database(); return db->with_read_lock([&]() { return _impl->get_history<account_history_object>(account, from, limit); }); } std::map<uint32_t, applied_withdraw_operation> account_history_api::get_account_sp_to_scr_transfers(const std::string& account, uint64_t from, uint32_t limit) const { const auto db = _impl->_app.chain_database(); return db->with_read_lock([&]() { std::map<uint32_t, applied_withdraw_operation> result; auto fill_funct = [&](const account_withdrawals_to_scr_history_object& obj) { auto it = result.emplace(obj.sequence, applied_withdraw_operation(db->get(obj.op))).first; auto& applied_op = it->second; share_type to_withdraw = 0; applied_op.op.weak_visit( [&](const withdraw_scorumpower_operation& op) { to_withdraw = op.scorumpower.amount; }); if (to_withdraw == 0u) { // If this is a zero-withdraw (such withdraw closes current active withdraw) applied_op.status = applied_withdraw_operation::empty; } else if (!obj.progress.empty()) { auto last_op = fc::raw::unpack<operation>(db->get(obj.progress.back()).serialized_op); last_op.weak_visit( [&](const acc_finished_vesting_withdraw_operation&) { // if last 'progress' operation is 'acc_finished_' then withdraw was finished applied_op.status = applied_withdraw_operation::finished; }, [&](const withdraw_scorumpower_operation&) { // if last 'progress' operation is 'withdraw_scorumpower_' then withdraw was either interrupted // or finished depending on pre-last 'progress' operation applied_op.status = applied_withdraw_operation::interrupted; }); if (obj.progress.size() > 1) { auto before_last_op_obj = db->get(*(obj.progress.rbegin() + 1)); auto before_last_op = fc::raw::unpack<operation>(before_last_op_obj.serialized_op); before_last_op.weak_visit([&](const acc_finished_vesting_withdraw_operation&) { // if pre-last 'progress' operation is 'acc_finished_' then withdraw was finished applied_op.status = applied_withdraw_operation::finished; }); } for (auto& id : obj.progress) { auto op = fc::raw::unpack<operation>(db->get(id).serialized_op); op.weak_visit( [&](const acc_to_acc_vesting_withdraw_operation& op) { applied_op.withdrawn += op.withdrawn.amount; }, [&](const acc_to_devpool_vesting_withdraw_operation& op) { applied_op.withdrawn += op.withdrawn.amount; }); } } }; _impl->get_history<account_withdrawals_to_scr_history_object>(account, from, limit, fill_funct); return result; }); } } // namespace blockchain_history } // namespace scorum
39.474286
119
0.633324
scorum
ff2beaf5448ece984586455a7d66ca52923bf014
876
cpp
C++
src/RocketEngine/component/TransformComponent.cpp
walthill/Rocket3D
45ba128699b354f21db04f4b114c81504c8e0771
[ "Apache-2.0" ]
null
null
null
src/RocketEngine/component/TransformComponent.cpp
walthill/Rocket3D
45ba128699b354f21db04f4b114c81504c8e0771
[ "Apache-2.0" ]
3
2019-12-07T01:28:17.000Z
2020-02-05T16:57:33.000Z
src/RocketEngine/component/TransformComponent.cpp
walthill/Rocket3D
45ba128699b354f21db04f4b114c81504c8e0771
[ "Apache-2.0" ]
null
null
null
#include "TransformComponent.h" TransformComponent::TransformComponent(const ComponentId & id) : Component(id) { } TransformComponent::~TransformComponent() { } void TransformComponent::setPosition(rkm::Vector3 pos) { mTransformData.position = pos; mDataChanged = true; } void TransformComponent::setData(const TransformData & data) { mTransformData.position = data.position; mTransformData.rotation.angle = data.rotation.angle; mTransformData.rotation.rotationAxis = data.rotation.rotationAxis; mTransformData.scale = data.scale; mDataChanged = true; } void TransformComponent::setScale(rkm::Vector3 scale) { mTransformData.scale = scale; mDataChanged = true; } void TransformComponent::setRotation(rkm::Vector3 rotationAxis, float angle) { mTransformData.rotation.angle = angle; mTransformData.rotation.rotationAxis = rotationAxis; mDataChanged = true; }
22.461538
76
0.78653
walthill
ff2f6e03a77ef7db646a79c478c93e1294d1b61e
1,727
cpp
C++
Failed/failed-1279B.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
3
2019-07-20T07:26:31.000Z
2020-08-06T09:31:09.000Z
Failed/failed-1279B.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
null
null
null
Failed/failed-1279B.cpp
fahimfarhan/legendary-coding-odyssey
55289e05aa04f866201c607bed00c505cd9c4df9
[ "MIT" ]
4
2019-06-20T18:43:32.000Z
2020-10-07T16:45:23.000Z
/* Author : Qazi Fahim Farhan (@fahimfarhan) */ /* May the CodeForces be with you! */ #include <iostream> // #include <sstream> // #include <cstdio> // #include <cmath> // #include <cstring> // #include <cctype> // #include <string> #include <vector> // #include <list> // #include <set> // #include <map> // #include <queue> // #include <stack> // #include <algorithm> // #include <functional> #include <iomanip> // std::setprecision using namespace std; #define PI 2*acos(0) //typedef long long int ll; #define ll long long int // other popular ones=> int64_t, uint64_t => use for 10^18 ll MODULO = 1e9+7; bool myAssert(bool b); void testDrivenDevelopment(); int start(int argc=0, char const *argv[] = NULL); // int n,m;s vector<int> *g; bool *isvisited; int main(int argc, char const *argv[]) { /* code */ // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); /* std::cout << std::fixed; std::cout << std::setprecision(10); cout << num1 << endl; */ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll T, sum, maximus, temp, pos, s, n, *a; cin>>T; while(T--){ cin>>n>>s; a = new ll[n+1]; sum = 0; for(int i=0; i<n; i++){ cin>>a[i]; sum += a[i]; } if(sum <= s){ cout<<0<<"\n"; } else{ maximus = -1; pos = 0; for(int i=0; i<n; i++){ temp = sum - a[i]; if( (temp > maximus) && (temp <= s)){ maximus = temp; pos = i; } } pos++; cout<<pos<<"\n"; } delete[] a; } return 0; }
20.317647
58
0.492183
fahimfarhan
ff321bb1d9038f5ec7a212fb06087a5dcd36877a
106
hpp
C++
testCMake/src/testComp.hpp
demotomohiro/testCMakePackage
171fb4c97b752eaaecec5660cb63289eb01919e9
[ "MIT" ]
null
null
null
testCMake/src/testComp.hpp
demotomohiro/testCMakePackage
171fb4c97b752eaaecec5660cb63289eb01919e9
[ "MIT" ]
null
null
null
testCMake/src/testComp.hpp
demotomohiro/testCMakePackage
171fb4c97b752eaaecec5660cb63289eb01919e9
[ "MIT" ]
null
null
null
#pragma once #include "testcomp_export.h" class TESTCOMP_EXPORT testComp { public: void print(); };
11.777778
32
0.716981
demotomohiro
ff329476abac6a51a1bcafb3a9cfa658b5b77a4d
1,115
cpp
C++
UVa/Competitive_Programming_Exercises/05-Mathematics/06-Cycle-Finding/11036.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
UVa/Competitive_Programming_Exercises/05-Mathematics/06-Cycle-Finding/11036.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
UVa/Competitive_Programming_Exercises/05-Mathematics/06-Cycle-Finding/11036.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
#include <bits/stdc++.h> using namespace std; const int SIZE = 110, LEN = 110; int N, n, m; long long a, b; char line[LEN], *p_, v[SIZE][9]; int f(long long x){ stack <long long> st; for(int i = 0; i < m; i++){ if( v[i][0] == 'x' ) st.push(x % N); else if( v[i][0] == 'N' ) st.push(N); else if( isdigit(v[i][0]) ) st.push(atoll(v[i]) % N); else{ a = st.top(), st.pop(); b = st.top(), st.pop(); if( v[i][0] == '+' ) st.push( ( a + b ) % N); else if( v[i][0] == '*' ) st.push( ( a * b ) % N); else return b % N; } } } int Brent_Cycle_Finding(long long xo){ long long p = 1, lambda = 1, tortoise = f(xo), hare = f(f(xo)); while( tortoise != hare ){ if( p == lambda ) tortoise = hare, p <<= 1, lambda = 0; hare = f(hare); lambda++; } return lambda; } int main(){ while(scanf("%d %d ", &N, &n), N | n){ cin.getline(line, LEN); p_ = strtok(line, " "), m = 0; while(p_) strcpy(v[m++], p_), p_ = strtok(NULL, " "); printf("%d\n", Brent_Cycle_Finding(n)); } return(0); }
24.23913
66
0.465471
TISparta
ff3d39ec918cf996673c4d584823aff79ecf9049
748
hpp
C++
R2017b/extern/include/MatlabDataArray/GetReturnType.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
null
null
null
R2017b/extern/include/MatlabDataArray/GetReturnType.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
null
null
null
R2017b/extern/include/MatlabDataArray/GetReturnType.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
null
null
null
/* Copyright 2017 The MathWorks, Inc. */ #ifndef MATLAB_DATA_GET_RETURN_TYPE_HPP_ #define MATLAB_DATA_GET_RETURN_TYPE_HPP_ #include "String.hpp" #include "Optional.hpp" #include <string> namespace matlab { namespace data { template<typename T> struct GetReturnType { typedef T type; }; template<> struct GetReturnType<String> { typedef MATLABString type; }; template<> struct GetReturnType<std::string> { typedef MATLABString type; }; template<> struct GetReturnType<const char*> { typedef MATLABString type; }; template<> struct GetReturnType<char> { typedef CHAR16_T type; }; } } #endif
19.684211
54
0.609626
catou93
ff3e881f63e2cc149bfccdc1e99e2eb6df9736b8
719
cpp
C++
state/state/Source1.cpp
katookei/cs202-18apcs3-group5
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
[ "MIT" ]
null
null
null
state/state/Source1.cpp
katookei/cs202-18apcs3-group5
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
[ "MIT" ]
null
null
null
state/state/Source1.cpp
katookei/cs202-18apcs3-group5
2ea17d891c67b740cc6f612e4f7738ec2c5c5f14
[ "MIT" ]
null
null
null
#include "Header.h" #include <string> baseState* Morning::getnext() { return new Evening; } string Morning::getName() { return "morning"; } string Evening::getName() { return "evening"; } string Night::getName() { return "night"; } baseState* Evening::getnext() { return new Night; } baseState* Night::getnext() { return new Morning; } void Sun::statechange() { if (pState) { baseState* State = pState->getnext(); delete State; pState = State; } } Sun::Sun() { pState = new Morning; } Sun::~Sun() { delete[] pState; } Sun::Sun(baseState* pContext) { pState = pContext; } void Sun::getNameState(baseState* a) { cout << a->getName(); }
12.186441
40
0.595271
katookei
ff42273a8490925f5ceee78c80f17ab26cc1d323
4,470
cc
C++
examples/coin.cc
joshbosley/lib_netsockets
931fb54993c5873cf2e621ee230b57c2345b667b
[ "Apache-2.0" ]
1
2021-02-16T10:05:24.000Z
2021-02-16T10:05:24.000Z
examples/coin.cc
joshbosley/lib_netsockets
931fb54993c5873cf2e621ee230b57c2345b667b
[ "Apache-2.0" ]
null
null
null
examples/coin.cc
joshbosley/lib_netsockets
931fb54993c5873cf2e621ee230b57c2345b667b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <string.h> #include "coin.hh" ///////////////////////////////////////////////////////////////////////////////////////////////////// //currency_t::currency_t ///////////////////////////////////////////////////////////////////////////////////////////////////// currency_t::currency_t() { } ///////////////////////////////////////////////////////////////////////////////////////////////////// //currency_t::get_currencies_list ///////////////////////////////////////////////////////////////////////////////////////////////////// int currency_t::get_currencies_list(const char* fname) { char *buf = 0; size_t length; FILE *f; f = fopen(fname, "rb"); if (!f) { std::cout << "cannot open " << fname << std::endl; return -1; } fseek(f, 0, SEEK_END); length = ftell(f); fseek(f, 0, SEEK_SET); buf = (char*)malloc(length); if (buf) { fread(buf, 1, length, f); } fclose(f); char *endptr; JsonValue value; JsonAllocator allocator; int status = jsonParse(buf, &endptr, &value, allocator); if (status != JSON_OK) { std::cout << "invalid JSON format for " << fname << std::endl; return -1; } JsonNode *root_obj = value.toNode(); //format is "coins" JSON object with an array of objects assert(std::string(root_obj->key).compare("coins") == 0); assert(root_obj->value.getTag() == JSON_ARRAY); JsonNode *arr = root_obj->value.toNode(); size_t nbr_curr = 0; for (JsonNode *node = arr; node != nullptr; node = node->next) { assert(node->value.getTag() == JSON_OBJECT); parse_coin(node->value); nbr_curr++; } assert(nbr_curr == m_coin_list.size()); std::cout << "parsed " << nbr_curr << " currencies..." << std::endl; free(buf); return 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //currency_t::parse_coin //object with {"id":2024,"name":"007Coin","code":"007"} ///////////////////////////////////////////////////////////////////////////////////////////////////// int currency_t::parse_coin(JsonValue value) { assert(value.getTag() == JSON_OBJECT); coin_list_t coin; for (JsonNode *node = value.toNode(); node != nullptr; node = node->next) { if (std::string(node->key).compare("id") == 0) { assert(node->value.getTag() == JSON_NUMBER); coin.id = (int)node->value.toNumber(); } else if (std::string(node->key).compare("name") == 0) { assert(node->value.getTag() == JSON_STRING); coin.name = node->value.toString(); } else if (std::string(node->key).compare("code") == 0) { assert(node->value.getTag() == JSON_STRING); coin.code = node->value.toString(); } } m_coin_list.push_back(coin); return 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //currency_t::get_coin_id ///////////////////////////////////////////////////////////////////////////////////////////////////// std::string currency_t::get_coin_id(std::string code) { std::string str; size_t size = m_coin_list.size(); for (size_t idx = 0; idx < size; idx++) { if (std::string(code).compare(m_coin_list.at(idx).code) == 0) { return std::to_string(m_coin_list.at(idx).id); } } return str; } ///////////////////////////////////////////////////////////////////////////////////////////////////// //currency_t::get_history ///////////////////////////////////////////////////////////////////////////////////////////////////// int currency_t::get_history(char* buf) { char *endptr; JsonValue value; JsonAllocator allocator; int status = jsonParse(buf, &endptr, &value, allocator); if (status != JSON_OK) { std::cout << "invalid JSON format" << std::endl; return -1; } JsonNode *root = value.toNode(); std::string code = root->value.toNode()->next->next->value.toString(); coin_history_t history(code); JsonNode *arr = root->next->next->next->value.toNode(); size_t nbr_hist = 0; for (JsonNode *node = arr; node != nullptr; node = node->next) { assert(node->value.getTag() == JSON_OBJECT); std::string date = node->value.toNode()->value.toString(); std::string price = node->value.toNode()->next->value.toString(); history.m_history.push_back(date_price_t(date, price)); nbr_hist++; } m_coin_history.push_back(history); return 0; }
28.471338
101
0.485235
joshbosley
ff436588cbe0f27fde9e6c99d66505ed48581ecb
3,530
cpp
C++
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
247
2018-11-02T18:50:55.000Z
2022-03-15T09:11:43.000Z
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
193
2018-11-02T20:12:44.000Z
2022-03-07T13:35:17.000Z
ogsr_engine/Layers/xrRenderPC_R1/Blender_Vertex_aref.cpp
stepa2/OGSR-Engine
32a23aa30506684be1267d9c4fc272350cd167c5
[ "Apache-2.0" ]
106
2018-10-26T11:33:01.000Z
2022-03-19T12:34:20.000Z
// Blender_Vertex_aref.cpp: implementation of the CBlender_Vertex_aref class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #pragma hdrstop #include "Blender_Vertex_aref.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBlender_Vertex_aref::CBlender_Vertex_aref() { description.CLS = B_VERT_AREF; description.version = 1; oAREF.value = 32; oAREF.min = 0; oAREF.max = 255; oBlend.value = FALSE; } CBlender_Vertex_aref::~CBlender_Vertex_aref() { } void CBlender_Vertex_aref::Save( IWriter& fs ) { IBlender::Save (fs); xrPWRITE_PROP (fs,"Alpha ref", xrPID_INTEGER, oAREF); xrPWRITE_PROP (fs,"Alpha-blend", xrPID_BOOL, oBlend); } void CBlender_Vertex_aref::Load( IReader& fs, u16 version ) { IBlender::Load (fs,version); switch (version) { case 0: xrPREAD_PROP (fs,xrPID_INTEGER, oAREF); oBlend.value = FALSE; break; case 1: default: xrPREAD_PROP (fs,xrPID_INTEGER, oAREF); xrPREAD_PROP (fs,xrPID_BOOL, oBlend); break; } } void CBlender_Vertex_aref::Compile(CBlender_Compile& C) { IBlender::Compile (C); if (C.bEditor) { C.PassBegin (); { C.PassSET_ZB (TRUE,TRUE); if (oBlend.value) C.PassSET_Blend (TRUE, D3DBLEND_SRCALPHA,D3DBLEND_INVSRCALPHA, TRUE,oAREF.value); else C.PassSET_Blend (TRUE, D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value); C.PassSET_LightFog (TRUE,TRUE); // Stage1 - Base texture C.StageBegin (); C.StageSET_Color (D3DTA_TEXTURE, D3DTOP_MODULATE, D3DTA_DIFFUSE); C.StageSET_Alpha (D3DTA_TEXTURE, D3DTOP_MODULATE, D3DTA_DIFFUSE); C.Stage_Texture (oT_Name); C.Stage_Matrix (oT_xform, 0); C.Stage_Constant ("$null"); C.StageEnd (); } C.PassEnd (); } else { switch (C.iElement) { case SE_R1_NORMAL_HQ: // Level view { LPCSTR sname = "vert"; if (C.bDetail_Diffuse) sname = "vert_dt"; if (oBlend.value) C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, TRUE,oAREF.value); else C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value); C.r_Sampler ("s_base", C.L_textures[0]); C.r_Sampler ("s_detail",C.detail_texture); C.r_End (); } break; case SE_R1_NORMAL_LQ: // Level view { LPCSTR sname = "vert"; if (oBlend.value) C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, TRUE,oAREF.value); else C.r_Pass (sname,sname,TRUE,TRUE,TRUE,TRUE,D3DBLEND_ONE, D3DBLEND_ZERO, TRUE,oAREF.value); C.r_Sampler ("s_base", C.L_textures[0]); C.r_End (); } break; case SE_R1_LPOINT: C.r_Pass ("vert_point","add_point",FALSE,TRUE,FALSE,TRUE,D3DBLEND_ONE,D3DBLEND_ONE,TRUE,oAREF.value); C.r_Sampler ("s_base", C.L_textures[0]); C.r_Sampler_clf ("s_lmap", TEX_POINT_ATT ); C.r_Sampler_clf ("s_att", TEX_POINT_ATT ); C.r_End (); break; case SE_R1_LSPOT: C.r_Pass ("vert_spot","add_spot",FALSE,TRUE,FALSE,TRUE,D3DBLEND_ONE,D3DBLEND_ONE,TRUE,oAREF.value); C.r_Sampler ("s_base", C.L_textures[0]); C.r_Sampler_clf ("s_lmap", "internal\\internal_light_att", true); C.r_Sampler_clf ("s_att", TEX_SPOT_ATT ); C.r_End (); break; case SE_R1_LMODELS: // Lighting only C.r_Pass ("vert_l","vert_l",FALSE); C.r_Sampler ("s_base",C.L_textures[0]); C.r_End (); break; } } }
28.24
123
0.639377
stepa2
ff43980396f6f059c1657875a6da097910af0caf
4,880
hpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/nall/directory.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
#ifndef NALL_DIRECTORY_HPP #define NALL_DIRECTORY_HPP #include <nall/intrinsics.hpp> #include <nall/sort.hpp> #include <nall/string.hpp> #include <nall/vector.hpp> #if defined(PLATFORM_WINDOWS) #include <nall/windows/utf8.hpp> #else #include <dirent.h> #include <stdio.h> #include <sys/types.h> #endif namespace nall { struct directory { static bool exists(const string &pathname); static lstring folders(const string &pathname, const string &pattern = "*"); static lstring files(const string &pathname, const string &pattern = "*"); static lstring contents(const string &pathname, const string &pattern = "*"); }; #if defined(PLATFORM_WINDOWS) inline bool directory::exists(const string &pathname) { DWORD result = GetFileAttributes(utf16_t(pathname)); if(result == INVALID_FILE_ATTRIBUTES) return false; return (result & FILE_ATTRIBUTE_DIRECTORY); } inline lstring directory::folders(const string &pathname, const string &pattern) { lstring list; string path = pathname; path.transform("/", "\\"); if(!strend(path, "\\")) path.append("\\"); path.append("*"); HANDLE handle; WIN32_FIND_DATA data; handle = FindFirstFile(utf16_t(path), &data); if(handle != INVALID_HANDLE_VALUE) { if(wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L"..")) { if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { string name = (const char*)utf8_t(data.cFileName); if(wildcard(name, pattern)) list.append(name); } } while(FindNextFile(handle, &data) != false) { if(wcscmp(data.cFileName, L".") && wcscmp(data.cFileName, L"..")) { if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { string name = (const char*)utf8_t(data.cFileName); if(wildcard(name, pattern)) list.append(name); } } } FindClose(handle); } if(list.size() > 0) list.sort(); for(auto &name : list) name.append("/"); //must append after sorting return list; } inline lstring directory::files(const string &pathname, const string &pattern) { lstring list; string path = pathname; path.transform("/", "\\"); if(!strend(path, "\\")) path.append("\\"); path.append("*"); HANDLE handle; WIN32_FIND_DATA data; handle = FindFirstFile(utf16_t(path), &data); if(handle != INVALID_HANDLE_VALUE) { if((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { string name = (const char*)utf8_t(data.cFileName); if(wildcard(name, pattern)) list.append(name); } while(FindNextFile(handle, &data) != false) { if((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { string name = (const char*)utf8_t(data.cFileName); if(wildcard(name, pattern)) list.append(name); } } FindClose(handle); } if(list.size() > 0) list.sort(); return list; } inline lstring directory::contents(const string &pathname, const string &pattern) { lstring folders = directory::folders(pathname); //pattern search of contents() should only filter files lstring files = directory::files(pathname, pattern); for(auto &file : files) folders.append(file); return folders; } #else inline bool directory::exists(const string &pathname) { DIR *dp = opendir(pathname); if(!dp) return false; closedir(dp); return true; } inline lstring directory::folders(const string &pathname, const string &pattern) { lstring list; DIR *dp; struct dirent *ep; dp = opendir(pathname); if(dp) { while(ep = readdir(dp)) { if(!strcmp(ep->d_name, ".")) continue; if(!strcmp(ep->d_name, "..")) continue; if(ep->d_type & DT_DIR) { if(wildcard(ep->d_name, pattern)) list.append(ep->d_name); } } closedir(dp); } if(list.size() > 0) list.sort(); for(auto &name : list) name.append("/"); //must append after sorting return list; } inline lstring directory::files(const string &pathname, const string &pattern) { lstring list; DIR *dp; struct dirent *ep; dp = opendir(pathname); if(dp) { while(ep = readdir(dp)) { if(!strcmp(ep->d_name, ".")) continue; if(!strcmp(ep->d_name, "..")) continue; if((ep->d_type & DT_DIR) == 0) { if(wildcard(ep->d_name, pattern)) list.append(ep->d_name); } } closedir(dp); } if(list.size() > 0) list.sort(); return list; } inline lstring directory::contents(const string &pathname, const string &pattern) { lstring folders = directory::folders(pathname); //pattern search of contents() should only filter files lstring files = directory::files(pathname, pattern); for(auto &file : files) folders.append(file); return folders; } #endif } #endif
31.688312
108
0.628893
redscientistlabs
ff45138950bb3bf10ac006e14d17faee17de66a0
533
cpp
C++
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
755
2019-07-10T01:26:39.000Z
2022-03-31T12:43:19.000Z
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
111
2020-02-28T23:30:10.000Z
2022-01-18T13:57:30.000Z
Sources/Overload/OvCore/src/OvCore/Scripting/LuaBinder.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
97
2019-11-06T15:19:56.000Z
2022-03-25T08:40:04.000Z
/** * @project: Overload * @author: Overload Tech. * @licence: MIT */ #include "OvCore/Scripting/LuaBinder.h" #include "OvCore/Scripting/LuaMathsBinder.h" #include "OvCore/Scripting/LuaActorBinder.h" #include "OvCore/Scripting/LuaComponentBinder.h" #include "OvCore/Scripting/LuaGlobalsBinder.h" void OvCore::Scripting::LuaBinder::CallBinders(sol::state& p_luaState) { auto& L = p_luaState; LuaMathsBinder::BindMaths(L); LuaActorBinder::BindActor(L); LuaComponentBinder::BindComponent(L); LuaGlobalsBinder::BindGlobals(L); }
24.227273
70
0.767355
kmqwerty
ff47ca22251ac8b8aac65c8bbc2460264d416b9f
8,543
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_datatype.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_datatype.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_datatype.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif #ifndef INCLUDED_CALC_DATATYPE #include "calc_datatype.h" #define INCLUDED_CALC_DATATYPE #endif // Library headers. #ifndef INCLUDED_SSTREAM #include <sstream> #define INCLUDED_SSTREAM #endif // PCRaster library headers. // Module headers. #ifndef INCLUDED_CALC_VS #include "calc_vs.h" #define INCLUDED_CALC_VS #endif #ifndef INCLUDED_CALC_DATATYPECLASH #include "calc_datatypeclash.h" #define INCLUDED_CALC_DATATYPECLASH #endif /*! \file This file contains the implementation of the DataType class. */ //------------------------------------------------------------------------------ // DEFINITION OF STATIC DATATYPE MEMBERS //------------------------------------------------------------------------------ //! restrict a VS /*! * \throw VSClash */ void calc::DataType::restrict(VS& vs, VS req) { VS newVs = ::intersect(vs,req); if (newVs==VS_UNKNOWN) throw VSClash(vs,req); vs=newVs; } //------------------------------------------------------------------------------ // DEFINITION OF DATATYPE MEMBERS //------------------------------------------------------------------------------ void calc::DataType::init() { d_vs =VS_ANYTHING; d_st =ST_ALL; d_allowPromotion=false; d_resultType =VS_FIELD; d_mapStackType =MapStackType(); } //! default ctor, any later restrictment will be valid calc::DataType::DataType() { init(); } //! ctor for ASTNumber/NonSpatial by its value calc::DataType::DataType(const double& value) { init(); d_vs=vsOfNumber(value); d_st=ST_NONSPATIAL; } //! ctor a Field datatype that may promote /*! \param vs must be in VS_FIELD \param st must be ST_SPATIAL,ST_NONSPATIAL (= fixed), ST_DERIVED (ST_EITHER) */ calc::DataType::DataType(VS vs, ST st) { init(); d_vs=vs; d_st=st; } //! ctor, d_st set on base of if vs is field or not calc::DataType::DataType(VS vs) { init(); d_vs=vs; d_st= isIn(d_vs,VS_FIELD) ?ST_EITHER:ST_NON; } //! ctor a datatype that has fixed ST calc::DataType::DataType(VS vs, bool spatial) { init(); d_vs=vs; d_st = spatial ? ST_SPATIAL:ST_NONSPATIAL; } calc::DataType::~DataType() { } //! Copy constructor. calc::DataType::DataType(DataType const& rhs): d_vs(rhs.d_vs), d_st(rhs.d_st), d_allowPromotion(rhs.d_allowPromotion), d_unit(rhs.d_unit), d_resultType(rhs.d_resultType), d_mapStackType(rhs.d_mapStackType), d_tableColTypes(rhs.d_tableColTypes) { } //! Assignment operator. calc::DataType& calc::DataType::operator=(DataType const& rhs) { if (this != &rhs) { d_vs = rhs.d_vs; d_st = rhs.d_st; d_allowPromotion= rhs.d_allowPromotion; d_unit = rhs.d_unit; d_resultType = rhs.d_resultType; d_mapStackType = rhs.d_mapStackType; d_tableColTypes = rhs.d_tableColTypes; } return *this; } //! set value of d_unit and vs to VS_S if !unit.none() void calc::DataType::setUnit(const Dimension& unit) { d_unit=unit; if (!d_unit.none()) d_vs=VS_S; } //! get value of d_unit const calc::Dimension& calc::DataType::unit() const { return d_unit; } //! this can return a set > 2 ! VS calc::DataType::vs() const { return d_vs; } //! is vs not a set but a single vs bool calc::DataType::singleVs() const { return(nrInSet(vs()) == 1); } bool calc::DataType::isField() const { return isSubset(d_vs,VS_FIELD); } ST calc::DataType::st() const { return d_st; } //! st is known and spatial bool calc::DataType::stSpatial() const { return d_st==ST_SPATIAL; } //! st is known and nonspatial bool calc::DataType::stNonSpatial() const { return d_st==ST_NONSPATIAL; } //! st is either bool calc::DataType::stEither() const { return d_st==ST_EITHER; } //! restrict the VS /*! * \throw VSClash */ void calc::DataType::restrict(VS req) { restrict(d_vs,req); } //! return if this allow \a spatialState ST calc::DataType::intersect(ST spatialState) const { return (ST)((int)d_st & (int)spatialState); } //! restrict this on requirements /*! * \param req requirements for this that it must be * (VSClash::mustBeOneOf() etc.). * * \throws VSClash or STClash, in case of exception \a this * is already (partially) modified */ void calc::DataType::restrict( const DataType& req) { // common for all restrict(req.vs()); switch(vs()) { case VS_TSS: restrict(d_resultType,req.resultType()); break; case VS_MAPSTACK: restrict(d_resultType,req.resultType()); d_mapStackType.update(req.mapStackType()); break; case VS_TABLE: if (d_tableColTypes.empty()) d_tableColTypes=req.tableColTypes(); // empty: no info to restict; if (req.tableColTypes().empty()) break; TableClash::checkNrOfColumns( d_tableColTypes.size(),req.tableColTypes().size()); for (size_t i=0; i< d_tableColTypes.size();++i) try { restrict(d_tableColTypes[i],req.tableColTypes()[i]); } catch(const VSClash& c) { throw TableClash(i+1,c); } break; default: { // check spatial type pcrcalc60, pcrcalc258,pcrcalc346 ST newSt = req.intersect(d_st); if (newSt == ST_ERROR) { // Only if req.allowPromotion() then \a this // (the DataType of an ASTPar) // may convert/promote from ST_NONSPATIAL to ST_SPATIAL. if (!req.allowPromotion()) throw STClash(stSpatial()); // else convert implict to spatial newSt = ST_SPATIAL; } d_st=newSt; } } } /*! * \pre symbolType is in (VS_TSS (output),VS_MAPSTACK) * \pre resultType is in VS_FIELD set */ void calc::DataType::setResultType(VS symbolType,VS resultType) { PRECOND(symbolType == VS_TSS || symbolType==VS_MAPSTACK); PRECOND(isSubset(resultType,VS_FIELD)); d_vs = symbolType; d_resultType= resultType; } //! reset tableColTypes, also change vs() to VS_TABLE void calc::DataType::setTableColTypes(const std::vector<VS>& tableColTypes) { d_vs = VS_TABLE; d_tableColTypes= tableColTypes; } //! set value of d_allowPromotion void calc::DataType::setAllowPromotion(bool allowPromotion) { d_allowPromotion=allowPromotion; } //! get value of d_allowPromotion bool calc::DataType::allowPromotion() const { return d_allowPromotion; } void calc::DataType::promoteToSpatial() { PRECOND(d_st==ST_EITHER || d_st!=ST_SPATIAL); d_st=ST_SPATIAL; } VS calc::DataType::resultType() const { return d_resultType; } const std::vector<VS>& calc::DataType::tableColTypes() const { return d_tableColTypes; } //! set value of d_mapStackType void calc::DataType::setMapStackType(const MapStackType& mapStackType) { d_mapStackType=mapStackType; } //! get value of d_mapStackType const calc::MapStackType& calc::DataType::mapStackType() const { return d_mapStackType; } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------ bool calc::operator==( const DataType& e1, const DataType& e2) { if (e1.vs()!=e2.vs()) return false; switch(e1.vs()) { case VS_TSS: case VS_MAPSTACK: return e1.resultType()==e2.resultType(); case VS_TABLE: return e1.tableColTypes()==e2.tableColTypes(); default: if (isIn(e1.vs(),VS_FIELD)) { // TODO d_unit in case of VS_S return e1.st()==e2.st(); } } return true; } bool calc::operator!=( const DataType& e1, const DataType& e2) { return !(e1==e2); } std::ostream & calc::operator<<( std::ostream& s, const calc::DataType& ft) { s << "d_vs(" << ft.vs() << ")"; const char *st("error"); switch (ft.st()) { case ST_NONSPATIAL: st="nonspatial"; break; case ST_SPATIAL: st="spatial"; break; case ST_EITHER: st="either"; break; case ST_ERROR: st="error"; break; case ST_NON: st="non"; break; case ST_ALL: st="all"; break; } s << "d_st(" << st << ")"; s << "d_resultType(" << ft.resultType() << ")"; for(size_t i=0; i < ft.tableColTypes().size(); ++i) // empty if not a table s << "\n\t d_tableColTypes(" << i << ":" << ft.tableColTypes()[i] << ")"; return s; }
22.540897
80
0.604823
quanpands
ff49c19e404fbc5d75388a4ef788048adb4623a6
4,688
cpp
C++
main.cpp
kambala-decapitator/MpqSimpleIO
922ab66d923d6abf654dd8c3e178dc263a1cb215
[ "MIT" ]
1
2018-11-21T10:16:02.000Z
2018-11-21T10:16:02.000Z
main.cpp
kambala-decapitator/MpqSimpleIO
922ab66d923d6abf654dd8c3e178dc263a1cb215
[ "MIT" ]
null
null
null
main.cpp
kambala-decapitator/MpqSimpleIO
922ab66d923d6abf654dd8c3e178dc263a1cb215
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <cstring> #include <StormLib/StormLib.h> using std::cerr; using std::endl; using std::string; int main(int argc, const char *argv[]) { if (argc < 3) { cerr << "min 2 params" << endl; return 1; } auto mode = argv[1]; auto isListMode = !strcmp(mode, "-l") || !strcmp(mode, "--list"); DWORD mpqFlag; if (isListMode || !strcmp(mode, "-r") || !strcmp(mode, "--read")) mpqFlag = STREAM_FLAG_READ_ONLY; else if (!strcmp(mode, "-w") || !strcmp(mode, "--write")) mpqFlag = STREAM_FLAG_WRITE_SHARE; else { cerr << "unknown mode: " << mode << endl; return 2; } if (!isListMode && argc < 5) { cerr << "not enough params for non-list mode" << endl; return 3; } HANDLE mpqHandle = nullptr; if (!SFileOpenArchive(argv[2], 0, BASE_PROVIDER_FILE | STREAM_PROVIDER_FLAT | mpqFlag, &mpqHandle)) { cerr << "failed to open MPQ, error: " << GetLastError() << endl; return 4; } auto closeMpq = [&mpqHandle]{ SFileCloseArchive(mpqHandle); }; if (mpqFlag == STREAM_FLAG_READ_ONLY) { // for list mode path mask is required const auto extraListFileArgIndex = isListMode ? 4 : 5; if (extraListFileArgIndex < argc) SFileAddListFile(mpqHandle, argv[extraListFileArgIndex]); auto mpqInternalPathMask = (!isListMode || argc > 3) ? argv[3] : "*"; SFILE_FIND_DATA findData; if (auto findHandle = SFileFindFirstFile(mpqHandle, mpqInternalPathMask, &findData, nullptr)) { string extractPath; if (!isListMode) { extractPath = string{argv[4]}; if (extractPath.back() != '/') #ifdef PLATFORM_WINDOWS if (extractPath.back() != '\\') #endif extractPath += '/'; } bool nextFileFound; do { auto fileInternalPath = findData.cFileName; if (isListMode) std::cout << findData.dwFileSize << " " << fileInternalPath << endl; else { auto fileExtractPath = extractPath + findData.szPlainName; if (!SFileExtractFile(mpqHandle, fileInternalPath, fileExtractPath.c_str(), SFILE_OPEN_FROM_MPQ)) cerr << "failed to extract file '" << fileInternalPath << "', error: " << GetLastError() << endl; } nextFileFound = SFileFindNextFile(findHandle, &findData); } while (nextFileFound); SFileFindClose(findHandle); } else { auto err = GetLastError(); cerr << "no files found with mask '" << mpqInternalPathMask << "'"; if (err != ERROR_NO_MORE_FILES) cerr << ", error: " << err; cerr << endl; } } else { string thirdParam{argv[3]}, prefixParam{"--prefix="}, internalPathPrefix; int filesStartIndex; bool isSinglePrefix; if ((isSinglePrefix = thirdParam.find(prefixParam) == 0)) { internalPathPrefix = thirdParam.substr(prefixParam.length()); filesStartIndex = 4; } else { filesStartIndex = 3; if ((argc - filesStartIndex) % 2) { cerr << "each input file must be balanced with an output one" << endl; closeMpq(); return 5; } } for (int i = filesStartIndex; i < argc; ++i) { string filePath{argv[i]}, internalPath; if (isSinglePrefix) { string fileName; auto lastSlashIndex = filePath.rfind('/'); #ifdef PLATFORM_WINDOWS if (lastSlashIndex == string::npos) lastSlashIndex = filePath.rfind('\\'); #endif internalPath = internalPathPrefix + filePath.substr(lastSlashIndex != string::npos ? lastSlashIndex + 1 : 0); } else internalPath = argv[++i]; auto s = "'" + filePath + "' => '" + internalPath + "'"; if (SFileAddFileEx(mpqHandle, filePath.c_str(), internalPath.c_str(), MPQ_FILE_COMPRESS | MPQ_FILE_REPLACEEXISTING, MPQ_COMPRESSION_PKWARE, MPQ_COMPRESSION_NEXT_SAME)) std::cout << s << endl; else cerr << s << " error: " << GetLastError() << endl; } SFileCompactArchive(mpqHandle, nullptr, false); } closeMpq(); return 0; }
33.014085
179
0.527944
kambala-decapitator
ff4b53804d65428f6412438e7d6375e678280101
1,736
cpp
C++
src/zobrist.cpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
src/zobrist.cpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
src/zobrist.cpp
x0x/hive
5cd9cc82f469b184dcf0a8161ba432d6abf79823
[ "MIT" ]
null
null
null
#include "../include/zobrist.hpp" #include "../include/types.hpp" #include "../include/move.hpp" namespace Zobrist { namespace randoms { Hash rnd_piece_turn_square[NUM_PIECE_TYPES][NUM_COLORS][NUM_SQUARES]; Hash rnd_black_move; Hash rnd_castle_side_turn[NUM_COLORS][NUM_CASTLE_SIDES]; Hash rnd_ep_file[8]; } void build_rnd_hashes() { PseudoRandom rnd(54651); for (int i = 0; i < NUM_PIECE_TYPES; i++) for (int j = 0; j < NUM_COLORS; j++) for (int k = 0; k < NUM_SQUARES; k++) randoms::rnd_piece_turn_square[i][j][k] = rnd.next(); randoms::rnd_black_move = rnd.next(); for (int i = 0; i < NUM_CASTLE_SIDES; i++) for (int j = 0; j < NUM_COLORS; j++) randoms::rnd_castle_side_turn[i][j] = rnd.next(); for (int i = 0; i < 8; i++) randoms::rnd_ep_file[i] = rnd.next(); } Hash get_piece_turn_square(PieceType piece, Turn turn, Square square) { return randoms::rnd_piece_turn_square[piece][turn][square]; } Hash get_black_move() { return randoms::rnd_black_move; } Hash get_castle_side_turn(CastleSide side, Turn turn) { return randoms::rnd_castle_side_turn[side][turn]; } Hash get_ep_file(int file) { return randoms::rnd_ep_file[file]; } Hash get_move_hash(Move move) { // Based on a simple linear congruential generator // These values have been tested for collisions for all possible Move values return 0x89b4fa525 * move.to_int() + 0xe3b2eb29df24cba7; } }
25.910448
85
0.574885
x0x
ff4dfb40b90e7c4ef65b5898c367efe97f2d2bfe
2,479
cc
C++
zetasql/reference_impl/parameters_test.cc
manifoldfinance/zetasql-formatter
88a7f98f7fff0e1032f43bbb66d4e6df588e09a6
[ "Apache-2.0" ]
1,779
2019-04-23T19:41:49.000Z
2022-03-31T18:53:18.000Z
zetasql/reference_impl/parameters_test.cc
manifoldfinance/zetasql-formatter
88a7f98f7fff0e1032f43bbb66d4e6df588e09a6
[ "Apache-2.0" ]
94
2019-05-22T00:30:05.000Z
2022-03-31T06:26:09.000Z
zetasql/reference_impl/parameters_test.cc
manifoldfinance/zetasql-formatter
88a7f98f7fff0e1032f43bbb66d4e6df588e09a6
[ "Apache-2.0" ]
153
2019-04-23T22:45:41.000Z
2022-02-18T05:44:10.000Z
// // Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "zetasql/reference_impl/parameters.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" using testing::ElementsAreArray; using testing::IsEmpty; using testing::UnorderedElementsAreArray; namespace zetasql { namespace { TEST(Parameters, Map) { ParameterMap map; map["p1"] = VariableId("v1"); map["p2"] = VariableId("v2"); Parameters params(map); EXPECT_TRUE(params.is_named()); ASSERT_THAT(params.named_parameters(), UnorderedElementsAreArray(map)); params.named_parameters()["p3"] = VariableId("v3"); ParameterMap new_map = map; new_map["p3"] = VariableId("v3"); EXPECT_THAT(params.named_parameters(), UnorderedElementsAreArray(new_map)); // No effect since 'params.is_named()' is already true. params.set_named(/*named=*/true); ASSERT_TRUE(params.is_named()); EXPECT_THAT(params.named_parameters(), UnorderedElementsAreArray(new_map)); // Clears 'params'. params.set_named(/*named=*/false); ASSERT_FALSE(params.is_named()); EXPECT_THAT(params.positional_parameters(), IsEmpty()); } TEST(Parameters, List) { const ParameterList list = {VariableId("v1"), VariableId("v2")}; Parameters params(list); EXPECT_FALSE(params.is_named()); ASSERT_THAT(params.positional_parameters(), ElementsAreArray(list)); params.positional_parameters().emplace_back("v3"); ParameterList new_list = list; new_list.emplace_back("v3"); EXPECT_THAT(params.positional_parameters(), ElementsAreArray(new_list)); // No effect since 'params.is_named()' is already false. params.set_named(/*named=*/false); ASSERT_FALSE(params.is_named()); EXPECT_THAT(params.positional_parameters(), ElementsAreArray(new_list)); // Clears 'params'. params.set_named(/*named=*/true); ASSERT_TRUE(params.is_named()); EXPECT_THAT(params.named_parameters(), IsEmpty()); } } // namespace } // namespace zetasql
30.9875
77
0.73457
manifoldfinance
ff4eabe708b199b46c699557f32d8bdaa38e2f4d
6,757
cpp
C++
dev/Code/Sandbox/Plugins/ParticleEditorPlugin/QT/ParticleLibraryAutoRecovery.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Sandbox/Plugins/ParticleEditorPlugin/QT/ParticleLibraryAutoRecovery.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Sandbox/Plugins/ParticleEditorPlugin/QT/ParticleLibraryAutoRecovery.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "stdafx.h" //Local #include "ParticleLibraryAutoRecovery.h" //Editor #include <EditorDefs.h> #include <IEditor.h> #include <Include/IEditorParticleManager.h> //QT #include <QTimer> #include <QSettings> #include <QMessageBox> #include <QDebug> #include <QObject> #define TIME_BETWEEN_BACKUPS 5 * 60 * 1000 ParticleLibraryAutoRecovery::ParticleLibraryAutoRecovery() : m_pLibraryManager(nullptr) , m_Timer(nullptr) { CRY_ASSERT(GetIEditor()); m_pLibraryManager = GetIEditor()->GetParticleManager(); m_Timer = new QTimer(); connect(m_Timer, &QTimer::timeout, this, [&](){ Save(); }); ResetTimer(); } ParticleLibraryAutoRecovery::~ParticleLibraryAutoRecovery() { SAFE_DELETE(m_Timer); } bool ParticleLibraryAutoRecovery::AttemptRecovery() { bool retval = false; if (HasExisting()) { QStringList libraryNames = GetBackupNames(); QString liblist; for (QString name : libraryNames) { liblist.append(name + "\n"); } //Prompt user to recover modified libraries QMessageBox msg(QMessageBox::NoIcon, QObject::tr("Unsaved files found!"), QObject::tr("The following files were found and recovered:\n\n") + liblist + QObject::tr("\nWould you like to recover the libraries?"), QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No | QMessageBox::StandardButton::Discard, nullptr); int response = msg.exec(); if (response == QMessageBox::StandardButton::Yes) { Load(); retval = true; } else if (response == QMessageBox::StandardButton::Discard) { Discard(); } } return retval; } void ParticleLibraryAutoRecovery::Save() { Discard(); //Discard the old CRY_ASSERT(GetIEditor()); CRY_ASSERT(GetIEditor()->GetSystem()); CRY_ASSERT(m_pLibraryManager); QSettings settings("Amazon", "Lumberyard"); QString group = "Recovery/"; settings.beginGroup(group); QString level = GetIEditor()->GetLevelName(); settings.beginWriteArray(level); int libCount = m_pLibraryManager->GetLibraryCount(); int saveIndex = 0; for (int i = 0; i < libCount; i++) { IDataBaseLibrary* library = m_pLibraryManager->GetLibrary(i); if (library->IsModified()) { XmlNodeRef node = GetIEditor()->GetSystem()->CreateXmlNode("ParticleLibrary"); QString file = library->GetFilename(); library->Serialize(node, false); if (node && file.length() > 0) { qDebug() << "Auto saved" << file << "for recovery"; settings.setArrayIndex(saveIndex++); settings.setValue("filepath", file); settings.setValue("xml", node->getXML().c_str()); } } } settings.endArray(); settings.endGroup(); settings.sync(); ResetTimer(); } void ParticleLibraryAutoRecovery::Load() { CRY_ASSERT(GetIEditor()); CRY_ASSERT(GetIEditor()->GetSystem()); CRY_ASSERT(m_pLibraryManager); QSettings settings("Amazon", "Lumberyard"); QString group = "Recovery/"; QString level = GetIEditor()->GetLevelName(); settings.beginGroup(group); int size = settings.beginReadArray(level); int arrayIndex = 0; for (int i = 0; i < size; i++) { QString filepath; QString xml; settings.setArrayIndex(arrayIndex++); xml = settings.value("xml").toString(); filepath = settings.value("filepath").toString().toLower(); if (!(xml.length() <= 0 && filepath.length() <= 0)) { XmlNodeRef node = GetIEditor()->GetSystem()->LoadXmlFromBuffer(xml.toStdString().c_str(), xml.length()); if (node) { //AddLibrary adds a .xml to the end of the library path, this will remove the extra for compatibilty filepath.replace(m_pLibraryManager->GetLibsPath().toLower(), ""); filepath.replace(".xml", ""); IDataBaseLibrary* library = m_pLibraryManager->AddLibrary(filepath.toStdString().c_str(), false); library->Serialize(node, true); } } } settings.endArray(); settings.endGroup(); ResetTimer(); } void ParticleLibraryAutoRecovery::Discard() { QSettings settings("Amazon", "Lumberyard"); QString group = "Recovery/"; QString level = GetIEditor()->GetLevelName(); settings.beginGroup(group); settings.beginGroup(level); settings.remove(""); settings.endGroup(); settings.endGroup(); settings.sync(); } QStringList ParticleLibraryAutoRecovery::GetBackupNames() { CRY_ASSERT(GetIEditor()); CRY_ASSERT(GetIEditor()->GetSystem()); QSettings settings("Amazon", "Lumberyard"); QString group = "Recovery/"; QString level = GetIEditor()->GetLevelName(); QStringList names; settings.beginGroup(group); int size = settings.beginReadArray(level); int arrayIndex = 0; for (int i = 0; i < size; i++) { QString filepath; QString xml; settings.setArrayIndex(arrayIndex++); xml = settings.value("xml").toString(); filepath = settings.value("filepath").toString(); if (!(xml.length() <= 0 && filepath.length() <= 0)) { XmlNodeRef node = GetIEditor()->GetSystem()->LoadXmlFromBuffer(xml.toStdString().c_str(), xml.length()); if (node) { //the recovered file is good, add to list of names names.append(filepath); } } } settings.endArray(); settings.endGroup(); return names; } bool ParticleLibraryAutoRecovery::HasExisting() { QSettings settings("Amazon", "Lumberyard"); QString group = "Recovery/"; QString level = GetIEditor()->GetLevelName(); settings.beginGroup(group); int size = settings.beginReadArray(level); settings.endArray(); settings.endGroup(); return size > 0; //there is something in recovery to recover } void ParticleLibraryAutoRecovery::ResetTimer() { CRY_ASSERT(m_Timer); m_Timer->start(TIME_BETWEEN_BACKUPS); }
30.853881
147
0.629569
brianherrera
ff4fed44d22385f82e0bb2bc16069c4216d11aa2
5,715
cpp
C++
searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
searchcore/src/vespa/searchcore/bmcluster/bm_message_bus.cpp
Anlon-Burke/vespa
5ecd989b36cc61716bf68f032a3482bf01fab726
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "bm_message_bus.h" #include "pending_tracker_hash.h" #include "pending_tracker.h" #include "storage_reply_error_checker.h" #include <vespa/messagebus/emptyreply.h> #include <vespa/messagebus/network/rpcnetworkparams.h> #include <vespa/messagebus/rpcmessagebus.h> #include <vespa/messagebus/ireplyhandler.h> #include <vespa/documentapi/messagebus/documentprotocol.h> #include <vespa/documentapi/messagebus/messages/documentmessage.h> #include <vespa/storageapi/mbusprot/storageprotocol.h> #include <vespa/storageapi/mbusprot/storagereply.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/log/log.h> LOG_SETUP(".bm_message_bus"); using documentapi::DocumentProtocol; using mbus::RPCMessageBus; using mbus::Reply; using mbus::SourceSession; using storage::mbusprot::StorageProtocol; using storage::mbusprot::StorageReply; namespace search::bmcluster { namespace { std::atomic<uint64_t> bm_message_bus_msg_id(0u); vespalib::string reply_as_string(Reply &reply) { vespalib::asciistream os; if (reply.getType() == 0) { os << "empty reply"; } else { os << "reply=" << reply.toString() << ", protocol=" << reply.getProtocol(); } os << ", "; auto message = reply.getMessage(); if (message) { os << "message=" << message->toString(); os << ", protocol=" << message->getProtocol(); } else { os << "no message"; } reply.setMessage(std::move(message)); os << ", "; if (reply.hasErrors()) { os << "errors=["; for (uint32_t i = 0; i < reply.getNumErrors(); ++i) { auto &error = reply.getError(i); if (i > 0) { os << ", "; } os << mbus::ErrorCode::getName(error.getCode()) << ": " << error.getMessage() << " (from " << error.getService() << ")"; } os << "]"; } else { os << "no errors"; } return os.str(); } } class BmMessageBus::ReplyHandler : public mbus::IReplyHandler, public StorageReplyErrorChecker { PendingTrackerHash _pending_hash; public: ReplyHandler(); ~ReplyHandler() override; void handleReply(std::unique_ptr<Reply> reply) override; void retain(uint64_t msg_id, PendingTracker &tracker) { _pending_hash.retain(msg_id, tracker); } void message_aborted(uint64_t msg_id); }; BmMessageBus::ReplyHandler::ReplyHandler() : mbus::IReplyHandler(), StorageReplyErrorChecker(), _pending_hash() { } BmMessageBus::ReplyHandler::~ReplyHandler() = default; void BmMessageBus::ReplyHandler::handleReply(std::unique_ptr<Reply> reply) { auto msg_id = reply->getContext().value.UINT64; auto tracker = _pending_hash.release(msg_id); if (tracker != nullptr) { bool failed = false; if (reply->getType() == 0 || reply->hasErrors()) { failed = true; // empty reply or error } else { auto protocol = reply->getProtocol(); if (protocol == DocumentProtocol::NAME) { } else if (protocol == StorageProtocol::NAME) { auto sreply = dynamic_cast<storage::mbusprot::StorageReply *>(reply.get()); if (sreply != nullptr) { check_error(*sreply->getReply()); } else { failed = true; // unexpected message type } } else { failed = true; // unexpected protocol } } if (failed) { ++_errors; if (_errors <= 10) { LOG(error, "Unexpected %s", reply_as_string(*reply).c_str()); } } tracker->release(); } else { ++_errors; LOG(error, "Untracked %s", reply_as_string(*reply).c_str()); } } void BmMessageBus::ReplyHandler::message_aborted(uint64_t msg_id) { ++_errors; auto tracker = _pending_hash.release(msg_id); tracker->release(); } BmMessageBus::BmMessageBus(const config::ConfigUri& config_uri, std::shared_ptr<const document::DocumentTypeRepo> document_type_repo) : _reply_handler(std::make_unique<ReplyHandler>()), _message_bus(), _session() { mbus::RPCNetworkParams params(config_uri); mbus::ProtocolSet protocol_set; protocol_set.add(std::make_shared<DocumentProtocol>(document_type_repo)); protocol_set.add(std::make_shared<StorageProtocol>(document_type_repo)); params.setIdentity(mbus::Identity("vespa-bm-client")); _message_bus = std::make_unique<mbus::RPCMessageBus>( protocol_set, params, config_uri); mbus::SourceSessionParams srcParams; srcParams.setThrottlePolicy(mbus::IThrottlePolicy::SP()); srcParams.setReplyHandler(*_reply_handler); _session = _message_bus->getMessageBus().createSourceSession(srcParams); } BmMessageBus::~BmMessageBus() { _session.reset(); _message_bus.reset(); _reply_handler.reset(); } uint32_t BmMessageBus::get_error_count() const { return _reply_handler->get_error_count(); } void BmMessageBus::send_msg(std::unique_ptr<mbus::Message> msg, const mbus::Route &route, PendingTracker &tracker) { auto msg_id = ++bm_message_bus_msg_id; _reply_handler->retain(msg_id, tracker); msg->setContext(mbus::Context(msg_id)); msg->setRetryEnabled(false); auto result = _session->send(std::move(msg), route); if (!result.isAccepted()) { LOG(error, "Message not accepeted, error is '%s'", result.getError().toString().c_str()); _reply_handler->message_aborted(msg_id); } } }
31.401099
132
0.635521
Anlon-Burke
ff500333886de0d1b87de76fd1659a0a1ab75b8b
1,218
cpp
C++
OptionPricer01/OptionPricer01/Option01.cpp
b01703020/Financial_Computing
d98d4f6e784997129ece15cdaf33c506e0f35c9e
[ "MIT" ]
null
null
null
OptionPricer01/OptionPricer01/Option01.cpp
b01703020/Financial_Computing
d98d4f6e784997129ece15cdaf33c506e0f35c9e
[ "MIT" ]
null
null
null
OptionPricer01/OptionPricer01/Option01.cpp
b01703020/Financial_Computing
d98d4f6e784997129ece15cdaf33c506e0f35c9e
[ "MIT" ]
null
null
null
// // Option01.cpp // OptionPricer01 // // Created by wu yen sun on 2022/2/11. // #include "Option01.h" #include "BinomialTreeModel.h" #include <iostream> #include <cmath> using namespace std; namespace fre { double PriceByCRR(double S0, double U, double D, double R, int N, double K) { double q = RiskNeutProb(U, D, R); // If you are using MAC XCode double Price[N+1]; // If you use Microsoft Visual Studio 2019 // double Price[9]; for (int i = 0; i < sizeof(Price)/sizeof(Price[0]); i++) { Price[i] = 0.0; } for (int i =0; i<=N; i++) { Price[i] = CallPayoff(CalculateAssetPrice(S0, U, D, N, i), K); } for (int n = N - 1; n >= 0; n--) { for (int i = 0; i <= n; i++) { Price[i] = (q * Price[i + 1] + (1 - q) * Price[i]) / R; } } return Price[0]; } double CallPayoff(double z, double K) { if (z > K) return z - K; return 0.0; } double fact(int k) { if ( k==0 || k==1 ) return 1; return fact(k-1)*k; } }
21
79
0.449097
b01703020
ff52b8ed5b5cc14d74b0833aa29d1ba74fd14811
157
cpp
C++
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
31
2018-10-30T09:54:23.000Z
2022-03-02T21:45:51.000Z
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
2
2016-12-24T23:39:20.000Z
2017-07-02T22:51:28.000Z
Level 1/Calculs et decouverte des variables/Kermesse/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
30
2018-10-25T12:28:36.000Z
2022-01-31T14:31:02.000Z
#include <iostream> using namespace std; int main() { int sum=0; for(int i=1;i<=50;++i) { sum+=i; cout<<sum<<endl; } return 0; }
11.214286
25
0.509554
Wurlosh
ff540f37cf63ca1cf46ffeef45629af6e3324ca6
2,459
cpp
C++
Flow/hopcroft.cpp
hasinfarhan/acm-notebook
b9a4d81a49e0e3c1e9ad130b8dcf08326bcc1673
[ "MIT" ]
1
2020-06-15T15:39:33.000Z
2020-06-15T15:39:33.000Z
Flow/hopcroft.cpp
Pervezali98/acm-notebook
b9a4d81a49e0e3c1e9ad130b8dcf08326bcc1673
[ "MIT" ]
null
null
null
Flow/hopcroft.cpp
Pervezali98/acm-notebook
b9a4d81a49e0e3c1e9ad130b8dcf08326bcc1673
[ "MIT" ]
1
2020-06-15T15:39:09.000Z
2020-06-15T15:39:09.000Z
// Maximum bipartite matching // Index from 1 // Find max independent set: // for(i = 1 → M) if (mat.matchL[i] > 0) { // if (mat.dist[i] < inf) { // for(j = 1 → N) if (ke[i][j]) right.erase(j); } // else left.erase(i); // } // Find vertices that belong to all maximum matching: // - L = vertices not matched on left side --> BFS from these vertices // (left --> right: unmatched edges, right --> left: matched edges) // reachable vertices on left side --> not belong to some maximum matching // - Do similar for right side // Find minimum vertex cover: // L = vertices not matched on left side --> BFS from these vertices // (left --> right: unmatched edges, right --> left: matched edges) // reachable vertices on left side --> not belong to some maximum matching // Let U be all visited vertices. from left side, take vertices that are not in U, from right side , take vertices that are in U; // all taken vertices must have a match struct Matching { int n; vector<int> matchL, matchR, dist; vector<bool> seen; vector< vector<int> > ke; Matching(int n) : n(n), matchL(n+1), matchR(n+1), dist(n+1), seen(n+1, false), ke(n+1) {} void addEdge(int u, int v) { ke[u].push_back(v); } bool bfs() { queue<int> qu; for(int u = 1; u <= n; ++u) if (!matchL[u]) { dist[u] = 0; qu.push(u); } else dist[u] = inf; dist[0] = inf; while (!qu.empty()) { int u = qu.front(); qu.pop(); for(__typeof(ke[u].begin()) v = ke[u].begin(); v != ke[u].end(); ++v) { if (dist[matchR[*v]] == inf) { dist[matchR[*v]] = dist[u] + 1; qu.push(matchR[*v]); } } } return dist[0] != inf; } bool dfs(int u) { if (u) { for(__typeof(ke[u].begin()) v = ke[u].begin(); v != ke[u].end(); ++v) if (dist[matchR[*v]] == dist[u] + 1 && dfs(matchR[*v])) { matchL[u] = *v; matchR[*v] = u; return true; } dist[u] = inf; return false; } return true; } int match() { int res = 0; while (bfs()) { for(int u = 1; u <= n; ++u) if (!matchL[u]) if (dfs(u)) ++res; } return res; } };
31.935065
131
0.480277
hasinfarhan
ff54160d545f8d65ef7661dacd855f07d56bd12e
402
cpp
C++
AtCoder/colopl2018-qual/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/colopl2018-qual/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/colopl2018-qual/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int n, x; cin >> n >> x; string s; cin >> s; long long int ans = 0; for (int i = 0; i < n; i++) { int a; cin >> a; if (s[i] == '1') { if (a > x) ans += x; else ans += a; } else ans += a; } cout << ans << endl; }
20.1
33
0.435323
H-Tatsuhiro
ff5494b59b52342db69938acba14185ad3267087
1,199
hpp
C++
ccsrc/cxx_experimental/include/ops/parametric/traits.hpp
Takishima/mindquantum
e90dfe474b759023d7ae18281b9a87cb8d223d04
[ "Apache-2.0" ]
null
null
null
ccsrc/cxx_experimental/include/ops/parametric/traits.hpp
Takishima/mindquantum
e90dfe474b759023d7ae18281b9a87cb8d223d04
[ "Apache-2.0" ]
null
null
null
ccsrc/cxx_experimental/include/ops/parametric/traits.hpp
Takishima/mindquantum
e90dfe474b759023d7ae18281b9a87cb8d223d04
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 <Huawei Technologies Co., Ltd> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PARAMETRIC_TRAITS_HPP #define PARAMETRIC_TRAITS_HPP #include <utility> #include "ops/parametric/config.hpp" namespace mindquantum::traits { template <typename ref_kind_t, typename... kinds_t> static constexpr bool kind_match(ref_kind_t&& ref_kind, kinds_t&&... kinds) #if MQ_HAS_CONCEPTS requires(sizeof...(kinds_t) > 0) #endif // MQ_HAS_CONCEPTS { #if !MQ_HAS_CONCEPTS static_assert(sizeof...(kinds_t) > 0); #endif // MQ_HAS_CONCEPTS return ((ref_kind == kinds) || ...); } } // namespace mindquantum::traits #endif /* PARAMETRIC_TRAITS_HPP */
32.405405
77
0.724771
Takishima
ff55a97d4f141d2ae3e2b184cc06e3e7b29a2026
1,052
cpp
C++
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
DSA Crack Sheet/solutions/Subarray with 0 sum.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-08-11T06:36:42.000Z
2021-08-11T06:36:42.000Z
/* Subarray with 0 sum ==================== Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum. Example 1: Input: 5 4 2 -3 1 6 Output: Yes Explanation: 2, -3, 1 is the subarray with sum 0. Example 2: Input: 5 4 2 0 1 6 Output: Yes Explanation: 0 is one of the element in the array so there exist a subarray with sum 0. Your Task: You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code. Expected Time Complexity: O(n). Expected Auxiliary Space: O(n). Constraints: 1 <= N <= 104 -105 <= a[i] <= 105 */ bool subArrayExists(int arr[], int n) { unordered_set<int> prefix_sums; int sum = 0; for (int i = 0; i < n; ++i) { sum += arr[i]; if (!sum) return true; if (prefix_sums.find(sum) != prefix_sums.end()) return true; prefix_sums.insert(sum); } return false; }
19.849057
237
0.668251
Akshad7829
ff57a99bb4bbd37f02a0fa6dac69a3ce2ee8ef6f
60
cpp
C++
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
Windows/VS2017/vtkIOVeraOut/vtkIOVeraOut.cpp
WinBuilds/VTK
508ab2644432973724259184f2cb83aced602484
[ "BSD-3-Clause" ]
null
null
null
#include "vtkIOVeraOut.h" vtkIOVeraOut::vtkIOVeraOut() { }
10
28
0.733333
WinBuilds
ff58813ebd02fdad515b5e0e27403d28a48bd47e
1,168
cpp
C++
solved/dominant striung(10745).cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
solved/dominant striung(10745).cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
solved/dominant striung(10745).cpp
goutomroy/uva.onlinejudge
5ce09d9e370ad78eabd0fd500ef77ce804e2d0f2
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> #include<stdlib.h> struct goutom { char a[11]; int len; }roy[15005]; bool flag[15005]; long c=0; int comp1(const void *A,const void *B) { goutom *x=(goutom*)A; goutom *y=(goutom*)B; return(x->len-y->len); } int comp2(const void *A,const void *B) { char *x=(char*)A; char *y=(char*)B; return(strcmp(x,y)); } void show( ) { int j,i,p,x,y; char t1[11],t2[11]; for(i=0;i<c;i++) { strcpy(t1,roy[i].a); for(j=i+1;j<c;j++) { strcpy(t2,roy[j].a); for(x=p=0;x<roy[i].len;x++) { for(y=0;y<roy[j].len;y++) if(t1[x]==t2[y]) { t2[y]=0; break; } if(y==roy[j].len) { p=1; break; } } if(p==0) { flag[i]=1; break; } if(p==0 && (roy[i].len==roy[j].len)) flag[j]=1; } } } void main() { char str[11],result[15002][11]; long i,u; while(scanf(" %s",str)==1) { strcpy(roy[c].a,str); roy[c++].len=strlen(str); } qsort(roy,c,sizeof(goutom),comp1); show( ); for(i=u=0;i<c;i++) if(flag[i]==0) strcpy(result[u++],roy[i].a); qsort(result,u,sizeof(result[0]),comp2); for(i=0;i<u;i++) puts(result[i]); }
14.243902
42
0.507705
goutomroy
ff5cd031a0f3ce32a8e1b4b29210d7403975e3fe
118
cpp
C++
libraries/chain/rate_limiting.cpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
3
2018-01-18T07:12:34.000Z
2018-01-22T10:00:29.000Z
libraries/chain/rate_limiting.cpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
null
null
null
libraries/chain/rate_limiting.cpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
2
2018-01-30T01:03:10.000Z
2019-02-28T09:04:06.000Z
#include <betterchain/chain/rate_limiting.hpp> namespace betterchain { namespace chain { } } /// betterchain::chain
19.666667
46
0.754237
betterchainio
ff5fecd1da8c4d9174fd7e1a1dba1d9e3d6f1cce
1,189
cpp
C++
Binary-Search/SquareRootOfInteger.cpp
devangi2000/InterviewBit
d7121858709684ddd0b41227f477cce6b82f523e
[ "MIT" ]
4
2022-01-04T18:32:52.000Z
2022-01-05T19:43:57.000Z
Binary-Search/SquareRootOfInteger.cpp
devangi2000/InterviewBit
d7121858709684ddd0b41227f477cce6b82f523e
[ "MIT" ]
null
null
null
Binary-Search/SquareRootOfInteger.cpp
devangi2000/InterviewBit
d7121858709684ddd0b41227f477cce6b82f523e
[ "MIT" ]
null
null
null
// Problem Description // Given an integer A. // Compute and return the square root of A. // If A is not a perfect square, return floor(sqrt(A)). // DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY. // NOTE: Do not use sort function from standard library. Users are expected to solve this in O(log(A)) time. // Input Format // The first and only argument given is the integer A. // Output Format // Return floor(sqrt(A)) // Example Input // Input 1: // 11 // Input 2: // 9 // Example Output // Output 1: // 3 // Output 2: // 3 // Example Explanation // Explanation: // When A = 11 , square root of A = 3.316. It is not a perfect square so we return // the floor which is 3. // When A = 9 which is a perfect square of 3, so we return 3. int Solution::sqrt(int A) { if(A == 0) return 0; int start = 1, end = A, ans = 1; while(start <= end){ int mid = (start + end) >> 1; if(mid <= (A/mid)){ // mid * mid <= A (here mid * mid could potentially give an overflow so divide it) ans = mid; start = mid + 1; } else end = mid - 1; } return ans; }
24.265306
112
0.568545
devangi2000
ff61fc705f65b24f5a78b3d5a011a0bc1723588b
1,174
cc
C++
src/kmer/KmerIntPair.cc
mgtools/kmerLSHSA
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
[ "Intel", "MIT" ]
null
null
null
src/kmer/KmerIntPair.cc
mgtools/kmerLSHSA
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
[ "Intel", "MIT" ]
null
null
null
src/kmer/KmerIntPair.cc
mgtools/kmerLSHSA
dcd17a00cb9a0b8ab8a14e822a894722ae8f52a1
[ "Intel", "MIT" ]
null
null
null
#include <cstdlib> #include "Kmer.h" #include "KmerIntPair.h" KmerIntPair::KmerIntPair(const Kmer &km, uint32_t val) { SetKey(km); SetVal(val); } void KmerIntPair::SetVal(const uint32_t val) { //char val8 = (val > 0xFF) ? 0xFF : (char)val; //memcpy(&this->v + KmerIntPair::IntOffset, &val8, sizeof(uint8_t)); //this->v[KmerIntPair::IntOffset] = val8; //this->v[KmerIntPair::IntOffset] = val; KmerIntPair::cnt = val; //memcpy(this+KmerIntPair::IntOffset, &val, sizeof(uint32_t)); } uint32_t KmerIntPair::GetVal() const { //uint8_t tmp = *reinterpret_cast<const uint8_t*>(this+KmerIntPair::IntOffset); //2/12/2015, uint8_t to uint32_t //uint32_t tmp = *reinterpret_cast<const uint32_t*>(this+KmerIntPair::IntOffset); //return tmp; //return (uint8_t)this->v[KmerIntPair::IntOffset]; return KmerIntPair::cnt; } const Kmer& KmerIntPair::GetKey() const { return *reinterpret_cast<const Kmer*>(this + KmerIntPair::KmerOffset); } void KmerIntPair::SetKey(const Kmer& km) { memcpy(this, &km, sizeof(Kmer)); } void SetKmerKey::operator()(KmerIntPair *value, const Kmer& km) { memcpy(value + KmerIntPair::KmerOffset, &km, sizeof(Kmer)); }
26.681818
83
0.697615
mgtools
ff621cc1b7e09aa5b246d87787c1ce738e2a1a8a
1,733
cpp
C++
done/revegetate(1).cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
done/revegetate(1).cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
done/revegetate(1).cpp
birdhumming/usaco
f011e7bd4b71de22736a61004e501af2b273b246
[ "OLDAP-2.2.1" ]
null
null
null
#include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; #define ii pair<int, int> #define ll long long #define vi vector<int> #define vc vector<char> #define pb push_back #define rz resize #define mp make_pair #define f first #define s second #define FOR(n) for (int i = 0; i < n; i++) #define FOR1(n) for (int i = 1; i <= n; i++) #define RFOR(n) for (int i = n - 1; i >= 0; i--) #define DFOR(n, m) FOR(n) for (int j = 0; j < m; j++) int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int ddx[8] = {1, 0, -1, -1, -1, 0, 1, 1}; int ddy[8] = {1, 1, 1, 0, -1, -1, -1, 0}; bool in_bounds(int x, int y, int n, int m) { if (x >= 0 && x < n && y >= 0 && y < m) return true; return false; } const int N = 2 * 1e5 + 10; int n, m; int p[N]; int find (int x) { if (p[x] == -1) return x; return p[x] = find(p[x]); } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (a >= n) swap(a, b); p[b] = a; } int main() { freopen("revegetate.in", "r", stdin); freopen("revegetate.out", "w", stdout); scanf("%d%d", &n, &m); memset(p, -1, sizeof p); FOR(m) { int a, b; char c; cin >> c >> a >> b; a--, b--; if (a > b) swap(a, b); if (c == 'S') { merge(a, b); merge(a + n, b + n); } else { merge(a, b + n); merge(b, a + n); } } int cnt = 0; FOR(n) { if (find(i) == find(i + n)) { printf("0"); return 0; } } FOR(n) merge(i, i + n); printf("1"); FOR(n) { if (i == find(i)) printf("0"); } cout<<endl; return 0; }
19.91954
56
0.448932
birdhumming
ff62b279e9daf74ffb0fafc797a4e900bc7bba43
1,325
hpp
C++
src/include/Serialization.hpp
coetaur0/MPICapsule
427ffcd2ee00c576127390b1282f405a794c3376
[ "Apache-2.0" ]
null
null
null
src/include/Serialization.hpp
coetaur0/MPICapsule
427ffcd2ee00c576127390b1282f405a794c3376
[ "Apache-2.0" ]
null
null
null
src/include/Serialization.hpp
coetaur0/MPICapsule
427ffcd2ee00c576127390b1282f405a794c3376
[ "Apache-2.0" ]
null
null
null
#ifndef __SERIALIZATION_H__ #define __SERIALIZATION_H__ #include <map> #include <unordered_map> #include <string> #include <cereal/cereal.hpp> #include <cereal/types/string.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/unordered_map.hpp> #include <cereal/archives/binary.hpp> template<typename Container> class Serialization { public : /** \brief This method serializes the container it received as parameter and returns it in the form of an std::string object. \param container An STL container to be serialized. \return An std::string object containing the serialized container. */ static std::string serialize(Container const& container){ std::stringstream ss; cereal::BinaryOutputArchive oarchive(ss); oarchive(container); return ss.str(); } /** \brief This method deserializes the content of an std::string representing a serialized container. \param serializedContainer An std::string object which contains a serialized container. \return The deserialized container of type 'Container' that was in the string. */ static Container deserialize(std::string const& serializedContainer){ std::stringstream ss(serializedContainer); Container container; cereal::BinaryInputArchive iarchive(ss); iarchive(container); return container; } }; #endif
25.980392
89
0.76
coetaur0
ff6b64ed10b27eedc5eca9bbbcd2bd6107df8e96
887
cc
C++
tests/libpyre/memory/direct-create.cc
lijun99/pyre
004dfd4c06489b4ba5b32877338ca6440f2d523b
[ "BSD-3-Clause" ]
3
2019-08-02T21:02:47.000Z
2021-09-08T13:59:43.000Z
tests/libpyre/memory/direct-create.cc
lijun99/pyre
004dfd4c06489b4ba5b32877338ca6440f2d523b
[ "BSD-3-Clause" ]
null
null
null
tests/libpyre/memory/direct-create.cc
lijun99/pyre
004dfd4c06489b4ba5b32877338ca6440f2d523b
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- // // michael a.g. aïvázis // orthologue // (c) 1998-2019 all rights reserved // // access the low level interface to create a file that can fit a grid of a specified size // // N.B.: this test leaves behind a file named "grid.dat" that is used by the other tests; it // must be cleaned up after the tests are run // portability #include <portinfo> // externals #include <unistd.h> // support #include <pyre/memory.h> // entry point int main() { // the cell type typedef double cell_t; // desired size size_t page = ::getpagesize(); // the name of the file pyre::memory::uri_t name {"grid.dat"}; // turn on the info channel pyre::journal::debug_t("pyre.geometry.direct").activate(); // create a file that can fit the payload pyre::memory::direct_t<cell_t>::create(name, 2*page); // all done return 0; } // end of file
22.74359
92
0.648253
lijun99
ff6bb205209b4365523602d463211594dbb9d585
1,546
cpp
C++
src/systems/systemmanager.cpp
lfowles/polarbear
3c008b3560a7b24c9e985bff0166650fd981e8a7
[ "MIT" ]
null
null
null
src/systems/systemmanager.cpp
lfowles/polarbear
3c008b3560a7b24c9e985bff0166650fd981e8a7
[ "MIT" ]
null
null
null
src/systems/systemmanager.cpp
lfowles/polarbear
3c008b3560a7b24c9e985bff0166650fd981e8a7
[ "MIT" ]
null
null
null
#include <polarbear/systems/systemmanager.hpp> void SystemManager::AddSystem(std::shared_ptr<System>& system) { systems.push_back(std::move(system)); }; void SystemManager::AddSystem(std::shared_ptr<System>&& system) { systems.push_back(std::move(system)); }; void SystemManager::AddSystem(System*&& system) { systems.push_back(std::shared_ptr<System>(system)); } void SystemManager::AddEntity(Entity& entity) { // This is good enough for now, with a mostly static list of entities and components, but in the future this will need some sort of hook on AddComponent/RemoveComponent auto entity_ptr = std::make_shared<Entity>(std::move(entity)); for (auto &system : systems) { system->entity_added(entity_ptr); } entities.push_back(entity_ptr); }; void SystemManager::update(ms time_elapsed) { accumulated_time += time_elapsed; while (accumulated_time > ms_per_update) { for (auto &system : systems) { system->update(ms_per_update); } accumulated_time -= ms_per_update; } }; void SystemManager::SetUpdateTime(s update_time) { ms_per_update = ms(update_time); }; std::vector<std::shared_ptr<Entity>> SystemManager::GetEntities(std::bitset<max_components> mask) { auto matching_entities = std::vector<std::shared_ptr<Entity>>{}; for (auto& entity : entities) { if ((mask & entity->component_mask) == mask) { matching_entities.push_back(entity); } } return matching_entities; }
25.344262
172
0.677878
lfowles
ff6c88f69489274d6befffab8f4071b630e516e9
7,761
cpp
C++
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
yus1108/UnsungEngine2
c824c049069a0d8283f84b09af7ae0182d9a48c9
[ "MIT" ]
null
null
null
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
yus1108/UnsungEngine2
c824c049069a0d8283f84b09af7ae0182d9a48c9
[ "MIT" ]
4
2021-03-12T06:11:36.000Z
2021-03-19T11:09:06.000Z
UEngine/UEngine/Game Architecture/Object/Component/Material.cpp
yus1108/UnsungEngine2
c824c049069a0d8283f84b09af7ae0182d9a48c9
[ "MIT" ]
null
null
null
#include "UEngine.h" #include "Material.h" void UEngine::Material::Awake() { colorBuffer = DXRenderer::DXConstantBuffer::Instantiate ( GetGameObject()->GetScene()->ResourceManager.GetNextCBufferID(), DXRenderer::Get(), GetGameObject()->GetScene()->ResourceManager.GetCBufferPreset(typeid(Color).raw_name()) ); spriteBuffer = DXRenderer::DXConstantBuffer::Instantiate ( GetGameObject()->GetScene()->ResourceManager.GetNextCBufferID(), DXRenderer::Get(), GetGameObject()->GetScene()->ResourceManager.GetCBufferPreset(typeid(UV).raw_name()) ); uv = UV{ 0, 0, 1, 1 }; colorBuffer->AttachData(&color.value, sizeof(Color)); spriteBuffer->AttachData(&uv.value, sizeof(UV)); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXConstantBuffer>(colorBuffer->UID, colorBuffer); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXConstantBuffer>(spriteBuffer->UID, spriteBuffer); } void UEngine::Material::Update() { auto renderComponent = GetComponent<RenderComponent>(); if (renderComponent == nullptr) return; if (renderObject != renderComponent->GetRenderObject()) { renderObject = renderComponent->GetRenderObject(); if (renderObject == nullptr) return; renderComponent->AddConstantBuffer(colorBuffer); renderComponent->AddConstantBuffer(spriteBuffer); if (imageTexture) renderComponent->AddImageTexture(imageTexture); if (imageSampler) renderComponent->AddImageSampler(imageSampler); } } void UEngine::Material::OnPreRender() { colorBuffer->Update(DXRenderer::Get()->GetImmediateDeviceContext()); spriteBuffer->Update(DXRenderer::Get()->GetImmediateDeviceContext()); } void UEngine::Material::OnDestroy() { auto renderComponent = GetComponent<RenderComponent>(); if (renderComponent == nullptr) return; if (renderObject != renderComponent->GetRenderObject()) { renderObject = renderComponent->GetRenderObject(); if (renderObject == nullptr) return; renderComponent->ClearConstantBuffers(); if (imageTexture) renderComponent->AddImageTexture(nullptr); if (imageSampler) renderComponent->AddImageSampler(nullptr); } } void UEngine::Material::DeSerialize(TiXmlNode* node) { Serializer::DeSerialize(node); std::wstring fileName; convert_utf8_to_unicode_string(fileName, this->fileName.value.c_str(), this->fileName.value.size()); using namespace std; std::string delimiter = "\n"; std::list<std::string> tokens; size_t pos = 0; while ((pos = samplerName.value.find(delimiter)) != std::string::npos) { tokens.emplace_back(samplerName.value.substr(0, pos)); samplerName.value.erase(0, pos + delimiter.length()); } D3D11_SAMPLER_DESC desc; desc.AddressU = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front(); desc.AddressV = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front(); desc.AddressW = static_cast<D3D11_TEXTURE_ADDRESS_MODE>(stoll(tokens.front())); tokens.pop_front(); desc.BorderColor[0] = stof(tokens.front()); tokens.pop_front(); desc.BorderColor[1] = stof(tokens.front()); tokens.pop_front(); desc.BorderColor[2] = stof(tokens.front()); tokens.pop_front(); desc.BorderColor[3] = stof(tokens.front()); tokens.pop_front(); desc.ComparisonFunc = static_cast<D3D11_COMPARISON_FUNC>(stoi(tokens.front())); tokens.pop_front(); desc.Filter = static_cast<D3D11_FILTER>(stoi(tokens.front())); tokens.pop_front(); desc.MaxAnisotropy = stoi(tokens.front()); tokens.pop_front(); desc.MaxLOD = stof(tokens.front()); tokens.pop_front(); desc.MinLOD = stof(tokens.front()); tokens.pop_front(); desc.MipLODBias = stof(tokens.front()); tokens.pop_front(); LoadImageMaterial(fileName, desc); } void UEngine::Material::LoadImageMaterial(std::wstring fileName) { // Sampler State D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.MaxAnisotropy = 1; samplerDesc.MaxLOD = FLT_MAX; samplerDesc.MinLOD = -FLT_MAX; samplerDesc.MipLODBias = 0; this->fileName = fileName; this->samplerName = DXRenderer::DXSamplerState::MakeName(samplerDesc); auto scene = GetGameObject()->GetScene(); imageTexture = scene->ResourceManager.GetResource<DXRenderer::DXTexture>(this->fileName.value); if (imageTexture == nullptr) { imageTexture = DXRenderer::DXTexture::Load(fileName); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture); } imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value); if (imageSampler == nullptr) { imageSampler = DXRenderer::DXSamplerState::Load(samplerDesc); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler); } color = Color{ 1, 1, 1, 1 }; if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture); if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler); } void UEngine::Material::LoadImageMaterial(std::wstring fileName, D3D11_TEXTURE_ADDRESS_MODE addressMode, D3D11_FILTER filter) { // Sampler State D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.AddressU = addressMode; samplerDesc.AddressV = addressMode; samplerDesc.AddressW = addressMode; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.Filter = filter; samplerDesc.MaxAnisotropy = 1; samplerDesc.MaxLOD = FLT_MAX; samplerDesc.MinLOD = -FLT_MAX; samplerDesc.MipLODBias = 0; this->fileName = fileName; this->samplerName = DXRenderer::DXSamplerState::MakeName(samplerDesc); auto scene = GetGameObject()->GetScene(); if (imageTexture == nullptr) { imageTexture = DXRenderer::DXTexture::Load(fileName); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture); } imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value); if (imageSampler == nullptr) { imageSampler = DXRenderer::DXSamplerState::Load(samplerDesc); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler); } color = Color{ 1, 1, 1, 1 }; if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture); if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler); } void UEngine::Material::LoadImageMaterial(std::wstring fileName, D3D11_SAMPLER_DESC desc) { this->fileName = fileName; this->samplerName = DXRenderer::DXSamplerState::MakeName(desc); auto scene = GetGameObject()->GetScene(); imageTexture = scene->ResourceManager.GetResource<DXRenderer::DXTexture>(this->fileName.value); if (imageTexture == nullptr) { imageTexture = DXRenderer::DXTexture::Load(fileName); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXTexture>(this->fileName.value, imageTexture); } imageSampler = scene->ResourceManager.GetResource<DXRenderer::DXSamplerState>(this->samplerName.value); if (imageSampler == nullptr) { imageSampler = DXRenderer::DXSamplerState::Load(desc); GetGameObject()->GetScene()->ResourceManager.AddResource<DXRenderer::DXSamplerState>(samplerName.value, imageSampler); } color = Color{ 1, 1, 1, 1 }; if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageTexture(imageTexture); if (renderObject != nullptr) GetComponent<RenderComponent>()->AddImageSampler(imageSampler); }
40.212435
125
0.768329
yus1108
ff6f2098a03899851322502b167fe797341fbfe9
856
cpp
C++
libraries/chain/chronicler.cpp
joticajulian/koinos-chain
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
[ "MIT" ]
null
null
null
libraries/chain/chronicler.cpp
joticajulian/koinos-chain
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
[ "MIT" ]
null
null
null
libraries/chain/chronicler.cpp
joticajulian/koinos-chain
b5db60b427ebb97dabf1acf8108e94bbc75a46d4
[ "MIT" ]
null
null
null
#include <koinos/chain/chronicler.hpp> namespace koinos::chain { void chronicler::set_session( std::shared_ptr< abstract_chronicler_session > s ) { _session = s; } void chronicler::push_event( protocol::event_data&& ev ) { ev.set_sequence( _seq_no ); bool within_session = false; if ( auto session = _session.lock() ) { within_session = true; session->push_event( ev ); } _events.emplace_back( std::make_pair( within_session, std::move( ev ) ) ); _seq_no++; } void chronicler::push_log( const std::string& message ) { if ( auto session = _session.lock() ) session->push_log( message ); else _logs.push_back( message ); } const std::vector< event_bundle >& chronicler::events() { return _events; } const std::vector< std::string >& chronicler::logs() { return _logs; } } // koinos::chain
19.454545
80
0.661215
joticajulian
ff7238226c23eeb1e27a7abe7bf5ae38d12c630d
225
cpp
C++
src/RE/Misc/FixedStrings.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
1
2021-08-30T20:33:43.000Z
2021-08-30T20:33:43.000Z
src/RE/Misc/FixedStrings.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
null
null
null
src/RE/Misc/FixedStrings.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
null
null
null
#include "RE/Misc/FixedStrings.h" namespace RE { FixedStrings* FixedStrings::GetSingleton() { using func_t = decltype(&FixedStrings::GetSingleton); REL::Relocation<func_t> func{ REL::ID(11308) }; return func(); } }
18.75
55
0.706667
fireundubh
ff741de3c66664729bfb2a3b8a0446d9fade17db
374
hpp
C++
Assignment7/Intersection.hpp
DanielDFY/GAMES101
f04148d0d0e44ee6e25769daefc45dad6011d42d
[ "MIT" ]
2
2021-05-28T12:28:33.000Z
2022-01-18T12:46:01.000Z
Assignment7/Intersection.hpp
DanielDFY/GAMES101
f04148d0d0e44ee6e25769daefc45dad6011d42d
[ "MIT" ]
null
null
null
Assignment7/Intersection.hpp
DanielDFY/GAMES101
f04148d0d0e44ee6e25769daefc45dad6011d42d
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "Object.hpp" #include "Material.hpp" #include "Math.hpp" class Object; struct Intersection { float time = FLOAT_INFINITY; Vector3f pos = { 0.0f }; Vector3f normal = { 0.0f }; Vector2f uv = { 0.0f }; std::shared_ptr<Object> obj_ptr = nullptr; std::shared_ptr<Material> mat_ptr = nullptr; };
20.777778
49
0.628342
DanielDFY
ff77a1e1532c4ce464df064e38c48546750665be
3,812
cpp
C++
asteroid/src/wrapper_glfw.cpp
Rekfuki/asteroidOpenGL
691ec2b2877d146d9b4a312dac894b2e8dafc014
[ "MIT" ]
1
2021-08-02T02:26:53.000Z
2021-08-02T02:26:53.000Z
asteroid/src/wrapper_glfw.cpp
Rekfuki/asteroidOpenGL
691ec2b2877d146d9b4a312dac894b2e8dafc014
[ "MIT" ]
null
null
null
asteroid/src/wrapper_glfw.cpp
Rekfuki/asteroidOpenGL
691ec2b2877d146d9b4a312dac894b2e8dafc014
[ "MIT" ]
1
2021-08-02T02:27:11.000Z
2021-08-02T02:27:11.000Z
/** wrapper_glfw.cpp Modified from the OpenGL GLFW example to provide a wrapper GLFW class and to include shader loader functions to include shaders as text files Iain Martin August 2014 */ #include "wrapper_glfw.h" /* Inlcude some standard headers */ #include <iostream> #include <fstream> #include <vector> using namespace std; /* Constructor for wrapper object */ GLWrapper::GLWrapper(int width, int height, const char* title) { this->width = width; this->height = height; this->title = title; this->fps = 60; this->running = true; /* Initialise GLFW and exit if it fails */ if (!glfwInit()) { cout << "Failed to initialize GLFW." << endl; exit(EXIT_FAILURE); } glfwWindowHint(GLFW_SAMPLES, 8); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef DEBUG glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif window = glfwCreateWindow(width, height, title, 0, 0); if (!window) { cout << "Could not open GLFW window." << endl; glfwTerminate(); exit(EXIT_FAILURE); } /* Obtain an OpenGL context and assign to the just opened GLFW window */ glfwMakeContextCurrent(window); /* Initialise GLLoad library. You must have obtained a current OpenGL */ if (!ogl_LoadFunctions()) { cerr << "oglLoadFunctions() failed. Exiting" << endl; glfwTerminate(); return; } /* Can set the Window title at a later time if you wish*/ glfwSetWindowTitle(window, title); glfwSetInputMode(window, GLFW_STICKY_KEYS, true); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } /* Terminate GLFW on destruvtion of the wrapepr object */ GLWrapper::~GLWrapper() { glfwTerminate(); } /* Returns the GLFW window handle, required to call GLFW functions outside this class */ GLFWwindow* GLWrapper::getWindow() { return window; } /* * Print OpenGL Version details */ void GLWrapper::DisplayVersion() { /* One way to get OpenGL version*/ int major, minor; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MAJOR_VERSION, &minor); cout << "OpenGL Version = " << major << "." << minor << endl; /* A more detailed way to the version strings*/ cout << "Vender: " << glGetString(GL_VENDOR) << endl; cout << "Version:" << glGetString(GL_VERSION) << endl; cout << "Renderer:" << glGetString(GL_RENDERER) << endl; } /* GLFW_Main function normally starts the windows system, calls any init routines and then starts the event loop which runs until the program ends */ int GLWrapper::eventLoop() { // Main loop while (!glfwWindowShouldClose(window)) { // Call function to draw your graphics renderer(); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } /* Register an error callback function */ void GLWrapper::setErrorCallback(void(*func)(int error, const char* description)) { glfwSetErrorCallback(func); } /* Register a display function that renders in the window */ void GLWrapper::setRenderer(void(*func)()) { this->renderer = func; } /* Register a callback that runs after the window gets resized */ void GLWrapper::setReshapeCallback(void(*func)(GLFWwindow* window, int w, int h)) { glfwSetFramebufferSizeCallback(window, func); } /* Register a callback to respond to keyboard events */ void GLWrapper::setKeyCallback(void(*func)(GLFWwindow* window, int key, int scancode, int action, int mods)) { glfwSetKeyCallback(window, func); } /* Register a callback to respond to mouse darf events */ void GLWrapper::setMouseCallback(void(*func)(GLFWwindow* window, double xpos, double ypos)) { glfwSetCursorPosCallback(window, func); } void GLWrapper::setWindowFocusCallback(void(*func)(GLFWwindow* window, int focused)) { glfwSetWindowFocusCallback(window, func); }
26.289655
108
0.729538
Rekfuki
ff7ade7c513008408294aa07a14e81873e322f55
302
cpp
C++
Codeforces/707A.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
Codeforces/707A.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
Codeforces/707A.cpp
DT3264/ProgrammingContestsSolutions
a297f2da654c2ca2815b9aa375c2b4ca0052269d
[ "MIT" ]
null
null
null
#include<stdio.h> using namespace std; int main(){ int x, y, i; char t; bool bnw = true; scanf("%d %d", &x, &y); for(i=0; i<x*y; i++){ scanf(" %c", &t); if(t!='B' && t!='W' && t!='G') bnw=false; } printf(bnw ? "#Black&White\n" : "#Color\n"); return 0; }
20.133333
49
0.440397
DT3264
ff7d4872d694567e752c3fcfa7090f7cfcda4718
4,670
cpp
C++
Source/WebCore/svg/SVGMPathElement.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebCore/svg/SVGMPathElement.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/svg/SVGMPathElement.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2007 Eric Seidel <eric@webkit.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "SVGMPathElement.h" #include "Document.h" #include "SVGAnimateMotionElement.h" #include "SVGDocumentExtensions.h" #include "SVGNames.h" #include "SVGPathElement.h" #include "XLinkNames.h" namespace WebCore { // Animated property definitions DEFINE_ANIMATED_STRING(SVGMPathElement, XLinkNames::hrefAttr, Href, href) DEFINE_ANIMATED_BOOLEAN(SVGMPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMPathElement) REGISTER_LOCAL_ANIMATED_PROPERTY(href) REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) END_REGISTER_ANIMATED_PROPERTIES inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document& document) : SVGElement(tagName, document) { ASSERT(hasTagName(SVGNames::mpathTag)); registerAnimatedPropertiesForSVGMPathElement(); } Ref<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document& document) { return adoptRef(*new SVGMPathElement(tagName, document)); } SVGMPathElement::~SVGMPathElement() { clearResourceReferences(); } void SVGMPathElement::buildPendingResource() { clearResourceReferences(); if (!isConnected()) return; String id; Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id); if (!target) { // Do not register as pending if we are already pending this resource. if (document().accessSVGExtensions().isPendingResource(this, id)) return; if (!id.isEmpty()) { document().accessSVGExtensions().addPendingResource(id, this); ASSERT(hasPendingResources()); } } else if (target->isSVGElement()) { // Register us with the target in the dependencies map. Any change of hrefElement // that leads to relayout/repainting now informs us, so we can react to it. document().accessSVGExtensions().addElementReferencingTarget(this, downcast<SVGElement>(target)); } targetPathChanged(); } void SVGMPathElement::clearResourceReferences() { document().accessSVGExtensions().removeAllTargetReferencesForElement(this); } Node::InsertionNotificationRequest SVGMPathElement::insertedInto(ContainerNode& rootParent) { SVGElement::insertedInto(rootParent); if (rootParent.isConnected()) return InsertionShouldCallFinishedInsertingSubtree; return InsertionDone; } void SVGMPathElement::finishedInsertingSubtree() { buildPendingResource(); } void SVGMPathElement::removedFrom(ContainerNode& rootParent) { SVGElement::removedFrom(rootParent); notifyParentOfPathChange(&rootParent); if (rootParent.isConnected()) clearResourceReferences(); } void SVGMPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGElement::parseAttribute(name, value); SVGURIReference::parseAttribute(name, value); SVGExternalResourcesRequired::parseAttribute(name, value); } void SVGMPathElement::svgAttributeChanged(const QualifiedName& attrName) { if (SVGURIReference::isKnownAttribute(attrName)) { InstanceInvalidationGuard guard(*this); buildPendingResource(); return; } SVGElement::svgAttributeChanged(attrName); } SVGPathElement* SVGMPathElement::pathElement() { Element* target = targetElementFromIRIString(href(), document()); if (is<SVGPathElement>(target)) return downcast<SVGPathElement>(target); return nullptr; } void SVGMPathElement::targetPathChanged() { notifyParentOfPathChange(parentNode()); } void SVGMPathElement::notifyParentOfPathChange(ContainerNode* parent) { if (is<SVGAnimateMotionElement>(parent)) downcast<SVGAnimateMotionElement>(*parent).updateAnimationPath(); } } // namespace WebCore
31.554054
135
0.750107
ijsf
ff7ebf7b323e30d1a6a7139e29f0fb281f3510ac
5,047
hpp
C++
include/matrix.hpp
blockahead/CGMRES_cpp
13a44e0022fbda6ab85b2d04131c230668197859
[ "MIT" ]
2
2021-12-21T09:03:04.000Z
2022-03-31T11:02:53.000Z
include/matrix.hpp
blockahead/CGMRES_cpp
13a44e0022fbda6ab85b2d04131c230668197859
[ "MIT" ]
null
null
null
include/matrix.hpp
blockahead/CGMRES_cpp
13a44e0022fbda6ab85b2d04131c230668197859
[ "MIT" ]
null
null
null
#pragma once #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #define DEBUG_MODE // ret = vec inline void mov(double* ret, const double* vec, const int16_t row) { int16_t i; for (i = 0; i < row; i++) { ret[i] = vec[i]; } } // ret = mat inline void mov(double* ret, const double* mat, const int16_t row, const int16_t col) { int16_t i; for (i = 0; i < row * col; i++) { ret[i] = mat[i]; } } // ret = vec1 + vec2 inline void add(double* ret, const double* vec1, const double* vec2, const int16_t row) { int16_t i; for (i = 0; i < row; i++) { ret[i] = vec1[i] + vec2[i]; } } // ret = mat1 + mat2 inline void add(double* ret, const double* mat1, const double* mat2, const int16_t row, const int16_t col) { int16_t i; for (i = 0; i < row * col; i++) { ret[i] = mat1[i] + mat2[i]; } } // ret = vec1 - vec2 inline void sub(double* ret, const double* vec1, const double* vec2, const int16_t row) { int16_t i; for (i = 0; i < row; i++) { ret[i] = vec1[i] - vec2[i]; } } // ret = mat1 - mat2 inline void sub(double* ret, const double* mat1, const double* mat2, const int16_t row, const int16_t col) { int16_t i; for (i = 0; i < row * col; i++) { ret[i] = mat1[i] - mat2[i]; } } // ret = vec * c inline void mul(double* ret, const double* vec, const double c, const int16_t row) { int16_t i; for (i = 0; i < row; i++) { ret[i] = vec[i] * c; } } // ret = mat * c inline void mul(double* ret, const double* mat, const double c, const int16_t row, const int16_t col) { int16_t i; for (i = 0; i < row * col; i++) { ret[i] = mat[i] * c; } } // ret = mat * vec inline void mul(double* ret, const double* mat, const double* vec, const int16_t row, const int16_t col) { int16_t i, j, idx; #ifdef DEBUG_MODE if (ret == vec) { printf("%s pointer error !\n", __func__); exit(-1); } #endif for (i = 0; i < row; i++) { ret[i] = 0.0; } for (j = 0; j < col; j++) { for (i = 0; i < row; i++) { idx = row * j + i; ret[i] += mat[idx] * vec[j]; } } } // ret = mat * mat inline void mul(double* ret, const double* mat1, const double* mat2, const int16_t l, const int16_t row, const int16_t col) { int16_t i, j, k, idx1, idx2, idx3; #ifdef DEBUG_MODE if (ret == mat1 || ret == mat2) { printf("%s pointer error !\n", __func__); exit(-1); } #endif for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { idx1 = col * i + j; ret[idx1] = 0; } for (k = 0; k < l; k++) { idx2 = col * i + k; for (j = 0; j < col; j++) { idx1 = col * i + j; idx3 = col * k + j; ret[idx1] += mat1[idx2] * mat2[idx3]; } } } } // ret = vec / c inline void div(double* ret, const double* vec, const double c, const int16_t row) { int16_t i; double inv_c = 1.0 / c; for (i = 0; i < row; i++) { ret[i] = vec[i] * inv_c; } } // ret = mat / c inline void div(double* ret, const double* mat, const double c, const int16_t row, const int16_t col) { int16_t i; double inv_c = 1.0 / c; for (i = 0; i < row * col; i++) { ret[i] = mat[i] * inv_c; } } // ret = norm(vec) inline double norm(const double* vec, int16_t n) { int16_t i; double ret = 0; for (i = 0; i < n; i++) { ret += vec[i] * vec[i]; } return sqrt(ret); } // ret = vec1' * vec2 inline double dot(const double* vec1, const double* vec2, const int16_t n) { int16_t i; double ret = 0; for (i = 0; i < n; i++) { ret += vec1[i] * vec2[i]; } return ret; } // ret = sign(x) inline double sign(const double x) { return (x < 0.0) ? -1.0 : 1.0; } // ret = mat \ vec // Gaussian elimination inline void linsolve(double* vec, double* mat, const int16_t n) { int16_t i, j, k, idx1, idx2, idx3; int16_t row_max_i; double row_max_val, buf; for (k = 0; k < n - 1; k++) { // Find i such that maximize A[i][k] idx1 = n * k + k; row_max_i = k; row_max_val = fabs(mat[idx1]); for (i = k + 1; i < n; i++) { idx1 = n * k + i; if (row_max_val < fabs(mat[idx1])) { row_max_val = fabs(mat[idx1]); row_max_i = i; } } // Swap rows if (row_max_i != k) { buf = vec[k]; vec[k] = vec[row_max_i]; vec[row_max_i] = buf; for (j = k; j < n; j++) { idx1 = n * j + k; idx2 = n * j + row_max_i; buf = mat[idx1]; mat[idx1] = mat[idx2]; mat[idx2] = buf; } } // Forward elimination idx1 = n * k + k; buf = 1.0 / mat[idx1]; for (i = k + 1; i < n; i++) { idx1 = n * k + i; mat[idx1] = mat[idx1] * buf; for (j = k + 1; j < n; j++) { idx2 = n * j + k; idx3 = n * j + i; mat[idx3] -= mat[idx1] * mat[idx2]; } vec[i] -= mat[idx1] * vec[k]; } } // Backward elimination for (i = n - 1; i >= 0; i--) { for (j = n - 1; j > i; j--) { idx1 = n * j + i; vec[i] -= mat[idx1] * vec[j]; } idx1 = n * i + i; vec[i] /= mat[idx1]; } }
22.53125
125
0.513176
blockahead
ff7fb9690e8d8095f4c504153fef19bbb2ad433f
43,691
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior // const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ZoneName_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ZoneName () const { return this->SimInfiltrationOrVentilation_ZoneName_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ZoneName_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ZoneName () { return this->SimInfiltrationOrVentilation_ZoneName_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ZoneName (const SimInfiltrationOrVentilation_ZoneName_type& x) { this->SimInfiltrationOrVentilation_ZoneName_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ZoneName (const SimInfiltrationOrVentilation_ZoneName_optional& x) { this->SimInfiltrationOrVentilation_ZoneName_ = x; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ZoneName (::std::auto_ptr< SimInfiltrationOrVentilation_ZoneName_type > x) { this->SimInfiltrationOrVentilation_ZoneName_.set (x); } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ThermstatHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ThermstatHt () const { return this->SimInfiltrationOrVentilation_ThermstatHt_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ThermstatHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ThermstatHt () { return this->SimInfiltrationOrVentilation_ThermstatHt_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ThermstatHt (const SimInfiltrationOrVentilation_ThermstatHt_type& x) { this->SimInfiltrationOrVentilation_ThermstatHt_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ThermstatHt (const SimInfiltrationOrVentilation_ThermstatHt_optional& x) { this->SimInfiltrationOrVentilation_ThermstatHt_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ComfHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ComfHt () const { return this->SimInfiltrationOrVentilation_ComfHt_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_ComfHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ComfHt () { return this->SimInfiltrationOrVentilation_ComfHt_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ComfHt (const SimInfiltrationOrVentilation_ComfHt_type& x) { this->SimInfiltrationOrVentilation_ComfHt_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_ComfHt (const SimInfiltrationOrVentilation_ComfHt_optional& x) { this->SimInfiltrationOrVentilation_ComfHt_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TempDiffThreshRpt () const { return this->SimInfiltrationOrVentilation_TempDiffThreshRpt_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TempDiffThreshRpt () { return this->SimInfiltrationOrVentilation_TempDiffThreshRpt_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TempDiffThreshRpt (const SimInfiltrationOrVentilation_TempDiffThreshRpt_type& x) { this->SimInfiltrationOrVentilation_TempDiffThreshRpt_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TempDiffThreshRpt (const SimInfiltrationOrVentilation_TempDiffThreshRpt_optional& x) { this->SimInfiltrationOrVentilation_TempDiffThreshRpt_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_PowerPerPlume_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_PowerPerPlume () const { return this->SimInfiltrationOrVentilation_PowerPerPlume_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_PowerPerPlume_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_PowerPerPlume () { return this->SimInfiltrationOrVentilation_PowerPerPlume_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_PowerPerPlume (const SimInfiltrationOrVentilation_PowerPerPlume_type& x) { this->SimInfiltrationOrVentilation_PowerPerPlume_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_PowerPerPlume (const SimInfiltrationOrVentilation_PowerPerPlume_optional& x) { this->SimInfiltrationOrVentilation_PowerPerPlume_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DesignEffectAreaDiff () const { return this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DesignEffectAreaDiff () { return this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DesignEffectAreaDiff (const SimInfiltrationOrVentilation_DesignEffectAreaDiff_type& x) { this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DesignEffectAreaDiff (const SimInfiltrationOrVentilation_DesignEffectAreaDiff_optional& x) { this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DiffSlotAngFromVertexical () const { return this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DiffSlotAngFromVertexical () { return this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DiffSlotAngFromVertexical (const SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_type& x) { this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_DiffSlotAngFromVertexical (const SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_optional& x) { this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_FlrDiffType_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_FlrDiffType () const { return this->SimInfiltrationOrVentilation_FlrDiffType_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_FlrDiffType_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_FlrDiffType () { return this->SimInfiltrationOrVentilation_FlrDiffType_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_FlrDiffType (const SimInfiltrationOrVentilation_FlrDiffType_type& x) { this->SimInfiltrationOrVentilation_FlrDiffType_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_FlrDiffType (const SimInfiltrationOrVentilation_FlrDiffType_optional& x) { this->SimInfiltrationOrVentilation_FlrDiffType_ = x; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_FlrDiffType (::std::auto_ptr< SimInfiltrationOrVentilation_FlrDiffType_type > x) { this->SimInfiltrationOrVentilation_FlrDiffType_.set (x); } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TransHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TransHt () const { return this->SimInfiltrationOrVentilation_TransHt_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_TransHt_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TransHt () { return this->SimInfiltrationOrVentilation_TransHt_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TransHt (const SimInfiltrationOrVentilation_TransHt_type& x) { this->SimInfiltrationOrVentilation_TransHt_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_TransHt (const SimInfiltrationOrVentilation_TransHt_optional& x) { this->SimInfiltrationOrVentilation_TransHt_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_NumbDiffPerZone_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_NumbDiffPerZone () const { return this->SimInfiltrationOrVentilation_NumbDiffPerZone_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_NumbDiffPerZone_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_NumbDiffPerZone () { return this->SimInfiltrationOrVentilation_NumbDiffPerZone_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_NumbDiffPerZone (const SimInfiltrationOrVentilation_NumbDiffPerZone_type& x) { this->SimInfiltrationOrVentilation_NumbDiffPerZone_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_NumbDiffPerZone (const SimInfiltrationOrVentilation_NumbDiffPerZone_optional& x) { this->SimInfiltrationOrVentilation_NumbDiffPerZone_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const { return this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () { return this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x) { this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x) { this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const { return this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () { return this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x) { this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x) { this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const { return this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () { return this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x) { this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x) { this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const { return this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () { return this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x) { this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x) { this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x; } const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () const { return this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior::SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 () { return this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_type& x) { this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (x); } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 (const SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_optional& x) { this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior // SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior () : ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (), SimInfiltrationOrVentilation_ZoneName_ (this), SimInfiltrationOrVentilation_ThermstatHt_ (this), SimInfiltrationOrVentilation_ComfHt_ (this), SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this), SimInfiltrationOrVentilation_PowerPerPlume_ (this), SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this), SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this), SimInfiltrationOrVentilation_FlrDiffType_ (this), SimInfiltrationOrVentilation_TransHt_ (this), SimInfiltrationOrVentilation_NumbDiffPerZone_ (this), SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this) { } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (RefId), SimInfiltrationOrVentilation_ZoneName_ (this), SimInfiltrationOrVentilation_ThermstatHt_ (this), SimInfiltrationOrVentilation_ComfHt_ (this), SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this), SimInfiltrationOrVentilation_PowerPerPlume_ (this), SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this), SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this), SimInfiltrationOrVentilation_FlrDiffType_ (this), SimInfiltrationOrVentilation_TransHt_ (this), SimInfiltrationOrVentilation_NumbDiffPerZone_ (this), SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this) { } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (x, f, c), SimInfiltrationOrVentilation_ZoneName_ (x.SimInfiltrationOrVentilation_ZoneName_, f, this), SimInfiltrationOrVentilation_ThermstatHt_ (x.SimInfiltrationOrVentilation_ThermstatHt_, f, this), SimInfiltrationOrVentilation_ComfHt_ (x.SimInfiltrationOrVentilation_ComfHt_, f, this), SimInfiltrationOrVentilation_TempDiffThreshRpt_ (x.SimInfiltrationOrVentilation_TempDiffThreshRpt_, f, this), SimInfiltrationOrVentilation_PowerPerPlume_ (x.SimInfiltrationOrVentilation_PowerPerPlume_, f, this), SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (x.SimInfiltrationOrVentilation_DesignEffectAreaDiff_, f, this), SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (x.SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_, f, this), SimInfiltrationOrVentilation_FlrDiffType_ (x.SimInfiltrationOrVentilation_FlrDiffType_, f, this), SimInfiltrationOrVentilation_TransHt_ (x.SimInfiltrationOrVentilation_TransHt_, f, this), SimInfiltrationOrVentilation_NumbDiffPerZone_ (x.SimInfiltrationOrVentilation_NumbDiffPerZone_, f, this), SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this), SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this), SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this), SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this), SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (x.SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_, f, this) { } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings (e, f | ::xml_schema::flags::base, c), SimInfiltrationOrVentilation_ZoneName_ (this), SimInfiltrationOrVentilation_ThermstatHt_ (this), SimInfiltrationOrVentilation_ComfHt_ (this), SimInfiltrationOrVentilation_TempDiffThreshRpt_ (this), SimInfiltrationOrVentilation_PowerPerPlume_ (this), SimInfiltrationOrVentilation_DesignEffectAreaDiff_ (this), SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ (this), SimInfiltrationOrVentilation_FlrDiffType_ (this), SimInfiltrationOrVentilation_TransHt_ (this), SimInfiltrationOrVentilation_NumbDiffPerZone_ (this), SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this), SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimInfiltrationOrVentilation_ZoneName // if (n.name () == "SimInfiltrationOrVentilation_ZoneName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< SimInfiltrationOrVentilation_ZoneName_type > r ( SimInfiltrationOrVentilation_ZoneName_traits::create (i, f, this)); if (!this->SimInfiltrationOrVentilation_ZoneName_) { this->SimInfiltrationOrVentilation_ZoneName_.set (r); continue; } } // SimInfiltrationOrVentilation_ThermstatHt // if (n.name () == "SimInfiltrationOrVentilation_ThermstatHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_ThermstatHt_) { this->SimInfiltrationOrVentilation_ThermstatHt_.set (SimInfiltrationOrVentilation_ThermstatHt_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_ComfHt // if (n.name () == "SimInfiltrationOrVentilation_ComfHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_ComfHt_) { this->SimInfiltrationOrVentilation_ComfHt_.set (SimInfiltrationOrVentilation_ComfHt_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_TempDiffThreshRpt // if (n.name () == "SimInfiltrationOrVentilation_TempDiffThreshRpt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_TempDiffThreshRpt_) { this->SimInfiltrationOrVentilation_TempDiffThreshRpt_.set (SimInfiltrationOrVentilation_TempDiffThreshRpt_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_PowerPerPlume // if (n.name () == "SimInfiltrationOrVentilation_PowerPerPlume" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_PowerPerPlume_) { this->SimInfiltrationOrVentilation_PowerPerPlume_.set (SimInfiltrationOrVentilation_PowerPerPlume_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_DesignEffectAreaDiff // if (n.name () == "SimInfiltrationOrVentilation_DesignEffectAreaDiff" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_) { this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_.set (SimInfiltrationOrVentilation_DesignEffectAreaDiff_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_DiffSlotAngFromVertexical // if (n.name () == "SimInfiltrationOrVentilation_DiffSlotAngFromVertexical" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_) { this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_.set (SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_FlrDiffType // if (n.name () == "SimInfiltrationOrVentilation_FlrDiffType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< SimInfiltrationOrVentilation_FlrDiffType_type > r ( SimInfiltrationOrVentilation_FlrDiffType_traits::create (i, f, this)); if (!this->SimInfiltrationOrVentilation_FlrDiffType_) { this->SimInfiltrationOrVentilation_FlrDiffType_.set (r); continue; } } // SimInfiltrationOrVentilation_TransHt // if (n.name () == "SimInfiltrationOrVentilation_TransHt" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_TransHt_) { this->SimInfiltrationOrVentilation_TransHt_.set (SimInfiltrationOrVentilation_TransHt_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_NumbDiffPerZone // if (n.name () == "SimInfiltrationOrVentilation_NumbDiffPerZone" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_NumbDiffPerZone_) { this->SimInfiltrationOrVentilation_NumbDiffPerZone_.set (SimInfiltrationOrVentilation_NumbDiffPerZone_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 // if (n.name () == "SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_) { this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 // if (n.name () == "SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_) { this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 // if (n.name () == "SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_) { this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 // if (n.name () == "SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_) { this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this)); continue; } } // SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2 // if (n.name () == "SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_) { this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_.set (SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_traits::create (i, f, this)); continue; } } break; } } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior* SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior (*this, f, c); } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: operator= (const SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior& x) { if (this != &x) { static_cast< ::schema::simxml::ResourcesGeneral::SimInfiltrationOrVentilation_RoomAirSettings& > (*this) = x; this->SimInfiltrationOrVentilation_ZoneName_ = x.SimInfiltrationOrVentilation_ZoneName_; this->SimInfiltrationOrVentilation_ThermstatHt_ = x.SimInfiltrationOrVentilation_ThermstatHt_; this->SimInfiltrationOrVentilation_ComfHt_ = x.SimInfiltrationOrVentilation_ComfHt_; this->SimInfiltrationOrVentilation_TempDiffThreshRpt_ = x.SimInfiltrationOrVentilation_TempDiffThreshRpt_; this->SimInfiltrationOrVentilation_PowerPerPlume_ = x.SimInfiltrationOrVentilation_PowerPerPlume_; this->SimInfiltrationOrVentilation_DesignEffectAreaDiff_ = x.SimInfiltrationOrVentilation_DesignEffectAreaDiff_; this->SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_ = x.SimInfiltrationOrVentilation_DiffSlotAngFromVertexical_; this->SimInfiltrationOrVentilation_FlrDiffType_ = x.SimInfiltrationOrVentilation_FlrDiffType_; this->SimInfiltrationOrVentilation_TransHt_ = x.SimInfiltrationOrVentilation_TransHt_; this->SimInfiltrationOrVentilation_NumbDiffPerZone_ = x.SimInfiltrationOrVentilation_NumbDiffPerZone_; this->SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffAInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; this->SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffBInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; this->SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffCInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; this->SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffDInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; this->SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_ = x.SimInfiltrationOrVentilation_CoeffEInFormKc_A_Gamma_B_C_D_Gamma_E_Gamma_2_; } return *this; } SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior:: ~SimInfiltrationOrVentilation_RoomAirSettings_UnderFloorAirDistributionExterior () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
55.375158
256
0.784418
EnEff-BIM
ff81008893ca08c20159b89ea87eb5b18719f820
1,013
cpp
C++
802.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
802.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
802.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
class Solution { public: vector<int> eventualSafeNodes(vector<vector<int>>& graph) { bool finish = false; vector<bool> outed(graph.size(), false); while(!finish){ finish = true; map<int,bool> zeroout; for(int i = 0; i < graph.size(); i++){ if(graph[i].size() == 0 && !outed[i]){ outed[i] = true; finish = false; zeroout[i] = true; } } for(int i = 0; i < graph.size(); i++){ for(int j = 0; j < graph[i].size(); j++){ if(zeroout[graph[i][j]]){ graph[i].erase(graph[i].begin() + j); j--; } } } } vector<int> ans; for(int i = 0; i < graph.size(); i++){ if(graph[i].size() == 0){ ans.push_back(i); } } return ans; } };
27.378378
63
0.358342
zfang399
ff82459288558066e464c5d47a60109a8bf0da7d
12,545
cpp
C++
source/Networking.cpp
MrPh1l/RocketPlugin
dab038ee6cd448df05805d894f45abefabbeeec3
[ "MIT" ]
null
null
null
source/Networking.cpp
MrPh1l/RocketPlugin
dab038ee6cd448df05805d894f45abefabbeeec3
[ "MIT" ]
null
null
null
source/Networking.cpp
MrPh1l/RocketPlugin
dab038ee6cd448df05805d894f45abefabbeeec3
[ "MIT" ]
null
null
null
// Networking.cpp // General networking calls for the RocketPlugin plugin. // // Author: Stanbroek // Version: 0.6.3 15/7/20 #include "Networking.h" #pragma comment(lib,"Ws2_32.lib") #include <WinSock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #pragma comment(lib, "iphlpapi.lib") #include <regex> /// <summary>Creates a thread to call functions on.</summary> WorkerThread::WorkerThread() { wantExit = false; thread = std::unique_ptr<std::thread>(new std::thread(std::bind(&WorkerThread::Entry, this))); } /// <summary>Waits for the thread to finish and removes it.</summary> WorkerThread::~WorkerThread() { { std::lock_guard<std::mutex> lock(queueMutex); wantExit = true; queuePending.notify_one(); } thread->join(); } /// <summary>Adds job_t's to the job queue to be execute on a sepperate thread.</summary> /// <param name="job">function to be executed</param> void WorkerThread::addJob(job_t job) { std::lock_guard<std::mutex> lock(queueMutex); jobQueue.push_back(job); queuePending.notify_one(); } /// <summary>Main loop of the thread.</summary> void WorkerThread::Entry() { job_t job; while (true) { { std::unique_lock<std::mutex> lock(queueMutex); queuePending.wait(lock, [&]() { return wantExit || !jobQueue.empty(); }); if (wantExit) { return; } job = jobQueue.front(); jobQueue.pop_front(); } job(); } } /// <summary>Checks whether the given IP is a valid ipv4.</summary> /// <param name="addr">IP to validate</param> /// <returns>Bool with is the IP is a valid ipv4 address</returns> bool Networking::isValidIPv4(const char* IPAddr) { const std::regex ipv4_regex("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"); std::string string = IPAddr; std::smatch match; if (std::regex_match(string, match, ipv4_regex, std::regex_constants::match_flag_type::format_default)) { return true; } return false; } /// <summary>Checks whether the given IP is not an internal ipv4.</summary> /// <param name="IPAddr">IP to validate</param> /// <returns>Bool with is the IP is not an internal ipv4 address</returns> bool Networking::isInternalIPv4(const char* IPAddr) { // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) if (std::strncmp(IPAddr, "192.168.", 8) == 0) { return true; } // 10.0.0.0 - 10.255.255.255 (10/8 prefix) if (std::strncmp(IPAddr, "10.", 3) == 0) { return true; } // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) if (std::strncmp(IPAddr, "172.", 4) == 0) { int i = atoi(IPAddr + 4); if ((16 <= i) && (i <= 31)) { return true; } } return false; } /// <summary>Checks whether the given IP is in the Hamachi ipv4 address space.</summary> /// <param name="IPAddr">IP to validate</param> /// <returns>Bool with is the IP is in the Hamachi ipv4 address space</returns> bool Networking::isHamachiAddr(const char* IPAddr) { // 25.0.0.0 - 25.255.255.255 (10/8 prefix) if (std::strncmp(IPAddr, "25.", 3) == 0) { return true; } return false; } /// <summary>Checks whether the given address is a valid domain name.</summary> /// <remarks>https://regexr.com/3au3g</remarks> /// <param name="addr">address to validate</param> /// <returns>Bool with is the address is a valid domain name</returns> bool Networking::isValidDomainName(const char* addr) { const std::regex domainname_regex("^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$"); std::string string = addr; std::smatch match; if (std::regex_match(string, match, domainname_regex, std::regex_constants::match_flag_type::format_default)) { return true; } return false; } /// <summary>Gets the internal IP address of the user.</summary> /// <returns>Internal IP address</returns> std::string Networking::getInternalIPAddress() { int i; std::string internalIPAddress; // Variables used by GetIpAddrTable PMIB_IPADDRTABLE pIPAddrTable; DWORD dwSize = 0; IN_ADDR IPAddr; // Before calling AddIPAddress we use GetIpAddrTable to get // an adapter to which we can add the IP. pIPAddrTable = (MIB_IPADDRTABLE*)malloc(sizeof(MIB_IPADDRTABLE)); if (pIPAddrTable) { // Make an initial call to GetIpAddrTable to get the // necessary size into the dwSize variable if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) { free(pIPAddrTable); pIPAddrTable = (MIB_IPADDRTABLE*)malloc(dwSize); } } if (pIPAddrTable) { // Make a second call to GetIpAddrTable to get the actual data we want if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == NO_ERROR) { for (i = 0; i < (int)pIPAddrTable->dwNumEntries; i++) { if (pIPAddrTable->table[i].wType & MIB_IPADDR_PRIMARY) { IPAddr.S_un.S_addr = (ULONG)pIPAddrTable->table[i].dwAddr; char ipBuf[sizeof "255.255.255.255"]; internalIPAddress = inet_ntop(AF_INET, &IPAddr, ipBuf, sizeof ipBuf); if (!isValidIPv4(internalIPAddress.c_str()) || !isInternalIPv4(internalIPAddress.c_str())) { internalIPAddress.clear(); } } } } free(pIPAddrTable); pIPAddrTable = NULL; } return internalIPAddress; } /// <summary>Tries to parse the external IP address from a http responce.</summary> /// <param name="buffer">Http responce</param> /// <returns>External IP address</returns> std::string parseExternalIPAddressFromResponce(std::string buffer) { size_t contentLengthOffset = buffer.find("Content-Length:") + 16; size_t contentLengthCount = buffer.find('\n', contentLengthOffset); int contentLength = strtol(buffer.substr(contentLengthOffset, contentLengthCount).c_str(), NULL, 10); size_t addrOffset = buffer.find("\r\n\r\n"); if (addrOffset == std::string::npos) { return ""; } return buffer.substr(addrOffset + 4, contentLength); } /// <summary>Tries to get the external IP address.</summary> /// <param name="addr">Contains the external IP address when threaded</param> /// <param name="threaded">Whether the action should be executed on another thread</param> /// <returns>External IP address</returns> std::string Networking::getExternalIPAddress(std::string host, std::string* addr, bool threaded) { if (threaded && addr == nullptr) { return ""; } if (threaded) { std::thread(getExternalIPAddress, host, addr, false).detach(); return ""; } // Initialize Winsock. WSADATA wsaData = { 0 }; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { return ""; } // Create a socket for sending data. SOCKET sendSocket = INVALID_SOCKET; sendSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sendSocket == INVALID_SOCKET) { WSACleanup(); return ""; } // Set up the addrDest structure with the IP address and port of the receiver. addrinfo hints; addrinfo* result = NULL; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo(host.c_str(), NULL, &hints, &result) != 0) { closesocket(sendSocket); WSACleanup(); return ""; } sockaddr_in addrDest; addrDest = *(sockaddr_in*)result->ai_addr; addrDest.sin_family = AF_INET; addrDest.sin_port = htons(80); if (connect(sendSocket, (sockaddr*)&addrDest, sizeof addrDest) == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); return ""; } // Send a datagram to the receiver std::string sendBuf = "GET / HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n"; if (sendto(sendSocket, sendBuf.c_str(), (int)sendBuf.size(), 0, (sockaddr*)&addrDest, (int)sizeof addrDest) == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); return ""; } // Wait until data received or timeout. fd_set fds; FD_ZERO(&fds); FD_SET(sendSocket, &fds); struct timeval tv; tv.tv_sec = 3; tv.tv_usec = 0; iResult = select(NULL, &fds, NULL, NULL, &tv); if (iResult == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); return ""; } // Connection timedout. else if (iResult == 0) { closesocket(sendSocket); WSACleanup(); return ""; } // Set up the addrRetDest structure for the IP address and port from the receiver. sockaddr_in addrRetDest; int addrRetDestSize = sizeof addrRetDest; // Recieve a datagram from the receiver. char recvBuf[1024]; int recvBufLen = 1024; if (recvfrom(sendSocket, recvBuf, recvBufLen, 0, (sockaddr*)&addrRetDest, &addrRetDestSize) == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); return ""; } closesocket(sendSocket); WSACleanup(); std::string externalIPAddress = parseExternalIPAddressFromResponce(recvBuf); if (!isValidIPv4(externalIPAddress.c_str()) || isInternalIPv4(externalIPAddress.c_str())) { return ""; } if (addr != nullptr) { *addr = externalIPAddress; } return externalIPAddress; } /// <summary>Tries ping host to see if they are reachable.</summary> /// <param name="IP">IP address of the host</param> /// <param name="port">Port of the server</param> /// <param name="threaded">Whether the action should be executed on another thread</param> /// <returns>Bool with if the host was reachable</returns> bool Networking::pingHost(std::string IP, unsigned short port, HostStatus* result, bool threaded) { if (threaded && result == nullptr) { return false; } if (threaded) { if (result != nullptr) { *result = HostStatus::HOST_BUSY; } std::thread(pingHost, IP, port, result, false).detach(); return false; } // Initialize Winsock. WSADATA wsaData = { 0 }; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { if (result != nullptr) { *result = HostStatus::HOST_ERROR; } return false; } // Create a socket for sending data. SOCKET sendSocket = INVALID_SOCKET; sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sendSocket == INVALID_SOCKET) { WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_ERROR; } return false; } // Set up the addrDest structure with the IP address and port of the receiver. sockaddr_in addrDest; addrDest.sin_family = AF_INET; addrDest.sin_port = htons(port); if (inet_pton(addrDest.sin_family, IP.c_str(), &addrDest.sin_addr.s_addr) != 1) { closesocket(sendSocket); WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_ERROR; } return false; } // Send a datagram to the receiver const char* sendBuf = "Hey host guy are you alive?"; if (sendto(sendSocket, sendBuf, (int)strlen(sendBuf), 0, (sockaddr*)&addrDest, (int)sizeof addrDest) == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_ERROR; } return false; } // Wait until data received or timeout. fd_set fds; FD_ZERO(&fds); FD_SET(sendSocket, &fds); struct timeval tv; tv.tv_sec = 5; tv.tv_usec = 0; iResult = select(NULL, &fds, NULL, NULL, &tv); if (iResult == SOCKET_ERROR) { closesocket(sendSocket); WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_ERROR; } return false; } // Connection timedout. else if (iResult == 0) { closesocket(sendSocket); WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_TIMEOUT; } return false; } closesocket(sendSocket); WSACleanup(); if (result != nullptr) { *result = HostStatus::HOST_ONLINE; } return true; }
29.940334
142
0.612914
MrPh1l
ff83e5b2516acae1e619830011c703965a870a35
22,330
cpp
C++
admin/wmi/wbem/winmgmt/mofcomp_dll/cbmofout.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/winmgmt/mofcomp_dll/cbmofout.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/winmgmt/mofcomp_dll/cbmofout.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) 1997-2001 Microsoft Corporation Module Name: CBMOFOUT.CPP Abstract: Declares the CBMOFOut class. History: a-davj 06-April-97 Created. --*/ #include "precomp.h" #include "wstring.h" #include "mofout.h" #include "mofdata.h" #include "bmof.h" #include "cbmofout.h" #include "trace.h" #include "strings.h" #include <wbemutil.h> //*************************************************************************** // // CBMOFOut::CBMOFOut // // DESCRIPTION: // // Constructor. Save the eventual destination name and writes the initial // structure out to the buffer. NOTE THAT TYPICALLY THE BMOFFileName will // be NULL and this object will not do anything. That deals with the 99% // of mofs that are not WMI! // // PARAMETERS: // // BMOFFileName Name of file to eventually write to. // //*************************************************************************** CBMOFOut::CBMOFOut( IN LPTSTR BMOFFileName, PDBG pDbg) : m_OutBuff(pDbg) { m_pDbg = pDbg; m_BinMof.dwSignature = BMOF_SIG; // spells BMOF m_BinMof.dwLength = sizeof(WBEM_Binary_MOF); // updated at end m_BinMof.dwVersion = 1; // 0x1 m_BinMof.dwEncoding = 1; // 0x1 = little endian, DWORD-aligned, no compression m_BinMof.dwNumberOfObjects = 0; // Total classes and instances in MOF if(BMOFFileName && lstrlen(BMOFFileName) > 0) { DWORD dwLen = lstrlen(BMOFFileName) + 1; m_pFile = new TCHAR[dwLen]; if(m_pFile) { StringCchCopyW(m_pFile, dwLen, BMOFFileName); m_OutBuff.AppendBytes((BYTE *)&m_BinMof, sizeof(WBEM_Binary_MOF)); } } else m_pFile = NULL; } //*************************************************************************** // // CBMOFOut::~CBMOFOut // // DESCRIPTION: // // Destructor. // //*************************************************************************** CBMOFOut::~CBMOFOut() { if(m_pFile) delete m_pFile; } //*************************************************************************** // // DWORD CBMOFOut::AddClass // // DESCRIPTION: // // Adds a class to the BMOF buffer. // // PARAMETERS: // // pObject pointer to class object. // bEmbedded TRUE if object is embedded. // // RETURN VALUE: // // Number of bytes written. // //*************************************************************************** DWORD CBMOFOut::AddClass( IN CMObject * pObject, IN BOOL bEmbedded) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); CMoQualifierArray * pQualifierSet = NULL; if(!m_pFile) return 0; WBEM_Object wo; wo.dwLength = sizeof(WBEM_Object); // updated later wo.dwOffsetQualifierList = 0xffffffff; wo.dwOffsetPropertyList = 0xffffffff; wo.dwOffsetMethodList = 0xffffffff; wo.dwType = (pObject->IsInstance()) ? 1 : 0; // 0 = class, 1 = instance m_OutBuff.AppendBytes((BYTE *)&wo, sizeof(WBEM_Object)); DWORD dwStartInfoOffset = m_OutBuff.GetOffset(); // Write class qualifier pQualifierSet = pObject->GetQualifiers(); if(pQualifierSet) { wo.dwOffsetQualifierList = m_OutBuff.GetOffset() - dwStartInfoOffset; AddQualSet(pQualifierSet); } wo.dwOffsetPropertyList = m_OutBuff.GetOffset() - dwStartInfoOffset; AddPropSet(pObject); wo.dwOffsetMethodList = m_OutBuff.GetOffset() - dwStartInfoOffset; AddMethSet(pObject); wo.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&wo, sizeof(WBEM_Object)); // If the object is not embedded, update the structure that keeps track // of top level objects. if(!bEmbedded) { m_BinMof.dwNumberOfObjects++; m_BinMof.dwLength = m_OutBuff.GetOffset(); m_OutBuff.WriteBytes(0, (BYTE *)&m_BinMof, sizeof(WBEM_Binary_MOF)); } return wo.dwLength; } //*************************************************************************** // // DWORD CBMOFOut::AddQualSet // // DESCRIPTION: // // Adds a qualifier set to the BMOF buffer. // // PARAMETERS: // // pQualifierSet pointer to qualifier object. // // RETURN VALUE: // // Number of bytes written. // //*************************************************************************** DWORD CBMOFOut::AddQualSet( IN CMoQualifierArray * pQualifierSet) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); WBEM_QualifierList ql; ql.dwLength = sizeof(WBEM_QualifierList); ql.dwNumQualifiers = 0; m_OutBuff.AppendBytes((BYTE *)&ql, sizeof(WBEM_QualifierList)); BSTR bstr = NULL; VARIANT var; VariantInit(&var); int i; for(i = 0; i < pQualifierSet->GetSize(); i++) { CMoQualifier * pQual = pQualifierSet->GetAt(i); if(pQual) { ql.dwNumQualifiers++; AddQualifier(pQual->GetName(), pQual->GetpVar(), pQual); } } ql.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&ql, sizeof(WBEM_QualifierList)); return ql.dwLength; } //*************************************************************************** // // DWORD CBMOFOut::AddPropSet // // DESCRIPTION: // // Adds the property set to the BMOF buffer. // // PARAMETERS: // // pObject pointer to class object. // // RETURN VALUE: // // Number of bytess written // //*************************************************************************** DWORD CBMOFOut::AddPropSet( IN CMObject * pObject) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); WBEM_PropertyList pl; BSTR bstr = NULL; VARIANT var; VariantInit(&var); IWbemQualifierSet* pQual = NULL; pl.dwLength = sizeof(WBEM_PropertyList); // updated later pl.dwNumberOfProperties = 0; m_OutBuff.AppendBytes((BYTE *)&pl, sizeof(WBEM_PropertyList)); // Loop through the properties int i; for(i = 0; i < pObject->GetNumProperties(); i++) { CMoProperty * pProp = pObject->GetProperty(i); if(pProp && pProp->IsValueProperty()) { pl.dwNumberOfProperties++; CMoQualifierArray * pQual = pProp->GetQualifiers(); AddProp(pProp->GetName(), pProp->GetpVar(), pQual,pProp->GetType(),pProp); } } // Store the class name and possibly the parent name as properties. VariantInit(&var); var.vt = VT_BSTR; var.bstrVal = SysAllocString(pObject->GetClassName()); AddProp(L"__CLASS", &var, NULL,VT_BSTR,NULL); pl.dwNumberOfProperties++; VariantClear(&var); if(pObject->GetNamespace() && wcslen(pObject->GetNamespace()) > 0) { VariantInit(&var); var.vt = VT_BSTR; var.bstrVal = SysAllocString(pObject->GetNamespace()); AddProp(L"__NAMESPACE", &var, NULL,VT_BSTR,NULL); pl.dwNumberOfProperties++; VariantClear(&var); } if(pObject->GetClassFlags() != 0) { VariantInit(&var); var.vt = VT_I4; var.lVal = pObject->GetClassFlags(); AddProp(L"__CLASSFLAGS", &var, NULL,VT_I4,NULL); pl.dwNumberOfProperties++; VariantClear(&var); } if(pObject->GetInstanceFlags() != 0) { VariantInit(&var); var.vt = VT_I4; var.lVal = pObject->GetInstanceFlags(); AddProp(L"__INSTANCEFLAGS", &var, NULL,VT_I4,NULL); pl.dwNumberOfProperties++; VariantClear(&var); } if(pObject->GetAlias() && wcslen(pObject->GetAlias()) > 0) { VariantInit(&var); var.vt = VT_BSTR; var.bstrVal = SysAllocString(pObject->GetAlias()); AddProp(L"__ALIAS", &var, NULL,VT_BSTR,NULL); pl.dwNumberOfProperties++; VariantClear(&var); } if(!pObject->IsInstance()) { CMoClass * pClass = (CMoClass * )pObject; var.vt = VT_BSTR; if(pClass->GetParentName() && wcslen(pClass->GetParentName()) > 0) { var.bstrVal = SysAllocString(pClass->GetParentName()); AddProp(L"__SUPERCLASS", &var, NULL,VT_BSTR,NULL); pl.dwNumberOfProperties++; VariantClear(&var); } }; pl.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&pl, sizeof(WBEM_PropertyList)); return pl.dwLength; } //*************************************************************************** // // DWORD CBMOFOut::AddMethSet // // DESCRIPTION: // // Adds the method set to the BMOF buffer. // // PARAMETERS: // // pObject pointer to class object. // // RETURN VALUE: // // Number of bytess written // //*************************************************************************** DWORD CBMOFOut::AddMethSet( IN CMObject * pObject) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); WBEM_PropertyList ml; SCODE sc; IWbemQualifierSet* pQual = NULL; ml.dwLength = sizeof(WBEM_PropertyList); // updated later ml.dwNumberOfProperties = 0; m_OutBuff.AppendBytes((BYTE *)&ml, sizeof(WBEM_PropertyList)); // Loop through the properties int i; for(i = 0; i < pObject->GetNumProperties(); i++) { CMoProperty * pProp = pObject->GetProperty(i); if(pProp && !pProp->IsValueProperty()) { ml.dwNumberOfProperties++; CMoQualifierArray * pQual = pProp->GetQualifiers(); // Create a variant that has an array of embedded object for each of out // input and output arg sets CMethodProperty * pMeth = (CMethodProperty *)pProp; VARIANT vSet; if(pMeth->GetInObj() || pMeth->GetOutObj()) { vSet.vt = VT_ARRAY | VT_EMBEDDED_OBJECT; SAFEARRAYBOUND aBounds[1]; // Note the you might have either inputs, or ouputs, or both if(pMeth->GetInObj() && pMeth->GetOutObj()) aBounds[0].cElements = 2; else aBounds[0].cElements = 1; aBounds[0].lLbound = 0; #ifdef _WIN64 vSet.parray = SafeArrayCreate(VT_R8, 1, aBounds); #else vSet.parray = SafeArrayCreate(VT_I4, 1, aBounds); #endif if(vSet.parray == NULL) return FALSE; long lIndex = 0; VARIANT var; if(pMeth->GetInObj()) { var.punkVal = (IUnknown *)pMeth->GetInObj(); sc = SafeArrayPutElement(vSet.parray, &lIndex, &var.punkVal); lIndex = 1; } if(pMeth->GetOutObj()) { var.punkVal = (IUnknown *)pMeth->GetOutObj(); sc = SafeArrayPutElement(vSet.parray, &lIndex, &var.punkVal); } } else vSet.vt = VT_NULL; AddProp(pProp->GetName(), &vSet, pQual,pProp->GetType(),pProp); } } ml.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&ml, sizeof(WBEM_PropertyList)); return ml.dwLength; } //*************************************************************************** // // DWORD CBMOFOut::AddProp // // DESCRIPTION: // // Adds a single property to the BMOF buffer. // // PARAMETERS: // // bstr property name // pvar variant containing value // pQual pointer to qualifier set if any. Caller will release. // dwType data type. Note that the variant might have type // VT_NULL if the property doesnt have a value. // RETURN VALUE: // // Number of bytes written // //*************************************************************************** DWORD CBMOFOut::AddProp( IN BSTR bstr, IN VARIANT * pvar, IN CMoQualifierArray * pQual, IN DWORD dwType, IN CMoProperty * pProp) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); WBEM_Property prop; prop.dwLength = sizeof(WBEM_Property); if(pvar->vt == VT_NULL || pvar->vt == VT_EMPTY) prop.dwType = dwType; else prop.dwType = pvar->vt; prop.dwOffsetName = 0xffffffff; prop.dwOffsetValue = 0xffffffff; prop.dwOffsetQualifierSet = 0xffffffff; m_OutBuff.AppendBytes((BYTE *)&prop, sizeof(WBEM_Property)); DWORD dwStartInfoOffset = m_OutBuff.GetOffset(); if(bstr) { prop.dwOffsetName = m_OutBuff.GetOffset() - dwStartInfoOffset; m_OutBuff.WriteBSTR(bstr); } if(pvar->vt != VT_EMPTY && pvar->vt != VT_NULL) { prop.dwOffsetValue = m_OutBuff.GetOffset() - dwStartInfoOffset; if(pProp) { CMoValue& Value = pProp->AccessValue(); AddVariant(pvar, &Value); prop.dwType = pvar->vt; } else AddVariant(pvar, NULL); } if(pQual) { prop.dwOffsetQualifierSet = m_OutBuff.GetOffset() - dwStartInfoOffset; AddQualSet(pQual); } prop.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&prop, sizeof(WBEM_Property)); return 1; } //*************************************************************************** // // DWORD CBMOFOut::AddQualifier // // DESCRIPTION: // // Adds a qualifier to the BMOF buffer. // // PARAMETERS: // // bstr qualifer name // pvar qualifier value // // RETURN VALUE: // // Number of bytes written. // //*************************************************************************** DWORD CBMOFOut::AddQualifier( IN BSTR bstr, IN VARIANT * pvar, CMoQualifier * pQual) { WBEM_Qualifier qu; DWORD dwStartingOffset = m_OutBuff.GetOffset(); long lFlavor = pQual->GetFlavor(); if(pQual->IsAmended()) lFlavor |= WBEM_FLAVOR_AMENDED; if(lFlavor) m_OutBuff.AddFlavor(lFlavor); qu.dwLength = sizeof(WBEM_Qualifier); // filled in later qu.dwType = pvar->vt; qu.dwOffsetName = 0xffffffff; qu.dwOffsetValue = 0xffffffff; m_OutBuff.AppendBytes((BYTE *)&qu, sizeof(WBEM_Qualifier)); DWORD dwStartInfoOffset = m_OutBuff.GetOffset(); // Write the qualifier name and data if(bstr) { qu.dwOffsetName = m_OutBuff.GetOffset() - dwStartInfoOffset; m_OutBuff.WriteBSTR(bstr); } if(pvar->vt != VT_EMPTY && pvar->vt != VT_NULL) { CMoValue& Value = pQual->AccessValue(); qu.dwOffsetValue = m_OutBuff.GetOffset() - dwStartInfoOffset; AddVariant(pvar, &Value); qu.dwType = pvar->vt; } qu.dwLength = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&qu, sizeof(WBEM_Qualifier)); return 0; } //*************************************************************************** // // DWORD CBMOFOut::AddVariant // // DESCRIPTION: // // Adds a value to the BMOF buffer. // // PARAMETERS: // // pvar value to add. // // RETURN VALUE: // // Total bytes written // //*************************************************************************** DWORD CBMOFOut::AddVariant(VARIANT * pvar, CMoValue * pValue) { if(pValue && pValue->GetNumAliases() > 0) pvar->vt |= VT_BYREF; VARTYPE vtSimple = pvar->vt & ~VT_ARRAY & ~VT_BYREF; if(pvar->vt & VT_ARRAY) { DWORD dwStartingOffset = m_OutBuff.GetOffset(); DWORD dwSize = 0; m_OutBuff.AppendBytes((BYTE *)&dwSize, sizeof(DWORD)); DWORD dwTotal = 0; SCODE sc; SAFEARRAY * psa; long ix[2] = {0,0}; long uLower, uUpper; psa = pvar->parray; sc = SafeArrayGetLBound(psa,1,&uLower); sc |= SafeArrayGetUBound(psa,1,&uUpper); if(sc != S_OK) return 0; // write the number of dimensions and the size of each DWORD dwNumDim = 1; // for now!!! m_OutBuff.AppendBytes((BYTE *)&dwNumDim, sizeof(long)); // Number of dimensions DWORD dwNumElem = uUpper - uLower + 1; m_OutBuff.AppendBytes((BYTE *)&dwNumElem, sizeof(long)); // Write out the row size DWORD dwStartingRowOffset = m_OutBuff.GetOffset(); DWORD dwRowSize = 0; m_OutBuff.AppendBytes((BYTE *)&dwRowSize, sizeof(DWORD)); // Get each element and write it for(ix[0] = uLower; ix[0] <= uUpper && sc == S_OK; ix[0]++) { VARIANT var; VariantInit(&var); var.vt = vtSimple; sc = SafeArrayGetElement(psa,ix,&var.bstrVal); if(sc != S_OK) { Trace(true, m_pDbg, SAFE_ARRAY_ERROR); } if(ix[0] < uUpper) m_OutBuff.SetPadMode(FALSE); else m_OutBuff.SetPadMode(TRUE); dwTotal += AddSimpleVariant(&var, ix[0], pValue); if(var.vt != VT_EMBEDDED_OBJECT) // Our dispatch is actual a CMObject * VariantClear(&var); } // Update the size of the property and the row. Note that having a separate size // is for possible future support of multi dimensional arrays. dwRowSize = m_OutBuff.GetOffset() - dwStartingRowOffset; m_OutBuff.WriteBytes(dwStartingRowOffset, (BYTE *)&dwRowSize, sizeof(DWORD)); dwSize = m_OutBuff.GetOffset() - dwStartingOffset; m_OutBuff.WriteBytes(dwStartingOffset, (BYTE *)&dwSize, sizeof(DWORD)); return dwTotal; } else return AddSimpleVariant(pvar, -1, pValue); } //*************************************************************************** // // DWORD CBMOFOut::AddSimpleVariant // // DESCRIPTION: // // Adds a non array variant to the BMOF buffer. // // PARAMETERS: // // pvar value to add. // iIndex set to -1 if property in scalar, or if array, has // the index of this element. Note that arrays are // broken up into simple variants. // // // RETURN VALUE: // // Bytes written //*************************************************************************** DWORD CBMOFOut::AddSimpleVariant(VARIANT * pvar, int iIndex, CMoValue * pValue) { DWORD dwSize = iTypeSize(pvar->vt & ~VT_BYREF); VARTYPE vtSimple = pvar->vt & ~VT_BYREF; if(pValue && pValue->GetNumAliases() && (vtSimple == VT_BSTR)) { WCHAR * wszAlias = NULL; int iTry, iAlIndex = -1; if(iIndex == -1) pValue->GetAlias(0, wszAlias, iAlIndex); else { for(iTry = 0; iTry < pValue->GetNumAliases(); iTry++) { pValue->GetAlias(iTry, wszAlias, iAlIndex); if(iIndex == iAlIndex) break; } if(iTry == pValue->GetNumAliases()) wszAlias = NULL; } if(wszAlias && iIndex == -1) pvar->bstrVal = SysAllocString(wszAlias); else if(wszAlias && iIndex != -1) { DWORD dwLen = wcslen(wszAlias)+2; WCHAR * pTemp = new WCHAR[dwLen]; if(pTemp == NULL) return 0; pTemp[0]= L'$'; StringCchCopyW(pTemp+1, dwLen-1, wszAlias); pvar->bstrVal = SysAllocString(pTemp); delete pTemp; } else if(wszAlias == NULL && iIndex != -1) { DWORD dwLen = wcslen(pvar->bstrVal)+2; WCHAR * pTemp = new WCHAR[dwLen]; if(pTemp == NULL) return 0; pTemp[0]= L' '; StringCchCopyW(pTemp+1, dwLen-1, pvar->bstrVal); pvar->bstrVal = SysAllocString(pTemp); delete pTemp; } } if(vtSimple == VT_BSTR) return m_OutBuff.WriteBSTR(pvar->bstrVal); else if(vtSimple == VT_EMBEDDED_OBJECT) { CMObject * pObj = (CMObject *)pvar->punkVal; return AddClass(pObj, TRUE); } else return m_OutBuff.AppendBytes((BYTE *)&pvar->bstrVal, dwSize); } //*************************************************************************** // // BOOL CBMOFOut::WriteFile // // DESCRIPTION: // // Writes the buffer out to the file. // //*************************************************************************** BOOL CBMOFOut::WriteFile() { BOOL bRet = FALSE; if(m_pFile) { m_BinMof.dwLength = m_OutBuff.GetOffset(); m_OutBuff.WriteBytes(0, (BYTE *)&m_BinMof, sizeof(WBEM_Binary_MOF)); #ifdef UNICODE char cFile[MAX_PATH]; wcstombs(cFile, m_pFile, MAX_PATH); bRet = m_OutBuff.WriteToFile(cFile); #else bRet = m_OutBuff.WriteToFile(m_pFile); #endif } return bRet; }
29.189542
93
0.504702
npocmaka
ff85d5202952e4ee43c758bcdeb18564c49a3419
4,627
cpp
C++
AngioLib/Segment.cpp
ltedgar-ed/AngioFE_original
2a57f8dfec3bc31aa63bf33719359676899bbb2a
[ "MIT" ]
null
null
null
AngioLib/Segment.cpp
ltedgar-ed/AngioFE_original
2a57f8dfec3bc31aa63bf33719359676899bbb2a
[ "MIT" ]
null
null
null
AngioLib/Segment.cpp
ltedgar-ed/AngioFE_original
2a57f8dfec3bc31aa63bf33719359676899bbb2a
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////// // Segment.cpp /////////////////////////////////////////////////////////////////////// // Include: #include "stdafx.h" #include "Segment.h" #include "vect3.h" #include "angio3d.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Segment::Segment() // Constructor for SEGMENT object { x[0]= 0; // x, y, z - Initialize the coordinates of the tips to 0 x[1]= 0; y[0]= 0; y[1]= 0; z[0]= 0; z[1]= 0; x0[0]= 0; // x, y, z - Initialize the coordinates of the tips to 0 x0[1]= 0; y0[0]= 0; y0[1]= 0; z0[0]= 0; z0[1]= 0; tip[0]= 0; // tip - Initialize the activity of the tips to 0 tip[1]= 0; length = 0; // length - Initialize the length of the segment to 0 // phi1 = 0; // phi1, phi2 - Initialize the orientation angles of the segment to 0 // phi2 = 0; label = 0; // label - Initialize label to 0 vessel = 0; // vessel - Initialize vessel to 0 BCdead = 0; // BCdead - Set boundary condition indicator to 'false' TofBirth = 0; // TofBirth - Initialize time of birth to 0 Recent_branch = 0; // Recent_branch - Initialize branching indicator to 0 init_branch = false; // init)branch - Set initial branching flag to 'false' sprout = 0; // sprout - Initialize sprout to 0 anast = 0; elem_tagged = false; bdyf_id[0] = -1; bdyf_id[1] = -1; mark_of_death = false; death_label = 0; tip_BC[0] = 0; tip_BC[1] = 0; tip_elem[0] = -1; tip_elem[1] = -1; seg_num = 0; seg_conn[0][0] = 0; seg_conn[0][1] = 0; seg_conn[1][0] = 0; seg_conn[1][1] = 0; //line_num = 0; } Segment::~Segment() // Destructor for SEGMENT object { } void Segment::findlength() { double new_length = sqrt(pow((x[1] - x[0]),2) + pow((y[1] - y[0]),2) + pow((z[1] - z[0]),2)); if (length < 0.0) length = -new_length; else length = new_length; uvect.x = x[1] - x[0]; uvect.y = y[1] - y[0]; uvect.z = z[1] - z[0]; if (length != 0) uvect = uvect/uvect.norm(); return; } void Segment::findunit() { uvect.x = x[1] - x[0]; uvect.y = y[1] - y[0]; uvect.z = z[1] - z[0]; if (uvect.norm() != 0.0) uvect = uvect/uvect.norm(); return; } //void Segment::findphi() //{ // vect3 vvect, xvvect, zvvect; // // if (length == 0.0) // return; // // vvect.x = x[1] - x[0]; // vvect.y = y[1] - y[0]; // vvect.z = z[1] - z[0]; // vvect = vvect/vvect.norm(); // // xvvect = vect3(vvect.x, vvect.y, 0); // //// double phi10 = phi1; //// double phi20 = phi2; // // // Calculate phi2 // phi2 = asin(vvect.z); // // double alt_phi2 = 0.; // // if (vvect.x < 0) // if (phi2 > 0) // alt_phi2 = pi - phi2; // else if (phi2 < 0) // alt_phi2 = -pi - phi2; // // if (fabs(phi20 - alt_phi2) < fabs(phi20 - phi2)) // phi2 = alt_phi2; // // // Calculate phi1 // double phi1_dot = 0.; // phi1_dot = xvvect*vect3(1,0,0); // // if (cos(phi2) != 0.0) // phi1 = acos(vvect.x/cos(phi2)); // else // phi1 = acos(phi1_dot); // // if (vvect.x/cos(phi2) > 1) // phi1 = 0; // else if (vvect.x/cos(phi2) < -1) // if (phi10 > 0) // phi1 = pi; // else if (phi10 < 0) // phi1 = -pi; // // if (vvect.y < 0) // phi1 = -phi1; // // if (vvect.norm() == 0.){ // phi1 = phi10; // phi2 = phi20;} // // if (vvect.y == 0.) // phi1 = phi10; // // if (vvect.z == 0.) // phi2 = 0.; // // return; //}
26.289773
236
0.376054
ltedgar-ed
ff8c88d46d362fdb777526683db6658185e2c709
1,168
cpp
C++
cf/Div2/D/Good Sequences/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/D/Good Sequences/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/D/Good Sequences/main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n; cin >> n; vector<pair<int, int>>in; vector<vector<int>>div(1e5+1); vector<int>primes; for (int i = 2; i <= 1e5; ++i) { for(int p : primes){ if(p>400){ break;} if(i%p==0){div[i].push_back(p); if(div[i/p].size()==0){ div[i].push_back(i/p); }} } if(!div[i].size()){primes.push_back(i);} } vector<int>mem(1e5+1, 0); for (int i = 0; i < n; ++i) { int cur; cin >> cur; if(div[cur].size()==0&&cur!=1){ mem[cur]++; } int newV=0; for (int j = 0; j < div[cur].size(); ++j) { newV=max(newV, mem[div[cur][j]]+1); } for (int j = 0; j < div[cur].size(); ++j) { mem[div[cur][j]]=newV; } } cout << max((int)1, *max_element(mem.begin(), mem.end())); }
23.836735
72
0.472603
wdjpng
ff8cd1ddb41d789a274b35ed9e4c6a3ebe0e7d0c
478
cc
C++
page_240_44.cc
coder52/Cpp-Primer-Solutions-2013
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
[ "MIT" ]
null
null
null
page_240_44.cc
coder52/Cpp-Primer-Solutions-2013
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
[ "MIT" ]
42
2021-08-08T10:36:33.000Z
2021-08-29T20:35:37.000Z
page_240_44.cc
coder52/Cpp-Primer-Solutions-2013
e68d8a8cd4f12b1dbc269b152d955b5ebcf6d9aa
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace::std; /* Page 240 Exercise 6.44: Rewrite the isShorter function from § 6.2.2 (p. 211) to be inline. */ // Put inline and constexpr Functions in Header Files. inline const string & shorterString(const string &s1, const string &s2){ return s1.size() <= s2.size() ? s1 : s2; } int main(int argc, char const *argv[]) { string s1 = "aaaaaa"; string s2 = "bbbb"; std::cout<<(shorterString(s1,s2)); return 0; }
17.703704
82
0.661088
coder52
ff8e893e905ad43b8b7ed22cc92087f7c96b1b96
3,824
cpp
C++
host_runtimes/linux_no_cma_test/test_ops.cpp
thenextged/uRDAI
119742ba032588586653d83937999b497c0a1ee9
[ "Apache-2.0" ]
3
2020-07-15T07:31:25.000Z
2020-07-15T07:31:29.000Z
host_runtimes/linux_no_cma_test/test_ops.cpp
thenextged/uRDAI
119742ba032588586653d83937999b497c0a1ee9
[ "Apache-2.0" ]
null
null
null
host_runtimes/linux_no_cma_test/test_ops.cpp
thenextged/uRDAI
119742ba032588586653d83937999b497c0a1ee9
[ "Apache-2.0" ]
null
null
null
#include "rdai_api.h" // ================= DATA extern RDAI_Platform clockwork_platform; static RDAI_Device clockwork_device = { { 1 }, { { "aha" }, { "halide_hardware" }, { "conv_3_3_clockwork" }, 1 }, &clockwork_platform, NULL, 1 }; static RDAI_Device *clockwork_platform_devices[2] = { &clockwork_device, NULL }; RDAI_Platform clockwork_platform = { RDAI_PlatformType::RDAI_CLOCKWORK_PLATFORM, { 0 }, NULL, clockwork_platform_devices }; // ================= Helpers static RDAI_Status make_status_error( RDAI_ErrorReason reason = RDAI_REASON_UNIMPLEMENTED ) { RDAI_Status status; status.status_code = RDAI_STATUS_ERROR; status.error_reason = reason; return status; } static RDAI_Status make_status_ok() { RDAI_Status status; status.status_code = RDAI_STATUS_OK; return status; } // ================= OPs static RDAI_MemObject * op_mem_allocate( RDAI_MemObjectType mem_object_type, size_t size, RDAI_Device *device) { return NULL; } static RDAI_Status op_mem_free( RDAI_MemObject *mem_object ) { return make_status_error(); } static RDAI_Status op_mem_copy( RDAI_MemObject *src, RDAI_MemObject *dest ) { return make_status_error(); } static RDAI_Status op_mem_copy_async( RDAI_MemObject *src, RDAI_MemObject *dest ) { return make_status_error(); } static RDAI_MemObject *op_mem_crop( RDAI_MemObject *src, size_t offset, size_t cropped_size ) { return NULL; } static RDAI_Status op_mem_free_crop( RDAI_MemObject *obj ) { return make_status_error(); } static RDAI_Platform *op_platform_create( void ) { return &clockwork_platform; } static RDAI_Status op_platform_destroy( RDAI_Platform *platform ) { return make_status_ok(); } static RDAI_Status op_platform_init( RDAI_Platform *platform, void *user_data ) { return make_status_error(); } static RDAI_Status op_platform_deinit( RDAI_Platform *platform, void *user_data ) { return make_status_error(); } static RDAI_Status op_device_init( RDAI_Device *device, void *user_data ) { return make_status_error(); } static RDAI_Status op_device_deinit( RDAI_Device *device, void *user_data ) { return make_status_error(); } static RDAI_Status op_device_run( RDAI_Device *device, RDAI_MemObject **mem_object_list ) { if( device && mem_object_list && mem_object_list[0] ) { size_t num_els = 1; while(mem_object_list[num_els]) num_els++; RDAI_MemObject *output = mem_object_list[num_els - 1]; for(size_t i = 0; i < output->size; i++) { output->host_ptr[i] = i & 0xFF; } return make_status_ok(); } return make_status_error(); } static RDAI_Status op_device_run_async( RDAI_Device *device, RDAI_MemObject **mem_object_list ) { return op_device_run( device, mem_object_list ); } static RDAI_Status op_sync( RDAI_AsyncHandle *handle ) { if(handle && handle->platform) { return make_status_ok(); } return make_status_error(); } // ======================== PlatformOps RDAI_PlatformOps ops = { .mem_allocate = op_mem_allocate, .mem_free = op_mem_free, .mem_copy = op_mem_copy, .mem_copy_async = op_mem_copy_async, .mem_crop = op_mem_crop, .mem_free_crop = op_mem_free_crop, .platform_create = op_platform_create, .platform_destroy = op_platform_destroy, .platform_init = op_platform_init, .platform_deinit = op_platform_deinit, .device_init = op_device_init, .device_deinit = op_device_deinit, .device_run = op_device_run, .device_run_async = op_device_run_async, .sync = op_sync };
24.512821
95
0.667103
thenextged
ff91193a900bc6e04002c3c74880441102d4350f
4,956
cpp
C++
arduino-ntpd/GPSTimeSource.cpp
jonsl/arduino_sntp
b19220e877dcd64edc4b4c47ca9e00585abaed2b
[ "MIT" ]
5
2020-12-17T13:07:46.000Z
2021-09-02T16:48:44.000Z
arduino-ntpd/GPSTimeSource.cpp
jonsl/arduino_sntp
b19220e877dcd64edc4b4c47ca9e00585abaed2b
[ "MIT" ]
null
null
null
arduino-ntpd/GPSTimeSource.cpp
jonsl/arduino_sntp
b19220e877dcd64edc4b4c47ca9e00585abaed2b
[ "MIT" ]
1
2019-02-25T09:40:09.000Z
2019-02-25T09:40:09.000Z
/* * File: GPSTimeSource.cpp * Description: * A time source that reads the time from a NMEA-compliant GPS receiver. * Author: Mooneer Salem <mooneer@gmail.com> * License: New BSD License */ #include "config.h" #ifdef ETH_RX_PIN #include "utility/w5100.h" #endif // ETH_RX_PIN #include "GPSTimeSource.h" #include "TimeUtilities.h" GPSTimeSource *GPSTimeSource::Singleton_ = NULL; volatile uint32_t overflows = 0; volatile uint32_t overflowsRecv = 0; void GPSTimeSource::enableInterrupts() { #ifdef ETH_RX_PIN // Enable Ethernet interrupt first to reduce difference between the two timers. // NOTE: NTP server must _always_ be initialized first to ensure that it occupies socket 0. W5100.writeIMR(0x01); #endif Singleton_ = this; pinMode(PPS_PIN, INPUT); TCCR4A = 0 ; // Normal counting mode TCCR4B = B010; // set prescale bits TCCR4B |= _BV(ICES4); // enable input capture when pin goes high TIMSK4 |= _BV(ICIE4); // enable input capture interrupt for timer 4 TIMSK4 |= _BV(TOIE4); // overflow interrupt #ifdef ETH_RX_PIN pinMode(ETH_RX_PIN, INPUT); TCCR5A = 0 ; // Normal counting mode TCCR5B = B010; // set prescale bits // enable input capture when pin goes low (default). TIMSK5 |= _BV(ICIE5); // enable input capture interrupt for timer 5 TIMSK5 |= _BV(TOIE5); // overflow interrupt #endif Serial.println("interrupts enabled"); } void GPSTimeSource::PpsInterrupt() { // Get saved time value. uint32_t tmrVal = (overflows << 16) | ICR4; GPSTimeSource::Singleton_->microsecondsPerSecond_ = (GPSTimeSource::Singleton_->microsecondsPerSecond_ + (tmrVal - Singleton_->millisecondsOfLastUpdate_)) / 2; GPSTimeSource::Singleton_->secondsSinceEpoch_++; GPSTimeSource::Singleton_->fractionalSecondsSinceEpoch_ = 0; GPSTimeSource::Singleton_->millisecondsOfLastUpdate_ = tmrVal; } void GPSTimeSource::RecvInterrupt() { // Get saved time value. uint32_t tmrVal = (overflowsRecv << 16) | ICR5; uint32_t tmrDiff = tmrVal - GPSTimeSource::Singleton_->millisecondsOfLastUpdate_; GPSTimeSource::Singleton_->fractionalSecondsOfRecv_ = (tmrDiff % GPSTimeSource::Singleton_->microsecondsPerSecond_) * (0xFFFFFFFF / GPSTimeSource::Singleton_->microsecondsPerSecond_); GPSTimeSource::Singleton_->secondsOfRecv_ = GPSTimeSource::Singleton_->secondsSinceEpoch_; if (tmrDiff > GPSTimeSource::Singleton_->microsecondsPerSecond_) { ++GPSTimeSource::Singleton_->secondsOfRecv_; } } ISR(TIMER4_OVF_vect) { ++overflows; } ISR(TIMER4_CAPT_vect) { GPSTimeSource::PpsInterrupt(); } ISR(TIMER5_OVF_vect) { ++overflowsRecv; } ISR(TIMER5_CAPT_vect) { GPSTimeSource::RecvInterrupt(); } void GPSTimeSource::updateFractionalSeconds_(void) { // Calculate new fractional value based on system runtime // since the EM-406 does not seem to return anything other than whole seconds. uint32_t lastTime = (overflows << 16) | TCNT4; uint32_t millisecondDifference = lastTime - millisecondsOfLastUpdate_; fractionalSecondsSinceEpoch_ = (millisecondDifference % microsecondsPerSecond_) * (0xFFFFFFFF / microsecondsPerSecond_); } void GPSTimeSource::now(uint32_t *secs, uint32_t *fract) { while (dataSource_.available()) { int c = dataSource_.read(); if (gps_.encode(c)) { // Grab time from now-valid data. int year; byte month, day, hour, minutes, second, hundredths; unsigned long fix_age; gps_.crack_datetime(&year, &month, &day, &hour, &minutes, &second, &hundredths, &fix_age); gps_.f_get_position(&lat_, &long_); // We don't want to use the time we've received if // the fix is invalid. if (fix_age != TinyGPS::GPS_INVALID_AGE && fix_age < 5000 && year >= 2013) { uint32_t tempSeconds = TimeUtilities::numberOfSecondsSince1900Epoch( year, month, day, hour, minutes, second); if (tempSeconds != secondsSinceEpoch_) { secondsSinceEpoch_ = tempSeconds; hasLocked_ = true; } } else { // Set time to 0 if invalid. // TODO: does the interface need an accessor for "invalid time"? secondsSinceEpoch_ = 0; fractionalSecondsSinceEpoch_ = 0; } } } updateFractionalSeconds_(); if (secs) { *secs = secondsSinceEpoch_; } if (fract) { *fract = fractionalSecondsSinceEpoch_; } }
30.592593
124
0.622074
jonsl
ff93253ed2e202bae31bc1427bd09cdbc0d4b6bb
4,565
cpp
C++
Projects/Core/EditContext.cpp
krisl/quip
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
[ "MIT" ]
null
null
null
Projects/Core/EditContext.cpp
krisl/quip
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
[ "MIT" ]
null
null
null
Projects/Core/EditContext.cpp
krisl/quip
a386f8bcecf59de9e9c7a6d6d8c077e49b72fb19
[ "MIT" ]
1
2020-07-11T22:45:16.000Z
2020-07-11T22:45:16.000Z
#include "EditContext.hpp" #include "Document.hpp" #include "EditMode.hpp" #include "JumpMode.hpp" #include "Location.hpp" #include "Mode.hpp" #include "NormalMode.hpp" #include "SearchMode.hpp" #include "Selection.hpp" #include "Transaction.hpp" #include <memory> namespace quip { EditContext::EditContext(PopupService* popupService, StatusService* statusService, ScriptHost* scriptHost) : EditContext(popupService, statusService, scriptHost, std::make_shared<Document>()) { } EditContext::EditContext(PopupService* popupService, StatusService* statusService, ScriptHost* scriptHost, std::shared_ptr<Document> document) : m_document(document) , m_fileTypeDatabase(*scriptHost) , m_selections(Selection(Location(0, 0))) , m_popupService(popupService) , m_statusService(statusService) { // Populate with standard file types. m_fileTypeDatabase.registerFileType("Text", "text", {"txt", "text"}); m_fileTypeDatabase.registerFileType("Markdown", "markdown", {"md", "markdown"}); m_fileTypeDatabase.registerFileType("C++ Source", "cpp", {"cpp", "cxx"}); m_fileTypeDatabase.registerFileType("C++ Header", "cpp", {"hpp", "hxx"}); m_fileTypeDatabase.registerFileType("C Source", "cpp", {"c"}); m_fileTypeDatabase.registerFileType("C/C++ Header", "cpp", {"h"}); m_fileTypeDatabase.registerFileType("GLSL Shader Source", "glsl", {"fsh", "vsh"}); // Populate with standard modes. m_modes.insert(std::make_pair("EditMode", std::make_shared<EditMode>())); m_modes.insert(std::make_pair("JumpMode", std::make_shared<JumpMode>())); m_modes.insert(std::make_pair("NormalMode", std::make_shared<NormalMode>())); m_modes.insert(std::make_pair("SearchMode", std::make_shared<SearchMode>())); enterMode("NormalMode"); } Document& EditContext::document() { return *m_document; } SelectionSet& EditContext::selections() { return m_selections; } Mode& EditContext::mode() { return *m_modeHistory.top(); } const std::map<std::string, SelectionDrawInfo>& EditContext::overlays() const { return m_overlays; } void EditContext::setOverlay(const std::string& name, const SelectionDrawInfo& overlay) { m_overlays[name] = overlay; } void EditContext::clearOverlay(const std::string& name) { auto cursor = m_overlays.find(name); if (cursor != std::end(m_overlays)) { m_overlays.erase(cursor); } } void EditContext::enterMode(const std::string& name) { enterMode(name, 0); } void EditContext::enterMode(const std::string& name, std::uint64_t how) { std::map<std::string, std::shared_ptr<Mode>>::iterator cursor = m_modes.find(name); if (cursor != m_modes.end()) { m_modeHistory.push(cursor->second); mode().enter(*this, how); } } void EditContext::leaveMode() { if (m_modeHistory.size() > 1) { mode().exit(*this); m_modeHistory.pop(); } } void EditContext::performTransaction(std::shared_ptr<Transaction> transaction) { transaction->perform(*this); m_onTransactionApplied.transmit(ChangeType::Do); m_undoStack.push(transaction); } bool EditContext::canUndo() const noexcept { return m_undoStack.size() > 0; } void EditContext::undo() { if (canUndo()) { m_undoStack.top()->rollback(*this); m_onTransactionApplied.transmit(ChangeType::Undo); m_redoStack.push(m_undoStack.top()); m_undoStack.pop(); } } bool EditContext::canRedo() const noexcept { return m_redoStack.size() > 0; } void EditContext::redo() { if (canRedo()) { m_redoStack.top()->perform(*this); m_onTransactionApplied.transmit(ChangeType::Redo); m_undoStack.push(m_redoStack.top()); m_redoStack.pop(); } } bool EditContext::processKeyEvent(Key key, Modifiers modifiers) { return mode().processKeyEvent(key, modifiers, *this); } bool EditContext::processKeyEvent(Key key, Modifiers modifiers, const std::string& text) { return mode().processKeyEvent(key, modifiers, text, *this); } ViewController& EditContext::controller() { return m_controller; } PopupService& EditContext::popupService() { return *m_popupService; } StatusService& EditContext::statusService() { return *m_statusService; } const FileTypeDatabase& EditContext::fileTypeDatabase() const { return m_fileTypeDatabase; } Signal<void (ChangeType)>& EditContext::onTransactionApplied() { return m_onTransactionApplied; } }
29.836601
144
0.679956
krisl
ff93faaad9cc3c830e1fda93e8dadb063b03675b
78
hpp
C++
vendor/github.com/bep/golibsass/internal/libsass/fn_colors.hpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
17
2020-02-06T22:21:59.000Z
2022-02-17T09:14:36.000Z
vendor/github.com/bep/golibsass/internal/libsass/fn_colors.hpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
5
2020-02-12T14:41:49.000Z
2021-11-03T19:45:00.000Z
vendor/github.com/bep/golibsass/internal/libsass/fn_colors.hpp
f110/hugo
d99379094f1352ece8751b54ace8964d0811916e
[ "Apache-2.0" ]
5
2020-02-28T08:01:50.000Z
2021-06-14T14:28:58.000Z
#ifndef USE_LIBSASS_SRC #include "../../libsass_src/src/fn_colors.hpp" #endif
19.5
46
0.75641
f110
91110d56e7980e6c228cdf8123d39498aee5b595
2,390
cc
C++
src/contest/dmoj/CCO_Prep_Corporative_Network.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
83
2017-08-30T01:20:03.000Z
2022-02-12T13:50:27.000Z
src/contest/dmoj/CCO_Prep_Corporative_Network.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
1
2015-08-20T13:37:59.000Z
2015-08-26T00:56:39.000Z
src/contest/dmoj/CCO_Prep_Corporative_Network.cc
anshika581/competitive-programming-1
c34fb89820cd7260661daa2283f492b07cd9f8d2
[ "Apache-2.0", "MIT" ]
41
2017-11-09T06:10:08.000Z
2022-01-11T14:10:25.000Z
#include <bits/stdc++.h> #define mp make_pair #define pb push_back #define INF 1 << 30 #define MOD 1000000007 #define rint(x) scanf("%d", &(x)) #define rlong(x) scanf("%lld", &(x)) #define SIZE 20010 #define LN 15 #define l(x) x << 1 #define r(x) x << 1 | 1 #define m(x, y) (x + y) / 2 using namespace std; typedef long long ll; typedef pair<int, int> pi; typedef pair<ll, ll> pll; int par[SIZE][LN], sum[SIZE][LN]; int id[SIZE], depth[SIZE]; bool notRoot[SIZE]; vector<vector<int>> adj(SIZE); int T, N; struct query { int a, b; query(int a, int b) { this->a = a; this->b = b; } }; void dfs(int u, int d) { depth[u] = d; for (int v : adj[u]) dfs(v, d + 1); } int root(int i) { return i == id[i] ? i : (id[i] = root(id[i])); } // j is par of i void join(int i, int j) { i = root(i); j = root(j); id[i] = j; } int lca(int a, int b) { if (a == b) return 0; int ret = 0; for (int i = LN - 1; i >= 0; i--) { if (par[b][i] != -1 && depth[par[b][i]] > depth[a]) { ret += sum[b][i]; b = par[b][i]; } } ret += sum[b][0]; return ret; } int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); rint(T); for (int t = 1; t <= T; t++) { rint(N); memset(par, -1, sizeof par); memset(sum, 0, sizeof sum); memset(notRoot, false, sizeof notRoot); for (int i = 0; i < N; i++) adj[i].clear(); for (int i = 0; i < N; i++) { id[i] = i; depth[i] = -1; } vector<query> q; char c; scanf(" %c", &c); while (c != 'O') { if (c == 'E') { int a; rint(a); q.pb(query(a - 1, -1)); } else { int u, v; rint(u), rint(v); u--, v--; adj[v].pb(u); notRoot[u] = true; par[u][0] = v; sum[u][0] = abs(v - u) % 1000; q.pb(query(u, v)); } scanf(" %c", &c); } for (int i = 0; i < N; i++) if (!notRoot[i]) dfs(i, 0); for (int i = 1; i < LN; i++) { for (int j = 0; j < N; j++) { if (par[j][i - 1] != -1) { par[j][i] = par[par[j][i - 1]][i - 1]; sum[j][i] = sum[j][i - 1] + sum[par[j][i - 1]][i - 1]; } } } for (query qu : q) { if (qu.b == -1) printf("%d\n", lca(root(qu.a), qu.a)); else join(qu.a, qu.b); } } return 0; }
17.835821
64
0.438075
anshika581
9112f5c47f4427c3c13786e2b27717a063c7a58a
481
hpp
C++
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
rawbby/WS20-CG-Pra-Dungeon-Crawler
4c1b372649a92fb08b8908054d82624ae2b68af5
[ "MIT" ]
null
null
null
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
rawbby/WS20-CG-Pra-Dungeon-Crawler
4c1b372649a92fb08b8908054d82624ae2b68af5
[ "MIT" ]
null
null
null
core/engine/inc/engine/component/GlBlendMaterialComponent.hpp
rawbby/WS20-CG-Pra-Dungeon-Crawler
4c1b372649a92fb08b8908054d82624ae2b68af5
[ "MIT" ]
null
null
null
#pragma once #include <engine/component/GlRenderComponent.hpp> #include <engine/component/GlMaterialComponent.hpp> #include <array> namespace engine::component { /** * Needed textures for OpenGl to render a object * with multiple materials. * Up to three materials are supported. */ struct GlBlendMaterialComponent : public GlRenderComponent { std::array<Material, 3> materials{}; GLuint tex_blend = GL_NONE; }; }
21.863636
52
0.669439
rawbby
91151dd3501291dbb1bf2a1522fc4d8d60ec81e5
1,108
cpp
C++
Program128.cpp
PRASAD-DANGARE/C_PROGRAMS
40c114b3f44a85e6d280eef680f29dcbe3434af2
[ "MIT" ]
1
2021-06-07T07:55:39.000Z
2021-06-07T07:55:39.000Z
Program128.cpp
PRASAD-DANGARE/C_PROGRAMS
40c114b3f44a85e6d280eef680f29dcbe3434af2
[ "MIT" ]
null
null
null
Program128.cpp
PRASAD-DANGARE/C_PROGRAMS
40c114b3f44a85e6d280eef680f29dcbe3434af2
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////// // // Class Name : StringX // Function Name : Accept(),StrlenX() // Description : Accept String From User And Count Length Of The String // Input : String // Output : String // Author : Prasad Dangare // Date : 27 Mar 2021 // /////////////////////////////////////////////////////////// #include<iostream> using namespace std; /* Input : Hello Output : string length is : 5 */ class StringX { public: char str[30]; // array void Accept() { cout << "Enter String\n"; scanf("%[^'\n']s",str); } int StrlenX() { int iCnt = 0; char *ptr = str; // pointer which points to str while(*ptr != '\0') { ptr++; iCnt++; } return iCnt; } }; int main() { int ret = 0; StringX obj; obj.Accept(); ret = obj.StrlenX(); cout << "String length is : " << ret << "\n"; return 0; }
17.870968
75
0.392599
PRASAD-DANGARE
91152d89bb1862b8e43622a4d3530c3269697936
10,518
cpp
C++
test/unit/detail/protocol/null_bitmap_traits.cpp
sehe/mysql
53da045c2c2c0f347ccd82888920d39d11f3f7a4
[ "BSL-1.0" ]
1
2021-03-07T20:45:35.000Z
2021-03-07T20:45:35.000Z
test/unit/detail/protocol/null_bitmap_traits.cpp
sehe/mysql
53da045c2c2c0f347ccd82888920d39d11f3f7a4
[ "BSL-1.0" ]
null
null
null
test/unit/detail/protocol/null_bitmap_traits.cpp
sehe/mysql
53da045c2c2c0f347ccd82888920d39d11f3f7a4
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "boost/mysql/detail/protocol/null_bitmap_traits.hpp" #include "test_common.hpp" #include <boost/test/data/test_case.hpp> #include <boost/test/data/monomorphic/collection.hpp> #include <array> using boost::mysql::detail::null_bitmap_traits; using boost::mysql::detail::stmt_execute_null_bitmap_offset; using boost::mysql::detail::binary_row_null_bitmap_offset; using namespace boost::unit_test; using namespace boost::mysql::test; BOOST_AUTO_TEST_SUITE(test_null_bitmap_traits) // byte_count struct byte_count_sample { std::size_t offset; std::size_t num_fields; std::size_t expected_value; }; std::ostream& operator<<(std::ostream& os, const byte_count_sample& val) { return os << "(offset=" << val.offset << ", num_fields=" << val.num_fields << ")"; } constexpr byte_count_sample all_byte_count_samples [] { { stmt_execute_null_bitmap_offset, 0, 0 }, { stmt_execute_null_bitmap_offset, 1, 1 }, { stmt_execute_null_bitmap_offset, 2, 1 }, { stmt_execute_null_bitmap_offset, 3, 1 }, { stmt_execute_null_bitmap_offset, 4, 1 }, { stmt_execute_null_bitmap_offset, 5, 1 }, { stmt_execute_null_bitmap_offset, 6, 1 }, { stmt_execute_null_bitmap_offset, 7, 1 }, { stmt_execute_null_bitmap_offset, 8, 1 }, { stmt_execute_null_bitmap_offset, 9, 2 }, { stmt_execute_null_bitmap_offset, 10, 2 }, { stmt_execute_null_bitmap_offset, 11, 2 }, { stmt_execute_null_bitmap_offset, 12, 2 }, { stmt_execute_null_bitmap_offset, 13, 2 }, { stmt_execute_null_bitmap_offset, 14, 2 }, { stmt_execute_null_bitmap_offset, 15, 2 }, { stmt_execute_null_bitmap_offset, 16, 2 }, { stmt_execute_null_bitmap_offset, 17, 3 }, { binary_row_null_bitmap_offset, 0, 1 }, { binary_row_null_bitmap_offset, 1, 1 }, { binary_row_null_bitmap_offset, 2, 1 }, { binary_row_null_bitmap_offset, 3, 1 }, { binary_row_null_bitmap_offset, 4, 1 }, { binary_row_null_bitmap_offset, 5, 1 }, { binary_row_null_bitmap_offset, 6, 1 }, { binary_row_null_bitmap_offset, 7, 2 }, { binary_row_null_bitmap_offset, 8, 2 }, { binary_row_null_bitmap_offset, 9, 2 }, { binary_row_null_bitmap_offset, 10, 2 }, { binary_row_null_bitmap_offset, 11, 2 }, { binary_row_null_bitmap_offset, 12, 2 }, { binary_row_null_bitmap_offset, 13, 2 }, { binary_row_null_bitmap_offset, 14, 2 }, { binary_row_null_bitmap_offset, 15, 3 }, { binary_row_null_bitmap_offset, 16, 3 }, { binary_row_null_bitmap_offset, 17, 3 }, }; BOOST_DATA_TEST_CASE(byte_count, data::make(all_byte_count_samples)) { null_bitmap_traits traits (sample.offset, sample.num_fields); BOOST_TEST(traits.byte_count() == sample.expected_value); } // is_null struct is_null_sample { std::size_t offset; std::size_t pos; bool expected; }; std::ostream& operator<<(std::ostream& os, const is_null_sample& value) { return os << "(offset=" << value.offset << ", pos=" << value.pos << ")"; } constexpr is_null_sample all_is_null_samples [] { { stmt_execute_null_bitmap_offset, 0, false }, { stmt_execute_null_bitmap_offset, 1, false }, { stmt_execute_null_bitmap_offset, 2, true }, { stmt_execute_null_bitmap_offset, 3, false }, { stmt_execute_null_bitmap_offset, 4, true }, { stmt_execute_null_bitmap_offset, 5, true }, { stmt_execute_null_bitmap_offset, 6, false }, { stmt_execute_null_bitmap_offset, 7, true }, { stmt_execute_null_bitmap_offset, 8, true }, { stmt_execute_null_bitmap_offset, 9, true }, { stmt_execute_null_bitmap_offset, 10, true }, { stmt_execute_null_bitmap_offset, 11, true }, { stmt_execute_null_bitmap_offset, 12, true }, { stmt_execute_null_bitmap_offset, 13, true }, { stmt_execute_null_bitmap_offset, 14, true }, { stmt_execute_null_bitmap_offset, 15, true }, { stmt_execute_null_bitmap_offset, 16, false }, { binary_row_null_bitmap_offset, 0, true }, { binary_row_null_bitmap_offset, 1, false }, { binary_row_null_bitmap_offset, 2, true }, { binary_row_null_bitmap_offset, 3, true }, { binary_row_null_bitmap_offset, 4, false }, { binary_row_null_bitmap_offset, 5, true }, { binary_row_null_bitmap_offset, 6, true }, { binary_row_null_bitmap_offset, 7, true }, { binary_row_null_bitmap_offset, 8, true }, { binary_row_null_bitmap_offset, 9, true }, { binary_row_null_bitmap_offset, 10, true }, { binary_row_null_bitmap_offset, 11, true }, { binary_row_null_bitmap_offset, 12, true }, { binary_row_null_bitmap_offset, 13, true }, { binary_row_null_bitmap_offset, 14, false }, { binary_row_null_bitmap_offset, 15, false }, { binary_row_null_bitmap_offset, 16, false }, }; BOOST_DATA_TEST_CASE(is_null, data::make(all_is_null_samples)) { std::array<std::uint8_t, 3> content { 0xb4, 0xff, 0x00 }; // 0b10110100, 0b11111111, 0b00000000 null_bitmap_traits traits (sample.offset, 17); // 17 fields bool actual = traits.is_null(content.data(), sample.pos); BOOST_TEST(actual == sample.expected); } BOOST_AUTO_TEST_CASE(is_null_one_field_stmt_execute_first_bit_zero) { std::uint8_t value = 0x00; null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1); BOOST_TEST(!traits.is_null(&value, 0)); } BOOST_AUTO_TEST_CASE(is_null_one_field_stmt_execute_first_bit_one) { std::uint8_t value = 0x01; null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1); BOOST_TEST(traits.is_null(&value, 0)); } BOOST_AUTO_TEST_CASE(is_null_one_field_binary_row_third_bit_zero) { std::uint8_t value = 0x00; null_bitmap_traits traits (binary_row_null_bitmap_offset, 1); BOOST_TEST(!traits.is_null(&value, 0)); } BOOST_AUTO_TEST_CASE(is_null_one_field_binary_row_third_bit_one) { std::uint8_t value = 0x04; // 0b00000100 null_bitmap_traits traits (binary_row_null_bitmap_offset, 1); BOOST_TEST(traits.is_null(&value, 0)); } // set_null struct set_null_sample { std::size_t offset; std::size_t pos; std::array<std::uint8_t, 3> expected; constexpr set_null_sample( std::size_t offset, std::size_t pos, const std::array<std::uint8_t, 3>& expected ) : offset(offset), pos(pos), expected(expected) { }; }; std::ostream& operator<<(std::ostream& os, const set_null_sample& value) { return os << "(offset=" << value.offset << ", pos=" << value.pos << ")"; } constexpr set_null_sample all_set_null_samples [] { { stmt_execute_null_bitmap_offset, 0, {0x01, 0, 0} }, { stmt_execute_null_bitmap_offset, 1, {0x02, 0, 0} }, { stmt_execute_null_bitmap_offset, 2, {0x04, 0, 0} }, { stmt_execute_null_bitmap_offset, 3, {0x08, 0, 0} }, { stmt_execute_null_bitmap_offset, 4, {0x10, 0, 0} }, { stmt_execute_null_bitmap_offset, 5, {0x20, 0, 0} }, { stmt_execute_null_bitmap_offset, 6, {0x40, 0, 0} }, { stmt_execute_null_bitmap_offset, 7, {0x80, 0, 0} }, { stmt_execute_null_bitmap_offset, 8, {0, 0x01, 0} }, { stmt_execute_null_bitmap_offset, 9, {0, 0x02, 0} }, { stmt_execute_null_bitmap_offset, 10, {0, 0x04, 0} }, { stmt_execute_null_bitmap_offset, 11, {0, 0x08, 0} }, { stmt_execute_null_bitmap_offset, 12, {0, 0x10, 0} }, { stmt_execute_null_bitmap_offset, 13, {0, 0x20, 0} }, { stmt_execute_null_bitmap_offset, 14, {0, 0x40, 0} }, { stmt_execute_null_bitmap_offset, 15, {0, 0x80, 0} }, { stmt_execute_null_bitmap_offset, 16, {0, 0, 0x01} }, { binary_row_null_bitmap_offset, 0, {0x04, 0, 0} }, { binary_row_null_bitmap_offset, 1, {0x08, 0, 0} }, { binary_row_null_bitmap_offset, 2, {0x10, 0, 0} }, { binary_row_null_bitmap_offset, 3, {0x20, 0, 0} }, { binary_row_null_bitmap_offset, 4, {0x40, 0, 0} }, { binary_row_null_bitmap_offset, 5, {0x80, 0, 0} }, { binary_row_null_bitmap_offset, 6, {0, 0x01, 0} }, { binary_row_null_bitmap_offset, 7, {0, 0x02, 0} }, { binary_row_null_bitmap_offset, 8, {0, 0x04, 0} }, { binary_row_null_bitmap_offset, 9, {0, 0x08, 0} }, { binary_row_null_bitmap_offset, 10, {0, 0x10, 0} }, { binary_row_null_bitmap_offset, 11, {0, 0x20, 0} }, { binary_row_null_bitmap_offset, 12, {0, 0x40, 0} }, { binary_row_null_bitmap_offset, 13, {0, 0x80, 0} }, { binary_row_null_bitmap_offset, 14, {0, 0, 0x01} }, { binary_row_null_bitmap_offset, 15, {0, 0, 0x02} }, { binary_row_null_bitmap_offset, 16, {0, 0, 0x04} }, }; BOOST_DATA_TEST_CASE(set_null, data::make(all_set_null_samples)) { std::array<std::uint8_t, 4> expected_buffer {}; // help detect buffer overruns std::memcpy(expected_buffer.data(), sample.expected.data(), 3); std::array<std::uint8_t, 4> actual_buffer {}; null_bitmap_traits traits (sample.offset, 17); // 17 fields traits.set_null(actual_buffer.data(), sample.pos); BOOST_TEST(expected_buffer == actual_buffer); } BOOST_AUTO_TEST_CASE(set_null_one_field_stmt_execute) { std::uint8_t value = 0; null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 1); traits.set_null(&value, 0); BOOST_TEST(value == 1); } BOOST_AUTO_TEST_CASE(set_null_one_field_binary_row) { std::uint8_t value = 0; null_bitmap_traits traits (binary_row_null_bitmap_offset, 1); traits.set_null(&value, 0); BOOST_TEST(value == 4); } BOOST_AUTO_TEST_CASE(set_null_multified_stmt_execute) { std::array<std::uint8_t, 4> expected_buffer { 0xb4, 0xff, 0x00, 0x00 }; std::array<std::uint8_t, 4> actual_buffer {}; null_bitmap_traits traits (stmt_execute_null_bitmap_offset, 17); // 17 fields for (std::size_t pos: {2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15}) { traits.set_null(actual_buffer.data(), pos); } BOOST_TEST(expected_buffer == actual_buffer); } BOOST_AUTO_TEST_CASE(set_null_multified_binary_row) { std::array<std::uint8_t, 4> expected_buffer { 0xb4, 0xff, 0x00, 0x00 }; std::array<std::uint8_t, 4> actual_buffer {}; null_bitmap_traits traits (binary_row_null_bitmap_offset, 17); // 17 fields for (std::size_t pos: {0, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13}) { traits.set_null(actual_buffer.data(), pos); } BOOST_TEST(expected_buffer == actual_buffer); } BOOST_AUTO_TEST_SUITE_END() // test_null_bitmap_traits
37.166078
99
0.699848
sehe
9116af031e910e83f64371dd953b7fac8df4f4f5
56,510
cpp
C++
src/IECoreRI/RendererImplementation.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
5
2016-07-26T06:09:28.000Z
2022-03-07T03:58:51.000Z
src/IECoreRI/RendererImplementation.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
null
null
null
src/IECoreRI/RendererImplementation.cpp
gcodebackups/cortex-vfx
72fa6c6eb3327fce4faf01361c8fcc2e1e892672
[ "BSD-3-Clause" ]
3
2015-03-25T18:45:24.000Z
2020-02-15T15:37:18.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreRI/private/RendererImplementation.h" #include "IECoreRI/PrimitiveVariableList.h" #include "IECoreRI/ParameterList.h" #include "IECoreRI/Convert.h" #include "IECoreRI/ScopedContext.h" #include "IECore/MessageHandler.h" #include "IECore/Shader.h" #include "IECore/SimpleTypedData.h" #include "IECore/MatrixAlgo.h" #include "IECore/Transform.h" #include "IECore/MatrixTransform.h" #include "IECore/Group.h" #include "IECore/MurmurHash.h" #include "boost/algorithm/string/case_conv.hpp" #include "boost/format.hpp" #include <iostream> #include "ri.h" #include "rx.h" using namespace IECore; using namespace IECoreRI; using namespace Imath; using namespace std; using namespace boost; //////////////////////////////////////////////////////////////////////// // AttributeState implementation //////////////////////////////////////////////////////////////////////// IECoreRI::RendererImplementation::AttributeState::AttributeState() { } IECoreRI::RendererImplementation::AttributeState::AttributeState( const AttributeState &other ) { primVarTypeHints = other.primVarTypeHints; } //////////////////////////////////////////////////////////////////////// // IECoreRI::RendererImplementation implementation //////////////////////////////////////////////////////////////////////// const unsigned int IECoreRI::RendererImplementation::g_shaderCacheSize = 10 * 1024 * 1024; tbb::queuing_rw_mutex IECoreRI::RendererImplementation::g_nLoopsMutex; std::vector<int> IECoreRI::RendererImplementation::g_nLoops; IECoreRI::RendererImplementation::RendererImplementation( RendererImplementationPtr parent ) : m_context( 0 ), m_sharedData( parent ? parent->m_sharedData : SharedData::Ptr( new SharedData ) ), m_options( parent ? parent->m_options : 0 ) { constructCommon(); } IECoreRI::RendererImplementation::RendererImplementation( SharedData::Ptr sharedData, IECore::CompoundDataPtr options ) : m_context( 0 ), m_sharedData( sharedData ), m_options( options ) { constructCommon(); } IECoreRI::RendererImplementation::RendererImplementation( const std::string &name ) : m_sharedData( new SharedData ) { m_options = new CompoundData(); constructCommon(); if( name!="" ) { RiBegin( (char *)name.c_str() ); } else { #ifdef PRMANEXPORT RiBegin( "launch:prman? -t" ); #else RiBegin( 0 ); #endif } m_context = RiGetContext(); } void IECoreRI::RendererImplementation::constructCommon() { m_camera = new Camera; m_camera->addStandardParameters(); m_camera->setTransform( new MatrixTransform() ); m_attributeStack.push( AttributeState() ); const char *fontPath = getenv( "IECORE_FONT_PATHS" ); if( fontPath ) { m_fontSearchPath.setPaths( fontPath, ":" ); } m_shaderCache = defaultShaderCache(); m_setOptionHandlers["ri:searchpath:shader"] = &IECoreRI::RendererImplementation::setShaderSearchPathOption; m_setOptionHandlers["ri:pixelsamples"] = &IECoreRI::RendererImplementation::setPixelSamplesOption; m_setOptionHandlers["ri:pixelSamples"] = &IECoreRI::RendererImplementation::setPixelSamplesOption; m_setOptionHandlers["searchPath:font"] = &IECoreRI::RendererImplementation::setFontSearchPathOption; m_getOptionHandlers["shutter"] = &IECoreRI::RendererImplementation::getShutterOption; m_getOptionHandlers["camera:shutter"] = &IECoreRI::RendererImplementation::getShutterOption; m_getOptionHandlers["camera:resolution"] = &IECoreRI::RendererImplementation::getResolutionOption; m_getOptionHandlers["searchPath:font"] = &IECoreRI::RendererImplementation::getFontSearchPathOption; m_setAttributeHandlers["ri:shadingRate"] = &IECoreRI::RendererImplementation::setShadingRateAttribute; m_setAttributeHandlers["ri:matte"] = &IECoreRI::RendererImplementation::setMatteAttribute; m_setAttributeHandlers["ri:color"] = &IECoreRI::RendererImplementation::setColorAttribute; m_setAttributeHandlers["color"] = &IECoreRI::RendererImplementation::setColorAttribute; m_setAttributeHandlers["ri:opacity"] = &IECoreRI::RendererImplementation::setOpacityAttribute; m_setAttributeHandlers["opacity"] = &IECoreRI::RendererImplementation::setOpacityAttribute; m_setAttributeHandlers["ri:sides"] = &IECoreRI::RendererImplementation::setSidesAttribute; m_setAttributeHandlers["doubleSided"] = &IECoreRI::RendererImplementation::setDoubleSidedAttribute; m_setAttributeHandlers["rightHandedOrientation"] = &IECoreRI::RendererImplementation::setRightHandedOrientationAttribute; m_setAttributeHandlers["ri:geometricApproximation:motionFactor"] = &IECoreRI::RendererImplementation::setGeometricApproximationAttribute; m_setAttributeHandlers["ri:geometricApproximation:focusFactor"] = &IECoreRI::RendererImplementation::setGeometricApproximationAttribute; m_setAttributeHandlers["name"] = &IECoreRI::RendererImplementation::setNameAttribute; m_setAttributeHandlers["ri:subsurface"] = &IECoreRI::RendererImplementation::setSubsurfaceAttribute; m_setAttributeHandlers["ri:detail"] = &IECoreRI::RendererImplementation::setDetailAttribute; m_setAttributeHandlers["ri:detailRange"] = &IECoreRI::RendererImplementation::setDetailRangeAttribute; m_getAttributeHandlers["ri:shadingRate"] = &IECoreRI::RendererImplementation::getShadingRateAttribute; m_getAttributeHandlers["ri:matte"] = &IECoreRI::RendererImplementation::getMatteAttribute; m_getAttributeHandlers["doubleSided"] = &IECoreRI::RendererImplementation::getDoubleSidedAttribute; m_getAttributeHandlers["rightHandedOrientation"] = &IECoreRI::RendererImplementation::getRightHandedOrientationAttribute; m_getAttributeHandlers["name"] = &IECoreRI::RendererImplementation::getNameAttribute; m_commandHandlers["ri:readArchive"] = &IECoreRI::RendererImplementation::readArchiveCommand; m_commandHandlers["ri:archiveRecord"] = &IECoreRI::RendererImplementation::archiveRecordCommand; m_commandHandlers["ri:illuminate"] = &IECoreRI::RendererImplementation::illuminateCommand; m_inMotion = false; } IECoreRI::RendererImplementation::~RendererImplementation() { if( m_context ) { RtContextHandle c = RiGetContext(); RiContext( m_context ); RiEnd(); if( c!=m_context ) { RiContext( c ); } } } //////////////////////////////////////////////////////////////////////// // options //////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::setOption( const std::string &name, IECore::ConstDataPtr value ) { if( !m_options ) { IECore::msg( Msg::Error, "IECoreRI::RendererImplementation::setOption", "Cannot call setOption on non-root renderer." ); return; } // we need to group related options together into a single RiOption or RiHider call, so we // just accumulate the options until worldBegin() where we'll emit them. m_options->writable()[name] = value->copy(); } IECore::ConstDataPtr IECoreRI::RendererImplementation::getOption( const std::string &name ) const { if( m_options ) { // we were created to perform a render from the beginning, and have been keeping // track of the options ourselves. const IECore::Data *result = m_options->member<IECore::Data>( name ); if( result ) { return result; } else { // we don't have the option set explicitly, so fall through and // try to use getRxOption to query the value from renderman directly. } } ScopedContext scopedContext( m_context ); GetOptionHandlerMap::const_iterator it = m_getOptionHandlers.find( name ); if( it!=m_getOptionHandlers.end() ) { return (this->*(it->second))( name ); } else if( name.compare( 0, 5, "user:" )==0 ) { #ifdef PRMANEXPORT return getRxOption( name.c_str() + 5 ); #else return getRxOption( name.c_str() ); #endif } else if( name.compare( 0, 3, "ri:" )==0 ) { return getRxOption( name.c_str() + 3 ); } else if( name.find_first_of( ":" )!=string::npos ) { // silently ignore options prefixed for some other RendererImplementation return 0; } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::getOption", format( "Unknown option \"%s\"." ) % name ); } return 0; } void IECoreRI::RendererImplementation::setShaderSearchPathOption( const std::string &name, IECore::ConstDataPtr d ) { if( ConstStringDataPtr s = runTimeCast<const StringData>( d ) ) { m_shaderCache = new CachedReader( SearchPath( s->readable(), ":" ), g_shaderCacheSize ); // no need to call RiOption as that'll be done in worldBegin(). } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::setOption", "Expected StringData for \"ri:searchpath:shader\"." ); } } void IECoreRI::RendererImplementation::setPixelSamplesOption( const std::string &name, IECore::ConstDataPtr d ) { if( ConstV2iDataPtr s = runTimeCast<const V2iData>( d ) ) { RiPixelSamples( s->readable().x, s->readable().y ); } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::setOption", "Expected V2iData for \"ri:pixelSamples\"." ); } } void IECoreRI::RendererImplementation::setFontSearchPathOption( const std::string &name, IECore::ConstDataPtr d ) { if( ConstStringDataPtr s = runTimeCast<const StringData>( d ) ) { m_fontSearchPath.setPaths( s->readable(), ":" ); } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::setOption", "Expected StringData for \"searchPath:font\"." ); } } IECore::ConstDataPtr IECoreRI::RendererImplementation::getFontSearchPathOption( const std::string &name ) const { return new StringData( m_fontSearchPath.getPaths( ":" ) ); } IECore::ConstDataPtr IECoreRI::RendererImplementation::getShutterOption( const std::string &name ) const { float shutter[2]; RxInfoType_t resultType; int resultCount; int s = RxOption( "Shutter", shutter, 2 * sizeof( float ), &resultType, &resultCount ); if( s==0 ) { if( resultType==RxInfoFloat && resultCount==2 ) { return new V2fData( V2f( shutter[0], shutter[1] ) ); } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getResolutionOption( const std::string &name ) const { float format[3]; RxInfoType_t resultType; int resultCount; int s = RxOption( "Format", format, 3 * sizeof( float ), &resultType, &resultCount ); if( s==0 ) { if( resultType==RxInfoFloat && resultCount==3 ) { return new V2iData( V2i( (int)format[0], (int)format[1] ) ); } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getRxOption( const char *name ) const { char result[16 * sizeof( RtFloat )]; // enough room for a matrix return type memset( result, 0, 16 * sizeof( RtFloat ) ); // 3delight has a bug where it'll try to free some random part of memory if this is not null (v 7.0.54) RxInfoType_t resultType; int resultCount; if( 0==RxOption( (char *)name, result, 16 * sizeof( RtFloat ), &resultType, &resultCount ) ) { return convert( result, resultType, resultCount ); } return 0; } void IECoreRI::RendererImplementation::camera( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); CompoundDataPtr parameterData = (new CompoundData( parameters ))->copy(); CameraPtr camera = new Camera( name, 0, parameterData ); camera->addStandardParameters(); // it simplifies outputCamera() to know that the camera is complete bool outputNow = false; CompoundDataMap::const_iterator outputNowIt=parameters.find( "ri:outputNow" ); if( outputNowIt!=parameters.end() ) { if( ConstBoolDataPtr b = runTimeCast<BoolData>( outputNowIt->second ) ) { outputNow = b->readable(); } else { msg( Msg::Error, "IECoreRI::RendererImplementation::camera", "\"ri:outputNow\" parameter should be of type BoolData." ); } } if( outputNow ) { outputCamera( camera ); m_camera = 0; } else { // add transform and store for output at worldBegin(). CompoundDataMap::const_iterator transformIt=parameters.find( "transform" ); if( transformIt!=parameters.end() ) { if( M44fDataPtr m = runTimeCast<M44fData>( transformIt->second ) ) { camera->setTransform( new MatrixTransform( m->readable() ) ); } else { msg( Msg::Error, "IECoreRI::RendererImplementation::camera", "\"transform\" parameter should be of type M44fData." ); } } else { camera->setTransform( new MatrixTransform( getTransform() ) ); } m_camera = camera; } } void IECoreRI::RendererImplementation::outputCamera( IECore::CameraPtr camera ) { // then shutter CompoundDataMap::const_iterator it = camera->parameters().find( "shutter" ); ConstV2fDataPtr shutterD = runTimeCast<const V2fData>( it->second ); RiShutter( shutterD->readable()[0], shutterD->readable()[1] ); // then hider it = camera->parameters().find( "ri:hider" ); if( it!=camera->parameters().end() ) { ConstStringDataPtr d = runTimeCast<const StringData>( it->second ); if( d ) { ParameterList p( camera->parameters(), "ri:hider:" ); RiHiderV( (char *)d->readable().c_str(), p.n(), p.tokens(), p.values() ); } else { msg( Msg::Error, "IECoreRI::RendererImplementation::worldBegin", "Camera \"ri:hider\" parameter should be of type StringData." ); } } // then resolution it = camera->parameters().find( "resolution" ); ConstV2iDataPtr d = runTimeCast<const V2iData>( it->second ); RiFormat( d->readable().x, d->readable().y, 1 ); // then screen window it = camera->parameters().find( "screenWindow" ); ConstBox2fDataPtr screenWindowD = runTimeCast<const Box2fData>( it->second ); RiScreenWindow( screenWindowD->readable().min.x, screenWindowD->readable().max.x, screenWindowD->readable().min.y, screenWindowD->readable().max.y ); // then crop window it = camera->parameters().find( "cropWindow" ); ConstBox2fDataPtr cropWindowD = runTimeCast<const Box2fData>( it->second ); RiCropWindow( cropWindowD->readable().min.x, cropWindowD->readable().max.x, cropWindowD->readable().min.y, cropWindowD->readable().max.y ); // then clipping it = camera->parameters().find( "clippingPlanes" ); ConstV2fDataPtr clippingD = runTimeCast<const V2fData>( it->second ); RiClipping( clippingD->readable()[0], clippingD->readable()[1] ); // then projection it = camera->parameters().find( "projection" ); ConstStringDataPtr projectionD = runTimeCast<const StringData>( it->second ); ParameterList p( camera->parameters(), "projection:" ); RiProjectionV( (char *)projectionD->readable().c_str(), p.n(), p.tokens(), p.values() ); // transform last if( camera->getTransform() ) { M44f m = camera->getTransform()->transform(); m.scale( V3f( 1.0f, 1.0f, -1.0f ) ); m.invert(); setTransform( m ); } } /// \todo This should be outputting several calls to display as a series of secondary displays, and also trying to find the best display /// to be used as the primary display. void IECoreRI::RendererImplementation::display( const std::string &name, const std::string &type, const std::string &data, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ParameterList pl( parameters ); RiDisplayV( (char *)name.c_str(), (char *)type.c_str(), (char *)data.c_str(), pl.n(), pl.tokens(), pl.values() ); } ///////////////////////////////////////////////////////////////////////////////////////// // world ///////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::worldBegin() { ScopedContext scopedContext( m_context ); // we implement the "editable" option by specifying the raytrace hider with // an "editable" parameter. preprocess our options to reflect that, warning // the user if they were trying to use any hider other than the raytrace one. const BoolData *editableData = m_options->member<BoolData>( "editable" ); if( editableData && editableData->readable() ) { const StringData *hiderData = m_options->member<StringData>( "ri:hider" ); if( hiderData && hiderData->readable() != "raytrace" ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::setOption", "Forcing hider to \"raytrace\" to support editable render." ); } m_options->writable()["ri:hider"] = new StringData( "raytrace" ); m_options->writable()["ri:hider:editable"] = new BoolData( true ); m_options->writable()["ri:hider:progressive"] = new BoolData( true ); } // output all our stored options std::set<std::string> categoriesDone; for( CompoundDataMap::const_iterator it = m_options->readable().begin(), eIt = m_options->readable().end(); it != eIt; it++ ) { const std::string &name = it->first.string(); bool processed = false; if( name.compare( 0, 8, "ri:hider" ) == 0 ) { if( categoriesDone.find( "hider" ) == categoriesDone.end() ) { const StringData *hiderData = m_options->member<StringData>( "ri:hider" ); const string hider = hiderData ? hiderData->readable() : "hidden"; ParameterList pl( m_options->readable(), "ri:hider:" ); RiHiderV( (char *)hider.c_str(), pl.n(), pl.tokens(), pl.values() ); categoriesDone.insert( "hider" ); } processed = true; } else if( name.compare( 0, 3, "ri:" )==0 ) { size_t i = name.find_first_of( ":", 3 ); if( i!=string::npos ) { // ri:*:* string category( name, 3, i-3 ); if( categoriesDone.find( category ) == categoriesDone.end() ) { string prefix( name, 0, i+1 ); ParameterList pl( m_options->readable(), prefix ); RiOptionV( (char *)category.c_str(), pl.n(), pl.tokens(), pl.values() ); categoriesDone.insert( category ); } processed = true; } } else if( name.compare( 0, 5, "user:" )==0 ) { // user:* if( categoriesDone.find( "user" ) == categoriesDone.end() ) { string s( name, 5 ); ParameterList pl( m_options->readable(), "user:" ); RiOptionV( "user", pl.n(), pl.tokens(), pl.values() ); categoriesDone.insert( "user" ); } processed = true; } else if( name == "editable" ) { processed = true; } // we might have custom handlers in addition to the default // handling above. invoke those. SetOptionHandlerMap::iterator hIt = m_setOptionHandlers.find( name ); if( hIt!=m_setOptionHandlers.end() ) { (this->*(hIt->second))( name, it->second ); processed = true; } if( !processed && ( name.find_first_of( ":" )==string::npos || name.compare( 0, 3, "ri:" ) == 0 ) ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::setOption", format( "Unknown option \"%s\"." ) % name ); } } // output any stored camera we might have if( m_camera ) { outputCamera( m_camera ); } // get the world fired up RiWorldBegin(); } void IECoreRI::RendererImplementation::worldEnd() { ScopedContext scopedContext( m_context ); RiWorldEnd(); } ///////////////////////////////////////////////////////////////////////////////////////// // transforms ///////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::transformBegin() { ScopedContext scopedContext( m_context ); RiTransformBegin(); } void IECoreRI::RendererImplementation::transformEnd() { ScopedContext scopedContext( m_context ); RiTransformEnd(); } void IECoreRI::RendererImplementation::setTransform( const Imath::M44f &m ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); RtMatrix mm; convert( m, mm ); RiTransform( mm ); } void IECoreRI::RendererImplementation::setTransform( const std::string &coordinateSystem ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); RiCoordSysTransform( (char *)coordinateSystem.c_str() ); } Imath::M44f IECoreRI::RendererImplementation::getTransform() const { return getTransform( "object" ); } Imath::M44f IECoreRI::RendererImplementation::getTransform( const std::string &coordinateSystem ) const { ScopedContext scopedContext( m_context ); M44f result; RtMatrix matrix; if( RxTransform( (char *)coordinateSystem.c_str(), "world", 0.0f, matrix ) == 0 ) { result = M44f( matrix ); } else { msg( Msg::Error, "IECoreRI::RendererImplementation::getTransform", boost::format( "Unable to transform to coordinate system \"%s\"." ) % coordinateSystem ); } return result; } void IECoreRI::RendererImplementation::concatTransform( const Imath::M44f &m ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); RtMatrix mm; convert( m, mm ); RiConcatTransform( mm ); } void IECoreRI::RendererImplementation::coordinateSystem( const std::string &name ) { ScopedContext scopedContext( m_context ); RiScopedCoordinateSystem( (char *)name.c_str() ); } ////////////////////////////////////////////////////////////////////////////////////////// // attribute code ////////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::attributeBegin() { ScopedContext scopedContext( m_context ); m_attributeStack.push( m_attributeStack.top() ); RiAttributeBegin(); } void IECoreRI::RendererImplementation::attributeEnd() { ScopedContext scopedContext( m_context ); if( m_attributeStack.size() ) { m_attributeStack.pop(); } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::attributeEnd", "No matching attributeBegin call." ); } RiAttributeEnd(); } void IECoreRI::RendererImplementation::setAttribute( const std::string &name, IECore::ConstDataPtr value ) { ScopedContext scopedContext( m_context ); SetAttributeHandlerMap::iterator it = m_setAttributeHandlers.find( name ); if( it!=m_setAttributeHandlers.end() ) { (this->*(it->second))( name, value ); } else if( name.compare( 0, 3, "ri:" )==0 ) { size_t i = name.find_first_of( ":", 3 ); if( i==string::npos ) { const CompoundData *compoundValue = runTimeCast<const CompoundData>( value ); if( !compoundValue ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::setAttribute", format( "Expected CompoundData for name matching \"ri:*\" but got \"%s\"." ) % value->typeName() ); } else { ParameterList pl( compoundValue->readable() ); RiAttributeV( (char *)name.c_str() + 3, pl.n(), pl.tokens(), pl.values() ); } } else { string s1( name, 3, i-3 ); string s2( name, i+1 ); ParameterList pl( s2, value ); RiAttributeV( (char *)s1.c_str(), pl.n(), pl.tokens(), pl.values() ); } } else if( name.compare( 0, 5, "user:" )==0 ) { string s( name, 5 ); ParameterList pl( s, value ); RiAttributeV( "user", pl.n(), pl.tokens(), pl.values() ); } else if( name.find_first_of( ":" )!=string::npos ) { // ignore attributes prefixed for some other RendererImplementation return; } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::setAttribute", format( "Unknown attribute \"%s\"." ) % name ); } } void IECoreRI::RendererImplementation::setShadingRateAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstFloatDataPtr f = runTimeCast<const FloatData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "ri:shadingRate attribute expects a FloatData value." ); return; } RiShadingRate( f->readable() ); } void IECoreRI::RendererImplementation::setMatteAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstBoolDataPtr f = runTimeCast<const BoolData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "ri:matte attribute expects a BoolData value." ); return; } RiMatte( f->readable() ? 1 : 0 ); } void IECoreRI::RendererImplementation::setColorAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstColor3fDataPtr f = runTimeCast<const Color3fData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "ri:color attribute expects a Color3fData value." ); return; } RiColor( (RtFloat *)&(f->readable().x) ); } void IECoreRI::RendererImplementation::setOpacityAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstColor3fDataPtr f = runTimeCast<const Color3fData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "ri:opacity attribute expects a Color3fData value." ); return; } RiOpacity( (RtFloat *)&(f->readable().x) ); } void IECoreRI::RendererImplementation::setSidesAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstIntDataPtr f = runTimeCast<const IntData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "ri:sides attribute expects an IntData value." ); return; } RiSides( f->readable() ); } void IECoreRI::RendererImplementation::setDoubleSidedAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstBoolDataPtr f = runTimeCast<const BoolData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "doubleSided attribute expects a BoolData value." ); return; } RiSides( f->readable() ? 2 : 1 ); } void IECoreRI::RendererImplementation::setRightHandedOrientationAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstBoolDataPtr f = runTimeCast<const BoolData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", "rightHandedOrientation attribute expects a BoolData value." ); return; } if( f->readable() ) { RiOrientation( "rh" ); } else { RiOrientation( "lh" ); } } void IECoreRI::RendererImplementation::setGeometricApproximationAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstFloatDataPtr f = runTimeCast<const FloatData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", format( "%s attribute expects an IntData value." ) % name ); return; } string s = string( name, name.find_last_of( ":" ) + 1 ); to_lower( s ); RiGeometricApproximation( (char *)s.c_str(), f->readable() ); } void IECoreRI::RendererImplementation::setNameAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstStringDataPtr f = runTimeCast<const StringData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", format( "%s attribute expects a StringData value." ) % name ); return; } ParameterList pl( "name", f ); RiAttributeV( "identifier", pl.n(), pl.tokens(), pl.values() ); } void IECoreRI::RendererImplementation::setSubsurfaceAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstCompoundDataPtr c = runTimeCast<const CompoundData>( d ); if( !c ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", format( "%s attribute expects a CompoundData value." ) % name ); return; } CompoundDataMap::const_iterator it = c->readable().find( "visibility" ); if( it==c->readable().end() ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", format( "%s attribute expected to contain a \"visibility\" value." ) % name ); return; } ConstStringDataPtr v = runTimeCast<const StringData>( it->second ); if( !v ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setAttribute", format( "%s attribute \"visibility\" value must be of type StringData." ) % name ); return; } const char *ssv = v->readable().c_str(); RiAttribute( "visibility", "string subsurface", &ssv, 0 ); CompoundDataPtr ssParms = c->copy(); ssParms->writable().erase( "visibility" ); ParameterList pl( ssParms->readable() ); RiAttributeV( "subsurface", pl.n(), pl.tokens(), pl.values() ); } void IECoreRI::RendererImplementation::setDetailAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstBox3fDataPtr b = runTimeCast<const Box3fData>( d ); if( !b ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setDetailAttribute", format( "%s attribute expects a Box3fData value." ) % name ); return; } RtBound bound; convert( b->readable(), bound ); RiDetail( bound ); } void IECoreRI::RendererImplementation::setDetailRangeAttribute( const std::string &name, IECore::ConstDataPtr d ) { ConstFloatVectorDataPtr f = runTimeCast<const FloatVectorData>( d ); if( !f ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setDetailRangeAttribute", format( "%s attribute expects a FloatVectorData value." ) % name ); return; } const vector<float> &values = f->readable(); if( values.size()!=4 ) { msg( Msg::Error, "IECoreRI::RendererImplementation::setDetailRangeAttribute", format( "Value must contain 4 elements (found %d)." ) % values.size() ); return; } RiDetailRange( values[0], values[1], values[2], values[3] ); } IECore::ConstDataPtr IECoreRI::RendererImplementation::getAttribute( const std::string &name ) const { ScopedContext scopedContext( m_context ); GetAttributeHandlerMap::const_iterator it = m_getAttributeHandlers.find( name ); if( it!=m_getAttributeHandlers.end() ) { return (this->*(it->second))( name ); } else if( name.compare( 0, 3, "ri:" )==0 ) { size_t i = name.find_first_of( ":", 3 ); if( i==string::npos ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::getAttribute", format( "Expected attribute name matching \"ri:*:*\" but got \"%s\"." ) % name ); return 0; } char result[16 * sizeof( RtFloat )]; // enough room for a matrix return type memset( result, 0, 16 * sizeof( RtFloat ) ); // 3delight has a bug where it'll try to free some random part of memory if this is not null (v 7.0.54) RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( (char *)name.c_str()+3, result, 16 * sizeof( RtFloat ), &resultType, &resultCount ) ) { return convert( result, resultType, resultCount ); } } else if( name.compare( 0, 5, "user:" )==0 ) { char result[16 * sizeof( RtFloat )]; // enough room for a matrix return type RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( (char *)name.c_str(), result, 16 * sizeof( RtFloat ), &resultType, &resultCount ) ) { return convert( result, resultType, resultCount ); } } else if( name.find_first_of( ":" )!=string::npos ) { // silently ignore attributes prefixed for some other RendererImplementation return 0; } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::getAttribute", format( "Unknown attribute \"%s\"." ) % name ); } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getShadingRateAttribute( const std::string &name ) const { float result = 0; RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( "ShadingRate", (char *)&result, sizeof( float ), &resultType, &resultCount ) ) { if( resultType==RxInfoFloat && resultCount==1 ) { return new FloatData( result ); } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getMatteAttribute( const std::string &name ) const { float result = 0; RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( "Matte", (char *)&result, sizeof( float ), &resultType, &resultCount ) ) { if( resultType==RxInfoFloat && resultCount==1 ) { return new BoolData( result > 0.0f ); } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getDoubleSidedAttribute( const std::string &name ) const { float result = 2; RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( "Sides", (char *)&result, sizeof( float ), &resultType, &resultCount ) ) { if( resultType==RxInfoFloat && resultCount==1 ) { if( result==1 ) { return new BoolData( false ); } else { return new BoolData( true ); } } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getRightHandedOrientationAttribute( const std::string &name ) const { char *result = 0; RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( "Ri:Orientation", &result, sizeof( char * ), &resultType, &resultCount ) ) { if( resultType==RxInfoStringV && resultCount==1 ) { // it'd be nice if we were just told "rh" or "lh" if( 0==strcmp( result, "rh" ) ) { return new BoolData( true ); } else if( 0==strcmp( result, "lh" ) ) { return new BoolData( false ); } // but in practice we seem to be told "outside" or "inside" else { bool determinantNegative = determinant( getTransform() ) < 0.0f; if( 0==strcmp( result, "outside" ) ) { return new BoolData( !determinantNegative ); } else if( 0==strcmp( result, "inside" ) ) { return new BoolData( determinantNegative ); } } } } return 0; } IECore::ConstDataPtr IECoreRI::RendererImplementation::getNameAttribute( const std::string &name ) const { char *result = 0; RxInfoType_t resultType; int resultCount; if( 0==RxAttribute( "identifier:name", (char *)&result, sizeof( char * ), &resultType, &resultCount ) ) { if( resultType==RxInfoStringV && resultCount==1 ) { return new StringData( result ); } } return 0; } IECore::CachedReaderPtr IECoreRI::RendererImplementation::defaultShaderCache() { static IECore::CachedReaderPtr g_defaultShaderCache = new CachedReader( SearchPath( getenv( "DL_SHADERS_PATH" ) ? getenv( "DL_SHADERS_PATH" ) : "", ":" ), g_shaderCacheSize ); return g_defaultShaderCache; } void IECoreRI::RendererImplementation::shader( const std::string &type, const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ConstShaderPtr s = 0; try { s = runTimeCast<const Shader>( m_shaderCache->read( name + ".sdl" ) ); if( !s ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::shader", format( "Couldn't load shader \"%s\"." ) % name ); return; } } catch( const std::exception &e ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::shader", format( "Couldn't load shader \"%s\" - %s" ) % name % e.what() ); return; // we don't want exceptions to halt rendering - we'd rather just report the error below } catch( ... ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::shader", format( "Couldn't load shader \"%s\" - an unknown exception was thrown" ) % name ); return; } // if we are here then we loaded a shader ok. now process the parameters for it and make the ri call. AttributeState &state = m_attributeStack.top(); state.primVarTypeHints.clear(); CompoundDataMap::const_iterator it = s->blindData()->readable().find( "ri:parameterTypeHints" ); if( it!=s->blindData()->readable().end() ) { if( ConstCompoundDataPtr h = runTimeCast<const CompoundData>( it->second ) ) { for( it=h->readable().begin(); it!=h->readable().end(); it++ ) { if( it->second->typeId()==StringData::staticTypeId() ) { state.primVarTypeHints.insert( std::pair<string, string>( it->first, staticPointerCast<const StringData>( it->second )->readable() ) ); } } } } if( type=="surface" || type=="ri:surface" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiSurfaceV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="displacement" || type=="ri:displacement" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiDisplacementV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="atmosphere" || type=="ri:atmosphere" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiAtmosphereV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="interior" || type=="ri:interior" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiInteriorV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="exterior" || type=="ri:exterior" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiExteriorV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="deformation" || type=="ri:deformation" ) { ParameterList pl( parameters, &state.primVarTypeHints ); RiDeformationV( (char *)name.c_str(), pl.n(), pl.tokens(), pl.values() ); } else if( type=="shader" || type=="ri:shader" ) { const StringData *handleData = 0; CompoundDataMap::const_iterator it = parameters.find( "__handle" ); if( it!=parameters.end() ) { handleData = runTimeCast<const StringData>( it->second ); } if( !handleData ) { msg( Msg::Error, "IECoreRI::RendererImplementation::shader", "Must specify StringData \"__handle\" parameter for coshaders." ); return; } CompoundDataMap parametersCopy = parameters; parametersCopy.erase( "__handle" ); ParameterList pl( parametersCopy, &state.primVarTypeHints ); RiShaderV( (char *)name.c_str(), (char *)handleData->readable().c_str(), pl.n(), pl.tokens(), pl.values() ); } } void IECoreRI::RendererImplementation::light( const std::string &name, const std::string &handle, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); IECore::CompoundDataMap parametersCopy = parameters; parametersCopy["__handleid"] = new StringData( handle ); ParameterList pl( parametersCopy ); RiLightSourceV( const_cast<char *>(name.c_str()), pl.n(), pl.tokens(), pl.values() ); } void IECoreRI::RendererImplementation::illuminate( const std::string &lightHandle, bool on ) { ScopedContext scopedContext( m_context ); RiIlluminate( (RtLightHandle)lightHandle.c_str(), on ); } ///////////////////////////////////////////////////////////////////////////////////////// // motion blur ///////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::motionBegin( const std::set<float> &times ) { m_delayedMotionTimes.resize( times.size() ); unsigned int i = 0; for( set<float>::const_iterator it = times.begin(); it!=times.end(); it++ ) { m_delayedMotionTimes[i++] = *it; } } void IECoreRI::RendererImplementation::delayedMotionBegin() { if( m_delayedMotionTimes.size() ) { RiMotionBeginV( m_delayedMotionTimes.size(), &*(m_delayedMotionTimes.begin() ) ); m_delayedMotionTimes.clear(); m_inMotion = true; } } void IECoreRI::RendererImplementation::motionEnd() { ScopedContext scopedContext( m_context ); RiMotionEnd(); m_inMotion = false; } ///////////////////////////////////////////////////////////////////////////////////////// // primitives ///////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::points( size_t numPoints, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); RiPointsV( numPoints, pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::disk( float radius, float z, float thetaMax, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); RiDiskV( z, radius, thetaMax, pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::curves( const IECore::CubicBasisf &basis, bool periodic, ConstIntVectorDataPtr numVertices, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); // emit basis if we're not in a motion block right now if( !m_inMotion ) { RtMatrix b; convert( basis.matrix, b ); RiBasis( b, basis.step, b, basis.step ); } // then emit any overdue motionbegin calls. delayedMotionBegin(); // finally emit the curves PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); vector<int> &numVerticesV = const_cast<vector<int> &>( numVertices->readable() ); RiCurvesV( (char *)( basis==CubicBasisf::linear() ? "linear" : "cubic" ), numVerticesV.size(), &*( numVerticesV.begin() ), (char *)( periodic ? "periodic" : "nonperiodic" ), pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::text( const std::string &font, const std::string &text, float kerning, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); #ifdef IECORE_WITH_FREETYPE IECore::FontPtr f = 0; FontMap::const_iterator it = m_fonts.find( font ); if( it!=m_fonts.end() ) { f = it->second; } else { string file = m_fontSearchPath.find( font ).string(); if( file!="" ) { try { f = new IECore::Font( file ); } catch( const std::exception &e ) { IECore::msg( IECore::Msg::Warning, "Renderer::text", e.what() ); } } m_fonts[font] = f; } if( !f ) { IECore::msg( IECore::Msg::Warning, "Renderer::text", boost::format( "Font \"%s\" not found." ) % font ); return; } f->setKerning( kerning ); f->meshGroup( text )->render( this ); #else IECore::msg( IECore::Msg::Warning, "Renderer::text", "IECore was not built with FreeType support." ); #endif // IECORE_WITH_FREETYPE } void IECoreRI::RendererImplementation::sphere( float radius, float zMin, float zMax, float thetaMax, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); RiSphereV( radius, zMin * radius, zMax * radius, thetaMax, pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::image( const Imath::Box2i &dataWindow, const Imath::Box2i &displayWindow, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); msg( Msg::Warning, "IECoreRI::RendererImplementation::image", "Not implemented" ); } void IECoreRI::RendererImplementation::mesh( IECore::ConstIntVectorDataPtr vertsPerFace, IECore::ConstIntVectorDataPtr vertIds, const std::string &interpolation, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); if( interpolation=="catmullClark" ) { int numNames = 1; const char *names[] = { "interpolateboundary", 0, 0, 0, 0, 0 }; int defaultNArgs[] = { 0, 0 }; const int *nArgs = defaultNArgs; const float *floats = 0; const int *integers = 0; IECore::PrimitiveVariableMap::const_iterator tagIt = primVars.find( "tags" ); if( tagIt != primVars.end() ) { const CompoundData *tagsData = runTimeCast<const CompoundData>( tagIt->second.data.get() ); if( tagsData ) { const StringVectorData *namesData = tagsData->member<const StringVectorData>( "names" ); const IntVectorData *nArgsData = tagsData->member<const IntVectorData>( "nArgs" ); const FloatVectorData *floatsData = tagsData->member<const FloatVectorData>( "floats" ); const IntVectorData *integersData = tagsData->member<const IntVectorData>( "integers" ); if( namesData && nArgsData && floatsData && integersData ) { // we only have room for 6 names in the array above as we're trying to avoid having to dynamically allocate // any memory here - should be ok as there are only 5 tag types currently specified by 3delight. numNames = std::min( (int)namesData->readable().size(), 6 ); for( int i=0; i<numNames; i++ ) { names[i] = namesData->readable()[i].c_str(); } nArgs = &(nArgsData->readable()[0]); floats = &(floatsData->readable()[0]); integers = &(integersData->readable()[0]); } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::mesh", "Primitive variable \"tags\" does not contain the required members - ignoring." ); } } else { msg( Msg::Warning, "IECoreRI::RendererImplementation::mesh", "Primitive variable \"tags\" is not of type CompoundData - ignoring." ); } } RiSubdivisionMeshV( "catmull-clark", vertsPerFace->readable().size(), (int *)&vertsPerFace->readable()[0], (int *)&vertIds->readable()[0], numNames, (char **)names, (int *)nArgs, (int *)integers, (float *)floats, pv.n(), pv.tokens(), pv.values() ); return; } if( interpolation!="linear" ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::mesh", boost::format( "Unsupported interpolation type \"%s\" - rendering as polygons." ) % interpolation ); } tbb::queuing_rw_mutex::scoped_lock lock( g_nLoopsMutex, false /* read only */ ); if( g_nLoops.size()<vertsPerFace->readable().size() ) { lock.upgrade_to_writer(); if( g_nLoops.size()<vertsPerFace->readable().size() ) // checking again as i think g_nLoops may have been resized by another thread getting the write lock first { g_nLoops.resize( vertsPerFace->readable().size(), 1 ); } lock.downgrade_to_reader(); } vector<int> &vertsPerFaceV = const_cast<vector<int> &>( vertsPerFace->readable() ); vector<int> &vertIdsV = const_cast<vector<int> &>( vertIds->readable() ); RiPointsGeneralPolygonsV( vertsPerFaceV.size(), &*(g_nLoops.begin()), &*(vertsPerFaceV.begin()), &*(vertIdsV.begin()), pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::nurbs( int uOrder, IECore::ConstFloatVectorDataPtr uKnot, float uMin, float uMax, int vOrder, IECore::ConstFloatVectorDataPtr vKnot, float vMin, float vMax, const IECore::PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); RiNuPatchV( uKnot->readable().size() - uOrder, // nu uOrder, const_cast<float *>( &(uKnot->readable()[0]) ), uMin, uMax, vKnot->readable().size() - vOrder, // nv vOrder, const_cast<float *>( &(vKnot->readable()[0]) ), vMin, vMax, pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::patchMesh( const CubicBasisf &uBasis, const CubicBasisf &vBasis, int nu, bool uPeriodic, int nv, bool vPeriodic, const PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); bool uLinear = uBasis == CubicBasisf::linear(); bool vLinear = vBasis == CubicBasisf::linear(); if ( uLinear != vLinear ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::mesh", "Mismatched u/v basis."); return; } if( !m_inMotion ) { RtMatrix ub, vb; convert( uBasis.matrix, ub ); convert( vBasis.matrix, vb ); RiBasis( ub, uBasis.step, vb, vBasis.step ); } delayedMotionBegin(); PrimitiveVariableList pv( primVars, &( m_attributeStack.top().primVarTypeHints ) ); const char *type = uLinear ? "bilinear" : "bicubic"; RiPatchMeshV( const_cast< char * >( type ), nu, (char *)( uPeriodic ? "periodic" : "nonperiodic" ), nv, (char *)( vPeriodic ? "periodic" : "nonperiodic" ), pv.n(), pv.tokens(), pv.values() ); } void IECoreRI::RendererImplementation::geometry( const std::string &type, const CompoundDataMap &topology, const PrimitiveVariableMap &primVars ) { ScopedContext scopedContext( m_context ); if( type=="teapot" || type=="ri:teapot" ) { delayedMotionBegin(); RiGeometry( "teapot", 0 ); } else { delayedMotionBegin(); msg( Msg::Warning, "IECoreRI::RendererImplementation::geometry", format( "Unsupported geometry type \"%s\"." ) % type ); } } void IECoreRI::RendererImplementation::procedural( IECore::Renderer::ProceduralPtr proc ) { ScopedContext scopedContext( m_context ); Imath::Box3f bound = proc->bound(); if( bound.isEmpty() ) { return; } RtBound riBound; riBound[0] = bound.min.x; riBound[1] = bound.max.x; riBound[2] = bound.min.y; riBound[3] = bound.max.y; riBound[4] = bound.min.z; riBound[5] = bound.max.z; ProceduralData *data = new ProceduralData; data->procedural = proc; data->sharedData = m_sharedData; data->options = m_options; #ifdef IECORERI_WITH_PROCEDURALV IECore::MurmurHash h = proc->hash(); if( h == IECore::MurmurHash() ) { // empty hash => no procedural level instancing RiProcedural( data, riBound, procSubdivide, procFree ); } else { std::string hashStr = h.toString(); // specify an instance key for procedural level instancing const char *tokens[] = { "instancekey" }; const char *keyPtr = hashStr.c_str(); void *values[] = { &keyPtr }; RiProceduralV( data, riBound, procSubdivide, procFree, 1, tokens, values ); } #else RiProcedural( data, riBound, procSubdivide, procFree ); #endif } void IECoreRI::RendererImplementation::procSubdivide( void *data, float detail ) { ProceduralData *proceduralData = reinterpret_cast<ProceduralData *>( data ); // we used to try to use the same IECoreRI::Renderer that had the original procedural() call issued to it. // this turns out to be incorrect as each procedural subdivide invocation is in a new RtContextHandle // and the original renderer would be trying to switch to its original context. so we just create a temporary // renderer which doesn't own a context and therefore use the context 3delight has arranged to call subdivide with. // we do however share SharedData with the parent renderer, so that we can share instances among procedurals. IECoreRI::RendererPtr renderer = new IECoreRI::Renderer( new RendererImplementation( proceduralData->sharedData, proceduralData->options ) ); proceduralData->procedural->render( renderer ); } void IECoreRI::RendererImplementation::procFree( void *data ) { ProceduralData *proceduralData = reinterpret_cast<ProceduralData *>( data ); delete proceduralData; } ///////////////////////////////////////////////////////////////////////////////////////// // instancing ///////////////////////////////////////////////////////////////////////////////////////// void IECoreRI::RendererImplementation::instanceBegin( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); #ifdef IECORERI_WITH_OBJECTBEGINV // we get to choose the name for the object const char *tokens[] = { "__handleid", "scope" }; const char *namePtr = name.c_str(); const char *scope = "world"; const void *values[] = { &namePtr, &scope }; SharedData::ObjectHandlesMutex::scoped_lock objectHandlesLock( m_sharedData->objectHandlesMutex ); m_sharedData->objectHandles[name] = RiObjectBeginV( 2, (char **)&tokens, (void **)&values ); #else // we have to put up with a rubbish name SharedData::ObjectHandlesMutex::scoped_lock objectHandlesLock( m_sharedData->objectHandlesMutex ); m_sharedData->objectHandles[name] = RiObjectBegin(); #endif } void IECoreRI::RendererImplementation::instanceEnd() { ScopedContext scopedContext( m_context ); RiObjectEnd(); } void IECoreRI::RendererImplementation::instance( const std::string &name ) { ScopedContext scopedContext( m_context ); SharedData::ObjectHandlesMutex::scoped_lock objectHandlesLock( m_sharedData->objectHandlesMutex, false /* read only lock */ ); SharedData::ObjectHandleMap::const_iterator hIt = m_sharedData->objectHandles.find( name ); if( hIt==m_sharedData->objectHandles.end() ) { msg( Msg::Error, "IECoreRI::RendererImplementation::instance", boost::format( "No object named \"%s\" available for instancing." ) % name ); return; } RiObjectInstance( const_cast<void *>( hIt->second ) ); } ///////////////////////////////////////////////////////////////////////////////////////// // commands ///////////////////////////////////////////////////////////////////////////////////////// IECore::DataPtr IECoreRI::RendererImplementation::command( const std::string &name, const CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); CommandHandlerMap::iterator it = m_commandHandlers.find( name ); if( it==m_commandHandlers.end() ) { msg( Msg::Warning, "IECoreRI::RendererImplementation::command", boost::format( "Unknown command \"%s\"" ) % name ); return 0; } return (this->*(it->second))( name, parameters ); } IECore::DataPtr IECoreRI::RendererImplementation::readArchiveCommand( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ConstStringDataPtr nameData; CompoundDataMap::const_iterator it = parameters.find( "name" ); if( it!=parameters.end() ) { nameData = runTimeCast<StringData>( it->second ); } if( !nameData ) { msg( Msg::Error, "IECoreRI::RendererImplementation::command", "ri:readArchive command expects a StringData value called \"name\"." ); return 0; } RiReadArchiveV( (char *)nameData->readable().c_str(), 0, 0, 0, 0 ); return 0; } IECore::DataPtr IECoreRI::RendererImplementation::archiveRecordCommand( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ConstStringDataPtr typeData; ConstStringDataPtr recordData; CompoundDataMap::const_iterator typeIt = parameters.find( "type" ); CompoundDataMap::const_iterator recordIt = parameters.find( "record" ); if( typeIt!=parameters.end() ) { typeData = runTimeCast<StringData>( typeIt->second ); } if( recordIt!=parameters.end() ) { recordData = runTimeCast<StringData>( recordIt->second ); } if( !(typeData && recordData) ) { msg( Msg::Error, "IECoreRI::RendererImplementation::command", "ri:archiveRecord command expects StringData values called \"type\" and \"record\"." ); return 0; } // if there are printf style format specifiers in the record then we're in trouble - we're about to pass them through a c interface which // isn't type safe, and not provide any additional arguments for them. try to avoid that by using boost format to catch the problem. try { string tested = boost::format( recordData->readable() ).str(); RiArchiveRecord( const_cast<char *>( typeData->readable().c_str() ), const_cast<char *>( tested.c_str() ) ); } catch( ... ) { msg( Msg::Error, "IECoreRI::RendererImplementation::command", "ri:archiveRecord \"record\" parameter appears to contain printf format specifiers." ); } return 0; } IECore::DataPtr IECoreRI::RendererImplementation::illuminateCommand( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ConstStringDataPtr handleData = 0; ConstBoolDataPtr stateData = 0; CompoundDataMap::const_iterator handleIt = parameters.find( "handle" ); CompoundDataMap::const_iterator stateIt = parameters.find( "state" ); if( handleIt!=parameters.end() ) { handleData = runTimeCast<StringData>( handleIt->second ); } if( stateIt!=parameters.end() ) { stateData = runTimeCast<BoolData>( stateIt->second ); } if( !(handleData && stateData) ) { msg( Msg::Error, "IECoreRI::RendererImplementation::command", "ri:illuminate command expects a StringData value called \"handle\" and a BoolData value called \"state\"." ); return 0; } RiIlluminate( (void *)handleData->readable().c_str(), stateData->readable() ); return 0; } void RendererImplementation::editBegin( const std::string &name, const IECore::CompoundDataMap &parameters ) { ScopedContext scopedContext( m_context ); ParameterList p( parameters ); RiEditBeginV( name.c_str(), p.n(), p.tokens(), p.values() ); } void RendererImplementation::editEnd() { ScopedContext scopedContext( m_context ); RiEditEnd(); }
33.757467
242
0.685012
gcodebackups
91176873d0a36a54867dd4ff301e820abc49303d
32,254
hpp
C++
iguana/reflection.hpp
yangxingpping/iguana
bc11d40347e972f5ffcaa7289163f1012d6c8c41
[ "Apache-2.0" ]
621
2017-03-12T08:49:01.000Z
2022-03-31T09:33:06.000Z
iguana/reflection.hpp
IndignantAngel/iguana
84849c3fba55fdf85edf2a600175961f5fcc7973
[ "Apache-2.0" ]
43
2017-03-13T01:40:18.000Z
2022-02-21T16:13:50.000Z
iguana/reflection.hpp
IndignantAngel/iguana
84849c3fba55fdf85edf2a600175961f5fcc7973
[ "Apache-2.0" ]
174
2017-02-09T02:00:30.000Z
2022-03-31T09:33:08.000Z
// // Created by Qiyu on 17-6-5. // #ifndef IGUANA_REFLECTION_HPP #define IGUANA_REFLECTION_HPP #include <iostream> #include <sstream> #include <string> #include <tuple> #include <iomanip> #include <map> #include <vector> #include <array> #include <type_traits> #include <functional> #include <string_view> #include "detail/itoa.hpp" #include "detail/traits.hpp" #include "detail/string_stream.hpp" namespace iguana::detail { /******************************************/ /* arg list expand macro, now support 120 args */ #define MAKE_ARG_LIST_1(op, arg, ...) op(arg) #define MAKE_ARG_LIST_2(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_1(op, __VA_ARGS__)) #define MAKE_ARG_LIST_3(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_2(op, __VA_ARGS__)) #define MAKE_ARG_LIST_4(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_3(op, __VA_ARGS__)) #define MAKE_ARG_LIST_5(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_4(op, __VA_ARGS__)) #define MAKE_ARG_LIST_6(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_5(op, __VA_ARGS__)) #define MAKE_ARG_LIST_7(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_6(op, __VA_ARGS__)) #define MAKE_ARG_LIST_8(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_7(op, __VA_ARGS__)) #define MAKE_ARG_LIST_9(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_8(op, __VA_ARGS__)) #define MAKE_ARG_LIST_10(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_9(op, __VA_ARGS__)) #define MAKE_ARG_LIST_11(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_10(op, __VA_ARGS__)) #define MAKE_ARG_LIST_12(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_11(op, __VA_ARGS__)) #define MAKE_ARG_LIST_13(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_12(op, __VA_ARGS__)) #define MAKE_ARG_LIST_14(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_13(op, __VA_ARGS__)) #define MAKE_ARG_LIST_15(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_14(op, __VA_ARGS__)) #define MAKE_ARG_LIST_16(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_15(op, __VA_ARGS__)) #define MAKE_ARG_LIST_17(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_16(op, __VA_ARGS__)) #define MAKE_ARG_LIST_18(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_17(op, __VA_ARGS__)) #define MAKE_ARG_LIST_19(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_18(op, __VA_ARGS__)) #define MAKE_ARG_LIST_20(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_19(op, __VA_ARGS__)) #define MAKE_ARG_LIST_21(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_20(op, __VA_ARGS__)) #define MAKE_ARG_LIST_22(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_21(op, __VA_ARGS__)) #define MAKE_ARG_LIST_23(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_22(op, __VA_ARGS__)) #define MAKE_ARG_LIST_24(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_23(op, __VA_ARGS__)) #define MAKE_ARG_LIST_25(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_24(op, __VA_ARGS__)) #define MAKE_ARG_LIST_26(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_25(op, __VA_ARGS__)) #define MAKE_ARG_LIST_27(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_26(op, __VA_ARGS__)) #define MAKE_ARG_LIST_28(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_27(op, __VA_ARGS__)) #define MAKE_ARG_LIST_29(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_28(op, __VA_ARGS__)) #define MAKE_ARG_LIST_30(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_29(op, __VA_ARGS__)) #define MAKE_ARG_LIST_31(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_30(op, __VA_ARGS__)) #define MAKE_ARG_LIST_32(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_31(op, __VA_ARGS__)) #define MAKE_ARG_LIST_33(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_32(op, __VA_ARGS__)) #define MAKE_ARG_LIST_34(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_33(op, __VA_ARGS__)) #define MAKE_ARG_LIST_35(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_34(op, __VA_ARGS__)) #define MAKE_ARG_LIST_36(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_35(op, __VA_ARGS__)) #define MAKE_ARG_LIST_37(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_36(op, __VA_ARGS__)) #define MAKE_ARG_LIST_38(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_37(op, __VA_ARGS__)) #define MAKE_ARG_LIST_39(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_38(op, __VA_ARGS__)) #define MAKE_ARG_LIST_40(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_39(op, __VA_ARGS__)) #define MAKE_ARG_LIST_41(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_40(op, __VA_ARGS__)) #define MAKE_ARG_LIST_42(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_41(op, __VA_ARGS__)) #define MAKE_ARG_LIST_43(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_42(op, __VA_ARGS__)) #define MAKE_ARG_LIST_44(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_43(op, __VA_ARGS__)) #define MAKE_ARG_LIST_45(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_44(op, __VA_ARGS__)) #define MAKE_ARG_LIST_46(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_45(op, __VA_ARGS__)) #define MAKE_ARG_LIST_47(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_46(op, __VA_ARGS__)) #define MAKE_ARG_LIST_48(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_47(op, __VA_ARGS__)) #define MAKE_ARG_LIST_49(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_48(op, __VA_ARGS__)) #define MAKE_ARG_LIST_50(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_49(op, __VA_ARGS__)) #define MAKE_ARG_LIST_51(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_50(op, __VA_ARGS__)) #define MAKE_ARG_LIST_52(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_51(op, __VA_ARGS__)) #define MAKE_ARG_LIST_53(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_52(op, __VA_ARGS__)) #define MAKE_ARG_LIST_54(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_53(op, __VA_ARGS__)) #define MAKE_ARG_LIST_55(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_54(op, __VA_ARGS__)) #define MAKE_ARG_LIST_56(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_55(op, __VA_ARGS__)) #define MAKE_ARG_LIST_57(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_56(op, __VA_ARGS__)) #define MAKE_ARG_LIST_58(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_57(op, __VA_ARGS__)) #define MAKE_ARG_LIST_59(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_58(op, __VA_ARGS__)) #define MAKE_ARG_LIST_60(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_59(op, __VA_ARGS__)) #define MAKE_ARG_LIST_61(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_60(op, __VA_ARGS__)) #define MAKE_ARG_LIST_62(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_61(op, __VA_ARGS__)) #define MAKE_ARG_LIST_63(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_62(op, __VA_ARGS__)) #define MAKE_ARG_LIST_64(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_63(op, __VA_ARGS__)) #define MAKE_ARG_LIST_65(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_64(op, __VA_ARGS__)) #define MAKE_ARG_LIST_66(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_65(op, __VA_ARGS__)) #define MAKE_ARG_LIST_67(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_66(op, __VA_ARGS__)) #define MAKE_ARG_LIST_68(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_67(op, __VA_ARGS__)) #define MAKE_ARG_LIST_69(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_68(op, __VA_ARGS__)) #define MAKE_ARG_LIST_70(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_69(op, __VA_ARGS__)) #define MAKE_ARG_LIST_71(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_70(op, __VA_ARGS__)) #define MAKE_ARG_LIST_72(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_71(op, __VA_ARGS__)) #define MAKE_ARG_LIST_73(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_72(op, __VA_ARGS__)) #define MAKE_ARG_LIST_74(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_73(op, __VA_ARGS__)) #define MAKE_ARG_LIST_75(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_74(op, __VA_ARGS__)) #define MAKE_ARG_LIST_76(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_75(op, __VA_ARGS__)) #define MAKE_ARG_LIST_77(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_76(op, __VA_ARGS__)) #define MAKE_ARG_LIST_78(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_77(op, __VA_ARGS__)) #define MAKE_ARG_LIST_79(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_78(op, __VA_ARGS__)) #define MAKE_ARG_LIST_80(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_79(op, __VA_ARGS__)) #define MAKE_ARG_LIST_81(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_80(op, __VA_ARGS__)) #define MAKE_ARG_LIST_82(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_81(op, __VA_ARGS__)) #define MAKE_ARG_LIST_83(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_82(op, __VA_ARGS__)) #define MAKE_ARG_LIST_84(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_83(op, __VA_ARGS__)) #define MAKE_ARG_LIST_85(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_84(op, __VA_ARGS__)) #define MAKE_ARG_LIST_86(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_85(op, __VA_ARGS__)) #define MAKE_ARG_LIST_87(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_86(op, __VA_ARGS__)) #define MAKE_ARG_LIST_88(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_87(op, __VA_ARGS__)) #define MAKE_ARG_LIST_89(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_88(op, __VA_ARGS__)) #define MAKE_ARG_LIST_90(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_89(op, __VA_ARGS__)) #define MAKE_ARG_LIST_91(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_90(op, __VA_ARGS__)) #define MAKE_ARG_LIST_92(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_91(op, __VA_ARGS__)) #define MAKE_ARG_LIST_93(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_92(op, __VA_ARGS__)) #define MAKE_ARG_LIST_94(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_93(op, __VA_ARGS__)) #define MAKE_ARG_LIST_95(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_94(op, __VA_ARGS__)) #define MAKE_ARG_LIST_96(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_95(op, __VA_ARGS__)) #define MAKE_ARG_LIST_97(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_96(op, __VA_ARGS__)) #define MAKE_ARG_LIST_98(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_97(op, __VA_ARGS__)) #define MAKE_ARG_LIST_99(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_98(op, __VA_ARGS__)) #define MAKE_ARG_LIST_100(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_99(op, __VA_ARGS__)) #define MAKE_ARG_LIST_101(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_100(op, __VA_ARGS__)) #define MAKE_ARG_LIST_102(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_101(op, __VA_ARGS__)) #define MAKE_ARG_LIST_103(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_102(op, __VA_ARGS__)) #define MAKE_ARG_LIST_104(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_103(op, __VA_ARGS__)) #define MAKE_ARG_LIST_105(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_104(op, __VA_ARGS__)) #define MAKE_ARG_LIST_106(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_105(op, __VA_ARGS__)) #define MAKE_ARG_LIST_107(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_106(op, __VA_ARGS__)) #define MAKE_ARG_LIST_108(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_107(op, __VA_ARGS__)) #define MAKE_ARG_LIST_109(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_108(op, __VA_ARGS__)) #define MAKE_ARG_LIST_110(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_109(op, __VA_ARGS__)) #define MAKE_ARG_LIST_111(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_110(op, __VA_ARGS__)) #define MAKE_ARG_LIST_112(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_111(op, __VA_ARGS__)) #define MAKE_ARG_LIST_113(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_112(op, __VA_ARGS__)) #define MAKE_ARG_LIST_114(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_113(op, __VA_ARGS__)) #define MAKE_ARG_LIST_115(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_114(op, __VA_ARGS__)) #define MAKE_ARG_LIST_116(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_115(op, __VA_ARGS__)) #define MAKE_ARG_LIST_117(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_116(op, __VA_ARGS__)) #define MAKE_ARG_LIST_118(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_117(op, __VA_ARGS__)) #define MAKE_ARG_LIST_119(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_118(op, __VA_ARGS__)) #define MAKE_ARG_LIST_120(op, arg, ...) op(arg), MARCO_EXPAND(MAKE_ARG_LIST_119(op, __VA_ARGS__)) #define ADD_VIEW(str) std::string_view(#str, sizeof(#str)-1) #define SEPERATOR , #define CON_STR_1(element, ...) ADD_VIEW(element) #define CON_STR_2(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_1(__VA_ARGS__)) #define CON_STR_3(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_2(__VA_ARGS__)) #define CON_STR_4(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_3(__VA_ARGS__)) #define CON_STR_5(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_4(__VA_ARGS__)) #define CON_STR_6(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_5(__VA_ARGS__)) #define CON_STR_7(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_6(__VA_ARGS__)) #define CON_STR_8(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_7(__VA_ARGS__)) #define CON_STR_9(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_8(__VA_ARGS__)) #define CON_STR_10(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_9(__VA_ARGS__)) #define CON_STR_11(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_10(__VA_ARGS__)) #define CON_STR_12(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_11(__VA_ARGS__)) #define CON_STR_13(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_12(__VA_ARGS__)) #define CON_STR_14(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_13(__VA_ARGS__)) #define CON_STR_15(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_14(__VA_ARGS__)) #define CON_STR_16(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_15(__VA_ARGS__)) #define CON_STR_17(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_16(__VA_ARGS__)) #define CON_STR_18(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_17(__VA_ARGS__)) #define CON_STR_19(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_18(__VA_ARGS__)) #define CON_STR_20(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_19(__VA_ARGS__)) #define CON_STR_21(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_20(__VA_ARGS__)) #define CON_STR_22(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_21(__VA_ARGS__)) #define CON_STR_23(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_22(__VA_ARGS__)) #define CON_STR_24(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_23(__VA_ARGS__)) #define CON_STR_25(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_24(__VA_ARGS__)) #define CON_STR_26(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_25(__VA_ARGS__)) #define CON_STR_27(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_26(__VA_ARGS__)) #define CON_STR_28(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_27(__VA_ARGS__)) #define CON_STR_29(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_28(__VA_ARGS__)) #define CON_STR_30(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_29(__VA_ARGS__)) #define CON_STR_31(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_30(__VA_ARGS__)) #define CON_STR_32(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_31(__VA_ARGS__)) #define CON_STR_33(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_32(__VA_ARGS__)) #define CON_STR_34(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_33(__VA_ARGS__)) #define CON_STR_35(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_34(__VA_ARGS__)) #define CON_STR_36(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_35(__VA_ARGS__)) #define CON_STR_37(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_36(__VA_ARGS__)) #define CON_STR_38(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_37(__VA_ARGS__)) #define CON_STR_39(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_38(__VA_ARGS__)) #define CON_STR_40(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_39(__VA_ARGS__)) #define CON_STR_41(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_40(__VA_ARGS__)) #define CON_STR_42(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_41(__VA_ARGS__)) #define CON_STR_43(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_42(__VA_ARGS__)) #define CON_STR_44(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_43(__VA_ARGS__)) #define CON_STR_45(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_44(__VA_ARGS__)) #define CON_STR_46(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_45(__VA_ARGS__)) #define CON_STR_47(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_46(__VA_ARGS__)) #define CON_STR_48(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_47(__VA_ARGS__)) #define CON_STR_49(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_48(__VA_ARGS__)) #define CON_STR_50(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_49(__VA_ARGS__)) #define CON_STR_51(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_50(__VA_ARGS__)) #define CON_STR_52(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_51(__VA_ARGS__)) #define CON_STR_53(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_52(__VA_ARGS__)) #define CON_STR_54(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_53(__VA_ARGS__)) #define CON_STR_55(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_54(__VA_ARGS__)) #define CON_STR_56(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_55(__VA_ARGS__)) #define CON_STR_57(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_56(__VA_ARGS__)) #define CON_STR_58(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_57(__VA_ARGS__)) #define CON_STR_59(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_58(__VA_ARGS__)) #define CON_STR_60(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_59(__VA_ARGS__)) #define CON_STR_61(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_60(__VA_ARGS__)) #define CON_STR_62(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_61(__VA_ARGS__)) #define CON_STR_63(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_62(__VA_ARGS__)) #define CON_STR_64(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_63(__VA_ARGS__)) #define CON_STR_65(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_64(__VA_ARGS__)) #define CON_STR_66(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_65(__VA_ARGS__)) #define CON_STR_67(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_66(__VA_ARGS__)) #define CON_STR_68(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_67(__VA_ARGS__)) #define CON_STR_69(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_68(__VA_ARGS__)) #define CON_STR_70(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_69(__VA_ARGS__)) #define CON_STR_71(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_70(__VA_ARGS__)) #define CON_STR_72(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_71(__VA_ARGS__)) #define CON_STR_73(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_72(__VA_ARGS__)) #define CON_STR_74(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_73(__VA_ARGS__)) #define CON_STR_75(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_74(__VA_ARGS__)) #define CON_STR_76(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_75(__VA_ARGS__)) #define CON_STR_77(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_76(__VA_ARGS__)) #define CON_STR_78(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_77(__VA_ARGS__)) #define CON_STR_79(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_78(__VA_ARGS__)) #define CON_STR_80(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_79(__VA_ARGS__)) #define CON_STR_81(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_80(__VA_ARGS__)) #define CON_STR_82(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_81(__VA_ARGS__)) #define CON_STR_83(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_82(__VA_ARGS__)) #define CON_STR_84(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_83(__VA_ARGS__)) #define CON_STR_85(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_84(__VA_ARGS__)) #define CON_STR_86(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_85(__VA_ARGS__)) #define CON_STR_87(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_86(__VA_ARGS__)) #define CON_STR_88(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_87(__VA_ARGS__)) #define CON_STR_89(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_88(__VA_ARGS__)) #define CON_STR_90(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_89(__VA_ARGS__)) #define CON_STR_91(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_90(__VA_ARGS__)) #define CON_STR_92(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_91(__VA_ARGS__)) #define CON_STR_93(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_92(__VA_ARGS__)) #define CON_STR_94(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_93(__VA_ARGS__)) #define CON_STR_95(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_94(__VA_ARGS__)) #define CON_STR_96(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_95(__VA_ARGS__)) #define CON_STR_97(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_96(__VA_ARGS__)) #define CON_STR_98(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_97(__VA_ARGS__)) #define CON_STR_99(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_98(__VA_ARGS__)) #define CON_STR_100(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_99(__VA_ARGS__)) #define CON_STR_101(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_100(__VA_ARGS__)) #define CON_STR_102(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_101(__VA_ARGS__)) #define CON_STR_103(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_102(__VA_ARGS__)) #define CON_STR_104(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_103(__VA_ARGS__)) #define CON_STR_105(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_104(__VA_ARGS__)) #define CON_STR_106(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_105(__VA_ARGS__)) #define CON_STR_107(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_106(__VA_ARGS__)) #define CON_STR_108(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_107(__VA_ARGS__)) #define CON_STR_109(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_108(__VA_ARGS__)) #define CON_STR_110(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_109(__VA_ARGS__)) #define CON_STR_111(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_110(__VA_ARGS__)) #define CON_STR_112(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_111(__VA_ARGS__)) #define CON_STR_113(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_112(__VA_ARGS__)) #define CON_STR_114(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_113(__VA_ARGS__)) #define CON_STR_115(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_114(__VA_ARGS__)) #define CON_STR_116(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_115(__VA_ARGS__)) #define CON_STR_117(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_116(__VA_ARGS__)) #define CON_STR_118(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_117(__VA_ARGS__)) #define CON_STR_119(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_118(__VA_ARGS__)) #define CON_STR_120(element, ...) ADD_VIEW(element) SEPERATOR MARCO_EXPAND(CON_STR_119(__VA_ARGS__)) #define RSEQ_N() \ 119,118,117,116,115,114,113,112,111,110,\ 109,108,107,106,105,104,103,102,101,100,\ 99,98,97,96,95,94,93,92,91,90, \ 89,88,87,86,85,84,83,82,81,80, \ 79,78,77,76,75,74,73,72,71,70, \ 69,68,67,66,65,64,63,62,61,60, \ 59,58,57,56,55,54,53,52,51,50, \ 49,48,47,46,45,44,43,42,41,40, \ 39,38,37,36,35,34,33,32,31,30, \ 29,28,27,26,25,24,23,22,21,20, \ 19,18,17,16,15,14,13,12,11,10, \ 9,8,7,6,5,4,3,2,1,0 #define ARG_N(\ _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \ _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \ _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \ _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \ _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \ _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \ _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, \ _71, _72, _73, _74, _75, _76, _77, _78, _79, _80, \ _81, _82, _83, _84, _85, _86, _87, _88, _89, _90, \ _91, _92, _93, _94, _95, _96, _97, _98, _99, _100, \ _101, _102, _103, _104, _105, _106, _107, _108, _109, _110, \ _111, _112, _113, _114, _115, _116, _117, _118, _119, N, ...) N #define MARCO_EXPAND(...) __VA_ARGS__ #define APPLY_VARIADIC_MACRO(macro, ...) MARCO_EXPAND(macro(__VA_ARGS__)) #define ADD_REFERENCE(t) std::reference_wrapper<decltype(t)>(t) #define ADD_REFERENCE_CONST(t) std::reference_wrapper<std::add_const_t<decltype(t)>>(t) #define FIELD(t) t #define MAKE_NAMES(...) #__VA_ARGS__, //note use MACRO_CONCAT like A##_##B direct may cause marco expand error #define MACRO_CONCAT(A, B) MACRO_CONCAT1(A, B) #define MACRO_CONCAT1(A, B) A##_##B #define MAKE_ARG_LIST(N, op, arg, ...) \ MACRO_CONCAT(MAKE_ARG_LIST, N)(op, arg, __VA_ARGS__) #define GET_ARG_COUNT_INNER(...) MARCO_EXPAND(ARG_N(__VA_ARGS__)) #define GET_ARG_COUNT(...) GET_ARG_COUNT_INNER(__VA_ARGS__, RSEQ_N()) #define MAKE_STR_LIST(...) \ MACRO_CONCAT(CON_STR, GET_ARG_COUNT(__VA_ARGS__))(__VA_ARGS__) #define MAKE_META_DATA_IMPL(STRUCT_NAME, ...) \ static auto iguana_reflect_members(STRUCT_NAME const&) \ { \ struct reflect_members \ { \ constexpr decltype(auto) static apply_impl(){\ return std::make_tuple(__VA_ARGS__);\ }\ using type = void;\ using size_type = std::integral_constant<size_t, GET_ARG_COUNT(__VA_ARGS__)>; \ constexpr static std::string_view name() { return std::string_view(#STRUCT_NAME, sizeof(#STRUCT_NAME)-1); }\ constexpr static size_t value() { return size_type::value; }\ constexpr static std::array<std::string_view, size_type::value> arr() { return arr_##STRUCT_NAME; }\ }; \ return reflect_members{}; \ } #define MAKE_META_DATA(STRUCT_NAME, N, ...) \ constexpr inline std::array<std::string_view, N> arr_##STRUCT_NAME = { MARCO_EXPAND(MACRO_CONCAT(CON_STR, N)(__VA_ARGS__)) };\ MAKE_META_DATA_IMPL(STRUCT_NAME, MAKE_ARG_LIST(N, &STRUCT_NAME::FIELD, __VA_ARGS__)) } namespace iguana { #define REFLECTION(STRUCT_NAME, ...) \ MAKE_META_DATA(STRUCT_NAME, GET_ARG_COUNT(__VA_ARGS__), __VA_ARGS__) template<typename T> using Reflect_members = decltype(iguana_reflect_members(std::declval<T>())); template <typename T, typename = void> struct is_reflection : std::false_type { }; template <typename T> struct is_reflection<T, std::void_t<typename Reflect_members<T>::type>> : std::true_type { }; template<typename T> inline constexpr bool is_reflection_v = is_reflection<T>::value; template<size_t I, typename T> constexpr decltype(auto) get(T&& t) { using M = decltype(iguana_reflect_members(std::forward<T>(t))); using U = decltype(std::forward<T>(t).*(std::get<I>(M::apply_impl()))); if constexpr(std::is_array_v<U>) { auto s = std::forward<T>(t).*(std::get<I>(M::apply_impl())); std::array<char, sizeof(U)> arr; memcpy(arr.data(), s, arr.size()); return arr; } else return std::forward<T>(t).*(std::get<I>(M::apply_impl())); } template <typename T, size_t ... Is> constexpr auto get_impl(T const& t, std::index_sequence<Is...>) { return std::make_tuple(get<Is>(t)...); } template <typename T, size_t ... Is> constexpr auto get_impl(T& t, std::index_sequence<Is...>) { return std::make_tuple(std::ref(get<Is>(t))...); } template <typename T> constexpr auto get(T const& t) { using M = decltype(iguana_reflect_members(t)); return get_impl(t, std::make_index_sequence<M::value()>{}); } template <typename T> constexpr auto get_ref(T& t) { using M = decltype(iguana_reflect_members(t)); return get_impl(t, std::make_index_sequence<M::value()>{}); } template<typename T, size_t I> constexpr const std::string_view get_name() { using M = decltype(iguana_reflect_members(std::declval<T>())); static_assert(I<M::value(), "out of range"); return M::arr()[I]; } template<typename T> constexpr const std::string_view get_name(size_t i) { using M = decltype(iguana_reflect_members(std::declval<T>())); // static_assert(I<M::value(), "out of range"); return M::arr()[i]; } template<typename T> constexpr const std::string_view get_name() { using M = decltype(iguana_reflect_members(std::declval<T>())); return M::name(); } template<typename T> constexpr std::enable_if_t<is_reflection<T>::value, size_t> get_value() { using M = decltype(iguana_reflect_members(std::declval<T>())); return M::value(); } template<typename T> constexpr std::enable_if_t<!is_reflection<T>::value, size_t> get_value() { return 1; } template<typename T> constexpr auto get_array() { using M = decltype(iguana_reflect_members(std::declval<T>())); return M::arr(); } template<typename T> constexpr auto get_index(std::string_view name) { using M = decltype(iguana_reflect_members(std::declval<T>())); constexpr auto arr = M::arr(); auto it = std::find_if(arr.begin(), arr.end(), [name](auto str){ return (str==name); }); return std::distance(arr.begin(), it); } template <class Tuple, class F, std::size_t...Is> void tuple_switch(std::size_t i, Tuple&& t, F&& f, std::index_sequence<Is...>) { ((i == Is && ((std::forward<F>(f)(std::get<Is>(std::forward<Tuple>(t)))), false)), ...); } //-------------------------------------------------------------------------------------------------------------// //-------------------------------------------------------------------------------------------------------------// template <typename... Args, typename F, std::size_t... Idx> constexpr void for_each(std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>) { (std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...); } template <typename... Args, typename F, std::size_t... Idx> constexpr void for_each(const std::tuple<Args...>& t, F&& f, std::index_sequence<Idx...>) { (std::forward<F>(f)(std::get<Idx>(t), std::integral_constant<size_t, Idx>{}), ...); } template<typename T, typename F> constexpr std::enable_if_t<is_reflection<T>::value> for_each(T&& t, F&& f) { using M = decltype(iguana_reflect_members(std::forward<T>(t))); for_each(M::apply_impl(), std::forward<F>(f), std::make_index_sequence<M::value()>{}); } template<typename T, typename F> constexpr std::enable_if_t<is_tuple<std::decay_t<T>>::value> for_each(T&& t, F&& f) { //using M = decltype(iguana_reflect_members(std::forward<T>(t))); constexpr const size_t SIZE = std::tuple_size_v<std::decay_t<T>>; for_each(std::forward<T>(t), std::forward<F>(f), std::make_index_sequence<SIZE>{}); } } #endif //IGUANA_REFLECTION_HPP
65.159596
130
0.73163
yangxingpping
911b5303fdd55db62e8eaa831a6fa25bf472e1a6
467
cpp
C++
solutions/IWaP5vb1.cpp
luyencode/cpp-solutions
627397fb887654e9f5ee64cfb73d708f6f6706f7
[ "MIT" ]
60
2021-04-10T11:17:33.000Z
2022-03-23T06:15:42.000Z
solutions/IWaP5vb1.cpp
letuankiet-29-10-2002/cpp-solutions
7d9cddf211af54ff207da883b469f4ddd75d5916
[ "MIT" ]
1
2021-08-13T11:32:27.000Z
2021-08-13T11:32:27.000Z
solutions/IWaP5vb1.cpp
letuankiet-29-10-2002/cpp-solutions
7d9cddf211af54ff207da883b469f4ddd75d5916
[ "MIT" ]
67
2021-04-10T17:32:50.000Z
2022-03-23T15:50:17.000Z
/* Sưu tầm bởi @nguyenvanhieuvn Thực hành nhiều bài tập hơn tại https://luyencode.net/ */ #include<stdio.h> #include<conio.h> float Tinh(float x) { float ketqua; if(x >= 5) ketqua = 2 * x * x + 5 * x + 9; else ketqua = -2 * x * x + 4 * x - 9; return ketqua; } int main() { float x; printf("\nNhap x: "); scanf("%f", &x); float ketqua = Tinh(x); printf("\nKet qua = %f", ketqua); getch(); return 0; }
16.103448
56
0.518201
luyencode
911b902ac7ce18b3b3eabaea143462dac640b1e5
7,045
cpp
C++
test/unit-tests/metafs/mim/metafs_io_request_test.cpp
iljoongkr/poseidonos
01ed7c323c4f6dbd99970f4b036ade2f0a4e4383
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/metafs/mim/metafs_io_request_test.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/metafs/mim/metafs_io_request_test.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include "src/metafs/mim/metafs_io_request.h" #include "test/unit-tests/metafs/mim/metafs_io_request_mock.h" #include <gtest/gtest.h> namespace pos { TEST(MetaFsIoRequest, ConstructorAndDestructor) { MetaFsIoRequest* req = new MetaFsIoRequest(); delete req; } TEST(MetaFsIoRequest, CopyMsg_SyncRequest_FromUserThread) { MockMetaFsIoRequest* reqOrigin = new MockMetaFsIoRequest(); MetaFsIoRequest* req = new MetaFsIoRequest(); EXPECT_CALL(*reqOrigin, GetError).Times(1); reqOrigin->ioMode = MetaIoMode::Sync; reqOrigin->originalMsg = nullptr; req->CopyUserReqMsg(*reqOrigin); EXPECT_EQ(reqOrigin->reqType, req->reqType); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->isFullFileIo, req->isFullFileIo); EXPECT_EQ(reqOrigin->fd, req->fd); EXPECT_EQ(reqOrigin->arrayId, req->arrayId); EXPECT_EQ(reqOrigin->buf, req->buf); EXPECT_EQ(reqOrigin->byteOffsetInFile, req->byteOffsetInFile); EXPECT_EQ(reqOrigin->byteSize, req->byteSize); EXPECT_EQ(reqOrigin->targetMediaType, req->targetMediaType); EXPECT_EQ(reqOrigin->aiocb, req->aiocb); EXPECT_EQ(reqOrigin->tagId, req->tagId); EXPECT_EQ(reqOrigin->baseMetaLpn, req->baseMetaLpn); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->GetError(), req->GetError()); EXPECT_EQ(reqOrigin->fileCtx, req->fileCtx); // from user thread to meta io scheduler EXPECT_EQ(reqOrigin, req->originalMsg); delete req; delete reqOrigin; } TEST(MetaFsIoRequest, CopyMsg_SyncRequest_FromScheduler) { MockMetaFsIoRequest* reqOrigin = new MockMetaFsIoRequest(); MetaFsIoRequest* req = new MetaFsIoRequest(); EXPECT_CALL(*reqOrigin, GetError).Times(1); reqOrigin->ioMode = MetaIoMode::Sync; reqOrigin->originalMsg = reqOrigin; req->CopyUserReqMsg(*reqOrigin); EXPECT_EQ(reqOrigin->reqType, req->reqType); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->isFullFileIo, req->isFullFileIo); EXPECT_EQ(reqOrigin->fd, req->fd); EXPECT_EQ(reqOrigin->arrayId, req->arrayId); EXPECT_EQ(reqOrigin->buf, req->buf); EXPECT_EQ(reqOrigin->byteOffsetInFile, req->byteOffsetInFile); EXPECT_EQ(reqOrigin->byteSize, req->byteSize); EXPECT_EQ(reqOrigin->targetMediaType, req->targetMediaType); EXPECT_EQ(reqOrigin->aiocb, req->aiocb); EXPECT_EQ(reqOrigin->tagId, req->tagId); EXPECT_EQ(reqOrigin->baseMetaLpn, req->baseMetaLpn); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->GetError(), req->GetError()); EXPECT_EQ(reqOrigin->fileCtx, req->fileCtx); // meta io scheduler to mio handler EXPECT_EQ(reqOrigin->originalMsg, req->originalMsg); delete req; delete reqOrigin; } TEST(MetaFsIoRequest, CopyMsg_AsyncRequest) { MockMetaFsIoRequest* reqOrigin = new MockMetaFsIoRequest(); MetaFsIoRequest* req = new MetaFsIoRequest(); EXPECT_CALL(*reqOrigin, GetError).Times(1); reqOrigin->ioMode = MetaIoMode::Async; req->CopyUserReqMsg(*reqOrigin); EXPECT_EQ(reqOrigin->reqType, req->reqType); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->isFullFileIo, req->isFullFileIo); EXPECT_EQ(reqOrigin->fd, req->fd); EXPECT_EQ(reqOrigin->arrayId, req->arrayId); EXPECT_EQ(reqOrigin->buf, req->buf); EXPECT_EQ(reqOrigin->byteOffsetInFile, req->byteOffsetInFile); EXPECT_EQ(reqOrigin->byteSize, req->byteSize); EXPECT_EQ(reqOrigin->targetMediaType, req->targetMediaType); EXPECT_EQ(reqOrigin->aiocb, req->aiocb); EXPECT_EQ(reqOrigin->tagId, req->tagId); EXPECT_EQ(reqOrigin->baseMetaLpn, req->baseMetaLpn); EXPECT_EQ(reqOrigin->ioMode, req->ioMode); EXPECT_EQ(reqOrigin->GetError(), req->GetError()); EXPECT_EQ(reqOrigin->fileCtx, req->fileCtx); delete req; delete reqOrigin; } TEST(MetaFsIoRequest, Validity_Negative0) { MetaFsIoRequest* req = new MetaFsIoRequest(); // positive req->reqType = MetaIoRequestType::Read; req->ioMode = MetaIoMode::Max; req->fd = MetaFsCommonConst::INVALID_FD; req->buf = nullptr; req->targetMediaType = MetaStorageType::Max; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, Validity_Negative1) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->reqType = MetaIoRequestType::Max; // positive req->ioMode = MetaIoMode::Sync; req->fd = MetaFsCommonConst::INVALID_FD; req->buf = nullptr; req->targetMediaType = MetaStorageType::Max; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, Validity_Negative2) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->reqType = MetaIoRequestType::Max; req->ioMode = MetaIoMode::Max; // positive req->fd = 0; req->buf = nullptr; req->targetMediaType = MetaStorageType::Max; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, Validity_Negative3) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->reqType = MetaIoRequestType::Max; req->ioMode = MetaIoMode::Max; req->fd = MetaFsCommonConst::INVALID_FD; // positive req->buf = (void*)this; req->targetMediaType = MetaStorageType::Max; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, Validity_Negative4) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->reqType = MetaIoRequestType::Max; req->ioMode = MetaIoMode::Max; req->fd = MetaFsCommonConst::INVALID_FD; req->buf = nullptr; // positive req->targetMediaType = MetaStorageType::SSD; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, Validity_Positive0) { MetaFsIoRequest* req = new MetaFsIoRequest(); // negative req->reqType = MetaIoRequestType::Max; req->ioMode = MetaIoMode::Async; req->fd = 0; req->buf = (void*)this; req->targetMediaType = MetaStorageType::Max; EXPECT_EQ(req->IsValid(), false); delete req; } TEST(MetaFsIoRequest, CheckSyncIo) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->ioMode = MetaIoMode::Async; EXPECT_EQ(req->IsSyncIO(), false); req->ioMode = MetaIoMode::Sync; EXPECT_EQ(req->IsSyncIO(), true); delete req; } TEST(MetaFsIoRequest, CheckIoDone) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->requestCount = 2; req->NotifyIoCompletionToClient(); EXPECT_EQ(req->IsIoCompleted(), false); req->NotifyIoCompletionToClient(); EXPECT_EQ(req->IsIoCompleted(), true); delete req; } TEST(MetaFsIoRequest, CheckErrors) { MetaFsIoRequest* req = new MetaFsIoRequest(); req->SetError(true); EXPECT_EQ(req->GetError(), true); req->SetError(false); EXPECT_EQ(req->GetError(), false); delete req; } TEST(MetaFsIoRequest, CheckRetryFlag) { MetaFsIoRequest* req = new MetaFsIoRequest(); EXPECT_EQ(req->GetRetryFlag(), false); req->SetRetryFlag(); EXPECT_EQ(req->GetRetryFlag(), true); delete req; } } // namespace pos
27.096154
66
0.698793
iljoongkr
911dda215577af18a10fa68681fec3b0cdf9b744
8,752
cpp
C++
gpu/src/particleapp.cpp
Melodeathguy/ParticleSolver
5cccb54454427029f3c05156854a3337369995e1
[ "MIT" ]
129
2015-07-06T16:57:03.000Z
2022-02-25T08:34:29.000Z
gpu/src/particleapp.cpp
Melodeathguy/ParticleSolver
5cccb54454427029f3c05156854a3337369995e1
[ "MIT" ]
null
null
null
gpu/src/particleapp.cpp
Melodeathguy/ParticleSolver
5cccb54454427029f3c05156854a3337369995e1
[ "MIT" ]
21
2015-07-07T05:52:08.000Z
2021-06-07T02:28:05.000Z
/* * This class controls helper classes for rendering and * updating the particle system. * * Mouse events, key events, window sizing, timing updates, * and render calls are all received by this application then * passed to the corresponding render or particlesystem class. */ #include <cuda_runtime.h> #include <QMouseEvent> #include <QWheelEvent> #include <QKeyEvent> #include <random> #include <unistd.h> #include "particleapp.h" #include "particlesystem.h" #include "renderer.h" #include "helper_math.h" #include "util.cuh" #define MAX_PARTICLES 15000 // (vbo size) #define PARTICLE_RADIUS 0.25f #define GRID_SIZE make_uint3(64, 64, 64) // 3D ParticleApp::ParticleApp() : m_particleSystem(NULL), m_renderer(NULL), m_mouseDownL(false), m_mouseDownR(false), m_fluidEmmiterOn(false), m_timer(-1.f) { cudaInit(); m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_renderer = new Renderer(m_particleSystem->getMinBounds(), m_particleSystem->getMaxBounds()); m_renderer->createVAO(m_particleSystem->getCurrentReadBuffer(), m_particleSystem->getParticleRadius()); makeInitScene(); } ParticleApp::~ParticleApp() { if (m_particleSystem) delete m_particleSystem; if (m_renderer) delete m_renderer; // cudaDeviceReset causes the driver to clean up all state. While // not mandatory in normal operation, it is good practice. It is also // needed to ensure correct operation when the application is being // profiled. Calling cudaDeviceReset causes all profile data to be // flushed before the application exits cudaDeviceReset(); } inline float frand() { return rand() / (float) RAND_MAX; } void ParticleApp::makeInitScene() { m_particleSystem->addRope(make_float3(0, 20, 0), make_float3(0, -.5, 0), .4f, 32, 1.f, true); } void ParticleApp::tick(float secs) { if (m_fluidEmmiterOn && m_timer <= 0.f) { m_particleSystem->addFluid(make_int3(-1,0,-1), make_int3(1,1,1), 1.f, 1.f, make_float3(0,0,1)); m_timer = 0.1f; } m_timer -= secs; m_particleSystem->update(secs); m_renderer->update(secs); } void ParticleApp::render() { m_renderer->render(m_particleSystem->getColorIndex(), m_particleSystem->getColors()); } void ParticleApp::mousePressed(QMouseEvent *e, float x, float y) { // shoot a particle into the sceen on left mouse click if (e->button() == Qt::LeftButton) { m_particleSystem->setParticleToAdd(m_renderer->getEye(), m_renderer->getDir(x, y) * 30.f, 2.f); m_mouseDownL = true; } else if (e->button() == Qt::RightButton) { m_mouseDownR = true; } } void ParticleApp::mouseReleased(QMouseEvent *e, float, float) { if (e->button() == Qt::LeftButton) { m_mouseDownL = false; } if (e->button() == Qt::RightButton) { m_mouseDownR = false; } } void ParticleApp::mouseMoved(QMouseEvent *e, float deltaX, float deltaY) { m_renderer->mouseMoved(e, deltaX, deltaY); } void ParticleApp::mouseScrolled(QWheelEvent *) {} void ParticleApp::keyPressed(QKeyEvent *e) { m_renderer->keyPressed(e); } void ParticleApp::keyReleased(QKeyEvent *e) { bool resetVbo = true; float3 h, vec; float angle; // numbers 0-9 toggle different scenes switch (e->key()) { case Qt::Key_1: // single rope delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); makeInitScene(); break; case Qt::Key_2: // single cloth delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addHorizCloth(make_int2(0, -3), make_int2(6,3), make_float3(.5f,7.f,.5f), make_float2(.3f, .3f), 3.f, false); break; case Qt::Key_3: // two fluids, different densities delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-7, 0, -5), make_int3(7, 20, 5), 5); m_particleSystem->addFluid(make_int3(-7, 0, -5), make_int3(7, 5, 5), 1.f, 2.f, colors[rand() % numColors]); m_particleSystem->addFluid(make_int3(-7, 5, -5), make_int3(7, 10, 5), 1.f, 3.f, colors[rand() % numColors]); break; case Qt::Key_4: // one solid particle stack delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addParticleGrid(make_int3(-3, 0, -3), make_int3(3, 20, 3), 1.f, false); break; case Qt::Key_5: // three solid particle stacks delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addParticleGrid(make_int3(-10, 0, -3), make_int3(-7, 10, 3), 1.f, false); m_particleSystem->addParticleGrid(make_int3(-3, 0, -3), make_int3(3, 10, 3), 1.f, false); m_particleSystem->addParticleGrid(make_int3(7, 0, -3), make_int3(10, 10, 3), 1.f, false); break; case Qt::Key_6: // particles on cloth delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addHorizCloth(make_int2(-10, -10), make_int2(10, 10), make_float3(.3f, 5.5f, .3f), make_float2(.1f, .1f), 10.f, true); m_particleSystem->addParticleGrid(make_int3(-3, 6, -3), make_int3(3, 15, 3), 1.f, false); break; case Qt::Key_7: // fluid blob delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addFluid(make_int3(-7, 6, -7), make_int3(7, 13, 7), 1.f, 1.5f, colors[rand() % numColors]); break; case Qt::Key_8: // combo scene delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); m_particleSystem->addHorizCloth(make_int2(14, -4), make_int2(24, 6), make_float3(.3f, 2.5f, .3f), make_float2(.25f, .25f), 10.f, true); m_particleSystem->addHorizCloth(make_int2(10, -10), make_int2(25, -5), make_float3(.3f, 15.5f, .3f), make_float2(.25f, .25f), 3.f, false); m_particleSystem->addRope(make_float3(-17, 20, -17), make_float3(0, -.5, 0.001f), .4f, 30, 1.f, true); m_particleSystem->addRope(make_float3(-16, 20, -17), make_float3(0, 0, .5f), .4f, 50, 1.f, true); m_particleSystem->addRope(make_float3(-17, 20, -16), make_float3(0, -.5, 0.001f), .4f, 40, 1.f, true); m_particleSystem->addParticleGrid(make_int3(17, 6, 0), make_int3(21, 11, 4), 1.f, false); m_particleSystem->addParticleGrid(make_int3(-12, 0, -20), make_int3(0, 12, -17), 1.f, false); m_particleSystem->addParticleGrid(make_int3(-18, 0, -15), make_int3(-16, 9, -12), 1.f, false); m_particleSystem->addStaticSphere(make_int3(5, 5, -10), make_int3(10, 10, -5), .5f); break; case Qt::Key_9: // ropes on immovable sphere delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); h = make_float3(0, 10, 0); for(int i = 0; i < 50; i++) { angle = M_PI * i * 0.02f; vec = make_float3(cos(angle), sin(angle), 0.f); m_particleSystem->addRope(vec*5.f + h, vec*.5f, .35f, 30, 1.f, true); } m_particleSystem->addStaticSphere(make_int3(-4, 7, -4), make_int3(4, 16, 4), .5f); break; case Qt::Key_0: // empty scene delete m_particleSystem; m_particleSystem = new ParticleSystem(PARTICLE_RADIUS, GRID_SIZE, MAX_PARTICLES, make_int3(-50, 0, -50), make_int3(50, 200, 50), 5); break; case Qt::Key_Space: // toggle fluids at origin m_fluidEmmiterOn = !m_fluidEmmiterOn; break; default: resetVbo = false; m_renderer->keyReleased(e); break; } if (resetVbo) { m_renderer->createVAO(m_particleSystem->getCurrentReadBuffer(), m_particleSystem->getParticleRadius()); } } void ParticleApp::resize(int w, int h) { m_renderer->resize(w, h); }
37.242553
146
0.650708
Melodeathguy
912054d2c2a48cac37549d883070c4ef5276c681
392
cpp
C++
Data/Data.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
2
2020-03-27T05:36:33.000Z
2021-10-30T07:47:33.000Z
Data/Data.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
null
null
null
Data/Data.cpp
tdm1223/CustomExplorer
e790cd2fbd401f2ff05e825e709fefc42e50d64e
[ "MIT" ]
null
null
null
#include "Data.h" Data::Data() { ::ZeroMemory(childType, sizeof(childType)); ::ZeroMemory(fileName, sizeof(fileName)); ::ZeroMemory(filePath, sizeof(filePath)); ::ZeroMemory(childName, sizeof(childName)); ::ZeroMemory(childAccessTime, sizeof(childAccessTime)); ::ZeroMemory(childSize, sizeof(childSize)); childLength = 0; fileSize = 0; } Data::~Data() { }
20.631579
59
0.665816
tdm1223
912172df92c3eb96eb62a4363f0c5cd08fd5d86e
2,141
cxx
C++
peripherals/sw/libhid/ut/ut-keyboard.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
peripherals/sw/libhid/ut/ut-keyboard.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
peripherals/sw/libhid/ut/ut-keyboard.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Package: Peripherals // /*! \file * * \ingroup periphs_ut * * \brief Unit test for libhid keyboard controller * * \author Daniel Packard (daniel@roadnarrows.com) * * \copyright * \h_copy 2013-2017. RoadNarrows LLC.\n * http://www.roadnarrows.com\n * All Rights Reserved */ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are // those of the authors and should not be interpreted as representing official // policies, either expressed or implied, of the FreeBSD Project. #include <iostream> #include <string> #include <gtest/gtest.h> using namespace std; static const float EPSILON = 0.0001; /*! * \ingroup periphs_ut * \defgroup periphs_ut_libhid_keyboard * \brief Fine-grained testing of keyboard library. * \{ */ /*! * \} */
34.532258
80
0.706212
roadnarrows-robotics
9122a62e3892015827bf4daa1971dee8079bf138
4,527
cc
C++
measure_statistics_in_data.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
measure_statistics_in_data.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
measure_statistics_in_data.cc
JackMaguire/RobotsAsAGraph
23208be8cfc34cd1f4db9f3cb7b680286e690f07
[ "MIT" ]
null
null
null
//g++ measure_statistics_in_data.cc -o measure_statistics_in_data --std=c++17 -I extern/RobotsCore/include/ -O3 -Wall -pedantic -Wextra -Wshadow #include "deserialize.hh" #include <iostream> #include <string> #include <vector> #include <fstream> #include <filesystem> namespace fs = std::filesystem; #include <robots_core/forecasting.hh> constexpr auto path_to_all_data = "data/all_data/"; constexpr auto outpath_to_training_data = "data/training_data.txt"; constexpr auto outpath_to_validation_data = "data/validation_data.txt"; //https://stackoverflow.com/questions/874134/find-out-if-string-ends-with-another-string-in-c bool ends_with( std::string const & value, std::string const & ending ){ if (ending.size() > value.size()) return false; return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } bool move_is_legal( Key const move, std::array< std::array< robots_core::ForecastResults, 3 >, 3 > const & forecasts ){ switch( move ){ case Key::Q: return forecasts[0][2].legal; case Key::W: return forecasts[1][2].legal; case Key::E: return forecasts[2][2].legal; case Key::A: return forecasts[0][1].legal; case Key::S: return forecasts[1][1].legal; case Key::D: return forecasts[2][1].legal; case Key::Z: return forecasts[0][0].legal; case Key::X: return forecasts[1][0].legal; case Key::C: return forecasts[2][0].legal; default: return true; } } int main(){ std::stringstream training_data; std::stringstream validation_data; int n_early_teleports = 0; std::array< long long unsigned int, 10 > safe_move_hist; safe_move_hist.fill( 0 ); std::array< std::array< long long unsigned int, 10 >, 3 > safe_move_hist_by_level; for( auto & a : safe_move_hist_by_level ) a.fill( 0 ); auto bin_for_level = []( int const level ){ if( level <= 22 ) return 0; else if( level <= 44 ) return 1; else return 2; }; int counter = 0; for( auto const & entry : fs::directory_iterator( path_to_all_data ) ){ if( ends_with( entry.path(), "gz" ) ) continue; //std::cout << entry.path() << std::endl; bool const validation = counter == 0; counter = (counter+1)%5; std::stringstream & stream = ( validation ? validation_data : training_data ); std::ifstream input( entry.path() ); //RAII close for( std::string line; getline( input, line ); ) { DataPoint const sample = deserialize( line ); //Skip move-less keys if( sample.key == Key::NONE || sample.key == Key::DELETE || sample.key == Key::R || sample.key == Key::SPACE ) continue; auto const forecasts = robots_core::forecast_all_moves(sample.game.board()); //Skip cascade situations if( forecasts[1][1].cascade_safe ) continue; //Skip illegal moves if( not move_is_legal( sample.key, forecasts ) ) continue; unsigned int num_safe_moves = 0; for( auto const & f1 : forecasts ){ for( auto const & f : f1 ){ if( f.legal ) ++num_safe_moves; } } //std::cout << "num_safe_moves: " << num_safe_moves << std::endl; ++safe_move_hist[ num_safe_moves ]; ++safe_move_hist_by_level [ bin_for_level( sample.level ) ] [ num_safe_moves ]; //Skip obvious teleports if( num_safe_moves == 0 ) continue; if( num_safe_moves > 0 and sample.key == Key::T ) { ++n_early_teleports; //upsample safe teleports stream << line << '\n'; stream << line << '\n'; stream << line << '\n'; stream << line << '\n'; } stream << line << '\n'; } } for( unsigned int i = 0; i < safe_move_hist.size(); ++i ){ std::cout << "safe_move_hist " << i << " " << safe_move_hist[i] << std::endl; } std::cout << "Levels 1-22:" << std::endl; for( unsigned int i = 0; i < safe_move_hist_by_level[0].size(); ++i ){ std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[0][i] << std::endl; } std::cout << "Levels 23-44:" << std::endl; for( unsigned int i = 0; i < safe_move_hist_by_level[1].size(); ++i ){ std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[1][i] << std::endl; } std::cout << "Levels 45-66:" << std::endl; for( unsigned int i = 0; i < safe_move_hist_by_level[2].size(); ++i ){ std::cout << "safe_move_hist " << i << " " << safe_move_hist_by_level[2][i] << std::endl; } std::cout << "n_early_teleports: " << n_early_teleports << std::endl; std::cout << training_data.str().size() << " " << validation_data.str().size() << std::endl; }
30.18
144
0.631986
JackMaguire
912365cc33f179f20856a201ed70169235341ae0
83
cpp
C++
Snake2DGameSFML/views/IGameView.cpp
melardev/CppSFMLSnakeGame
afb241656c64968fb44f08a734cb61aea6cb49cd
[ "MIT" ]
null
null
null
Snake2DGameSFML/views/IGameView.cpp
melardev/CppSFMLSnakeGame
afb241656c64968fb44f08a734cb61aea6cb49cd
[ "MIT" ]
null
null
null
Snake2DGameSFML/views/IGameView.cpp
melardev/CppSFMLSnakeGame
afb241656c64968fb44f08a734cb61aea6cb49cd
[ "MIT" ]
null
null
null
#include "IGameView.h" IGameView::IGameView() { } IGameView::~IGameView() { }
6.384615
23
0.638554
melardev
91273f09df8a64f484be59b2685f8d58bd24ab5d
813
hpp
C++
TGEngine/io/Mouse.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/io/Mouse.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/io/Mouse.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../util/VectorUtil.hpp" #include "../util/Annotations.hpp" #include <glm/glm.hpp> namespace tg_io { /* * These variables can be used to track the mouses position */ extern glm::vec2 pos; extern glm::vec2 delta; /* * These variables can be used to check if the buttons are down; */ extern bool FIRST_MOUSE_BUTTON; extern bool SECOND_MOUSE_BUTTON; extern bool THIRED_MOUSE_BUTTON; /* * Internal mouse handling list */ extern std::vector<void(*)(glm::vec2, glm::vec2)> mouse_handler; /* * Internal mouse handling method */ SINCE(0, 0, 3) void inputupdate(glm::vec2 pos, glm::vec2 delta); /* * With this method you can add a Listener that is called everytime an input is detected */ SINCE(0, 0, 3) void addListener(void(*mouse)(glm::vec2, glm::vec2)); }
21.972973
89
0.693727
ThePixly
912ee50bc6fea304044f5716f624130aa155d807
4,215
hpp
C++
test/inheritance.hpp
IRCAD/camp
fbbada73d6fd25c30f22a69f195c871757e362dd
[ "MIT" ]
6
2017-12-27T03:13:29.000Z
2021-01-04T15:07:18.000Z
test/inheritance.hpp
fw4spl-org/camp
e70eca1d2bf7f20df782dacc5d6baa51ce364e12
[ "MIT" ]
1
2021-10-19T14:03:39.000Z
2021-10-19T14:03:39.000Z
test/inheritance.hpp
IRCAD/camp
fbbada73d6fd25c30f22a69f195c871757e362dd
[ "MIT" ]
1
2019-08-30T15:20:46.000Z
2019-08-30T15:20:46.000Z
/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information (contact@tegesoft.com) ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. ** ****************************************************************************/ #ifndef CAMPTEST_INHERITANCE_HPP #define CAMPTEST_INHERITANCE_HPP #include <camp/camptype.hpp> #include <camp/class.hpp> namespace InheritanceTest { struct MyClass1 { MyClass1() : p1(10), po1(10) {} virtual ~MyClass1() {} int p1; int f1() const {return 1;} int po1; int fo1() {return 1;} CAMP_RTTI(); }; struct MyClass2 { MyClass2() : p2(20), po2(20) {} virtual ~MyClass2() {} int p2; int f2() const {return 2;} virtual int fv() const {return p2;} int po2; int fo2() {return 2;} CAMP_RTTI(); }; struct MyClass3 : public MyClass1, public MyClass2 { MyClass3() : p3(30), po3(30) {} virtual ~MyClass3() {} int p3; int f3() const {return 3;} virtual int fv() const {return p3;} int po3; int fo3() {return 3;} CAMP_RTTI(); }; struct MyClass4 : public MyClass3 { MyClass4() : p4(40), po4(40) {} virtual ~MyClass4() {} int p4; int f4() const {return 4;} virtual int fv() const {return p4;} int po4; int fo4() {return 4;} CAMP_RTTI(); }; void declare() { camp::Class::declare<MyClass1>("InheritanceTest::MyClass1") .function("f1", &MyClass1::f1) .property("p1", &MyClass1::p1) .function("overridden", &MyClass1::fo1) .property("overridden", &MyClass1::po1); camp::Class::declare<MyClass2>("InheritanceTest::MyClass2") .function("f2", &MyClass2::f2) .property("p2", &MyClass2::p2) .function("virtual", &MyClass2::fv) .function("overridden", &MyClass2::fo2) .property("overridden", &MyClass2::po2); camp::Class::declare<MyClass3>("InheritanceTest::MyClass3") .base<MyClass1>() .base<MyClass2>() .function("f3", &MyClass3::f3) .property("p3", &MyClass3::p3) .function("overridden", &MyClass3::fo3) .property("overridden", &MyClass3::po3); camp::Class::declare<MyClass4>("InheritanceTest::MyClass4") .base<MyClass3>() .function("f4", &MyClass4::f4) .property("p4", &MyClass4::p4) .function("overridden", &MyClass4::fo4) .property("overridden", &MyClass4::po4); } } CAMP_AUTO_TYPE(InheritanceTest::MyClass1, &InheritanceTest::declare) CAMP_AUTO_TYPE(InheritanceTest::MyClass2, &InheritanceTest::declare) CAMP_AUTO_TYPE(InheritanceTest::MyClass3, &InheritanceTest::declare) CAMP_AUTO_TYPE(InheritanceTest::MyClass4, &InheritanceTest::declare) #endif // CAMPTEST_INHERITANCE_HPP
34.268293
90
0.599763
IRCAD
9130ffb8e1c78448390bfb7e8b07474ab8b98d11
9,443
cc
C++
bin/zxdb/console/verbs_control.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
bin/zxdb/console/verbs_control.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
bin/zxdb/console/verbs_control.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "garnet/bin/zxdb/console/verbs.h" #include <algorithm> #include "garnet/bin/zxdb/client/session.h" #include "garnet/bin/zxdb/common/err.h" #include "garnet/bin/zxdb/console/command.h" #include "garnet/bin/zxdb/console/command_utils.h" #include "garnet/bin/zxdb/console/console.h" #include "garnet/bin/zxdb/console/output_buffer.h" namespace zxdb { namespace { // help ------------------------------------------------------------------------ const char kHelpShortHelp[] = R"(help / h: Help.)"; const char kHelpHelp[] = R"(help Yo dawg, I heard you like help on your help so I put help on the help in the help.)"; const char kHelpIntro[] = R"(Help! Type "help <topic>" for more information. Command syntax Verbs "step" Applies the "step" verb to the currently selected thread. "mem-read --size=16 0x12345678" Pass a named switch and an argument. Nouns "thread" List available threads "thread 1" Select thread with ID 1 to be the default. Noun-Verb combinations "thread 4 step" Steps thread 4 of the current process regardless of the currently selected thread. "process 1 thread 4 step" Steps thread 4 of process 1 regardless of the currently selected thread or process. )"; std::string FormatGroupHelp(const char* heading, std::vector<std::string>* items) { std::sort(items->begin(), items->end()); std::string help("\n"); help.append(heading); help.append("\n"); for (const auto& line : *items) help += " " + line + "\n"; return help; } std::string GetReference() { std::string help = kHelpIntro; // Group all verbs by their CommandGroup. Add nouns to this since people // will expect, for example, "breakpoint" to be in the breakpoints section. std::map<CommandGroup, std::vector<std::string>> groups; // Get the separate noun reference and add to the groups. help += "\nNouns\n"; std::vector<std::string> noun_lines; for (const auto& pair : GetNouns()) { noun_lines.push_back(pair.second.short_help); groups[pair.second.command_group].push_back(pair.second.short_help); } std::sort(noun_lines.begin(), noun_lines.end()); for (const auto& line : noun_lines) help += " " + line + "\n"; // Add in verbs. for (const auto& pair : GetVerbs()) groups[pair.second.command_group].push_back(pair.second.short_help); help += FormatGroupHelp("General", &groups[CommandGroup::kGeneral]); help += FormatGroupHelp("Process", &groups[CommandGroup::kProcess]); help += FormatGroupHelp("Assembly", &groups[CommandGroup::kAssembly]); help += FormatGroupHelp("Breakpoint", &groups[CommandGroup::kBreakpoint]); help += FormatGroupHelp("Query", &groups[CommandGroup::kQuery]); help += FormatGroupHelp("Step", &groups[CommandGroup::kStep]); return help; } Err DoHelp(ConsoleContext* context, const Command& cmd) { OutputBuffer out; if (cmd.args().empty()) { // Generic help, list topics and quick reference. out.FormatHelp(GetReference()); Console::get()->Output(std::move(out)); return Err(); } const std::string& on_what = cmd.args()[0]; const char* help = nullptr; // Check for a noun. const auto& string_noun = GetStringNounMap(); auto found_string_noun = string_noun.find(on_what); if (found_string_noun != string_noun.end()) { // Find the noun record to get the help. This is guaranteed to exist. const auto& nouns = GetNouns(); help = nouns.find(found_string_noun->second)->second.help; } else { // Check for a verb const auto& string_verb = GetStringVerbMap(); auto found_string_verb = string_verb.find(on_what); if (found_string_verb != string_verb.end()) { // Find the verb record to get the help. This is guaranteed to exist. const auto& verbs = GetVerbs(); help = verbs.find(found_string_verb->second)->second.help; } else { // Not a valid command. out.OutputErr(Err("\"" + on_what + "\" is not a valid command.\n" "Try just \"help\" to get a list.")); Console::get()->Output(std::move(out)); return Err(); } } out.FormatHelp(help); Console::get()->Output(std::move(out)); return Err(); } // quit ------------------------------------------------------------------------ const char kQuitShortHelp[] = R"(quit / q: Quits the debugger.)"; const char kQuitHelp[] = R"(quit Quits the debugger.)"; Err DoQuit(ConsoleContext* context, const Command& cmd) { // This command is special-cased by the main loop so it shouldn't get // executed. return Err(); } // connect --------------------------------------------------------------------- const char kConnectShortHelp[] = R"(connect: Connect to a remote system for debugging.)"; const char kConnectHelp[] = R"(connect <remote_address> Connectes to a debug_agent at the given address/port. Both IP address and port are required. See also "disconnect". Addresses Addresses can be of the form "<host> <port>" or "<host>:<port>". When using the latter form, IPv6 addresses must be [bracketed]. Otherwise the brackets are optional. Examples connect mystem.localnetwork 1234 connect mystem.localnetwork:1234 connect 192.168.0.4:1234 connect 192.168.0.4 1234 connect [1234:5678::9abc] 1234 connect 1234:5678::9abc 1234 connect [1234:5678::9abc]:1234 )"; Err DoConnect(ConsoleContext* context, const Command& cmd, CommandCallback callback = nullptr) { // Can accept either one or two arg forms. std::string host; uint16_t port = 0; if (cmd.args().size() == 0) { return Err(ErrType::kInput, "Need host and port to connect to."); } else if (cmd.args().size() == 1) { Err err = ParseHostPort(cmd.args()[0], &host, &port); if (err.has_error()) return err; } else if (cmd.args().size() == 2) { Err err = ParseHostPort(cmd.args()[0], cmd.args()[1], &host, &port); if (err.has_error()) return err; } else { return Err(ErrType::kInput, "Too many arguments."); } context->session()->Connect(host, port, [callback](const Err& err) { if (err.has_error()) { // Don't display error message if they canceled the connection. if (err.type() != ErrType::kCanceled) Console::get()->Output(err); } else { OutputBuffer msg; msg.Append("Connected successfully.\n"); // Assume if there's a callback this is not being run interactively. // Otherwise, show the usage tip. if (!callback) { msg.Append(Syntax::kWarning, "👉 "); msg.Append(Syntax::kComment, "Normally you will \"run <program path>\" or \"attach " "<process koid>\"."); } Console::get()->Output(std::move(msg)); } if (callback) callback(err); }); Console::get()->Output("Connecting (use \"disconnect\" to cancel)...\n"); return Err(); } // disconnect ------------------------------------------------------------------ const char kDisconnectShortHelp[] = R"(disconnect: Disconnect from the remote system.)"; const char kDisconnectHelp[] = R"(disconnect Disconnects from the remote system, or cancels an in-progress connection if there is one. There are no arguments. )"; Err DoDisconnect(ConsoleContext* context, const Command& cmd, CommandCallback callback = nullptr) { if (!cmd.args().empty()) return Err(ErrType::kInput, "\"disconnect\" takes no arguments."); context->session()->Disconnect([callback](const Err& err) { if (err.has_error()) Console::get()->Output(err); else Console::get()->Output("Disconnected successfully."); // We call the given callbasck if (callback) callback(err); }); return Err(); } // cls ------------------------------------------------------------------------- const char kClsShortHelp[] = "cls: clear screen."; const char kClsHelp[] = R"(cls Clears the contents of the console. Similar to "clear" on a shell. There are no arguments. )"; Err DoCls(ConsoleContext* context, const Command& cmd, CommandCallback callback = nullptr) { if (!cmd.args().empty()) return Err(ErrType::kInput, "\"cls\" takes no arguments."); Console::get()->Clear(); if (callback) callback(Err()); return Err(); } } // namespace void AppendControlVerbs(std::map<Verb, VerbRecord>* verbs) { (*verbs)[Verb::kHelp] = VerbRecord(&DoHelp, {"help", "h"}, kHelpShortHelp, kHelpHelp, CommandGroup::kGeneral); (*verbs)[Verb::kQuit] = VerbRecord(&DoQuit, {"quit", "q"}, kQuitShortHelp, kQuitHelp, CommandGroup::kGeneral); (*verbs)[Verb::kConnect] = VerbRecord(&DoConnect, {"connect"}, kConnectShortHelp, kConnectHelp, CommandGroup::kGeneral); (*verbs)[Verb::kDisconnect] = VerbRecord(&DoDisconnect, {"disconnect"}, kDisconnectShortHelp, kDisconnectHelp, CommandGroup::kGeneral); (*verbs)[Verb::kCls] = VerbRecord(&DoCls, {"cls"}, kClsShortHelp, kClsHelp, CommandGroup::kGeneral); } } // namespace zxdb
30.659091
80
0.617918
PowerOlive
9134061fd02256535a0f48748da9c2f6b4302e72
17,181
cpp
C++
src/OutputStruct.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/OutputStruct.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/OutputStruct.cpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
//------------------------------------------------------------------ // **MEDYAN** - Simulation Package for the Mechanochemical // Dynamics of Active Networks, v3.1 // // Copyright (2015-2016) Papoian Lab, University of Maryland // // ALL RIGHTS RESERVED // // See the MEDYAN web page for more information: // http://www.medyan.org //------------------------------------------------------------------ #include "OutputStruct.hpp" #include <iterator> #include <string> #include "common.h" #include "MathFunctions.h" #include "Parser.h" #include "Bead.h" #include "BranchingPoint.h" #include "Bubble.h" #include "Cylinder.h" #include "Filament.h" #include "Linker.h" #include "MotorGhost.h" #include "Structure/SurfaceMesh/Membrane.hpp" #include "Structure/SurfaceMesh/Vertex.hpp" using namespace mathfunc; /****************************************************************************** OutputStruct for Filaments ******************************************************************************/ //@{ constexpr char OutputStructFilament::name[]; void OutputStructFilament::getFromSystemWithoutChildren() { _id = _filament->getId(); _type = _filament->getType(); _numBeads = _filament->getCylinderVector().size() + 1; _deltaMinusEnd = _filament->getDeltaMinusEnd(); _deltaPlusEnd = _filament->getDeltaPlusEnd(); // Store coordinates _coords.reserve(_numBeads); for (auto cylinder : _filament->getCylinderVector()) _coords.push_back(Vec<3, floatingpoint>(cylinder->getFirstBead()->coordinate())); _coords.push_back(Vec<3, floatingpoint>(_filament->getCylinderVector().back()->getSecondBead()->coordinate())); } void OutputStructFilament::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructFilament::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << " " << _numBeads << " " << _deltaMinusEnd << " " << _deltaPlusEnd << std::endl; for(auto& coord: _coords) for(floatingpoint value: coord) os << value << " "; os << std::endl; } void OutputStructFilament::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type >> _numBeads >> _deltaMinusEnd >> _deltaPlusEnd; std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); _coords.clear(); floatingpoint tmp; while(newIss >> tmp) { mathfunc::Vec< 3, floatingpoint > coord; coord[0] = tmp; newIss >> coord[1] >> coord[2]; _coords.push_back(coord); } } //@} /****************************************************************************** OutputStruct for Linkers ******************************************************************************/ //@{ constexpr char OutputStructLinker::name[]; void OutputStructLinker::getFromSystemWithoutChildren() { _id = _linker->getId(); _type = _linker->getType(); // Store coordinates _coords = {{ vector2Vec<3, floatingpoint>(midPointCoordinate( _linker->getFirstCylinder()->getFirstBead()->vcoordinate(), _linker->getFirstCylinder()->getSecondBead()->vcoordinate(), _linker->getFirstCylinder()->adjustedrelativeposition(_linker->getFirstPosition()) )), vector2Vec<3, floatingpoint>(midPointCoordinate( _linker->getSecondCylinder()->getFirstBead()->vcoordinate(), _linker->getSecondCylinder()->getSecondBead()->vcoordinate(), _linker->getSecondCylinder()->adjustedrelativeposition(_linker->getSecondPosition()) )) }}; } void OutputStructLinker::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructLinker::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << std::endl; for(auto& coord: _coords) for(floatingpoint value: coord) os << value << " "; os << std::endl; } void OutputStructLinker::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type; std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); for(auto& coord: _coords) for(floatingpoint& value: coord) newIss >> value; } //@} /****************************************************************************** OutputStruct for Motors ******************************************************************************/ //@{ constexpr char OutputStructMotor::name[]; void OutputStructMotor::getFromSystemWithoutChildren() { _id = _motor->getId(); _type = _motor->getType(); // Store coordinates _coords = {{ vector2Vec<3, floatingpoint>(midPointCoordinate( _motor->getFirstCylinder()->getFirstBead()->vcoordinate(), _motor->getFirstCylinder()->getSecondBead()->vcoordinate(), _motor->getFirstCylinder()->adjustedrelativeposition(_motor->getFirstPosition()) )), vector2Vec<3, floatingpoint>(midPointCoordinate( _motor->getSecondCylinder()->getFirstBead()->vcoordinate(), _motor->getSecondCylinder()->getSecondBead()->vcoordinate(), _motor->getSecondCylinder()->adjustedrelativeposition(_motor->getSecondPosition()) )) }}; } void OutputStructMotor::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructMotor::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << " " << _bound << std::endl; for(auto& coord: _coords) for(floatingpoint value: coord) os << value << " "; os << std::endl; } void OutputStructMotor::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type >> _bound; std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); for(auto& coord: _coords) for(floatingpoint& value: coord) newIss >> value; } //@} /****************************************************************************** OutputStruct for Branchers ******************************************************************************/ //@{ constexpr char OutputStructBrancher::name[]; void OutputStructBrancher::getFromSystemWithoutChildren() { _id = _brancher->getId(); _type = _brancher->getType(); // Store coordinates _coord = vector2Vec<3, floatingpoint>(_brancher->coordinate); } void OutputStructBrancher::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructBrancher::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << std::endl; for(floatingpoint value: _coord) os << value << " "; os << std::endl; } void OutputStructBrancher::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type; std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); for(floatingpoint& value: _coord) newIss >> value; } //@} /****************************************************************************** OutputStruct for Bubbles ******************************************************************************/ //@{ constexpr char OutputStructBubble::name[]; void OutputStructBubble::getFromSystemWithoutChildren() { _id = _bubble->getId(); _type = _bubble->getType(); // Store coordinates _coord = _bubble->coord; } void OutputStructBubble::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructBubble::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << std::endl; for(floatingpoint value: _coord) os << value << " "; os << std::endl; } void OutputStructBubble::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type; std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); for(floatingpoint& value: _coord) newIss >> value; } //@} /****************************************************************************** OutputStruct for Membranes ******************************************************************************/ //@{ constexpr char OutputStructMembrane::name[]; void OutputStructMembrane::getFromSystemWithoutChildren() { _id = _membrane->getId(); _type = _membrane->getType(); memInfo_ = _membrane->getMesh().extract< Initializer >(); _numVertices = memInfo_.attributeInitializerInfo.vertexCoordinateList.size(); _numTriangles = memInfo_.triangleVertexIndexList.size(); numBorders_ = (memInfo_.borderVertexIndexList.has_value() ? memInfo_.borderVertexIndexList->size() : 0); } void OutputStructMembrane::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); } void OutputStructMembrane::outputFromStoredWithoutChildren(std::ostream& os) { os << name << " " << _id << " " << _type << " " << _numVertices << ' ' << _numTriangles << ' ' << numBorders_ << '\n'; // print coordinates for(const auto& it : memInfo_.attributeInitializerInfo.vertexCoordinateList) { for(floatingpoint value : it) os << value << ' '; os << '\n'; } // print triangles for(const auto& it : memInfo_.triangleVertexIndexList) { for(size_t value : it) os << value << ' '; os << '\n'; } // print borders if(const auto& blist = memInfo_.borderVertexIndexList; blist.has_value()) { for(const auto& border : *blist) { os << border.size() << ' '; // First number is the number of vertices for(auto v : border) os << v << ' '; os << '\n'; } } } void OutputStructMembrane::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _id >> _type >> _numVertices >> _numTriangles >> numBorders_; memInfo_.attributeInitializerInfo.vertexCoordinateList.reserve(_numVertices); memInfo_.triangleVertexIndexList.reserve(_numTriangles); memInfo_.borderVertexIndexList.emplace(); memInfo_.borderVertexIndexList->reserve(numBorders_); for(size_t i = 0; i < _numVertices; ++i) { std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); memInfo_.attributeInitializerInfo.vertexCoordinateList.emplace_back(); auto& coord = memInfo_.attributeInitializerInfo.vertexCoordinateList.back(); // Record coordinates for(floatingpoint& value: coord) newIss >> value; } for(size_t i = 0; i < _numTriangles; ++i) { std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); memInfo_.triangleVertexIndexList.emplace_back(); auto& indices = memInfo_.triangleVertexIndexList.back(); // Record indices for(size_t& value : indices) { newIss >> value; } } for(size_t i = 0; i < numBorders_; ++i) { std::string nextLine; std::getline(is, nextLine); std::istringstream newIss(nextLine); // First number is the number of vertices on this border size_t nv; newIss >> nv; auto& indices = memInfo_.borderVertexIndexList->emplace_back(nv); for(size_t& value : indices) { newIss >> value; } } } //@} /****************************************************************************** OutputStruct for snapshots ******************************************************************************/ //@{ void OutputStructSnapshot::getFromSystem() { getFromSystemWithoutChildren(); for(auto filament: Filament::getFilaments()) { filamentStruct.emplace_back(filament); filamentStruct.back().getFromSystem(); } for(auto linker: Linker::getLinkers()) { linkerStruct.emplace_back(linker); linkerStruct.back().getFromSystem(); } for(auto motor: MotorGhost::getMotorGhosts()) { motorStruct.emplace_back(motor); motorStruct.back().getFromSystem(); } for(auto brancher: BranchingPoint::getBranchingPoints()) { brancherStruct.emplace_back(brancher); brancherStruct.back().getFromSystem(); } for(auto bubble: Bubble::getBubbles()) { bubbleStruct.emplace_back(bubble); bubbleStruct.back().getFromSystem(); } for(auto membrane: Membrane::getMembranes()) { membraneStruct.emplace_back(membrane); membraneStruct.back().getFromSystem(); } // Note: new children should be added here } void OutputStructSnapshot::getFromSystemWithoutChildren() { simulationTime = tau(); _numFilaments = Filament::numFilaments(); _numLinkers = Linker::numLinkers(); _numMotorGhosts = MotorGhost::numMotorGhosts(); _numBranchingPoints = BranchingPoint::numBranchingPoints(); _numBubbles = Bubble::numBubbles(); _numMembranes = Membrane::numMembranes(); } void OutputStructSnapshot::outputFromSystem(std::ostream& os) { getFromSystemWithoutChildren(); outputFromStoredWithoutChildren(os); for(auto filament: Filament::getFilaments()) { filamentStruct.emplace_back(filament); filamentStruct.back().outputFromSystem(os); } for(auto linker: Linker::getLinkers()) { linkerStruct.emplace_back(linker); linkerStruct.back().outputFromSystem(os); } for(auto motor: MotorGhost::getMotorGhosts()) { motorStruct.emplace_back(motor); motorStruct.back().outputFromSystem(os); } for(auto brancher: BranchingPoint::getBranchingPoints()) { brancherStruct.emplace_back(brancher); brancherStruct.back().outputFromSystem(os); } for(auto bubble: Bubble::getBubbles()) { bubbleStruct.emplace_back(bubble); bubbleStruct.back().outputFromSystem(os); } for(auto membrane: Membrane::getMembranes()) { membraneStruct.emplace_back(membrane); membraneStruct.back().outputFromSystem(os); } // Note: new children should be added here } void OutputStructSnapshot::outputFromStored(std::ostream& os) { outputFromStoredWithoutChildren(os); for(auto& it: filamentStruct) { it.outputFromStored(os); } for(auto& it: linkerStruct) { it.outputFromStored(os); } for(auto& it: motorStruct) { it.outputFromStored(os); } for(auto& it: brancherStruct) { it.outputFromStored(os); } for(auto& it: bubbleStruct) { it.outputFromStored(os); } for(auto& it: membraneStruct) { it.outputFromStored(os); } // Note: new children should be added here } void OutputStructSnapshot::outputFromStoredWithoutChildren(std::ostream& os) { os << _snapshot << " " << simulationTime << " " << _numFilaments << " " << _numLinkers << " " << _numMotorGhosts << " " << _numBranchingPoints << " " << _numBubbles << " " << _numMembranes << std::endl; } void OutputStructSnapshot::getFromOutput(std::istream& is, std::istringstream& iss) { iss >> _snapshot >> simulationTime >> _numFilaments >> _numLinkers >> _numMotorGhosts >> _numBranchingPoints >> _numBubbles >> _numMembranes; std::string nextLine; do { std::getline(is, nextLine); if(!is || nextLine.empty()) break; std::istringstream newIss(nextLine); std::string name; newIss >> name; if(name == OutputStructFilament::name) { filamentStruct.emplace_back(nullptr); filamentStruct.back().getFromOutput(is, newIss); } else if(name == OutputStructLinker::name) { linkerStruct.emplace_back(nullptr); linkerStruct.back().getFromOutput(is, newIss); } else if(name == OutputStructMotor::name) { motorStruct.emplace_back(nullptr); motorStruct.back().getFromOutput(is, newIss); } else if(name == OutputStructBrancher::name) { brancherStruct.emplace_back(nullptr); brancherStruct.back().getFromOutput(is, newIss); } else if(name == OutputStructBubble::name) { bubbleStruct.emplace_back(nullptr); bubbleStruct.back().getFromOutput(is, newIss); } else if(name == OutputStructMembrane::name) { membraneStruct.emplace_back(nullptr); membraneStruct.back().getFromOutput(is, newIss); } // TODO: other children } while(true); } //@}
31.012635
115
0.590827
allen-cell-animated
91342f9c3f6c57c5228ee5914a86e8334b981890
4,262
hpp
C++
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
HerrFroehlich/ns3-CompressedSensing
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
[ "MIT" ]
null
null
null
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
HerrFroehlich/ns3-CompressedSensing
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
[ "MIT" ]
null
null
null
src/compressed-sensing/lib/include/Armadillo/armadillo_bits/glue_times_bones.hpp
HerrFroehlich/ns3-CompressedSensing
f5e4e56aeea97794695ecef6183bdaa1b72fd1de
[ "MIT" ]
null
null
null
// Copyright (C) 2008-2012 NICTA (www.nicta.com.au) // Copyright (C) 2008-2012 Conrad Sanderson // // This file is part of the Armadillo C++ library. // It is provided without any warranty of fitness // for any purpose. You can redistribute this file // and/or modify it under the terms of the GNU // Lesser General Public License (LGPL) as published // by the Free Software Foundation, either version 3 // of the License or (at your option) any later version. // (see http://www.opensource.org/licenses for more info) //! \addtogroup glue_times //! @{ //! \brief //! Template metaprogram depth_lhs //! calculates the number of Glue<Tx,Ty, glue_type> instances on the left hand side argument of Glue<Tx,Ty, glue_type> //! i.e. it recursively expands each Tx, until the type of Tx is not "Glue<..,.., glue_type>" (i.e the "glue_type" changes) template<typename glue_type, typename T1> struct depth_lhs { static const uword num = 0; }; template<typename glue_type, typename T1, typename T2> struct depth_lhs< glue_type, Glue<T1,T2,glue_type> > { static const uword num = 1 + depth_lhs<glue_type, T1>::num; }; template<bool is_eT_blas_type> struct glue_times_redirect2_helper { template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X); }; template<> struct glue_times_redirect2_helper<true> { template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X); }; template<uword N> struct glue_times_redirect { template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X); }; template<> struct glue_times_redirect<2> { template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X); }; template<> struct glue_times_redirect<3> { template<typename T1, typename T2, typename T3> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue< Glue<T1,T2,glue_times>,T3,glue_times>& X); }; template<> struct glue_times_redirect<4> { template<typename T1, typename T2, typename T3, typename T4> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue< Glue< Glue<T1,T2,glue_times>, T3, glue_times>, T4, glue_times>& X); }; //! Class which implements the immediate multiplication of two or more matrices class glue_times { public: template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_times>& X); template<typename T1> arma_hot inline static void apply_inplace(Mat<typename T1::elem_type>& out, const T1& X); template<typename T1, typename T2> arma_hot inline static void apply_inplace_plus(Mat<typename T1::elem_type>& out, const Glue<T1, T2, glue_times>& X, const sword sign); template<typename eT1, typename eT2> inline static void apply_mixed(Mat<typename promote_type<eT1,eT2>::result>& out, const Mat<eT1>& X, const Mat<eT2>& Y); template<typename eT, const bool do_trans_A, const bool do_trans_B> arma_inline static uword mul_storage_cost(const Mat<eT>& A, const Mat<eT>& B); template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_scalar_times> arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const eT val); template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_trans_C, const bool do_scalar_times> arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const Mat<eT>& C, const eT val); template<typename eT, const bool do_trans_A, const bool do_trans_B, const bool do_trans_C, const bool do_trans_D, const bool do_scalar_times> arma_hot inline static void apply(Mat<eT>& out, const Mat<eT>& A, const Mat<eT>& B, const Mat<eT>& C, const Mat<eT>& D, const eT val); }; class glue_times_diag { public: template<typename T1, typename T2> arma_hot inline static void apply(Mat<typename T1::elem_type>& out, const Glue<T1, T2, glue_times_diag>& X); }; //! @}
31.109489
149
0.725012
HerrFroehlich
9136118bf7e85372ff0889915166fd9dec2a4405
3,810
cpp
C++
qt-creator-opensource-src-4.6.1/src/plugins/vcsbase/submiteditorfile.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/plugins/vcsbase/submiteditorfile.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/plugins/vcsbase/submiteditorfile.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "submiteditorfile.h" #include "vcsbasesubmiteditor.h" #include <utils/fileutils.h> #include <QFileInfo> using namespace VcsBase; using namespace VcsBase::Internal; using namespace Utils; /*! \class VcsBase::Internal::SubmitEditorFile \brief The SubmitEditorFile class provides a non-saveable IDocument for submit editor files. */ SubmitEditorFile::SubmitEditorFile(const VcsBaseSubmitEditorParameters *parameters, VcsBaseSubmitEditor *parent) : Core::IDocument(parent), m_modified(false), m_editor(parent) { setId(parameters->id); setMimeType(QLatin1String(parameters->mimeType)); setTemporary(true); connect(m_editor, &VcsBaseSubmitEditor::fileContentsChanged, this, &Core::IDocument::contentsChanged); } Core::IDocument::OpenResult SubmitEditorFile::open(QString *errorString, const QString &fileName, const QString &realFileName) { if (fileName.isEmpty()) return OpenResult::ReadError; FileReader reader; if (!reader.fetch(realFileName, QIODevice::Text, errorString)) return OpenResult::ReadError; const QString text = QString::fromLocal8Bit(reader.data()); if (!m_editor->setFileContents(text.toUtf8())) return OpenResult::CannotHandle; setFilePath(FileName::fromString(fileName)); setModified(fileName != realFileName); return OpenResult::Success; } QByteArray SubmitEditorFile::contents() const { return m_editor->fileContents(); } bool SubmitEditorFile::setContents(const QByteArray &contents) { return m_editor->setFileContents(contents); } void SubmitEditorFile::setModified(bool modified) { if (m_modified == modified) return; m_modified = modified; emit changed(); } bool SubmitEditorFile::save(QString *errorString, const QString &fileName, bool autoSave) { const FileName fName = fileName.isEmpty() ? filePath() : FileName::fromString(fileName); FileSaver saver(fName.toString(), QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text); saver.write(m_editor->fileContents()); if (!saver.finalize(errorString)) return false; if (autoSave) return true; setFilePath(FileName::fromUserInput(fName.toFileInfo().absoluteFilePath())); setModified(false); if (!errorString->isEmpty()) return false; emit changed(); return true; } Core::IDocument::ReloadBehavior SubmitEditorFile::reloadBehavior(ChangeTrigger state, ChangeType type) const { Q_UNUSED(state) Q_UNUSED(type) return BehaviorSilent; }
32.288136
114
0.691339
kevinlq
9139519824739e375fe970eb2975f38416c31c21
4,381
cpp
C++
tasksexplorerd/task/system_helpers.cpp
astavonin/Tasks-Explorer
3feb2d9a0a4694812de6aa895a809899c62fe5c1
[ "BSD-3-Clause" ]
40
2015-03-20T13:23:16.000Z
2021-07-20T14:17:21.000Z
tasksexplorerd/task/system_helpers.cpp
varenc/Tasks-Explorer
85558fad7dd48fd2f81bcc58193f5cb4a6aaf263
[ "BSD-3-Clause" ]
7
2016-08-01T21:01:25.000Z
2018-04-28T10:34:03.000Z
tasksexplorerd/task/system_helpers.cpp
varenc/Tasks-Explorer
85558fad7dd48fd2f81bcc58193f5cb4a6aaf263
[ "BSD-3-Clause" ]
9
2015-01-29T19:28:17.000Z
2018-04-30T19:08:52.000Z
#include "system_helpers.h" #include <stdio.h> #include <utils.h> #include <prettyprint.hpp> #include <string> namespace tasks { proc_info_vec build_tasks_list() { static size_t maxProcsCount = 500; bool done = false; proc_info_vec procs( maxProcsCount ); static const int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; do { size_t length = maxProcsCount * sizeof( kinfo_proc ); sysctl( (int *)name, ( sizeof( name ) / sizeof( *name ) ) - 1, &procs[0], &length, nullptr, 0 ); if( length != 0 ) { done = true; procs.resize( length / sizeof( kinfo_proc ) ); } else { sysctl( (int *)name, ( sizeof( name ) / sizeof( *name ) ) - 1, nullptr, &length, nullptr, 0 ); maxProcsCount = length / sizeof( kinfo_proc ) * 1.5; procs.resize( maxProcsCount ); } } while( !done ); return procs; } boost::optional<std::vector<char>> read_proc_args( pid_t pid, logger_ptr log ) { boost::optional<std::vector<char>> res; if( pid == 0 ) // we will not be able to extract data for kernel_task return res; static int argmax = [&log]() -> int { int name[] = {CTL_KERN, KERN_ARGMAX, 0}; int argmax = 0; size_t size = sizeof( argmax ); int ret = sysctl( name, 2, &argmax, &size, nullptr, 0 ); if( ret != 0 ) { log->error( "{}: unable to get argmax, will use 1MB instead", __func__ ); argmax = 1024 * 1024; } return argmax; }(); std::vector<char> procargv( argmax ); int name[] = {CTL_KERN, KERN_PROCARGS2, pid}; size_t size = argmax; int err = sysctl( name, 3, &procargv[0], &size, nullptr, 0 ); if( err != 0 ) log->warn( "{}: unable to get environment for PID {}", __func__, pid ); else res = procargv; return res; } proc_args parse_proc_args( const std::vector<char> &procargv, logger_ptr /*log*/ ) { proc_args parsedArgs; if( procargv.size() < sizeof( int ) ) return parsedArgs; const char *all_arguments = &procargv[0]; int argc = *( (int *)all_arguments ); parsedArgs.path_name.assign( all_arguments + sizeof( argc ) ); static const char app[] = ".app/"; auto appBegin = parsedArgs.path_name.rfind( app ); if( appBegin != std::string::npos ) { auto nameBegin = parsedArgs.path_name.rfind( "/", appBegin ) + 1; parsedArgs.app_name.assign( parsedArgs.path_name, nameBegin, appBegin - nameBegin + sizeof( app ) - 2 ); } else { auto execBegin = parsedArgs.path_name.rfind( "/" ) + 1; parsedArgs.app_name.assign( parsedArgs.path_name, execBegin, appBegin - execBegin ); } all_arguments += sizeof( argc ) + parsedArgs.path_name.length(); while( *( ++all_arguments ) != '\0' ) { } while( *( ++all_arguments ) == '\0' ) { } if( argc > 0 ) { const char *ptr = all_arguments; for( int i = 0; i < argc; ++i ) { std::string arg( ptr ); ptr += arg.length() + 1; parsedArgs.argv.push_back( std::move( arg ) ); } all_arguments = ptr; } all_arguments--; do { if( *all_arguments == '\0' ) { all_arguments++; if( *all_arguments == '\0' ) break; else { auto pos = strchr( all_arguments, '=' ); parsedArgs.env.emplace( std::string( all_arguments, pos - all_arguments ), std::string( pos + 1 ) ); } } all_arguments++; } while( true ); return parsedArgs; } std::ostream &operator<<( std::ostream &os, const proc_args &p ) { os << "struct proc_args(" << std::hex << &p << std::dec << ") \n{\n" << "app_name: " << p.app_name << "\n" << "path_name: " << p.path_name << "\n" << "argv(" << p.argv.size() << "):" << p.argv << "\n" << "env(" << p.env.size() << "):" << p.env << "\n" << "}"; return os; } }
27.904459
79
0.497375
astavonin