blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
3ba45dbd8a6a26fd67249ebf90f5e4b6d2b9978e
df9b3c94b9aae189112fd1a16b4e4974a364dbee
/src/cpp_lib/narray.h
9f5173aaabf8182a6896976e5bda5f2f1c587e24
[]
no_license
ypei92/Latte-Compiler
a16b5b47cf0face6d89ec7bcb3f99c650aa04cd4
3015bd93febe1feb2339d8ae01656b4ffe4f9984
refs/heads/master
2020-12-24T18:51:06.010591
2016-05-16T13:15:20
2016-05-16T13:15:20
57,238,366
0
0
null
null
null
null
UTF-8
C++
false
false
657
h
narray.h
#include <vector> #include <math.h> #include <iostream> using namespace std; float* xavier(vector<int> dim){ int size = 1; float fan_in = 1.0; for(int i = 0; i < dim.size() - 1; ++i){ size *= dim[i]; fan_in *= dim[i]; } size *= dim[dim.size()-1]; float scale = sqrt(3.0/fan_in); float* buffer = new float[size]; for(int i = 0; i < size; ++i){ buffer[i] = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX)) - 2 * scale - scale; cout<< buffer[i] <<endl; } return buffer; } int main(){ vector<int> dim; dim.push_back(3); dim.push_back(2); xavier(dim); }
830d115f27ed694409d5f6885d14c4adc9ab7227
a97304ac7e4391d46c1cde399dc90a4d8422bab0
/sketch_feb28b — копия.ino
ba1f673c6a1558aa1fa8536a9288596ab8cd2a80
[]
no_license
TinyAxolotl/AutoLogger
e90ccaa2954f31127b1158df1fc204f6c58444eb
01abdb7509e54aac5fbe8a8634e253b0721b83d7
refs/heads/main
2023-04-18T13:10:46.963138
2021-04-28T13:37:13
2021-04-28T13:37:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,859
ino
sketch_feb28b — копия.ino
#include <Wire.h> #include <SPI.h> #include <Arduino.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <MPU6050_tockn.h> #include <BMx280I2C.h> #include <SD.h> #define I2C_ADDRESS 0x76 #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels MPU6050 mpu6050(Wire); BMx280I2C bmx280(I2C_ADDRESS); Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); File myFile; int numOfFile = 0; String nameOfFile = "logger"; const int chipSelect = 4; long timer = 0, timers = 0; double currentPressure = 0, groundPressure = 0, altitude = 0; long rawAccX, rawAccY, rawAccZ; double total, max_total; void setup() { Serial.begin(115200); pinMode(PC13, OUTPUT); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64 Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } //delay(2000); display.cp437(true); // Use full 256 char 'Code Page 437' font display.clearDisplay(); display.setTextColor(WHITE); display.setTextSize(3); display.setCursor(30,20); display.println(utf8rus("ХАИ")); display.setTextSize(1); display.setCursor(20,50); display.println(utf8rus("Кафедра 501")); display.display(); delay(5000); display.clearDisplay(); display.setCursor(0,0); //while (!Serial); display.print("MPU6050..."); display.display(); Wire.begin(); mpu6050.begin(); mpu6050.writeMPU6050(MPU6050_ACCEL_CONFIG, 0x18); mpu6050.calcGyroOffsets(true); display.println("OK!"); display.display(); display.print("BMP280..."); display.display(); if (!bmx280.begin()) { Serial.println("begin() failed. check your BMx280 Interface and I2C Address."); display.println("ERROR! ERROR! ERROR!"); display.display(); while (1); } bmx280.resetToDefaults(); bmx280.writeOversamplingPressure(BMx280MI::OSRS_P_x16); bmx280.writeOversamplingTemperature(BMx280MI::OSRS_T_x16); display.println("OK!"); display.display(); bmx280.measure(); for(int i = 0; i<50; i++) { while(!bmx280.hasValue()) {} groundPressure = bmx280.getPressure64(); bmx280.measure(); } bmx280.measure(); display.print("SD card..."); display.display(); Serial.print("Initializing SD card..."); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); display.println("ERROR! ERROR! ERROR!"); display.display(); // don't do anything more: while (1); } Serial.println("card initialized."); display.println("OK!"); display.display(); nameOfFile += String(numOfFile); nameOfFile += String(".txt"); numOfFile++; while(SD.exists(nameOfFile)) { nameOfFile = "logger"; numOfFile++; nameOfFile += String(numOfFile); nameOfFile += String(".txt"); } while(!SD.exists(nameOfFile)) { if (!SD.exists(nameOfFile)) { Serial.println("Creating file..."); myFile = SD.open(nameOfFile, FILE_WRITE); myFile.close(); } if (SD.exists(nameOfFile)) { Serial.println("file exists."); } else { Serial.println("file exist."); } } display.println("File name is:"); display.setTextSize(1); display.println(nameOfFile); display.display(); delay(1000); digitalWrite(PC13, HIGH); // Initialization successful } void loop() { String dataString = ""; mpu6050.update(); if(millis() - timers > 50) { char buf[12]; display.clearDisplay(); display.setTextColor(WHITE); display.setTextSize(2); display.setCursor(0,0); display.println(utf8rus("Ускорение:")); sprintf(buf, "%2.3f", double(total/2048)); display.print(buf); display.println(" G"); display.println(utf8rus("максимум:")); sprintf(buf, "%2.3f", double(max_total/2048)); display.print(buf); display.println(" G"); display.display(); timers = millis(); } if(millis() - timer > 2){ /* Serial.println("======================================================="); Serial.print("temp : ");Serial.println(mpu6050.getTemp());*/ /*Serial.print("accX : ");Serial.print(mpu6050.getAccX()); Serial.print("\taccY : ");Serial.print(mpu6050.getAccY()); Serial.print("\taccZ : ");Serial.println(mpu6050.getAccZ()); Serial.print("rawAccX : ");Serial.print(mpu6050.getRawAccX()); Serial.print("\trawAccY : ");Serial.print(mpu6050.getRawAccY()); Serial.print("\trawAccZ : ");Serial.println(mpu6050.getRawAccZ());*/ dataString += String(millis()); dataString += String(","); dataString += String(mpu6050.getAccX()); dataString += String(","); dataString += String(mpu6050.getAccY()); dataString += String(","); dataString += String(mpu6050.getAccZ()); dataString += String(","); rawAccX = mpu6050.getRawAccX(); dataString += String(rawAccX); dataString += String(","); rawAccY = mpu6050.getRawAccY(); dataString += String(rawAccY); dataString += String(","); rawAccZ = mpu6050.getRawAccZ(); dataString += String(rawAccZ); dataString += String(","); total = sqrt(pow(rawAccX, 2) + pow(rawAccY, 2) + pow(rawAccZ, 2)); if(total > max_total) { max_total = total; } dataString += String(total); dataString += String(","); dataString += String(mpu6050.getGyroX()); dataString += String(","); dataString += String(mpu6050.getGyroY()); dataString += String(","); dataString += String(mpu6050.getGyroZ()); dataString += String(","); if(bmx280.hasValue()) { currentPressure = bmx280.getPressure64(); //Serial.println(currentPressure); altitude = (44330 * (1-pow((currentPressure/groundPressure),0.1903))); //Serial.println(altitude); bmx280.measure(); } dataString += String(currentPressure); dataString += String(","); dataString += String(altitude); dataString += String(";"); myFile = SD.open(nameOfFile, FILE_WRITE); if (myFile) { myFile.println(dataString); myFile.close(); // print to the serial port too: Serial.println(dataString); } /* Serial.print("gyroX : ");Serial.print(mpu6050.getGyroX()); Serial.print("\tgyroY : ");Serial.print(mpu6050.getGyroY()); Serial.print("\tgyroZ : ");Serial.println(mpu6050.getGyroZ()); Serial.print("accAngleX : ");Serial.print(mpu6050.getAccAngleX()); Serial.print("\taccAngleY : ");Serial.println(mpu6050.getAccAngleY()); Serial.print("gyroAngleX : ");Serial.print(mpu6050.getGyroAngleX()); Serial.print("\tgyroAngleY : ");Serial.print(mpu6050.getGyroAngleY()); Serial.print("\tgyroAngleZ : ");Serial.println(mpu6050.getGyroAngleZ()); Serial.print("angleX : ");Serial.print(mpu6050.getAngleX()); Serial.print("\tangleY : ");Serial.print(mpu6050.getAngleY()); Serial.print("\tangleZ : ");Serial.println(mpu6050.getAngleZ()); Serial.println("=======================================================\n");*/ timer = millis(); } } /* Функция перекодировки русских букв из UTF-8 в Win-1251 */ String utf8rus(String source) { int i,k; String target; unsigned char n; char m[2] = { '0', '\0' }; k = source.length(); i = 0; while (i < k) { n = source[i]; i++; if (n >= 0xC0) { switch (n) { case 0xD0: { n = source[i]; i++; if (n == 0x81) { n = 0xA8; break; } if (n >= 0x90 && n <= 0xBF) n = n + 0x30; break; } case 0xD1: { n = source[i]; i++; if (n == 0x91) { n = 0xB8; break; } if (n >= 0x80 && n <= 0x8F) n = n + 0x70; break; } } } m[0] = n; target = target + String(m); } return target; }
389c5cbdaf433400c3edecff0c2704758e4c3c3b
da1ffd58bffb95b47d48872e2d85facaa0395bcd
/1.tan_c++/9.use_class_obj/c9-8.fun_quote_arg.cpp
790ec8ba2b0a8c22e2b0e57a98d6e096a67d942a
[]
no_license
wcybxzj/cplusplus_www
94e303faaa4331220949b81ff5aee1736f722ec9
eda796f52c8fa88cfae5f8c99817e583785faf02
refs/heads/master
2020-04-19T18:29:34.882672
2019-01-30T16:22:08
2019-01-30T16:22:08
168,364,708
0
0
null
null
null
null
UTF-8
C++
false
false
314
cpp
c9-8.fun_quote_arg.cpp
#include <iostream> using namespace std; class Time{ public: Time(int h, int m, int s): \ hour(h),minute(m),sec(s){} int hour; int minute; int sec; }; void fun(Time &t) { t.hour = 123; } int main(int argc, const char *argv[]) { Time t1(10, 20, 30); fun(t1); cout << t1.hour <<endl; return 0; }
5266a7ffe4159ce11d6ebcd08a12253c40c2043a
d70ffa58b4cfeb21a9d7d51d530369488b2c07a2
/Graph Valid Tree.cpp
d3ff16e832291f44c6d0cdbe8ac4e1a523781431
[]
no_license
pramod3009/leetcode
0eb0c04e537d4a353114594debc1c792b7783e65
5f4e165b7e7d0e99607522a62a1b29d165559a83
refs/heads/master
2023-06-21T11:19:05.445737
2021-07-25T22:44:50
2021-07-25T22:44:50
273,813,595
0
1
null
null
null
null
UTF-8
C++
false
false
842
cpp
Graph Valid Tree.cpp
class Solution { public: bool result = true; map<int, vector<int>> graph; void dfs(int node, int parent, vector<bool> &visited){ if(visited[node]){ result = false; return; } visited[node] = true; for(auto enemy : graph[node]){ if(enemy != parent){ dfs(enemy, node, visited); } } } bool validTree(int n, vector<vector<int>>& edges) { for(auto &edge : edges){ graph[edge[0]].push_back(edge[1]); graph[edge[1]].push_back(edge[0]); } vector<bool> visited(n, false); dfs(0, -1, visited); for(auto v : visited){ if(!v){ return false; } } return result; } };
7d7087c442428334c2fb52c0f5d724c21b3917eb
451a19113f4eab676a23862ea201195b3cf08527
/src/Image.cpp
3b288953adfbef254c3dcc31715049fd3715f639
[]
no_license
daviddoria/PatchMatchImageStack
49a66ff9a571f13f417bcdb95625bfacb3da0359
28f667b26b548d56f99bfe79a3d6800f78a54955
refs/heads/master
2021-01-01T20:48:30.956886
2012-05-26T11:07:23
2012-05-26T11:07:23
4,435,912
3
0
null
null
null
null
UTF-8
C++
false
false
6,880
cpp
Image.cpp
#include "main.h" #include "Image.h" #include "itkVectorImage.h" #include "itkImageRegionIterator.h" #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "header.h" // The rest of the Image class is inlined. // Inlining the destructor makes the compiler unhappy, so it goes here instead // If you think there is a bug here, there is almost certainly // actually a bug somewhere else which is corrupting the memory table // or the image header. It will often crash here as a result because // this is where things get freed. Image::~Image() { //printf("In image destructor\n"); fflush(stdout); // if (!refCount) { // //printf("Deleting NULL image\n"); fflush(stdout); // return; // the image was a dummy // } // //printf("Decremementing refcount\n"); fflush(stdout); // refCount[0]--; // if (*refCount <= 0) { // //printf("Deleting image\n"); fflush(stdout); // //debug(); // delete refCount; // //printf("refCount deleted\n"); fflush(stdout); // //debug(); // delete[] memory; // //printf("data deleted\n"); fflush(stdout); // //debug(); // } //printf("Leaving image desctructor\n"); fflush(stdout); } void Image::WriteMeta(const std::string& filename) { typedef itk::VectorImage<float, 2> ImageType; ImageType::Pointer itkimage = ImageType::New(); itk::Index<2> itkcorner = {{0,0}}; itk::Size<2> itksize = {{this->width, this->height}}; itk::ImageRegion<2> itkregion(itkcorner, itksize); itkimage->SetRegions(itkregion); itkimage->SetNumberOfComponentsPerPixel(this->channels); itkimage->Allocate(); itk::ImageRegionIterator<ImageType> imageIterator(itkimage, itkregion); while(!imageIterator.IsAtEnd()) { ImageType::PixelType pixel; pixel.SetSize(this->channels); for(unsigned int channel = 0; channel < this->channels; ++channel) { pixel[channel] = this->operator()(imageIterator.GetIndex()[0], imageIterator.GetIndex()[1])[channel]; } imageIterator.Set(pixel); ++imageIterator; } typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(itkimage); writer->Update(); } void Image::WriteMask(const std::string& filename) { if(this->channels != 1) { std::cerr << "Can't WriteMask with an image with " << this->channels << " channels." << std::endl; return; } typedef itk::Image<unsigned char, 2> ImageType; ImageType::Pointer itkimage = ImageType::New(); itk::Index<2> itkcorner = {{0,0}}; itk::Size<2> itksize = {{this->width, this->height}}; itk::ImageRegion<2> itkregion(itkcorner, itksize); itkimage->SetRegions(itkregion); itkimage->Allocate(); itk::ImageRegionIterator<ImageType> imageIterator(itkimage, itkregion); while(!imageIterator.IsAtEnd()) { ImageType::PixelType pixel = 255. * this->operator()(imageIterator.GetIndex()[0], imageIterator.GetIndex()[1])[0]; imageIterator.Set(pixel); ++imageIterator; } typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(itkimage); writer->Update(); } void Image::WritePNG(const std::string& filename) { if(this->channels < 3) { std::cerr << "Can't WritePNG with an image with only " << this->channels << " channels." << std::endl; return; } typedef itk::Image<itk::CovariantVector<unsigned char, 3> , 2> ImageType; ImageType::Pointer itkimage = ImageType::New(); itk::Index<2> itkcorner = {{0,0}}; itk::Size<2> itksize = {{this->width, this->height}}; itk::ImageRegion<2> itkregion(itkcorner, itksize); itkimage->SetRegions(itkregion); itkimage->Allocate(); itk::ImageRegionIterator<ImageType> imageIterator(itkimage, itkregion); while(!imageIterator.IsAtEnd()) { ImageType::PixelType pixel; for(unsigned int channel = 0; channel < 3; ++channel) { pixel[channel] = 255. * this->operator()(imageIterator.GetIndex()[0], imageIterator.GetIndex()[1])[channel]; } imageIterator.Set(pixel); ++imageIterator; } typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(itkimage); writer->Update(); } void Image::Zero() { for(unsigned int x = 0; x < this->width; ++x) { for(unsigned int y = 0; y < this->height; ++y) { for(unsigned int c = 0; c < this->channels; ++c) { this->operator()(x,y)[c] = 0; } } } } // Window Window::CopyData(Window im) // { // // if(im.width != this->width || im.height != this->height || im.channels != this->channels) // // { // // std::cerr << "im: " << im.width << " " << im.height << " " << im.channels << std::endl; // // std::cerr << "this: " << this->width << " " << this->height << " " << this->channels << std::endl; // // throw std::runtime_error("Can only copy images of the same size!"); // // } // // std::cout << "im: " << im.width << " " << im.height << " " << im.channels << std::endl; // *this = Image(im.width, im.height, 1, im.channels); // std::cout << "this: " << this->width << " " << this->height << " " << this->channels << std::endl; // // for(unsigned int x = 0; x < this->width; ++x) // { // for(unsigned int y = 0; y < this->height; ++y) // { // for(unsigned int c = 0; c < this->channels; ++c) // { // //this->operator()(x,y)[c] = im(x,y)[c]; // (*this)(x,y)[c] = im(x,y)[c]; // } // } // } // } void Image::CopyData(Image im) { if(im.width != this->width || im.height != this->height || im.channels != this->channels) { std::cerr << "im: " << im.width << " " << im.height << " " << im.channels << std::endl; std::cerr << "this: " << this->width << " " << this->height << " " << this->channels << std::endl; throw std::runtime_error("Can only copy images of the same size!"); } // std::cout << "im: " << im.width << " " << im.height << " " << im.channels << std::endl; // *this = Image(im.width, im.height, 1, im.channels); // std::cout << "this: " << this->width << " " << this->height << " " << this->channels << std::endl; for(unsigned int x = 0; x < this->width; ++x) { for(unsigned int y = 0; y < this->height; ++y) { for(unsigned int c = 0; c < this->channels; ++c) { //this->operator()(x,y)[c] = im(x,y)[c]; (*this)(x,y)[c] = im(x,y)[c]; } } } } void Image::SetAllComponents(const int x, const int y, const float value) { for(unsigned int c = 0; c < this->channels; ++c) { (*this)(x,y)[c] = value; } } #include "footer.h"
8cb5614b96465ddc0319bc7258bdc72942cd05ef
c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5
/summer_2k15_coding/codeforces/311/1.cpp
e08002d3880ed7a185224b04ad2cb7e12360fb03
[]
no_license
crystal95/Competetive-Programming-at-different-platforms
c9ad1684f6258539309d07960ed6abfa7d1a16d0
92d283171b0ae0307e9ded473c6eea16f62cb60e
refs/heads/master
2021-01-09T21:44:28.175506
2016-03-27T21:26:26
2016-03-27T21:26:26
54,848,617
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
cpp
1.cpp
#include <numeric> #include <string> #include <functional> #include<stdio.h> #include<iostream> #include<vector> #include<algorithm> using namespace std; #define fr(i,n) for(i=0;i<n;i++) typedef vector<int> vi; typedef vector<long long int > vll; typedef long long int ll; typedef vector<unsigned long long int > vull; typedef unsigned long long int ull; int main () { long long int i,j,k,l,n,m,min1,min2,min3,max1,max2,max3,ans1,ans2,ans3,tmp=0; cin>>n; cin>>min1>>max1>>min2>>max2>>min3>>max3; tmp=min1+min2+min3;ans1=min1;ans2=min2;ans3=min3; if(tmp<n) { if(tmp-min1+max1<=n) { tmp=tmp-min1+max1; ans1=max1; } else { tmp=tmp-min1; ans1=n-tmp; tmp+=n-tmp; } } if(tmp<n) { if(tmp-min2+max2<=n) { tmp=tmp-min2+max2; ans2=max2; } else { tmp=tmp-min2; ans2=n-tmp; tmp+=n-tmp; } } if(tmp<n) { if(tmp-min3+max3<=n) { tmp=tmp-min3+max3; ans3=max3; } else { tmp=tmp-min3; ans3=n-tmp; tmp+=n-tmp; } } cout<<ans1<<" "<<ans2<<" "<<ans3<<endl; return 0; }
bf3a2caff4e9a05c251cade07cf841cdea05cfe3
80d926e7590cf3a1a034758101c232d5d346eb1d
/src/petuum_ps_common/include/ps_app.hpp
ee1e2b5a86c15a7143b6c6430d785beba933d5dd
[ "BSD-3-Clause" ]
permissive
thudzj/bosen
ee9a6176cdf2b228a3ea0da4bc445939a00d447a
6135a86f6a8126e3b46491598eb97fb1de04628b
refs/heads/master
2020-04-17T03:40:45.702351
2016-08-24T02:03:59
2016-08-24T02:03:59
66,038,408
1
0
null
null
null
null
UTF-8
C++
false
false
5,345
hpp
ps_app.hpp
// Author: Binghong Chen // Date: 2016.06.30 #include <petuum_ps_common/include/petuum_ps.hpp> #include <petuum_ps_common/include/system_gflags.hpp> //#include <petuum_ps_common/include/configs.hpp> //#include <petuum_ps_common/util/utils.hpp> #include <thread> #include <map> #include <vector> #include <cstdint> #include <glog/logging.h> #include <gflags/gflags.h> namespace petuum { enum RowType { kUndefinedRow = 0 , kDenseFloatRow = 1 , kDenseIntRow = 2 , kSparseFloatRow = 3 , kSparseIntRow = 4 }; struct TableConfig { // Required config for table. std::string name; // name is used to fetch the table RowType row_type{kUndefinedRow}; int64_t num_cols{-1}; int64_t num_rows{-1}; int staleness{0}; // Optional configs // Number of rows to cache in process cache. Default -1 means all rows. int64_t num_rows_to_cache{-1}; // Estimated upper bound # of pending oplogs in terms of # of rows. Default // -1 means all rows. int64_t num_oplog_rows{-1}; // kDenseRowOpLog or kSparseRowOpLog int oplog_type{RowOpLogType::kDenseRowOpLog}; }; class PsApp { public: void Run(int num_worker_threads=1) { process_barrier_.reset(new boost::barrier(num_worker_threads)); // Step 1.0. Register common row types PSTableGroup::RegisterRow< DenseRow<float>>(kDenseFloatRow); PSTableGroup::RegisterRow< DenseRow<int32_t>>(kDenseIntRow); PSTableGroup::RegisterRow< SparseRow<float>>(kSparseFloatRow); PSTableGroup::RegisterRow< SparseRow<int>>(kSparseIntRow); std::vector<TableConfig> configs = ConfigTables(); // Step 1.1. Initialize Table Group TableGroupConfig table_group_config; table_group_config.num_comm_channels_per_client = 1; table_group_config.num_total_clients = FLAGS_num_clients; table_group_config.num_tables = configs.size(); GetHostInfos(FLAGS_hostfile, &table_group_config.host_map); table_group_config.client_id = FLAGS_client_id; // +1 to include the main() thread table_group_config.num_local_app_threads = num_worker_threads + 1; // Consistency model table_group_config.consistency_model = SSPPush; // False to disallow table access for the main thread. PSTableGroup::Init(table_group_config, false); client_id_ = FLAGS_client_id; // Create Tables for (int i = 0; i < configs.size(); ++i) { auto config = ConvertTableConfig(configs[i]); PSTableGroup::CreateTable(i, config); table_names_[configs[i].name] = i; } PSTableGroup::CreateTableDone(); InitApp(); // Spin num_worker_threads to run. LOG(INFO) << "Starting program with " << num_worker_threads << " threads " << "on client " << table_group_config.client_id; std::vector<std::thread> threads(num_worker_threads); for (auto& thr : threads) { thr = std::thread(&PsApp::RunWorkerThread, this); } for (auto& thr : threads) { thr.join(); } // Shutdown PSTableGroup PSTableGroup::ShutDown(); LOG(INFO) << "Program finished and shut down!"; } protected: PsApp() : thread_counter_(0) {}; ~PsApp() {}; // InitApp() can data loading in single-thread. Or it can do nothing. It may // not access PS table. virtual void InitApp() = 0; // Return a set of table configuration. See TableConfig struct. virtual std::vector<TableConfig> ConfigTables() = 0; virtual void WorkerThread(int client_id, int thread_id) = 0; template<typename V> Table<V> GetTable(const std::string& table_name) { auto it = table_names_.find(table_name); CHECK(it != table_names_.cend()) << "Table " << table_name << " was not registered"; return PSTableGroup::GetTableOrDie<V>(it->second); } private: void RunWorkerThread() { PSTableGroup::RegisterThread(); int thread_id = thread_counter_++; WorkerThread(client_id_, thread_id); PSTableGroup::DeregisterThread(); } // Convert from a simplified TableConfig to ClientTableConfig ClientTableConfig ConvertTableConfig(const TableConfig& config) { // Check required fields in TableConfig CHECK_NE("", config.name) << "Table name must be set"; CHECK_NE(-1, config.num_rows) << "Table " << config.name << " num_rows must be set."; CHECK_NE(-1, config.num_cols) << "Table " << config.name << " num_cols must be set."; CHECK_NE(kUndefinedRow, config.row_type) << "Table " << config.name << " row_type must be set."; ClientTableConfig table_config; table_config.table_info.table_staleness = config.staleness; table_config.table_info.row_type = config.row_type; table_config.table_info.row_capacity = config.num_cols; table_config.process_cache_capacity = config.num_rows_to_cache == -1 ? config.num_rows : config.num_rows_to_cache; table_config.table_info.row_oplog_type = config.oplog_type; table_config.oplog_capacity = config.num_oplog_rows == -1 ? config.num_rows : config.num_oplog_rows; table_config.table_info.dense_row_oplog_capacity = table_config.table_info.row_capacity; return table_config; } protected: boost::scoped_ptr<boost::barrier> process_barrier_; private: std::atomic<int> thread_counter_; int client_id_; // Map table name to PS's internal table ID. std::map<std::string, int> table_names_; }; } // namespace petuum
d937c6016211b615349f20519c673635d9b9f78e
6f193dc4945caca3e445d016c8743e29cdddf7d0
/motor1.2.ino
6bea50376e06cb8d58340fdbe471b51f21348ed9
[]
no_license
Andreea200318/UTILITY-WEATHER-ROVER
725b7340fd9051990ad2810e44f72e5cf2d1a377
85bd62ff7473092031f79fb6334c6562989e9903
refs/heads/main
2023-04-17T18:26:52.129368
2021-04-23T16:16:36
2021-04-23T16:16:36
360,931,446
0
0
null
null
null
null
UTF-8
C++
false
false
1,910
ino
motor1.2.ino
#include <AFMotor.h> #include <NewPing.h> #include <Servo.h> #define TRIG_PIN A0 #define ECHO_PIN A1 NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); AF_DCMotor motor1(1, MOTOR12_1KHZ); AF_DCMotor motor2(2, MOTOR12_1KHZ); AF_DCMotor motor3(3, MOTOR34_1KHZ); AF_DCMotor motor4(4, MOTOR34_1KHZ); Servo myservo; int distance = 100; int speedSet = 0; int incomingByte; char val; void setup() { Serial.begin(9600); myservo.attach(10); myservo.write(115); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == 'W' || incomingByte == 'w') { motor1.run(FORWARD); motor2.run(FORWARD); motor3.run(FORWARD); motor4.run(FORWARD); for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) { motor1.setSpeed(speedSet); motor2.setSpeed(speedSet); motor3.setSpeed(speedSet); motor4.setSpeed(speedSet); delay(5); } } if (incomingByte == 'X' || incomingByte == 'x') { motor1.run(RELEASE); motor2.run(RELEASE); motor3.run(RELEASE); motor4.run(RELEASE); } if (incomingByte == 'A' || incomingByte == 'a') { motor1.run(BACKWARD); motor2.run(BACKWARD); motor3.run(FORWARD); motor4.run(FORWARD); delay(500); } if (incomingByte == 'D' || incomingByte == 'd') { motor1.run(FORWARD); motor2.run(FORWARD); motor3.run(BACKWARD); motor4.run(BACKWARD); delay(500); } if (incomingByte == 'S' || incomingByte == 's') { motor1.run(BACKWARD); motor2.run(BACKWARD); motor3.run(BACKWARD); motor4.run(BACKWARD); for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) { motor1.setSpeed(speedSet); motor2.setSpeed(speedSet); motor3.setSpeed(speedSet); motor4.setSpeed(speedSet); delay(5); } } } }
18f8ea33ebf400adb423ef2aa0474859fe2d31e9
a3cb1c1c73a7057db55951e3704a69634f5f39da
/lib86cpu/x86/frontend.h
90716da39e7d78dc350a73bc68904370c118b30f
[ "BSD-2-Clause" ]
permissive
killvxk/lib86cpu
408a4d390fe51c1b8904b35c4e10dac60f07c65b
e8f7dd7233f9f6011bb68f5e3a57f966e9aed6a7
refs/heads/master
2023-08-30T18:04:41.280162
2021-11-10T10:09:26
2021-11-10T10:09:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,020
h
frontend.h
/* * x86 llvm frontend exports to translator * * ergo720 Copyright (c) 2019 */ #pragma once std::vector<BasicBlock *> gen_bbs(cpu_t *cpu, const unsigned num); void gen_exp_fn(cpu_t *cpu); void optimize(cpu_t *cpu); void get_ext_fn(cpu_t *cpu); StructType *get_struct_reg(cpu_t *cpu); StructType *get_struct_eflags(cpu_t *cpu); Value *gep_emit(cpu_t *cpu, Value *gep_start, const int gep_index); Value *gep_emit(cpu_t *cpu, Value *gep_start, Value *gep_index); Value *gep_emit(cpu_t *cpu, Value *gep_start, std::vector<Value *> &vec_index); Value *get_r8h_pointer(cpu_t *cpu, Value *gep_start); Value *get_operand(cpu_t *cpu, ZydisDecodedInstruction *instr, const unsigned opnum); int get_reg_idx(ZydisRegister reg); int get_seg_prfx_idx(ZydisDecodedInstruction *instr); Value *mem_read_emit(cpu_t *cpu, Value *addr, const unsigned idx, const unsigned is_priv); void mem_write_emit(cpu_t *cpu, Value *addr, Value *value, const unsigned idx, const unsigned is_priv); void check_io_priv_emit(cpu_t *cpu, Value *port, uint8_t size_mode); void stack_push_emit(cpu_t *cpu, std::vector<Value *> &vec, uint32_t size_mode); std::vector<Value *> stack_pop_emit(cpu_t *cpu, uint32_t size_mode, const unsigned num, const unsigned pop_at = 0); void link_direct_emit(cpu_t *cpu, std::vector<addr_t> &vec_addr, Value *target_addr); void link_dst_only_emit(cpu_t *cpu); Value *calc_next_pc_emit(cpu_t *cpu, size_t instr_size); Value *floor_division_emit(cpu_t *cpu, Value *D, Value *d, size_t q_bits); void raise_exp_inline_emit(cpu_t *cpu, std::vector<Value *> &exp_data); BasicBlock *raise_exception_emit(cpu_t *cpu, std::vector<Value *> &exp_data); void lcall_pe_emit(cpu_t *cpu, std::vector<Value *> &vec, uint8_t size_mode, uint32_t ret_eip); void ljmp_pe_emit(cpu_t *cpu, Value *sel, uint8_t size_mode, uint32_t eip); void ret_pe_emit(cpu_t *cpu, uint8_t size_mode, bool is_iret); std::vector<Value *> check_ss_desc_priv_emit(cpu_t *cpu, Value *sel, Value *cs = nullptr, Value *cpl = nullptr, BasicBlock *bb_exp = nullptr); std::vector<Value *> check_seg_desc_priv_emit(cpu_t *cpu, Value *sel); void set_access_flg_seg_desc_emit(cpu_t *cpu, Value *desc, Value *desc_addr); std::vector<Value *> read_seg_desc_emit(cpu_t *cpu, Value *sel, BasicBlock *bb_exp = nullptr); Value *read_seg_desc_base_emit(cpu_t *cpu, Value *desc); Value *read_seg_desc_limit_emit(cpu_t *cpu, Value *desc); Value *read_seg_desc_flags_emit(cpu_t *cpu, Value *desc); std::vector<Value *> read_tss_desc_emit(cpu_t *cpu, Value *sel); std::vector<Value *> read_stack_ptr_from_tss_emit(cpu_t *cpu, Value *cpl, BasicBlock *bb_exp = nullptr); void write_seg_reg_emit(cpu_t *cpu, const unsigned reg, std::vector<Value *> &vec); Value *get_immediate_op(cpu_t *cpu, ZydisDecodedInstruction *instr, uint8_t idx, uint8_t size_mode); Value *get_register_op(cpu_t *cpu, ZydisDecodedInstruction *instr, uint8_t idx); void set_flags_sum(cpu_t *cpu, std::vector<Value *> &vec, uint8_t size_mode); void set_flags_sub(cpu_t *cpu, std::vector<Value *> &vec, uint8_t size_mode); void set_flags(cpu_t *cpu, Value *res, Value *aux, uint8_t size_mode); void update_fpu_state_after_mmx_emit(cpu_t *cpu, int idx, Value *tag, bool is_write); void write_eflags(cpu_t *cpu, Value *eflags, Value *mask); void hook_emit(cpu_t *cpu, hook *obj); #define CTX() (*cpu->ctx) #define getBB() BasicBlock::Create(CTX(), "", cpu->bb->getParent(), 0) #define getBBs(n) gen_bbs(cpu, n) #define getIntegerType(x) (IntegerType::get(CTX(), x)) #define getPointerType(x) (PointerType::getUnqual(x)) #define getIntegerPointerType() (cpu->dl->getIntPtrType(CTX())) #define getVoidType() (Type::getVoidTy(CTX())) #define getArrayType(x, n) (ArrayType::get(x, n)) #define MEM_LD8_idx 0 #define MEM_LD16_idx 1 #define MEM_LD32_idx 2 #define MEM_LD64_idx 3 #define IO_LD8_idx 4 #define IO_LD16_idx 5 #define IO_LD32_idx 6 #define MEM_ST8_idx 0 #define MEM_ST16_idx 1 #define MEM_ST32_idx 2 #define MEM_ST64_idx 3 #define IO_ST8_idx 4 #define IO_ST16_idx 5 #define IO_ST32_idx 6 #define GET_REG_idx(reg) get_reg_idx(reg) #define GET_IMM() get_immediate_op(cpu, &instr, OPNUM_SRC, size_mode) #define GET_IMM8() get_immediate_op(cpu, &instr, OPNUM_SRC, SIZE8) #define GET_REG(idx) get_register_op(cpu, &instr, idx) #define GET_OP(op) get_operand(cpu, &instr, op) #define GET_RM(idx, r, m) rm = GET_OP(idx); \ switch (instr.operands[idx].type) \ { \ case ZYDIS_OPERAND_TYPE_REGISTER: \ r \ break; \ \ case ZYDIS_OPERAND_TYPE_MEMORY: \ m \ break; \ \ default: \ LIB86CPU_ABORT_msg("Invalid operand type used in GET_RM macro!"); \ } #define INTPTR(v) ConstantInt::get(getIntegerPointerType(), reinterpret_cast<uintptr_t>(v)) #define CONSTs(s, v) ConstantInt::get(getIntegerType(s), v) #define CONST1(v) CONSTs(1, v) #define CONST8(v) CONSTs(8, v) #define CONST16(v) CONSTs(16, v) #define CONST32(v) CONSTs(32, v) #define CONST64(v) CONSTs(64, v) #define ALLOC(ty) new AllocaInst(ty, 0, "", cpu->bb) #define ALLOCs(s) ALLOC(getIntegerType(s)) #define ALLOC8() ALLOCs(8) #define ALLOC16() ALLOCs(16) #define ALLOC32() ALLOCs(32) #define ALLOC64() ALLOCs(64) #define ST(ptr, v) new StoreInst(v, ptr, cpu->bb) #define LD(ptr) new LoadInst(ptr, "", false, cpu->bb) #define UNREACH() new UnreachableInst(CTX(), cpu->bb) #define INTRINSIC(id) CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::id), "", cpu->bb) #define INTRINSIC_ty(id, ty, arg) CallInst::Create(Intrinsic::getDeclaration(cpu->mod, Intrinsic::id, ty), arg, "", cpu->bb) #define ZEXTs(s, v) new ZExtInst(v, getIntegerType(s), "", cpu->bb) #define ZEXT8(v) ZEXTs(8, v) #define ZEXT16(v) ZEXTs(16, v) #define ZEXT32(v) ZEXTs(32, v) #define ZEXT64(v) ZEXTs(64, v) #define SEXTs(s, v) new SExtInst(v, getIntegerType(s), "", cpu->bb) #define SEXT8(v) SEXTs(8, v) #define SEXT16(v) SEXTs(16, v) #define SEXT32(v) SEXTs(32, v) #define SEXT64(v) SEXTs(64, v) #define IBITCASTs(s, v) new BitCastInst(v, getPointerType(getIntegerType(s)), "", cpu->bb) #define IBITCAST8(v) IBITCASTs(8, v) #define IBITCAST16(v) IBITCASTs(16, v) #define IBITCAST32(v) IBITCASTs(32, v) #define TRUNCs(s,v) new TruncInst(v, getIntegerType(s), "", cpu->bb) #define TRUNC8(v) TRUNCs(8, v) #define TRUNC16(v) TRUNCs(16, v) #define TRUNC32(v) TRUNCs(32, v) #define ADD(a, b) BinaryOperator::Create(Instruction::Add, a, b, "", cpu->bb) #define SUB(a, b) BinaryOperator::Create(Instruction::Sub, a, b, "", cpu->bb) #define MUL(a, b) BinaryOperator::Create(Instruction::Mul, a, b, "", cpu->bb) #define UDIV(a, b) BinaryOperator::Create(Instruction::UDiv, a, b, "", cpu->bb) #define SDIV(a, b) BinaryOperator::Create(Instruction::SDiv, a, b, "", cpu->bb) #define FLOOR_DIV(a, b, bits) floor_division_emit(cpu, a, b, bits) #define UREM(a, b) BinaryOperator::Create(Instruction::URem, a, b, "", cpu->bb) #define SREM(a, b) BinaryOperator::Create(Instruction::SRem, a, b, "", cpu->bb) #define AND(a, b) BinaryOperator::Create(Instruction::And, a, b, "", cpu->bb) #define XOR(a, b) BinaryOperator::Create(Instruction::Xor, a, b, "", cpu->bb) #define OR(a, b) BinaryOperator::Create(Instruction::Or, a, b, "", cpu->bb) #define NOT(a) BinaryOperator::CreateNot(a, "", cpu->bb) #define NEG(a) BinaryOperator::CreateNeg(a, "", cpu->bb) #define ASHR(a, sh) BinaryOperator::Create(Instruction::AShr, a, sh, "", cpu->bb) #define SHR(a, sh) BinaryOperator::Create(Instruction::LShr, a, sh, "", cpu->bb) #define SHL(a, sh) BinaryOperator::Create(Instruction::Shl, a, sh, "", cpu->bb) #define BR_COND(t, f, val) BranchInst::Create(t, f, val, cpu->bb) #define BR_UNCOND(t) BranchInst::Create(t, cpu->bb) #define ICMP_EQ(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_EQ, a, b, "") #define ICMP_NE(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_NE, a, b, "") #define ICMP_UGT(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_UGT, a, b, "") #define ICMP_UGE(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_UGE, a, b, "") #define ICMP_ULT(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_ULT, a, b, "") #define ICMP_ULE(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_ULE, a, b, "") #define ICMP_SGE(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_SGE, a, b, "") #define ICMP_SGT(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_SGT, a, b, "") #define ICMP_SLT(a, b) new ICmpInst(*cpu->bb, ICmpInst::ICMP_SLT, a, b, "") #define NOT_ZERO(s, v) AND(SHR(OR(v, SUB(CONSTs(s, 0), v)), CONSTs(s, s-1)), CONSTs(s, 1)) #define SWITCH_new(n, v, def) SwitchInst::Create(v, def, n, cpu->bb) #define SWITCH_add(s, v, bb) addCase(CONSTs(s, v), bb) #define INT2PTR(ty, v) new IntToPtrInst(v, ty, "", cpu->bb) #define GEP(ptr, idx) gep_emit(cpu, ptr, idx) #define GEP_R32(idx) GEP(cpu->ptr_regs, idx) #define GEP_R16(idx) IBITCAST16(GEP(cpu->ptr_regs, idx)) #define GEP_R8L(idx) IBITCAST8(GEP(cpu->ptr_regs, idx)) #define GEP_R8H(idx) get_r8h_pointer(cpu, IBITCAST8(GEP(cpu->ptr_regs, idx))) #define GEP_SEL(idx) GEP(GEP(cpu->ptr_regs, idx), SEG_SEL_idx) #define GEP_EAX() GEP_R32(EAX_idx) #define GEP_ECX() GEP_R32(ECX_idx) #define GEP_EDX() GEP_R32(EDX_idx) #define GEP_EBX() GEP_R32(EBX_idx) #define GEP_ESP() GEP_R32(ESP_idx) #define GEP_EBP() GEP_R32(EBP_idx) #define GEP_ESI() GEP_R32(ESI_idx) #define GEP_EDI() GEP_R32(EDI_idx) #define GEP_ES() GEP_SEL(ES_idx) #define GEP_CS() GEP_SEL(CS_idx) #define GEP_SS() GEP_SEL(SS_idx) #define GEP_DS() GEP_SEL(DS_idx) #define GEP_FS() GEP_SEL(FS_idx) #define GEP_GS() GEP_SEL(GS_idx) #define GEP_CR0() GEP_R32(CR0_idx) #define GEP_CR1() GEP_R32(CR1_idx) #define GEP_CR2() GEP_R32(CR2_idx) #define GEP_CR3() GEP_R32(CR3_idx) #define GEP_CR4() GEP_R32(CR4_idx) #define GEP_DR0() GEP_R32(DR0_idx) #define GEP_DR1() GEP_R32(DR1_idx) #define GEP_DR2() GEP_R32(DR2_idx) #define GEP_DR3() GEP_R32(DR3_idx) #define GEP_DR4() GEP_R32(DR4_idx) #define GEP_DR5() GEP_R32(DR5_idx) #define GEP_DR6() GEP_R32(DR6_idx) #define GEP_DR7() GEP_R32(DR7_idx) #define GEP_EFLAGS() GEP_R32(EFLAGS_idx) #define GEP_EIP() GEP_R32(EIP_idx) #define GEP_PARITY() GEP(cpu->ptr_eflags, 2) #define ST_R32(val, idx) ST(GEP_R32(idx), val) #define ST_R16(val, idx) ST(GEP_R16(idx), val) #define ST_R8L(val, idx) ST(GEP_R8L(idx), val) #define ST_R8H(val, idx) ST(GEP_R8H(idx), val) #define ST_REG_val(val, reg) ST(reg, val) #define ST_SEG(val, seg) ST(GEP_SEL(seg), val) #define ST_SEG_HIDDEN(val, seg, idx) ST(GEP(GEP(GEP(cpu->ptr_regs, seg), SEG_HIDDEN_idx), idx), val) #define ST_MM64(val, idx) ST(GEP(GEP(cpu->ptr_regs, idx), F80_LOW_idx), val) #define ST_MM_HIGH(val, idx) ST(GEP(GEP(cpu->ptr_regs, idx), F80_HIGH_idx), val) #define LD_R32(idx) LD(GEP_R32(idx)) #define LD_R16(idx) LD(GEP_R16(idx)) #define LD_R8L(idx) LD(GEP_R8L(idx)) #define LD_R8H(idx) LD(GEP_R8H(idx)) #define LD_REG_val(reg) LD(reg) #define LD_SEG(seg) LD(GEP_SEL(seg)) #define LD_SEG_HIDDEN(seg, idx) LD(GEP(GEP(GEP(cpu->ptr_regs, seg), SEG_HIDDEN_idx), idx)) #define LD_MM32(idx) LD(IBITCAST32(GEP(GEP(cpu->ptr_regs, idx), F80_LOW_idx))) #define LD_MEM(idx, addr) mem_read_emit(cpu, addr, idx, 0) #define ST_MEM(idx, addr, val) mem_write_emit(cpu, addr, val, idx, 0) #define LD_MEM_PRIV(idx, addr) mem_read_emit(cpu, addr, idx, 2) #define ST_MEM_PRIV(idx, addr, val) mem_write_emit(cpu, addr, val, idx, 2) #define MEM_PUSH(vec) stack_push_emit(cpu, vec, size_mode) #define MEM_POP(n) stack_pop_emit(cpu, size_mode, n) #define MEM_POP_AT(n, at) stack_pop_emit(cpu, size_mode, n, at) #define LD_IO(idx, port) CallInst::Create(cpu->ptr_mem_ldfn[idx], std::vector<Value *> { cpu->ptr_cpu_ctx, port }, "", cpu->bb) #define ST_IO(idx, port, val) CallInst::Create(cpu->ptr_mem_stfn[idx], std::vector<Value *> { cpu->ptr_cpu_ctx, port, val }, "", cpu->bb) #define LD_PARITY(idx) LD(GetElementPtrInst::CreateInBounds(GEP_PARITY(), std::vector<Value *> { CONST32(0), idx }, "", cpu->bb)) #define RAISE(code, idx) raise_exception_emit(cpu, std::vector<Value *> { CONST32(0), code, CONST16(idx), cpu->instr_eip }) #define RAISE0(idx) raise_exception_emit(cpu, std::vector<Value *> { CONST32(0), CONST16(0), CONST16(idx), cpu->instr_eip }) #define RAISEin(addr, code, idx, eip) raise_exp_inline_emit(cpu, std::vector<Value *> { CONST32(addr), CONST16(code), CONST16(idx), CONST32(eip) }); \ cpu->bb = getBBs(1)[0] #define RAISEin0(idx) raise_exp_inline_emit(cpu, std::vector<Value *> { CONST32(0), CONST16(0), CONST16(idx), cpu->instr_eip }); \ cpu->bb = getBBs(1)[0] #define SET_FLG_SUM(sum, a, b) set_flags_sum(cpu, std::vector<Value *> { sum, a , b }, size_mode) #define SET_FLG_SUB(sub, a, b) set_flags_sub(cpu, std::vector<Value *> { sub, a , b }, size_mode) #define SET_FLG(res, aux) set_flags(cpu, res, aux, size_mode) #define UPDATE_FPU_AFTER_MMX(tag, idx, w) update_fpu_state_after_mmx_emit(cpu, idx, tag, w) #define UPDATE_FPU_AFTER_MMX_w(tag, idx) UPDATE_FPU_AFTER_MMX(tag, idx, true) #define UPDATE_FPU_AFTER_MMX_r(tag, idx) UPDATE_FPU_AFTER_MMX(tag, idx, false) #define REP_start() vec_bb.push_back(BasicBlock::Create(CTX(), "", cpu->bb->getParent(), 0)); \ Value *ecx, *zero; \ if (addr_mode == ADDR16) { \ ecx = LD_R16(ECX_idx); \ zero = CONST16(0); \ } \ else { \ ecx = LD_R32(ECX_idx); \ zero = CONST32(0); \ } \ BR_COND(vec_bb[3], vec_bb[2], ICMP_NE(ecx, zero)); \ cpu->bb = vec_bb[3]; #define REP() Value *ecx, *zero, *one; \ if (addr_mode == ADDR16) { \ ecx = LD_R16(ECX_idx); \ zero = CONST16(0); \ one = CONST16(1); \ ecx = SUB(ecx, one); \ ST_R16(ecx, ECX_idx); \ } \ else { \ ecx = LD_R32(ECX_idx); \ zero = CONST32(0); \ one = CONST32(1); \ ecx = SUB(ecx, one); \ ST_R32(ecx, ECX_idx); \ } \ BR_COND(vec_bb[3], vec_bb[2], ICMP_NE(ecx, zero)) #define REPNZ() Value *ecx, *zero, *one; \ if (addr_mode == ADDR16) { \ ecx = LD_R16(ECX_idx); \ zero = CONST16(0); \ one = CONST16(1); \ ecx = SUB(ecx, one); \ ST_R16(ecx, ECX_idx); \ } \ else { \ ecx = LD_R32(ECX_idx); \ zero = CONST32(0); \ one = CONST32(1); \ ecx = SUB(ecx, one); \ ST_R32(ecx, ECX_idx); \ } \ BR_COND(vec_bb[3], vec_bb[2], AND(ICMP_NE(ecx, zero), ICMP_NE(LD_ZF(), CONST32(0)))) #define REPZ() Value *ecx, *zero, *one; \ if (addr_mode == ADDR16) { \ ecx = LD_R16(ECX_idx); \ zero = CONST16(0); \ one = CONST16(1); \ ecx = SUB(ecx, one); \ ST_R16(ecx, ECX_idx); \ } \ else { \ ecx = LD_R32(ECX_idx); \ zero = CONST32(0); \ one = CONST32(1); \ ecx = SUB(ecx, one); \ ST_R32(ecx, ECX_idx); \ } \ BR_COND(vec_bb[3], vec_bb[2], AND(ICMP_NE(ecx, zero), ICMP_EQ(LD_ZF(), CONST32(0)))) // the lazy eflags idea comes from reading these two papers: // How Bochs Works Under the Hood (2nd edition) http://bochs.sourceforge.net/How%20the%20Bochs%20works%20under%20the%20hood%202nd%20edition.pdf // A Proposal for Hardware-Assisted Arithmetic Overflow Detection for Array and Bitfield Operations http://www.emulators.com/docs/LazyOverflowDetect_Final.pdf #define SUM_COUT_VEC(a, b, s) OR(AND(a, b), AND(OR(a, b), NOT(s))) #define SUB_COUT_VEC(a, b, d) OR(AND(NOT(a), b), AND(NOT(XOR(a, b)), d)) #define MASK_FLG8(a) AND(OR(SHL(a, CONST32(24)), a), CONST32(0xC0000008)) #define MASK_FLG16(a) AND(OR(SHL(a, CONST32(16)), a), CONST32(0xC0000008)) #define MASK_FLG32(a) AND(a, CONST32(0xC0000008)) #define GEN_SUM_VEC8(a, b, r) MASK_FLG8(ZEXT32(SUM_COUT_VEC(a, b, r))) #define GEN_SUM_VEC16(a, b, r) MASK_FLG16(ZEXT32(SUM_COUT_VEC(a, b, r))) #define GEN_SUM_VEC32(a, b, r) MASK_FLG32(SUM_COUT_VEC(a, b, r)) #define GEN_SUB_VEC8(a, b, r) MASK_FLG8(ZEXT32(SUB_COUT_VEC(a, b, r))) #define GEN_SUB_VEC16(a, b, r) MASK_FLG16(ZEXT32(SUB_COUT_VEC(a, b, r))) #define GEN_SUB_VEC32(a, b, r) MASK_FLG32(SUB_COUT_VEC(a, b, r)) #define ST_FLG_SUM_AUX8(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUM_VEC8(a, b, r)) #define ST_FLG_SUM_AUX16(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUM_VEC16(a, b, r)) #define ST_FLG_SUM_AUX32(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUM_VEC32(a, b, r)) #define ST_FLG_SUB_AUX8(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUB_VEC8(a, b, r)) #define ST_FLG_SUB_AUX16(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUB_VEC16(a, b, r)) #define ST_FLG_SUB_AUX32(a, b, r) ST(GEP(cpu->ptr_eflags, 1), GEN_SUB_VEC32(a, b, r)) #define ST_FLG_AUX(val) ST(GEP(cpu->ptr_eflags, 1), val) #define ST_FLG_RES_ext(val) ST(GEP(cpu->ptr_eflags, 0), SEXT32(val)) #define ST_FLG_RES(val) ST(GEP(cpu->ptr_eflags, 0), val) #define LD_FLG_RES() LD(GEP(cpu->ptr_eflags, 0)) #define LD_FLG_AUX() LD(GEP(cpu->ptr_eflags, 1)) #define LD_CF() AND(LD_FLG_AUX(), CONST32(0x80000000)) #define LD_OF() AND(XOR(LD_FLG_AUX(), SHL(LD_FLG_AUX(), CONST32(1))), CONST32(0x80000000)) #define LD_ZF() LD_FLG_RES() #define LD_SF() XOR(SHR(LD_FLG_RES(), CONST32(31)), AND(LD_FLG_AUX(), CONST32(1))) #define LD_PF() LD_PARITY(AND(XOR(LD_FLG_RES(), SHR(LD_FLG_AUX(), CONST32(8))), CONST32(0xFF))) #define LD_AF() AND(LD_FLG_AUX(), CONST32(8)) #define ABORT(str) \ do { \ CallInst *ci = CallInst::Create(cpu->ptr_abort_fn, ConstantExpr::getIntToPtr(INTPTR(str), getPointerType(getIntegerType(8))), "", cpu->bb); \ ci->setCallingConv(CallingConv::C); \ } while (0)
22397ac826df9c4a30b4547211538f2501f0dec1
b2bd15f5422b3683531440f616defebdd6b5fa85
/Hoja1_Ejercicio1.cpp
fc3e7246ebfd1c9d697f4b80130b3ff414928cc7
[]
no_license
AugustoMorante/Asignacion20
ccf5b07ffe478aced49631f481f08e546443a8af
efb5641e74357b49fe9b067d8a27086064cfacd0
refs/heads/master
2020-06-06T04:46:37.272861
2019-06-20T05:48:53
2019-06-20T05:48:53
192,641,348
0
0
null
null
null
null
UTF-8
C++
false
false
5,158
cpp
Hoja1_Ejercicio1.cpp
#include "stdafx.h" #include <iostream> #include <conio.h> #include <time.h> #include <stdlib.h> using namespace System; using namespace std; void GenerarValoresMatriz(int** matriz, int &filas, int &columnas) { for (int fila = 0; fila < filas; fila++) { for (int columna = 0; columna < columnas; columna++) { matriz[fila][columna] = rand() % 11; } } } void MostrarMatriz(int** matriz, int& filas, int& columnas) { for (int fila = 0; fila < filas; fila++) { for (int columna = 0; columna < columnas; columna++) { cout << matriz[fila][columna] << " "; } cout << endl; } } void MostrarMatrizTranspuesta(int** matriz, int& filas, int& columnas) { for (int columna = 0; columna < columnas; columna++) { for (int fila = 0; fila < filas; fila++) { cout << matriz[fila][columna] << " "; } cout << endl; } } void SumaFilas(int** matriz, int& filas, int& columnas, int* sumas) { for (int fila = 0; fila < filas; fila++) { for (int columna = 0; columna < columnas; columna++) { sumas[fila] = sumas[fila] + matriz[fila][columna]; } } } void PromedioFilas(int** matriz, int& filas, int& columnas, double* promedios) { for (int fila = 0; fila < filas; fila++) { for (int columna = 0; columna < columnas; columna++) { promedios[fila] = promedios[fila] + matriz[fila][columna]; } promedios[fila] = promedios[fila] / columnas; } } void PromedioColumnas(int** matriz, int& filas, int& columnas, double* promedios) { for (int columna = 0; columna < columnas; columna++) { for (int fila = 0; fila < filas; fila++) { promedios[columna] = promedios[columna] + matriz[fila][columna]; } promedios[columna] = promedios[columna] / filas; } } void IniciarMatrizCeros(int** matriz, int& filas, int& columnas) { for (int fila = 0; fila < filas; fila++) { for (int columna = 0; columna < columnas; columna++) { matriz[fila][columna] = 0; } } } void IniciarArregloCerosInt(int* arreglo, int& tamanio) { for (int i = 0; i < tamanio; i++) { arreglo[i] = 0; } } void IniciarArregloCerosFloat(double* arreglo, int& tamanio) { for (int i = 0; i < tamanio; i++) { arreglo[i] = 0.0; } } int MayorArregloInt(int* arreglo, int& tamanio) { int mayor = -1; for (int i = 0; i < tamanio; i++) { if (arreglo[i] > mayor) { mayor = arreglo[i]; } } return mayor; } int MenorArregloInt(int* arreglo, int& tamanio) { int menor = 100000; for (int i = 0; i < tamanio; i++) { if (arreglo[i] < menor) { menor = arreglo[i]; } } return menor; } double MayorArregloFloat(double* arreglo, int& tamanio) { double mayor = -1.0; for (int i = 0; i < tamanio; i++) { if (arreglo[i] > mayor) { mayor = arreglo[i]; } } return mayor; } void MayorMatrizInt(int** matriz, int& filas, int& columnas, int& mayorValor, int& posFila, int& posCol) { for (int i = 0; i < filas; i++) { for (int j = 0; j < columnas; j++) { if (matriz[i][j] > mayorValor) { mayorValor = matriz[i][j]; posFila = i; posCol = j; } } } } int main() { int** matriz; int filas; int columnas; int* suma; double* promedios; int posFila = -1; int posCol = -1; int mayorValor = -1; do { cout << "Ingrese el numero de filas: "; cin >> filas; } while (filas <= 0 || filas > 10); do { cout << "Ingrese el numero de columnas: "; cin >> columnas; } while (columnas <= 0 || columnas > 10); matriz = new int*[filas]; for (int fila = 0; fila < filas; fila++) { matriz[fila] = new int[columnas]; } suma = new int[filas]; promedios = new double[filas]; IniciarMatrizCeros(matriz, filas, columnas); IniciarArregloCerosInt(suma, filas); IniciarArregloCerosFloat(promedios, filas); GenerarValoresMatriz(matriz, filas, columnas); MostrarMatriz(matriz, filas, columnas); cout << endl; MostrarMatrizTranspuesta(matriz, filas, columnas); cout << endl; SumaFilas(matriz, filas, columnas, suma); cout << endl; PromedioFilas(matriz, filas, columnas, promedios); for (int i = 0; i < filas; i++) { cout << "La suma de la fila #" << i << ": " << suma[i] << endl; } cout << "El mayor valor de las sumas es: " << MayorArregloInt(suma, filas); cout << endl; cout << "El menor valor de las sumas es: " << MenorArregloInt(suma, filas); cout << endl; for (int i = 0; i < filas; i++) { cout << "El promedio de la fila " << i << ": " << promedios[i] << endl; } cout << endl; delete[] promedios; promedios = new double[columnas]; IniciarArregloCerosFloat(promedios, columnas); PromedioColumnas(matriz, filas, columnas, promedios); for (int i = 0; i < filas; i++) { cout << "El promedio de la columna :" << i << ": " << promedios[i] << endl; } cout << "El mayor valor de los promedios: " << MayorArregloFloat(promedios, columnas); cout << endl; MayorMatrizInt(matriz, filas, columnas, mayorValor, posFila, posCol); cout << "El mayor valor de la matriz es: " << mayorValor << endl; cout << "Fila: " << posFila << endl; cout << "Columna: " << posCol << endl; for (int fila = 0; fila < filas; fila++) { delete[] matriz[fila]; } delete[] matriz; delete[] suma; delete[] promedios; _getch(); return 0; }
0aa8579eb8ff42f5240b64e3d737009ed4842a97
cb80a8562d90eb969272a7ff2cf52c1fa7aeb084
/inletTest5/0.05/yPlus
50ff7a1822fd2f9c6d77fe95b57ce3f649bad35c
[]
no_license
mahoep/inletCFD
eb516145fad17408f018f51e32aa0604871eaa95
0df91e3fbfa60d5db9d52739e212ca6d3f0a28b2
refs/heads/main
2023-08-30T22:07:41.314690
2021-10-14T19:23:51
2021-10-14T19:23:51
314,657,843
0
0
null
null
null
null
UTF-8
C++
false
false
9,306
yPlus
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.05"; object yPlus; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 0; boundaryField { bottomEmptyFaces { type empty; } topEmptyFaces { type empty; } inlet { type calculated; value uniform 0; } outlet { type calculated; value uniform 0; } walls { type calculated; value nonuniform List<scalar> 988 ( 13.3616 13.3704 13.3783 13.3869 13.3947 13.4031 13.4106 13.4189 13.4262 13.4342 13.4414 13.4491 13.4561 13.4636 13.4704 13.4777 13.4843 13.4914 13.4977 13.5047 13.5109 13.5176 13.5236 13.5301 13.536 13.5423 13.548 13.5541 13.5597 13.5656 13.571 13.5768 13.5821 13.5877 13.5928 13.5983 13.6033 13.6086 13.6134 13.6185 13.6232 13.6282 13.6328 13.6376 13.642 13.6467 13.651 13.6555 13.6596 13.664 13.668 13.6723 13.6761 13.6802 13.684 13.688 13.6916 13.6955 13.699 13.7027 13.7061 13.7097 13.713 13.7165 13.7197 13.7231 13.7262 13.7295 13.7325 13.7357 13.7386 13.7416 13.7444 13.7474 13.7501 13.753 13.7556 13.7584 13.7609 13.7636 13.766 13.7686 13.7709 13.7735 13.7757 13.7782 13.7803 13.7827 13.7848 13.7871 13.7891 13.7913 13.7933 13.7954 13.7973 13.7994 13.8012 13.8032 13.8049 13.8069 13.8086 13.8104 13.8121 13.8139 13.8155 13.8173 13.8188 13.8205 13.822 13.8236 13.8251 13.8266 13.828 13.8296 13.8309 13.8325 13.8338 13.8353 13.8365 13.8379 13.8392 13.8406 13.8418 13.8432 13.8443 13.8456 13.8467 13.848 13.8491 13.8503 13.8514 13.8526 13.8537 13.8549 13.8559 13.857 13.858 13.8591 13.8601 13.8612 13.8621 13.8632 13.8641 13.8651 13.866 13.867 13.8679 13.8688 13.8697 13.8706 13.8715 13.8724 13.8732 13.8741 13.8749 13.8757 13.8765 13.8774 13.8782 13.879 13.8797 13.8806 13.8813 13.8821 13.8828 13.8837 13.8843 13.8852 13.8859 13.8867 13.8873 13.8881 13.8888 13.8896 13.8902 13.891 13.8916 13.8924 13.893 13.8938 13.8945 13.8952 13.8959 13.8967 13.8973 13.8981 13.8988 13.8996 13.9004 13.9011 13.9021 13.9029 13.9036 13.9046 13.9052 13.9063 13.907 13.9081 13.9089 13.91 13.9108 13.912 13.9127 13.9139 13.9147 13.9159 13.9167 13.9179 13.9186 13.9197 13.9204 13.9214 13.9221 13.9231 13.9238 13.9247 13.9256 13.9265 13.928 13.919 13.941 13.9123 13.9266 13.9069 14.2061 14.669 11.0347 7.68399 8.23387 9.76245 8.53663 8.69032 7.051 7.31236 8.59209 9.239 8.2871 9.04501 8.32959 9.04849 8.88545 9.56118 9.61098 9.9145 8.52105 9.28647 10.6466 9.30623 9.59972 7.77705 8.07262 10.2647 8.11132 8.71304 8.94649 9.11797 8.10257 8.61495 7.3317 7.68084 7.80319 8.53088 59.8855 38.7546 47.9319 9.7952 7.30914 6.05335 30.7576 9.38164 16.7642 422.537 188.923 125.692 156.831 356.308 238.246 278.506 478.909 514.162 509.433 420.524 475.427 107.504 72.4067 84.3748 376.723 281.74 315.838 240.22 202.818 147.778 164.791 124.898 105.165 84.2737 69.5794 55.5922 43.6068 45.8741 20.2384 19.013 18.7046 18.4704 6.47931 6.6422 18.6007 17.4144 22.7379 17.0508 15.0307 7.74075 7.73399 23.4219 23.5066 8.42396 6.32758 6.38063 6.8095 7.13478 23.5529 23.273 8.44563 7.30397 7.23571 6.37895 6.39816 7.4066 7.33633 22.7215 22.1276 21.4336 20.7128 19.9967 19.3069 18.6515 18.0365 7.6169 7.44539 6.32612 5.79321 7.31121 6.77901 6.47418 5.78747 5.5822 6.2506 5.74104 17.4634 16.9326 16.4417 15.9882 7.38779 6.23298 5.20479 15.5726 15.192 6.76025 5.4178 5.01171 7.11028 5.8576 5.23642 7.96882 6.53424 5.38885 6.59167 6.04015 14.8458 14.5311 8.21104 7.80044 5.98266 5.87255 7.12478 6.81399 7.69226 6.55916 6.26273 5.8149 5.81135 8.14159 8.21945 8.02055 8.06817 7.14214 7.52026 9.11416 6.66801 6.84839 7.22303 7.61352 7.69871 8.30061 7.3743 7.83014 9.339 6.84786 7.06051 8.92257 6.4768 6.67808 42.137 34.809 28.1102 14.248 16.3613 13.9933 8.4754 7.10335 13.7663 6.16944 13.5639 5.58958 13.3857 13.2286 13.0918 12.9725 7.43139 4.15458 8.74152 7.74753 7.39667 12.8698 7.13432 7.04669 12.7813 12.7059 6.89679 12.6417 6.86454 6.74087 6.71762 12.5872 6.59488 6.57564 12.5411 12.5026 12.4704 6.46426 6.43818 6.34646 6.35121 6.2767 6.26206 6.18364 6.20074 6.13096 6.11884 12.4431 6.04859 6.06626 12.4203 12.4005 12.3839 12.369 12.3562 12.344 12.3335 12.3228 12.3132 6.00282 12.3029 5.99226 12.2936 5.92859 5.94651 5.8883 5.87886 12.2832 12.2739 5.82042 12.2626 5.83842 12.254 5.7845 5.77596 5.72191 5.74003 5.68995 5.68247 5.6327 5.65125 5.60509 5.5988 5.55814 5.56967 5.53225 5.52793 5.49279 5.50626 5.4837 5.48446 5.4959 5.5642 5.68914 5.94452 6.45063 7.0488 12.2421 12.2339 12.2223 12.2143 12.203 12.1953 12.1841 12.177 12.1664 12.1601 12.15 12.1447 12.1357 12.1316 12.1236 12.1208 12.1142 12.1131 12.1078 12.1081 12.1048 12.1061 12.1045 12.1068 12.1074 12.1107 12.1132 12.1174 12.1213 12.1263 12.1308 12.137 12.1422 12.1495 12.1552 12.1634 12.1697 12.179 12.1857 12.1959 12.2032 12.2144 12.2224 12.2342 12.2432 12.2557 12.2655 12.2785 12.2894 12.3031 12.3147 12.3289 12.3414 12.3561 12.3693 12.3843 12.3982 12.4138 12.428 12.444 12.4587 12.475 12.4899 12.5065 12.5217 12.5385 12.5537 12.5706 12.586 12.603 12.6184 12.6353 12.6508 12.6677 12.6831 12.6999 12.7152 12.7319 12.747 12.7636 12.7786 12.7949 12.8097 12.8257 12.8403 12.8561 12.8705 12.8859 12.9 12.9153 12.929 12.9439 12.9575 12.972 12.9852 12.9995 13.0124 13.0263 13.0388 13.0524 13.0647 13.0779 13.0899 13.1027 13.1144 13.127 13.1383 13.1505 13.1615 13.1734 13.1841 13.1957 13.2061 13.2174 13.2275 13.2384 13.2483 13.2589 13.2686 13.2788 13.2882 13.2982 13.3074 13.317 13.3259 13.3353 13.344 13.3531 13.2813 10.237 10.9555 11.4321 11.6412 9.58694 10.2332 10.8401 11.1961 12.4753 9.20079 9.62938 9.85729 10.7605 13.0322 11.2994 11.5826 10.2619 11.1722 10.0153 10.6157 9.47332 9.85808 14.0843 14.5388 12.5961 12.6222 10.6407 11.106 14.0488 10.4816 10.7768 12.0584 12.221 10.4192 10.8314 12.3367 12.386 15.6878 15.5814 15.4476 12.7951 12.621 12.6701 12.3738 16.0652 17.1295 16.1004 13.3548 13.1384 14.0331 13.3958 15.6448 13.0345 12.6587 13.0608 12.6399 14.8928 11.0204 11.3652 13.0351 13.0553 13.5151 11.6656 11.9989 10.7006 11.435 11.9701 12.2253 9.9499 10.3161 10.4878 11.1679 9.68232 10.1111 9.73037 10.6278 9.51574 10.3246 11.7632 9.39334 10.1604 10.2336 10.6061 9.16605 9.90075 8.49971 8.95833 8.83461 9.48871 11.3498 9.92718 10.2981 8.25741 8.54306 9.22028 9.95019 8.90264 9.71369 8.62143 9.33965 8.12059 8.36971 9.11866 9.98554 12.166 10.6024 10.9812 8.8686 9.25262 19.2446 14.8527 14.1374 16.9179 15.1715 14.1439 7.6494 15.2701 32.9681 30.7018 29.1314 28.0266 27.1993 26.5268 25.9075 25.1975 24.624 24.1853 23.8628 23.5293 23.2896 23.0266 22.8407 22.627 22.476 22.2975 22.1701 22.0166 21.906 21.7706 21.6723 21.5504 21.4614 21.3499 21.2681 21.1648 21.0889 20.9923 20.9209 20.8297 20.7621 20.6754 20.6111 20.5283 20.4668 20.3875 20.3284 20.2521 20.1951 20.1215 20.0664 19.9952 19.9417 19.8726 19.8206 19.7534 19.7027 19.6374 19.5878 19.5241 19.4757 19.4134 19.366 19.3051 19.2585 19.1988 19.153 19.0944 19.0493 18.9916 18.9471 18.8902 18.8462 18.79 18.7465 18.6909 18.6477 18.5926 18.5497 18.495 18.4523 18.398 18.3555 18.3013 18.2589 18.2049 18.1624 18.1085 18.066 18.0119 17.9693 17.9151 17.8723 17.8179 17.7749 17.7201 17.6767 17.6216 17.5778 17.5222 17.4779 17.4217 17.3769 17.3201 17.2747 17.2172 17.1712 17.113 17.0663 17.0071 16.9597 16.8996 16.8514 16.7903 16.7413 16.6791 16.6291 16.5658 16.5148 16.4502 16.3982 16.3322 16.279 16.2116 16.1572 16.0882 16.0325 15.962 15.9049 15.8326 15.7742 15.7 15.6401 15.5641 15.5025 15.4245 15.3613 15.2812 15.2163 15.134 15.0673 14.9828 14.9142 14.8273 14.7568 14.6675 14.595 14.5031 14.4285 14.3339 14.2572 14.1599 14.0809 13.9807 13.8994 13.7962 13.7126 13.6063 13.5203 13.4109 13.3224 13.2098 13.1189 13.0031 12.9097 12.7907 12.695 12.5728 12.4746 12.3493 12.2485 12.1205 12.0166 11.8869 11.7782 11.6499 11.5315 11.4133 11.3261 11.2221 11.1404 11.0377 10.9553 10.851 10.7667 10.6604 10.5742 10.4661 10.3784 10.269 10.1803 10.07 9.98094 9.87033 9.78149 9.67124 9.58332 9.47416 9.3879 9.28057 9.19672 9.09198 9.01127 8.90988 8.83302 8.73572 8.66339 8.57072 8.50346 8.41604 8.35421 8.2724 8.21619 8.14013 8.08965 8.01946 7.97467 7.91028 7.87096 7.81204 7.77778 7.72405 7.6944 7.64552 7.62001 7.57551 7.55362 7.51311 7.49428 7.4572 7.44051 7.40639 7.39122 7.35969 7.34561 7.31593 7.30238 7.27356 7.25986 7.22969 7.21705 7.1813 7.16919 7.13946 7.11531 7.09992 7.04008 7.05775 7.19727 35.7801 7.40705 ) ; } rightWall { type calculated; value uniform 0; } symmetryLine { type symmetryPlane; } } // ************************************************************************* //
014881adf5c21f34c7f1bd5258df22c230fd83bc
8069c2519f114011f3b50f8133a4616707bb3693
/homework3/ex1.cpp
ff10f238c815333cecbd3173d7e8c1c022f02ff9
[ "MIT" ]
permissive
codeworm96/SE105-Programming-1
0ccd17a013bb8f6705bbfd1a3bc481b5f2a74052
9b82316d33779befcef8c641a85df7137006450a
refs/heads/master
2020-05-31T11:21:38.466090
2015-08-04T06:19:56
2015-08-04T06:19:56
40,160,067
4
0
null
null
null
null
GB18030
C++
false
false
471
cpp
ex1.cpp
/*本道题目的题号是:1 *要求是:编程求 1!+2!+…+12!,并试着简化程序。 */ #include <iostream> using namespace std; long factorial_sum(int n) { int fac = 1;//for factorial int sum = 0;//for sum for (int i = 1; i <= n; ++i){ fac *= i; sum += fac; }//calculate return sum; } int main() try{ //no input cout << "1!+2!+...+12!=" << factorial_sum(12) << endl;//output return 0; } catch (...){ cerr << "Unknown error!" << endl; return 1; }
07fb100f63ede18dcbc999d648600a5878640ca4
5380c83245a3cf71deb5bab469ee25e5ec6d402a
/c/sdl/03_event_driven/main.cpp
38d0ef23b28d34a7d5a46ba300cc48b366b555e5
[]
no_license
edo9k/learn
e45520ea1f923c6a2f46b830b654eafff593fc53
87ee38690e6fa19d3a830df06f0620175dacf1b9
refs/heads/master
2023-08-10T05:52:19.844586
2023-08-01T21:57:54
2023-08-01T21:57:54
121,974,250
2
0
null
null
null
null
UTF-8
C++
false
false
1,757
cpp
main.cpp
#include <SDL2/SDL.h> #include <stdio.h> // constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; // declarations bool init(); bool loadMedia(); void close(); // variables SDL_Window* gWindow = NULL; SDL_Surface* gScreenSurface = NULL; SDL_Surface* gXOut = NULL; // actual functions bool init() { bool success = true; if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { printf( "SDL did not init right. SDL_Error: %s\n", SDL_GetError()); success = false; } else { gWindow = SDL_CreateWindow( "SDL Tutorial 03", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if ( gWindow == NULL ) { printf("Window dit not init. SDL_Error: %s\n", SDL_GetError() ); success = false; } else { gScreenSurface = SDL_GetWindowSurface( gWindow ); } } return success; } bool loadMedia() { bool success = true; gXOut = SDL_LoadBMP("test.bmp"); if( gXOut == NULL ) { printf("Could not load image %s. SDL_Error %s\n", "test.bmp", SDL_GetError() ); success = false; } return success; } void close() { SDL_FreeSurface( gXOut ); gXOut = NULL; SDL_DestroyWindow( gWindow ); gWindow = NULL; SDL_Quit(); } int main( int argc, char* args[] ) { if ( init() && loadMedia() ) { bool quit = false; SDL_Event e; while ( !quit ) { while ( SDL_PollEvent( &e ) != 0 ) if ( e.type == SDL_QUIT ) { printf("Detected an SDL_QUIT event. Exiting...\n\n"); quit = true; } SDL_BlitSurface( gXOut, NULL, gScreenSurface, NULL ); SDL_UpdateWindowSurface( gWindow ); } } else printf("Some weird shit happned."); close(); return 0; }
0ffedc38a012a573b196e42c122dc44104404807
d74ce09a4e4dc5daa0ec1ca03721415bd8a16dd1
/Mc2Code/MiniCA/csp11/CertKitCsp.cpp
e36413516efbf8ca27b51ba52ba638032594af10
[]
no_license
zxlooong/minica
cdc01698db3a5c1e31ec8283cf97e67854cb3a14
f41977c2bc75e277515c47bae8ca7fb7c7c10275
refs/heads/master
2020-06-07T13:40:25.399117
2013-04-24T03:23:32
2013-04-24T03:23:32
7,943,806
3
4
null
null
null
null
GB18030
C++
false
false
46,020
cpp
CertKitCsp.cpp
////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <Rpc.h> //#include "dbglog.h" #include "CBase64.h" #include "MemTools.h" #include "Certificate.h" #include "CertKitCsp.h" using namespace MemTools; ////////////////////////////////////////////////////////////////////////// CCertKitCsp::CCertKitCsp() { Reset(); } BOOL CCertKitCsp::Reset() { // if not for specific csp, this must set to TRUE; m_bUseRegEnv = TRUE; m_hProv = NULL; m_hPrivKey = NULL; m_hStore = NULL; //Microsoft RSA Strong: default len = 1024bit m_lGenKeyFlag = CRYPT_EXPORTABLE | CRYPT_USER_PROTECTED; m_lKeySpec = AT_KEYEXCHANGE; //AT_SIGNATURE ; m_iEncAlg = CALG_DES; m_iHashAlg = CALG_SHA1; //support below 3 method: //#define szOID_RSA_MD5RSA "1.2.840.113549.1.1.4" //#define szOID_RSA_SHA1RSA "1.2.840.113549.1.1.5" //#define szOID_X957_SHA1DSA "1.2.840.10040.4.3" m_sReqSignAlgOid = szOID_RSA_MD5RSA; m_bReqUsingExitKeySet = TRUE; m_bReqWriteCert2Csp = TRUE; m_sReqRegKey = REG_SUB_KEY_TO_WRITE; m_sCtnName = GenGUID(); m_sReqCtnName = GenGUID(); m_lProvType = PROV_RSA_FULL; m_sCertReqCN = SZ_CERT_RDN_VALUE; m_CtnList.clear(); m_CspCertList.clear(); m_MyStoreCertList.clear(); m_CspList.clear(); m_RdnMap.clear(); //RSA Full: Microsoft RSA Strong Cryptographic Provider if(!GetDefaultCSP(m_sCspName, m_lProvType)) m_sCspName = _T("Microsoft RSA Strong Cryptographic Provider"); return TRUE; } CCertKitCsp::~CCertKitCsp() { if (m_hPrivKey) CryptDestroyKey(m_hPrivKey); if (m_hProv) CryptReleaseContext(m_hProv, 0); if (m_hStore) CertCloseStore(m_hStore, 0); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// BOOL CCertKitCsp::SetReqRegKey(const TCHAR* szRegKey) { if(szRegKey && _tcslen(szRegKey)>0) m_sReqRegKey = szRegKey; else return FALSE; return TRUE; } BOOL CCertKitCsp::GetReqRegKey(tstring &szRegKey) { szRegKey = m_sReqRegKey; return TRUE; } BOOL CCertKitCsp::SetCspName(const TCHAR* szCspName) { if(szCspName && _tcslen(szCspName)>0) m_sCspName = szCspName; else return FALSE; return TRUE; } BOOL CCertKitCsp::GetCspName(tstring& szCspName) { szCspName = m_sCspName; return TRUE; } BOOL CCertKitCsp::SetCspType(long lPtype) { m_lProvType = lPtype; return TRUE; } BOOL CCertKitCsp::GetCspType(long& lPtype) { lPtype = m_lProvType; return TRUE; } BOOL CCertKitCsp::SetCtnName(const TCHAR* szCtnName) { if(szCtnName && _tcslen(szCtnName)>0) m_sCtnName = szCtnName; else return false; return TRUE; } BOOL CCertKitCsp::GetCtnName(tstring& szCtnName) { szCtnName = m_sCtnName; return TRUE; } BOOL CCertKitCsp::GetReqCtnName(tstring& szCtnName) { szCtnName = m_sReqCtnName; return TRUE; } BOOL CCertKitCsp::SetReqCtnName(const TCHAR* szCtnName) { if(szCtnName && _tcslen(szCtnName)>0) m_sReqCtnName = szCtnName; else return false; return TRUE; } BOOL CCertKitCsp::SetHashAlg(ALG_ID iAlgID) { m_iHashAlg = iAlgID; return TRUE; } BOOL CCertKitCsp::GetHashAlg(ALG_ID& iAlgID) { iAlgID = m_iHashAlg; return TRUE; } BOOL CCertKitCsp::SetReqSignAlgOid(const TCHAR* szAlgOID) { if(szAlgOID && _tcslen(szAlgOID)>0) { CT2ACharBuf buf(szAlgOID); m_sReqSignAlgOid = buf.ptr; } else return FALSE; return TRUE; } BOOL CCertKitCsp::GetReqSignAlgOid(tstring& szAlgOID) { CA2TCharBuf buf(m_sReqSignAlgOid.c_str()); szAlgOID = buf.ptr; return TRUE; } BOOL CCertKitCsp::SetCryptAlg(ALG_ID iAlg) { m_iEncAlg = iAlg; return TRUE; } BOOL CCertKitCsp::GetCryptAlg(ALG_ID& iAlg) { iAlg = m_iEncAlg; return TRUE; } BOOL CCertKitCsp::SetKeySpec(long lKeySpec) { m_lKeySpec = lKeySpec; return TRUE; } BOOL CCertKitCsp::GetKeySpec(long& lKeySpec) { lKeySpec = m_lKeySpec; return TRUE; } BOOL CCertKitCsp::SetGenKeyFlag(long lFlag) { m_lGenKeyFlag = lFlag; return TRUE; } BOOL CCertKitCsp::GetGenKeyFlag(long& lFlag) { lFlag = m_lGenKeyFlag; return TRUE; } BOOL CCertKitCsp::SetBWriteCert2Csp(BOOL bTrue) { m_bReqWriteCert2Csp = bTrue; return TRUE; } BOOL CCertKitCsp::GetBWriteCert2Csp(BOOL& bTrue) { bTrue = m_bReqWriteCert2Csp; return TRUE; } BOOL CCertKitCsp::SetBUsingExitingKeySet(BOOL bTrue) { m_bReqUsingExitKeySet = bTrue; return TRUE; } BOOL CCertKitCsp::GetBUsingExitingKeySet(BOOL& bTrue) { bTrue = m_bReqUsingExitKeySet; return TRUE; } BOOL CCertKitCsp::SetBUseReqRegEnv(BOOL bTrue) { m_bUseRegEnv = bTrue; return TRUE; } BOOL CCertKitCsp::GetBUseReqRegEnv(BOOL& bTrue) { bTrue = m_bUseRegEnv; return TRUE; } BOOL CCertKitCsp::GetCtnList(Tstrlist &vcCtnList) { LONG lRet; BOOL bRet; lRet = EnumCtn(); bRet = lRet ? FALSE: TRUE; vcCtnList = m_CtnList; return bRet; } BOOL CCertKitCsp::SetCertReqCN(const TCHAR* szCertRdn) { if(szCertRdn && _tcslen(szCertRdn)>0) m_sCertReqCN = szCertRdn; else return FALSE; return TRUE; } BOOL CCertKitCsp::GetCertReqCN(tstring& szCertRdnName) { szCertRdnName = m_sCertReqCN; return TRUE; } BOOL CCertKitCsp::SetCertReqRdnName(const TCHAR* szRdntype, const TCHAR* szCertRdn) { return TRUE; } BOOL CCertKitCsp::GetCertReqRdnName(const TCHAR* szRdntype, tstring& szCertRdnName) { return TRUE; } BOOL CCertKitCsp::GetCertReqDnName(tstring& szCertDnName) { szCertDnName = m_sCertReqDN; return TRUE; } BOOL CCertKitCsp::SetCertReqDnName(const TCHAR* szCertDnName) { //"cn =asdfasdf, M=asdfasdf" //std::map<tstring> tRdnList; //TODO: clip sz 2 list, & clip every list item'rdn sz, & turn rdn sz 2 oid return TRUE; } BOOL CCertKitCsp::MsgGapFix(const TCHAR* szMsg, tstring& szMsgFix) { // \r or \n ---> \r\n szMsgFix = _T(""); tstring szToFixBuf = szMsg; int iToFixLen = _tcslen(szMsg); int ipos = 0; for(int i=0; i<iToFixLen; i++){ if ( (_T('\n') == szToFixBuf[i] || _T('\r') == szToFixBuf[i]) && !(_T('\r') == szToFixBuf[i-1] && _T('\n') == szToFixBuf[i]) && !(_T('\n') == szToFixBuf[i+1] && _T('\r') == szToFixBuf[i])) { szMsgFix += szToFixBuf.substr(ipos, i-ipos); ipos = i+1; szMsgFix += _T("\r\n"); } } if(ipos<iToFixLen) szMsgFix += szToFixBuf.substr(ipos,iToFixLen-ipos+1); //MessageBox(NULL, szToSign.c_str(), NULL, MB_OK); return TRUE; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// long CCertKitCsp::AlgStr2uiAlg(const TCHAR* szAlg, ALG_ID& uiAlg) { if (_tccmp(szAlg, _T("DES"))) { uiAlg = CALG_DES; return S_OK; } //hash else if (_tccmp(szAlg, _T("MD5")) || _tccmp(szAlg, _T("md5"))) { uiAlg = CALG_MD5; return S_OK; } else if (_tccmp(szAlg, _T("SHA1")) || _tccmp(szAlg, _T("sha1"))) { uiAlg = CALG_SHA1; return S_OK; } //symmetrical else if (_tccmp(szAlg, _T("DES"))) { uiAlg = CALG_DES; return S_OK; } else if (_tccmp(szAlg, _T("AES"))) { uiAlg = CALG_AES; return S_OK; } else if (_tccmp(szAlg, _T("3DES"))) { uiAlg = CALG_3DES; return S_OK; } //asymmetric else return S_FALSE; } LONG CCertKitCsp::AlgStr2szOID(const TCHAR* szAlg, tstring& szAlgOID) { // if (_tccmp(szAlg, _T("DES"))) // { szAlgOID = CALG_DES; return S_OK; } // // //hash // else if (_tccmp(szAlg, _T("MD5")) || _tccmp(szAlg, _T("md5"))) // { szAlgOID = CALG_MD5; return S_OK; } // // else if (_tccmp(szAlg, _T("SHA1")) || _tccmp(szAlg, _T("sha1"))) // { szAlgOID = CALG_SHA1; return S_OK; } // // // //symmetrical // else if (_tccmp(szAlg, _T("DES"))) // { szAlgOID = CALG_DES; return S_OK; } // // else if (_tccmp(szAlg, _T("AES"))) // { szAlgOID = CALG_AES; return S_OK; } // // else if (_tccmp(szAlg, _T("3DES"))) // { szAlgOID = CALG_3DES; return S_OK; } // // //asymmetric //certreq if (_tccmp(szAlg, _T("MD5RSASIGN")) || _tccmp(szAlg, _T("md5rsasign"))) { CA2TCharBuf buf(szOID_OIWSEC_md5RSASign); szAlgOID = buf.ptr; return S_OK; } else if (_tccmp(szAlg, _T("SHA1RSASIGN")) || _tccmp(szAlg, _T("sha1rsasign"))) { CA2TCharBuf buf(szOID_OIWSEC_sha1RSASign); szAlgOID = buf.ptr; return S_OK; } else if (_tccmp(szAlg, _T("MD5RSA")) || _tccmp(szAlg, _T("md5rsa"))) { CA2TCharBuf buf(szOID_OIWSEC_md5RSASign); szAlgOID = buf.ptr; return S_OK; } else if (_tccmp(szAlg, _T("SHA1RSA")) || _tccmp(szAlg, _T("sha1rsa"))) { CA2TCharBuf buf(szOID_OIWSEC_sha1RSASign); szAlgOID = buf.ptr; return S_OK; } else return S_FALSE; } BOOL CCertKitCsp::GetDefaultCSP(tstring &CspName, long lPtype) { BOOL bret = FALSE; DWORD lenth; bret = CryptGetDefaultProvider(lPtype, NULL, CRYPT_MACHINE_DEFAULT, NULL, &lenth); if (!bret) return bret; CTCharBuf pname(lenth); bret = CryptGetDefaultProvider(lPtype, NULL, CRYPT_MACHINE_DEFAULT, pname.ptr, &lenth); CspName = pname.ptr; return bret; } tstring CCertKitCsp::GenGUID() { tstring szname; UUID uuidName; #if defined(UNICODE) || defined(_UNICODE) unsigned short* UNamePtr = NULL; #else unsigned char* UNamePtr = NULL; #endif UuidCreate(&uuidName); UuidToString(&uuidName,&UNamePtr); szname = (TCHAR*)UNamePtr; RpcStringFree(&UNamePtr); return szname; } BOOL CCertKitCsp::GetCspList(const ulong lType, Tstrlist &vcCspList) { return EnumCSP(lType, vcCspList); } BOOL CCertKitCsp::EnumCSP(const ulong lType, Tstrlist &vcCspList) { vcCspList.clear(); DWORD nszName; DWORD dwType; DWORD idx = 0; while( CryptEnumProviders( idx, NULL, 0, &dwType, NULL, &nszName ) ) { TCHAR *pszName = NULL; pszName = (TCHAR *)new TCHAR[nszName]; CryptEnumProviders( idx, NULL, 0, &dwType, pszName, &nszName ); idx++; tstring str = pszName; if(lType == dwType) vcCspList.push_back(str); delete []pszName; } if (vcCspList.size()==0) return FALSE; return TRUE; } LONG CCertKitCsp::CertInfoFind(uchar *ucmodulus, ulong ulmodlen, tstring &szProvName, tstring &szCtnName, DWORD &dKeySpec, DWORD &dProvType) { if(!ucmodulus) return ERROR_INVALID_PARAMETER; LONG lRet = ERROR_SUCCESS; BOOL bFind = FALSE; HCRYPTPROV hProv = NULL; lRet = EnumCtn(); if(lRet) return lRet; if(m_CtnList.size()==0) return ERROR_NO_MORE_ITEMS; for (unsigned int i = 0; i<m_CtnList.size();i++) { lRet = CryptAcquireContext(&hProv, m_CtnList[i].c_str(), m_sCspName.c_str(), m_lProvType, 0); if (!lRet) continue; ulong nPubkeyInfo; lRet = CryptExportPublicKeyInfo(hProv, m_lKeySpec, XENCODETYPE, NULL, &nPubkeyInfo ); if (!lRet) continue; CByteBuf bufPubkeyInfo(nPubkeyInfo); lRet = CryptExportPublicKeyInfo(hProv, m_lKeySpec, XENCODETYPE, (PCERT_PUBLIC_KEY_INFO) bufPubkeyInfo.ptr, &nPubkeyInfo ); if (!lRet) continue; uchar ucbuf[4097]={0}; ulong ulbuflen = 4096; lRet = GetPubkeyModulus((PCERT_PUBLIC_KEY_INFO)bufPubkeyInfo.ptr, ucbuf, &ulbuflen); if(lRet) continue; if(0 == memcmp(ucbuf, ucmodulus, ulmodlen)) { bFind = TRUE; szProvName = m_sCspName; szCtnName = m_CtnList[i].c_str(); dKeySpec = m_lKeySpec; dProvType = m_lProvType; break; } } lRet = bFind?ERROR_SUCCESS:GetLastError(); return lRet; } LONG CCertKitCsp::GetPubkeyModulus(PCERT_PUBLIC_KEY_INFO pPubkeyInfo, uchar *cert_modulus, ulong *modulus_len) { if(!cert_modulus) return ERROR_INVALID_PARAMETER; BYTE *pData = NULL; UINT len_len = 0; short lenMod = 0; long mode_len = 0; CRYPT_BIT_BLOB &blob = pPubkeyInfo->PublicKey; pData = blob.pbData; if(*pData != 0x30){ return ERROR_INVALID_HANDLE; } pData += 1; if(*pData > 0x80){ len_len = *pData & 0x7f; pData += 1; pData += len_len; } else pData += 1; if(*pData != 0x02){ return ERROR_INVALID_HANDLE; } pData += 1; if(*pData > 0x80) { //*pData > 0x80,so len_len > 0 len_len = *pData & 0x7f; pData += 1; if(len_len == 1){ mode_len = *pData; } else{ FlipBuffer(pData,len_len); memcpy(&lenMod,pData,len_len); mode_len = lenMod; } pData += len_len; } else { mode_len = *pData; pData += 1; } //抠掉开头的0x00? ulong ulModulusLen = 0; if(*pData == 0x00) { pData += 1; ulModulusLen = mode_len-1; } else ulModulusLen = mode_len; if(cert_modulus == NULL) { *modulus_len = ulModulusLen; } else { if(*modulus_len < ulModulusLen) { return ERROR_INVALID_HANDLE; } *modulus_len = ulModulusLen; memcpy(cert_modulus,pData,ulModulusLen); } return ERROR_SUCCESS; } LONG CCertKitCsp::EnumCtn() { AutoHProv hProv; LONG lRet = ERROR_SUCCESS; m_CtnList.clear(); do { lRet = CryptAcquireContext(hProv,NULL,m_sCspName.c_str(),PROV_RSA_FULL,CRYPT_VERIFYCONTEXT); if(!lRet) break; uchar ucCtnBuf[100]={0}; DWORD ulCtnLen; lRet = CryptGetProvParam(hProv, PP_ENUMCONTAINERS, NULL, &ulCtnLen,CRYPT_FIRST); if(!lRet) break; lRet = CryptGetProvParam(hProv, PP_ENUMCONTAINERS, ucCtnBuf, &ulCtnLen,CRYPT_FIRST); if(!lRet) break; CA2TCharBuf tcbufa((char*)ucCtnBuf); m_CtnList.push_back(tcbufa.ptr); while(lRet) { lRet = CryptGetProvParam(hProv, PP_ENUMCONTAINERS, ucCtnBuf, &ulCtnLen, CRYPT_NEXT); if( !lRet && (ERROR_NO_MORE_ITEMS == GetLastError()) ){ lRet = TRUE; break; } ucCtnBuf[ulCtnLen] = 0; CA2TCharBuf tcbuf((char*)ucCtnBuf); m_CtnList.push_back(tcbuf.ptr); } } while (0); lRet = lRet?ERROR_SUCCESS:GetLastError(); return lRet; } void CCertKitCsp::FlipBuffer(uchar *pBuf, ulong ulLen) { if(0 == ulLen) return; unsigned char ucTemp; for(unsigned long i = 0; i < ulLen >> 1; ++i) { ucTemp = pBuf[i]; pBuf[i] = pBuf[ulLen - i - 1]; pBuf[ulLen - i - 1] = ucTemp; } } ////////////////////////////////////////////////////////////////////////// LONG CCertKitCsp::CreateP10(tstring& rszP10) { HRESULT hRet = ERROR_SUCCESS; BOOL bRet; rszP10 = _T(""); tstring szErrInfo; tstring strtmp; do{ bRet = CryptAcquireContext(&m_hProv, m_sReqCtnName.c_str(), m_sCspName.c_str(), m_lProvType, CRYPT_NEWKEYSET ); if( !bRet ) { hRet = GetLastError(); break; } bRet = CryptGenKey(m_hProv, m_lKeySpec, m_lGenKeyFlag, &m_hPrivKey); if( !bRet ) { hRet = GetLastError(); break; } DWORD nPubkeyInfo; bRet = CryptExportPublicKeyInfo(m_hProv, m_lKeySpec, XENCODETYPE, NULL, &nPubkeyInfo ); if( !bRet ) { hRet = GetLastError(); break; } CByteBuf bufPubkeyInfo(nPubkeyInfo); bRet = CryptExportPublicKeyInfo(m_hProv, m_lKeySpec, XENCODETYPE, (PCERT_PUBLIC_KEY_INFO) bufPubkeyInfo.ptr, &nPubkeyInfo ); if( !bRet ) { hRet = GetLastError(); break; } CERT_NAME_BLOB certNameBlob; CByteBuf bufCertNameBb(4096); certNameBlob.pbData = bufCertNameBb.ptr; if (m_RdnMap.size() == 0) X509CNStuff(certNameBlob); else X509DNStuff(certNameBlob); CERT_REQUEST_INFO pCertReqInfo; pCertReqInfo.dwVersion = CERT_REQUEST_V1; pCertReqInfo.Subject = certNameBlob; pCertReqInfo.SubjectPublicKeyInfo = *(CERT_PUBLIC_KEY_INFO*)(bufPubkeyInfo.ptr); pCertReqInfo.cAttribute = 0; pCertReqInfo.rgAttribute = NULL; CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CRYPT_OBJID_BLOB Parameters; memset(&Parameters, 0, sizeof(Parameters)); //DBGLOG(("m_sReqAlg = %s, len=%d", m_sReqSignAlgOid.c_str(), m_sReqSignAlgOid.length())); //support below 3 method: //#define szOID_RSA_MD5RSA "1.2.840.113549.1.1.4" //#define szOID_RSA_SHA1RSA "1.2.840.113549.1.1.5" //#define szOID_X957_SHA1DSA "1.2.840.10040.4.3" SignatureAlgorithm.pszObjId = (LPSTR)m_sReqSignAlgOid.c_str(); SignatureAlgorithm.Parameters = Parameters; DWORD cbEncodeCertReqInfo; bRet = CryptSignAndEncodeCertificate( m_hProv, m_lKeySpec, X509_ASN_ENCODING, X509_CERT_REQUEST_TO_BE_SIGNED, &pCertReqInfo, &SignatureAlgorithm, NULL, NULL, &cbEncodeCertReqInfo ); if( !bRet ) { hRet = GetLastError(); break; } CByteBuf pbEncodeCertReqInfo(cbEncodeCertReqInfo); bRet = CryptSignAndEncodeCertificate( m_hProv, m_lKeySpec, X509_ASN_ENCODING, X509_CERT_REQUEST_TO_BE_SIGNED, &pCertReqInfo, &SignatureAlgorithm, NULL, pbEncodeCertReqInfo.ptr, &cbEncodeCertReqInfo ); if( !bRet ) { hRet = GetLastError(); break; } tstring szhashPubkey = HashPubKeyInfo(m_hProv, &pCertReqInfo.SubjectPublicKeyInfo); if(m_bUseRegEnv) CertInfoBackup(m_sCspName, m_sReqCtnName, szhashPubkey, m_lKeySpec, m_lProvType); DWORD cbBase64EncodeCertReqInfo = cbEncodeCertReqInfo*2+128; CTCharBuf pbBase64EncodeCertReqInfo(cbBase64EncodeCertReqInfo); CBase64::Encode(pbEncodeCertReqInfo.ptr, cbEncodeCertReqInfo, pbBase64EncodeCertReqInfo.ptr, &cbBase64EncodeCertReqInfo); rszP10 = pbBase64EncodeCertReqInfo.ptr; #if defined(_DEBUG) || defined(DEBUG) MessageBox(NULL, rszP10.c_str(), szhashPubkey.c_str(), MB_OK); #endif }while(0); if( m_hPrivKey ) CryptDestroyKey(m_hPrivKey); if( m_hProv ) CryptReleaseContext(m_hProv,0); return hRet; } LONG CCertKitCsp::AcceptP7(const TCHAR* szP7, int iType) { LONG lRet = 0; HRESULT hRet = S_OK; HCRYPTMSG hP7 = NULL; do{ BOOL bRet; hP7 = CryptMsgOpenToDecode(XENCODETYPE, 0, 0, 0, NULL, NULL ); tstring szP7b64; PemHandle(szP7, szP7b64); unsigned long binp7len = szP7b64.length(); CByteBuf binp7(binp7len*2); CBase64::Decode(szP7b64.c_str(), binp7.ptr, &binp7len); bRet = CryptMsgUpdate(hP7, binp7.ptr, binp7len, TRUE); if( !bRet ) { hRet = GetLastError(); break; } DWORD certCount = 0; DWORD cbLen = sizeof(certCount); CryptMsgGetParam(hP7,CMSG_CERT_COUNT_PARAM,0,&certCount, &cbLen); if( certCount == 0 ) { hRet = GetLastError(); break; } for( ulong i = 0 ; i < (certCount > 10 ? 10: certCount) ; i++ ) { DWORD cbCertLen = 0; CryptMsgGetParam(hP7,CMSG_CERT_PARAM,i,NULL, &cbCertLen); CByteBuf certBuf(cbCertLen); CryptMsgGetParam(hP7,CMSG_CERT_PARAM,i,certBuf.ptr, &cbCertLen); PCCERT_CONTEXT pCert=CertCreateCertificateContext(XENCODETYPE, certBuf.ptr,cbCertLen); tstring szProvName, szCtnName; DWORD dwKeySpec, dwProvType; uchar ucmodulus[4096] = {0}; ulong ulmodlen; tstring szHashPubkey = HashPubKeyInfo(NULL, &pCert->pCertInfo->SubjectPublicKeyInfo); tstring szRegKey = m_sReqRegKey; szRegKey += _T("\\"); szRegKey += szHashPubkey; HKEY hKeydir = NULL; lRet = RegOpenKeyEx(HKEY_CURRENT_USER, szRegKey.c_str(), 0, KEY_ALL_ACCESS, &hKeydir ); if( lRet == ERROR_SUCCESS ) { RegCloseKey(hKeydir); lRet = CertInfoRecovery(szHashPubkey, szProvName, szCtnName, dwKeySpec, dwProvType); } else { CCertificate curcert; curcert.Attach(pCert); curcert.GetModulus(ucmodulus, &ulmodlen); lRet = CertInfoFind(ucmodulus, ulmodlen, szProvName, szCtnName, dwKeySpec, dwProvType); } if( lRet == ERROR_SUCCESS ) { HCERTSTORE hMyStore = NULL; hMyStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"My" ); if( hMyStore == NULL ){ hRet = GetLastError(); break; } CRYPT_KEY_PROV_INFO keyProvInfo; CT2WCharBuf szwProvName(szProvName.c_str()); CT2WCharBuf szwCtnName(szCtnName.c_str()); keyProvInfo.pwszProvName = szwProvName.ptr; keyProvInfo.pwszContainerName = szwCtnName.ptr; keyProvInfo.dwProvType = dwProvType; keyProvInfo.dwFlags = 0; keyProvInfo.cProvParam = 0; keyProvInfo.rgProvParam = NULL; keyProvInfo.dwKeySpec = dwKeySpec; bRet = CertSetCertificateContextProperty( pCert, CERT_KEY_PROV_INFO_PROP_ID, CERT_STORE_NO_CRYPT_RELEASE_FLAG, &keyProvInfo ); if( !bRet ) { hRet = GetLastError(); break; } bRet = CertAddCertificateContextToStore( hMyStore, pCert, CERT_STORE_ADD_REPLACE_EXISTING, NULL); CertCloseStore(hMyStore,0); if( !bRet ) { hRet = GetLastError(); break; } // 将证书写入CSP if( m_bReqWriteCert2Csp ) { bRet = CryptAcquireContext(&m_hProv, szCtnName.c_str(), szProvName.c_str(), dwProvType,0); if( !bRet || m_hProv == NULL ){ hRet = GetLastError(); break; } bRet = CryptGetUserKey(m_hProv, dwKeySpec, &m_hPrivKey); if( !bRet || m_hPrivKey == NULL ){ hRet = GetLastError(); break; } bRet = CryptSetKeyParam(m_hPrivKey, KP_CERTIFICATE,certBuf.ptr,0); } m_sReqCtnName = szCtnName; m_sCspName = szProvName; if (m_bUseRegEnv) RegDeleteKey(HKEY_CURRENT_USER, szRegKey.c_str()); } else { // 安装ROOT证书 BOOL bRoot = FALSE; if( (pCert->pCertInfo->Issuer.cbData == pCert->pCertInfo->Subject.cbData) &&(memcmp(pCert->pCertInfo->Issuer.pbData, pCert->pCertInfo->Subject.pbData, pCert->pCertInfo->Subject.cbData) == 0) ) { bRoot = TRUE; } void * storeName = L"Ca"; if(bRoot) storeName = L"Root"; HCERTSTORE hSysStore = NULL; hSysStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, storeName); CertAddCertificateContextToStore(hSysStore,pCert,CERT_STORE_ADD_USE_EXISTING,NULL); CertCloseStore(hSysStore,0); } CertFreeCertificateContext(pCert); } }while(0); if( hP7 ) CryptMsgClose(hP7); if( m_hPrivKey ) CryptDestroyKey(m_hPrivKey); if( m_hProv ) CryptReleaseContext(m_hProv,0); return hRet; } LONG CCertKitCsp::AcceptCert(const TCHAR* szCert, int iType) { if(!szCert) return ERROR_INVALID_PARAMETER; LONG lRet = 0; HRESULT hRet = ERROR_SUCCESS; BOOL bRet; tstring szCertb64; PemHandle(szCert, szCertb64); unsigned long binCertLen = szCertb64.length(); CByteBuf binCert(binCertLen); CBase64::Decode(szCertb64.c_str(), binCert.ptr, &binCertLen); do{ PCCERT_CONTEXT pCert=CertCreateCertificateContext(XENCODETYPE, binCert.ptr, binCertLen); if(!pCert){ hRet = GetLastError(); break; } tstring szProvName, szCtnName; DWORD dwKeySpec, dwProvType; uchar ucmodulus[4096] = {0}; ulong ulmodlen; tstring szHashPubkey = HashPubKeyInfo(NULL, &pCert->pCertInfo->SubjectPublicKeyInfo); tstring szRegKey = m_sReqRegKey; szRegKey += _T("\\"); szRegKey += szHashPubkey; HKEY hKeydir = NULL; lRet = RegOpenKeyEx(HKEY_CURRENT_USER, szRegKey.c_str(), 0, KEY_ALL_ACCESS, &hKeydir ); if( lRet == ERROR_SUCCESS ) { RegCloseKey(hKeydir); lRet = CertInfoRecovery(szHashPubkey, szProvName, szCtnName, dwKeySpec, dwProvType); } else { CCertificate curcert; curcert.Attach(pCert); curcert.GetModulus(ucmodulus, &ulmodlen); lRet = CertInfoFind(ucmodulus, ulmodlen, szProvName, szCtnName, dwKeySpec, dwProvType); if(lRet){ hRet = lRet; break; } } if( lRet == ERROR_SUCCESS ) { HCERTSTORE hMyStore = NULL; hMyStore = CertOpenStore( CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"My" ); if( hMyStore == NULL ){ hRet = GetLastError(); break; } CRYPT_KEY_PROV_INFO keyProvInfo; CT2WCharBuf szwProvName(szProvName.c_str()); CT2WCharBuf szwCtnName(szCtnName.c_str()); keyProvInfo.pwszProvName = szwProvName.ptr; keyProvInfo.pwszContainerName = szwCtnName.ptr; keyProvInfo.dwProvType = dwProvType; keyProvInfo.dwFlags = 0; keyProvInfo.cProvParam = 0; keyProvInfo.rgProvParam = NULL; keyProvInfo.dwKeySpec = dwKeySpec; bRet = CertSetCertificateContextProperty( pCert, CERT_KEY_PROV_INFO_PROP_ID, CERT_STORE_NO_CRYPT_RELEASE_FLAG, &keyProvInfo ); if( !bRet ) { hRet = GetLastError(); break; } bRet = CertAddCertificateContextToStore( hMyStore, pCert, CERT_STORE_ADD_REPLACE_EXISTING, NULL); CertCloseStore(hMyStore,0); if( !bRet ) { hRet = GetLastError(); break; } // 将证书写入CSP if( m_bReqWriteCert2Csp ) { bRet = CryptAcquireContext(&m_hProv, szCtnName.c_str(), szProvName.c_str(), dwProvType,0); if( !bRet || m_hProv == NULL ){ hRet = GetLastError(); break; } bRet = CryptGetUserKey(m_hProv, dwKeySpec, &m_hPrivKey); if( !bRet || m_hPrivKey == NULL ){ hRet = GetLastError(); break; } bRet = CryptSetKeyParam(m_hPrivKey, KP_CERTIFICATE,binCert.ptr,0); } m_sReqCtnName = szCtnName; m_sCspName = szProvName; if (m_bUseRegEnv) RegDeleteKey(HKEY_CURRENT_USER, szRegKey.c_str()); } }while(0); if( m_hPrivKey ) CryptDestroyKey(m_hPrivKey); if( m_hProv ) CryptReleaseContext(m_hProv,0); return hRet; } LONG CCertKitCsp::AcceptP12(const TCHAR* szP12, const TCHAR* szPsw, int iOpt) { return S_OK; } // // int // CCertKitCsp::FormPrivateKeyBlob(PBYTE pKey, DWORD dwKeyLen, DWORD keyalg, // PBYTE& pKeyBlob, DWORD &dwBlobLen) // { // ULONG ulRet = 0x7300; // BLOBHEADER header; // RSAPUBKEY pubkey; // // header.bType = PRIVATEKEYBLOB; // header.bVersion = CUR_BLOB_VERSION; // header.aiKeyAlg = keyalg; // header.reserved = 0; // // pubkey.bitlen = 1024; // pubkey.magic = 0x32415352; // pubkey.pubexp = 65537; // // PBYTE pPos = pKey + 2; // PBYTE pLen = pKey + 1; // WORD dwLen =0; // DWORD dwN,dwD,dwE,dwP,dwQ,dwDmp1,dwDmq1,dwIqmp; // // if(0x82 == *pLen) // { // dwLen = *pPos; // dwLen <<= 8; // dwLen |= *(pPos + 1); // } // else if(0x81 == *pLen) // dwLen = *(BYTE*)pPos; // // DWORD dwTotalLen = 0; // // // if(dwKeyLen - 4 != dwLen) return ulRet; // dwKeyLen = dwLen +4; // //n // pPos += 3 + 2 + 2; // if(0x0 == *(pPos + 1)){ // dwN = *pPos - 1; pPos += 2; // } // else{ // dwN = *pPos; pPos ++; // } // dwTotalLen += dwN; // PBYTE n = (PBYTE) malloc(dwN); // memcpy(n,pPos,dwN); // pPos += dwN + 1; // // //e // dwE = *pPos; // // dwTotalLen += dwE; // PBYTE e = (PBYTE)malloc(dwE); // memcpy(e,pPos+1,dwE); // pPos += dwE + 1 + 2; // // //skip d // if(0x0 == *(pPos + 1)){ // dwD = *pPos - 1; pPos += 2; // } // else{ // dwD = *pPos; pPos ++; // } // dwTotalLen += dwD; // PBYTE d = (PBYTE)malloc(dwD); // memcpy(d,pPos,dwD); // pPos += dwD + 1; // // //p // if(0x0 == *(pPos + 1)){ // dwP = *pPos - 1; pPos += 2; // } // else{ // dwP = *pPos; pPos ++; // } // dwTotalLen += dwP; // PBYTE p = (PBYTE)malloc(dwP); // memcpy(p,pPos,dwP); // pPos += dwP + 1; // // //q // if(0x0 == *(pPos + 1)){ // dwQ = *pPos - 1; pPos += 2; // } // else{ // dwQ = *pPos; pPos ++; // } // dwTotalLen += dwQ; // PBYTE q = (PBYTE)malloc(dwQ); // memcpy(q,pPos,dwQ); // pPos += dwQ + 1; // // //dmp1 // if(0x0 == *(pPos + 1)){ // dwDmp1 = *pPos - 1; pPos += 2; // } // else{ // dwDmp1 = *pPos; pPos ++; // } // dwTotalLen += dwDmp1; // PBYTE dmp1 = (PBYTE)malloc(dwDmp1); // memcpy(dmp1,pPos,dwDmp1); // pPos += dwDmp1 + 1; // // //dmp1 // if(0x0 == *(pPos + 1)){ // dwDmq1 = *pPos - 1; pPos += 2; // } // else{ // dwDmq1 = *pPos; pPos ++; // } // dwTotalLen += dwDmq1; // PBYTE dmq1 = (PBYTE)malloc(dwDmq1); // memcpy(dmq1,pPos,dwDmq1); // pPos += dwDmq1 + 1; // // //iqmp // if(0x0 == *(pPos + 1)){ // dwIqmp = *pPos - 1; pPos += 2; // } // else{ // dwIqmp = *pPos; pPos ++; // } // dwTotalLen += dwIqmp; // PBYTE iqmp = (PBYTE)malloc(dwIqmp); // memcpy(iqmp,pPos,dwIqmp); // // if(dwTotalLen != pubkey.bitlen*9/16) return ulRet; // // dwBlobLen = sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) + dwTotalLen; // PBYTE pTemp = (PBYTE) malloc(dwBlobLen); // // pKeyBlob = pTemp; // // memcpy(pTemp,&header,sizeof(BLOBHEADER)); // pTemp += sizeof(BLOBHEADER); // memcpy(pTemp,&pubkey,sizeof(RSAPUBKEY)); // pTemp += sizeof(RSAPUBKEY); // // //Reverse the byte sequence for private blob // MemoryReverse(n,dwN); // MemoryReverse(p,dwP); // MemoryReverse(q,dwQ); // MemoryReverse(dmp1,dwDmp1); // MemoryReverse(dmq1,dwDmq1); // MemoryReverse(iqmp,dwIqmp); // MemoryReverse(d,dwD); // /**/ // memcpy(pTemp,n,dwN); // pTemp += dwN; // memcpy(pTemp,p,dwP); // pTemp += dwP; // memcpy(pTemp,q,dwQ); // pTemp += dwQ; // memcpy(pTemp,dmp1,dwDmp1); // pTemp += dwDmp1; // memcpy(pTemp,dmq1,dwDmq1); // pTemp += dwDmq1; // memcpy(pTemp,iqmp,dwIqmp); // pTemp += dwIqmp; // memcpy(pTemp,d,dwD); // pTemp += dwD; // // if(n) free(n); // if(e) free(e); // if(d) free(d); // if(p) free(p); // if(q) free(q); // if(dmp1) free(dmp1); // if(dmq1) free(dmq1); // if(iqmp) free(iqmp); // // return 0; // } void CCertKitCsp::MemoryReverse(PBYTE &pData,DWORD dwLen) { BYTE b; PBYTE pBegin,pEnd; DWORD dwMid = dwLen /2; pBegin = pData; pEnd = pData + dwLen -1; while(pBegin < pEnd) { b = *pBegin; *pBegin = *pEnd; *pEnd = b; pBegin++; pEnd--; } } LONG CCertKitCsp::CertInfoBackup(tstring szProvName, tstring szCtnName, tstring szHashPubkey, DWORD dKeySpec, DWORD dProvType) { HKEY hdir = NULL; LONG lRet = S_OK; tstring sztmp; tstring szRegKey = m_sReqRegKey; szRegKey += _T("\\"); szRegKey += szHashPubkey; lRet = RegCreateKeyEx( HKEY_CURRENT_USER, szRegKey.c_str(), 0, NULL, 0, KEY_ALL_ACCESS,NULL, &hdir, NULL ); if( lRet != 0 ) return S_FALSE; // ProviderName RegSetValueEx(hdir, SZ_CERT_PRVNAME, 0, REG_SZ,(BYTE*)szProvName.c_str(), szProvName.length()*sizeof(TCHAR)); // ContainerName RegSetValueEx(hdir, SZ_CERT_CTNNAME, 0, REG_SZ, (BYTE*)szCtnName.c_str(), szCtnName.length()*sizeof(TCHAR)); // KeySpec RegSetValueEx(hdir, SZ_CERT_KEYSPEC, 0, REG_DWORD, (BYTE*)&dKeySpec, sizeof(DWORD)); // ProviderType RegSetValueEx(hdir, SZ_CERT_PRVTYPE, 0, REG_DWORD, (BYTE*)&dProvType, sizeof(DWORD)); // PublicKeyHash RegSetValueEx(hdir, SZ_CERT_PUBHASH, 0, REG_SZ, (BYTE *)szHashPubkey.c_str(), szHashPubkey.length()*sizeof(TCHAR)); // GenTime SYSTEMTIME systime; GetLocalTime(&systime); TCHAR timebuf[128]; wsprintf(timebuf,_T("%04d-%02d-%02d %02d:%02d:%02d") , systime.wYear,systime.wMonth,systime.wDay , systime.wHour,systime.wMinute,systime.wSecond); sztmp = timebuf; RegSetValueEx(hdir, SZ_CERT_GENTIME, 0, REG_SZ, (BYTE*)sztmp.c_str(), sztmp.length()*sizeof(TCHAR)); RegCloseKey(hdir); //TODO: error handle return TRUE; } LONG CCertKitCsp::CertInfoRecovery(tstring &szPubkeyHash, tstring &szProvName, tstring &szCtnName, DWORD &dwKeySpec, DWORD &dwProvType) { HKEY hKeydir = NULL; LONG lRet = S_OK; tstring sztmp; tstring szRegKey = m_sReqRegKey; szRegKey += _T("\\"); szRegKey += szPubkeyHash; do { lRet = RegOpenKeyEx(HKEY_CURRENT_USER, szRegKey.c_str(), 0, KEY_ALL_ACCESS, &hKeydir ); if( lRet != ERROR_SUCCESS ) break; DWORD vType = 0; DWORD vLen = 0; // ProviderName lRet = RegQueryValueEx(hKeydir, SZ_CERT_PRVNAME, NULL, &vType, NULL, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_SZ ) break; CTCharBuf providerName(vLen+1); lRet = RegQueryValueEx(hKeydir, SZ_CERT_PRVNAME, NULL, &vType, (BYTE*)providerName.ptr, &vLen); if(lRet != ERROR_SUCCESS || vType != REG_SZ ) break; szProvName = providerName.ptr; // ContainerName lRet = RegQueryValueEx(hKeydir, SZ_CERT_CTNNAME, NULL, &vType, NULL, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_SZ ) break; CTCharBuf containerName(vLen+1); lRet = RegQueryValueEx(hKeydir, SZ_CERT_CTNNAME, NULL, &vType, (BYTE*)containerName.ptr, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_SZ ) break; szCtnName = containerName.ptr; // ProviderType lRet = RegQueryValueEx(hKeydir, SZ_CERT_PRVTYPE, NULL, &vType, NULL, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_DWORD ) break; DWORD providerType = 0; lRet = RegQueryValueEx(hKeydir, SZ_CERT_PRVTYPE, NULL, &vType, (BYTE *)&providerType, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_DWORD ) break; dwKeySpec = providerType; // KeySpec lRet = RegQueryValueEx(hKeydir, SZ_CERT_KEYSPEC, NULL, &vType, NULL, &vLen); if(lRet != ERROR_SUCCESS || vType != REG_DWORD ) break; DWORD keySpec = 0; lRet = RegQueryValueEx(hKeydir, SZ_CERT_KEYSPEC, NULL, &vType, (BYTE *)&keySpec, &vLen ); if(lRet != ERROR_SUCCESS || vType != REG_DWORD ) break; dwProvType = keySpec; RegCloseKey(hKeydir); hKeydir = NULL; } while (0); if(lRet != ERROR_SUCCESS) lRet = GetLastError(); return lRet; } tstring CCertKitCsp::HashPubKeyInfo(HCRYPTPROV hProv, CERT_PUBLIC_KEY_INFO *keyinfo) { TCHAR hashed[256] = {0}; BYTE hash[128]; DWORD hashlen = sizeof(hash); tstring szHashed; CryptHashPublicKeyInfo(NULL, CALG_SHA1, 0, XENCODETYPE, keyinfo, hash, &hashlen); for( ulong i = 0 ; i < hashlen ; i++ ) _stprintf(hashed + i * 2, _T("%02x"), hash[i]); szHashed = hashed; return szHashed; } LONG CCertKitCsp::InstallRootCert(PCERT_CONTEXT pCert) { HCERTSTORE hSysStore = NULL; TCHAR szStore[20] = {0}; LONG lRet = ERROR_SUCCESS; return lRet; } LONG CCertKitCsp::InstallRootCert(TCHAR* szB64Cert) { if (!szB64Cert) return ERROR_BAD_ARGUMENTS; LONG lRet = ERROR_SUCCESS; CCertificate Cert(szB64Cert); if (!Cert.IsAttached()) return ERROR_INVALID_HANDLE; HCERTSTORE hSysStore = NULL; WCHAR szStore[20] = {0}; do { CByteBuf pbCertBuf(_tcslen(szB64Cert)*2); DWORD certlen = _tcslen(szB64Cert)*2; CBase64::Decode(szB64Cert, pbCertBuf.ptr, &certlen); if(CryptVerifyCertificateSignature(NULL, XENCODETYPE, pbCertBuf.ptr, certlen, &Cert.GetContext()->pCertInfo->SubjectPublicKeyInfo)) { wcscpy(szStore, L"ROOT"); break; } BOOL bIsCACert = FALSE, bIsEntity = FALSE, bHasCAUsage = FALSE; PCERT_EXTENSION pExt3; pExt3 = CertFindExtension(szOID_BASIC_CONSTRAINTS2, Cert.GetContext()->pCertInfo->cExtension, Cert.GetContext()->pCertInfo->rgExtension); PCERT_BASIC_CONSTRAINTS2_INFO pInfo; DWORD cbInfo; if(NULL != pExt3) { if(TRUE == CryptDecodeObject(X509_ASN_ENCODING, X509_BASIC_CONSTRAINTS2, pExt3->Value.pbData, pExt3->Value.cbData, NULL, NULL, &cbInfo)) { pInfo =(PCERT_BASIC_CONSTRAINTS2_INFO)LocalAlloc(LPTR, cbInfo); if(NULL != pInfo) { if(TRUE == CryptDecodeObject(X509_ASN_ENCODING, X509_BASIC_CONSTRAINTS2, pExt3->Value.pbData, pExt3->Value.cbData, NULL, pInfo, &cbInfo)) { bIsCACert = pInfo->fCA; bIsEntity = !pInfo->fCA; } } } } BYTE KeyUsageBits; // Intended key usage bits copied to here. DWORD cbKeyUsageByteCount = 1; // 1 byte will be copied to *pbKeyUsage BOOL Return = CertGetIntendedKeyUsage(X509_ASN_ENCODING, Cert.GetContext()->pCertInfo,&KeyUsageBits,cbKeyUsageByteCount); if(Return) { if((KeyUsageBits & CERT_KEY_CERT_SIGN_KEY_USAGE) ||(KeyUsageBits & CERT_CRL_SIGN_KEY_USAGE)) { bHasCAUsage = TRUE; } } if(bIsEntity) { wcscpy(szStore, L"ADDRESSBOOK"); break; } if(bIsCACert || bHasCAUsage) { wcscpy(szStore, L"CA"); break; } wcscpy(szStore, L"CA"); }while (0); do { hSysStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_NO_CRYPT_RELEASE_FLAG, szStore); if (!hSysStore) { lRet = GetLastError(); break; } if(!CertAddCertificateContextToStore(hSysStore, Cert.GetContext(), CERT_STORE_ADD_USE_EXISTING,NULL)){ lRet = GetLastError(); break; } } while (0); if (hSysStore) CertCloseStore(hSysStore, 0); return lRet; } LONG CCertKitCsp::X509DNStuff(CERT_NAME_BLOB &certNameBlob) { LONG lret = ERROR_SUCCESS; BOOL bRet = FALSE; //char* szRdn = (char*)malloc(m_sCertRdn.length()*2); //memset(szRdn, 0, m_sCertRdn.length()*2); CT2UTF8CharBuf t2aBuf(m_sCertReqCN.c_str()); //strcpy(szRdn, t2aBuf.ptr); //m_Ptrs.add((byte*)szRdn); // RDN VALUE CERT_RDN_VALUE_BLOB blobCn; blobCn.pbData = (BYTE *) t2aBuf.ptr; blobCn.cbData = strlen(t2aBuf.ptr); // RDN ATTR : CN = VALUE CERT_RDN_ATTR certRdnAttr[1]; certRdnAttr[0].pszObjId = szOID_COMMON_NAME; certRdnAttr[0].dwValueType = CERT_RDN_PRINTABLE_STRING;//CERT_RDN_UTF8_STRING;// | CERT_RDN_ENABLE_UTF8_UNICODE_FLAG; certRdnAttr[0].Value = blobCn; // DN : ... CERT_RDN certRdn[1]; certRdn[0].cRDNAttr = 1; certRdn[0].rgRDNAttr = certRdnAttr; // NAME_INFO CERT_NAME_INFO certNameInfo; certNameInfo.cRDN = 1; certNameInfo.rgRDN = certRdn; DWORD cbEncoded; CryptEncodeObject(XENCODETYPE, X509_NAME, &certNameInfo, NULL, &cbEncoded ); CByteBuf bufCertNameInfo(cbEncoded); CryptEncodeObject(XENCODETYPE, X509_NAME, &certNameInfo, bufCertNameInfo.ptr, &cbEncoded); memcpy(certNameBlob.pbData, bufCertNameInfo.ptr, cbEncoded); certNameBlob.cbData = cbEncoded; // certNameBlob.pbData = bufCertNameInfo.ptr; return lret; } LONG CCertKitCsp::X509CNStuff(CERT_NAME_BLOB &certNameBlob) { LONG lret = ERROR_SUCCESS; BOOL bRet = FALSE; //char* szRdn = (char*)malloc(m_sCertRdn.length()*2); //memset(szRdn, 0, m_sCertRdn.length()*2); CT2UTF8CharBuf t2aBuf(m_sCertReqCN.c_str()); //strcpy(szRdn, t2aBuf.ptr); //m_Ptrs.add((byte*)szRdn); // RDN VALUE CERT_RDN_VALUE_BLOB blobCn; blobCn.pbData = (BYTE *) t2aBuf.ptr; blobCn.cbData = strlen(t2aBuf.ptr); // RDN ATTR : CN = VALUE CERT_RDN_ATTR certRdnAttr[1]; certRdnAttr[0].pszObjId = szOID_COMMON_NAME; certRdnAttr[0].dwValueType = CERT_RDN_PRINTABLE_STRING;//CERT_RDN_UTF8_STRING;// | CERT_RDN_ENABLE_UTF8_UNICODE_FLAG; certRdnAttr[0].Value = blobCn; // DN : ... CERT_RDN certRdn[1]; certRdn[0].cRDNAttr = 1; certRdn[0].rgRDNAttr = certRdnAttr; // NAME_INFO CERT_NAME_INFO certNameInfo; certNameInfo.cRDN = 1; certNameInfo.rgRDN = certRdn; DWORD cbEncoded; CryptEncodeObject(XENCODETYPE, X509_NAME, &certNameInfo, NULL, &cbEncoded ); CByteBuf bufCertNameInfo(cbEncoded); CryptEncodeObject(XENCODETYPE, X509_NAME, &certNameInfo, bufCertNameInfo.ptr, &cbEncoded); memcpy(certNameBlob.pbData, bufCertNameInfo.ptr, cbEncoded); certNameBlob.cbData = cbEncoded; // certNameBlob.pbData = bufCertNameInfo.ptr; return lret; } LONG CCertKitCsp::HashData(const BYTE* pdata, long datalen,tstring& szHash) { HCRYPTPROV hCryptProv = NULL; HCRYPTHASH hHash = NULL; long lRet = S_FALSE; DWORD dwHashLen = 0; BYTE pHashValue[512] = {0}; //签名值 int i = 0; TCHAR szHashBuf[100] = {0}; do { if(!CryptAcquireContext(&hCryptProv,NULL, NULL,PROV_RSA_FULL, 0)) if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) break; if(!CryptCreateHash(hCryptProv, m_iHashAlg, 0, 0, &hHash)) break; if (!CryptHashData(hHash, (const unsigned char *)pdata, datalen, 0 )) break; if(!CryptGetHashParam(hHash,HP_HASHVAL ,NULL,&dwHashLen,0)) break; if(!CryptGetHashParam(hHash,HP_HASHVAL,pHashValue,&dwHashLen,0)) break; for (i=0; i<(int)dwHashLen; i++) _stprintf(&(szHashBuf[i*2]), _T("%02X"), pHashValue[i]); szHash = szHashBuf; } while (0); lRet = GetLastError(); if(hHash) CryptDestroyHash(hHash); if(hCryptProv) CryptReleaseContext(hCryptProv, 0); return lRet; } LONG CCertKitCsp::VerifySignData(const TCHAR* szdata, const TCHAR* szSignature, const TCHAR* szCert, ulong ulOpt) { LONG lRet = ERROR_SUCCESS; if (!szdata || !szSignature || !szCert) return ERROR_BAD_ARGUMENTS; DWORD ldatalen = _tcslen(szdata)*2; CByteBuf pbDatebuf(ldatalen); CBase64::Decode(szdata, pbDatebuf.ptr, &ldatalen); DWORD lsiglen = _tcslen(szSignature)*2; CByteBuf pbSignature(lsiglen); CBase64::Decode(szSignature, pbSignature.ptr, &lsiglen); HCRYPTPROV hProv = NULL; HCRYPTKEY hPubKey = NULL; HCRYPTHASH hHash = NULL; CCertificate Cert(szCert); do { if (!Cert.IsAttached()) break; if(!CryptAcquireContext(&hProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, 0)) break; if(!CryptImportPublicKeyInfo(hProv, XENCODETYPE, &(Cert.GetContext()->pCertInfo->SubjectPublicKeyInfo), &hPubKey)) break; if(!CryptCreateHash(hProv, m_iHashAlg, 0, 0, &hHash)) break; if (!CryptHashData(hHash, pbDatebuf.ptr, ldatalen, 0 )) break; if (!CryptVerifySignature(hHash, pbSignature.ptr, lsiglen, hPubKey, NULL, 0)) break; } while (0); lRet = GetLastError(); if(hHash) CryptDestroyHash(hHash); if(hProv) CryptReleaseContext(hProv, 0); return lRet; } LONG CCertKitCsp::VerifySignature(const TCHAR* szMsg, const TCHAR* szSignature, ulong ulOpt) { LONG lRet = ERROR_SUCCESS; if (!szMsg || !szSignature) return ERROR_BAD_ARGUMENTS; CByteBuf pbMsgbuf(_tcslen(szMsg)); DWORD lMsglen = _tcslen(szMsg); CBase64::Decode(szMsg, pbMsgbuf.ptr, &lMsglen); CByteBuf pbSignature(_tcslen(szSignature)); DWORD lsiglen = _tcslen(szSignature); CBase64::Decode(szSignature, pbSignature.ptr, &lsiglen); const BYTE* pMsg = pbMsgbuf.ptr; PCCERT_CONTEXT pSignerCert; CRYPT_VERIFY_MESSAGE_PARA param={sizeof(param),XENCODETYPE,0,NULL,0}; if(!CryptVerifyDetachedMessageSignature(&param,0,pbSignature.ptr,lsiglen,1,&pMsg, &lsiglen, &pSignerCert)) return GetLastError(); if (pSignerCert) CertFreeCertificateContext(pSignerCert); return lRet; } BOOL CCertKitCsp::SzDN2iMap(const TCHAR* szDN) { return TRUE; } BOOL CCertKitCsp::GetCspCertList(Tcerlist &vcCertList) { vcCertList.clear(); EnumCtn(); int sizea = m_CtnList.size(); if (m_CtnList.size() == 0) return FALSE; for(unsigned int i=0; i<m_CtnList.size(); i++) { AutoHProv hProv; AutoHPkey hUserKeyX; AutoHPkey hUserKeyS; CByteBuf certBufX(4096); CByteBuf certBufS(4096); DWORD ulCertLen = 4096; if(!CryptAcquireContext(hProv, m_CtnList[i].c_str(), m_sCspName.c_str(), m_lProvType, 0)) continue; if(CryptGetUserKey(hProv, AT_KEYEXCHANGE, hUserKeyX)){ if(CryptGetKeyParam(hUserKeyX, KP_CERTIFICATE, certBufX.ptr, &ulCertLen, 0)){ CCertificate curCert; curCert.Attach(certBufX.ptr, ulCertLen); curCert.SetCtnName(m_CtnList[i].c_str()); curCert.SetKeySpec(AT_KEYEXCHANGE); curCert.SetProvName(m_sCspName.c_str()); if(curCert.IsAttached()) m_CspCertList.push_back(curCert); } } if(CryptGetUserKey(hProv, AT_SIGNATURE, hUserKeyS)){ if(CryptGetKeyParam(hUserKeyS, KP_CERTIFICATE, certBufS.ptr, &ulCertLen, 0)){ CCertificate curCert; curCert.Attach(certBufS.ptr, ulCertLen); curCert.SetCtnName(m_CtnList[i].c_str()); curCert.SetKeySpec(AT_SIGNATURE); curCert.SetProvName(m_sCspName.c_str()); if(curCert.IsAttached()) m_CspCertList.push_back(curCert); } } } if (m_CspCertList.size() == 0) return FALSE; vcCertList = m_CspCertList; return TRUE; } BOOL CCertKitCsp::GetMyStroeCertList(Tcerlist &vcCertList) { return TRUE; } BOOL CCertKitCsp::PemHandle(const TCHAR* szPem, tstring& szB64) { tstring szBuf = szPem; if (tstring::npos != szBuf.find(_T("----"))) { if(tstring::npos != szBuf.find_first_of(_T("\r\n"))) { size_t size1 = 0, size2 = 0; size1 = szBuf.find_first_of(_T("\r\n")); size2 = szBuf.find_last_of(_T("\r\n")); szBuf = szBuf.substr(size1, size2 - size1); } else if(tstring::npos != szBuf.find_first_of(_T("\n"))) { size_t size1 = 0, size2 = 0; size1 = szBuf.find_first_of(_T("\n")); size2 = szBuf.find_last_of(_T("\n")); szBuf = szBuf.substr(size1, size2 - size1); } else if(tstring::npos != szBuf.find_first_of(_T("\r"))) { size_t size1 = 0, size2 = 0; size1 = szBuf.find_first_of(_T("\r")); size2 = szBuf.find_last_of(_T("\r")); szBuf = szBuf.substr(size1, size2 - size1); } } tstring::iterator itr = szBuf.end(); itr--; for (; itr != szBuf.begin(); itr--) { if(_T('\n') == *itr || _T('\r') == *itr){ szBuf.erase(itr); itr = szBuf.end(); itr--; } } szB64 = szBuf; return TRUE; } //////////////////////////////////////////////////////////////////////////
d8d6acb7cec7cccbe3fa4d096c6ee06b84385082
0674e81a160161996251fb4b063c801330ccd1e2
/fbhc/2015/qual/C_fariskhi.cpp
81f5a02d1abb952c34afb4233ee507750bc7ac29
[]
no_license
joshuabezaleel/cp
8a2c9b44605810da4367efeb981f822ae5e1e9a2
57f365458cca38c3c0fb1f5af1c6b44b74f3b53e
refs/heads/master
2022-07-19T00:39:34.395495
2020-05-23T20:37:20
2020-05-23T20:37:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,593
cpp
C_fariskhi.cpp
#include <algorithm> #include <bitset> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <math.h> #include <queue> #include <stack> #include <set> #include <vector> using namespace std; #define ll long long #define EPS 1e-9 #define INF 2000000000 #define pb push_back #define mp make_pair #define fi first #define se second #define sz(a) a.size() #define fill(a, b) memset(a, b, sizeof(a)) #define vsort(a) sort(a.begin(), a.end()) #define rep(a, b) for (int a = 0; a < b; a++) #define forn(a, b, c) for (int a = b; a <= c; a++) #define ford(a, b, c) for (int a = b; a >= c; a--) string area[111]; bool flag[105][105][5]; int main() { int t; scanf("%d", &t); forn(i, 1, t) { printf("Case #%d: ", i); int m, n; int sr, sc; vector<pair<int, int> > laser; scanf("%d %d", &m, &n); rep(j, m) { cin >> area[j]; rep(k, area[j].length()) { if (area[j][k] == 'S') { sr = j; sc = k; } if (area[j][k] == '^' || area[j][k] == 'v' || area[j][k] == '>' || area[j][k] == '<') { laser.pb(mp(j, k)); } } } queue<pair<int, pair<int, pair<int, int> > > > q; q.push(mp(0, mp(0, mp(sr, sc)))); bool first = true; int ans = -1; rep(j, m) { rep(k, n) { rep(l, 4) { flag[j][k][l] = false; } } } while (!q.empty()) { int x = q.front().fi; int nn = q.front().se.fi; int r = q.front().se.se.fi; int c = q.front().se.se.se; q.pop(); // printf("%d %d %d %d\n", x, nn, r, c); if (!first) { if (r < 0 || c < 0 || r >= m || c >= n) continue; if (flag[r][c][x]) continue; if (area[r][c] != '.' && area[r][c] != 'G' && area[r][c] != 'S') continue; flag[r][c][x] = true; bool tabrak = false; rep(j, laser.size()) { int rl = laser[j].fi; int cl = laser[j].se; int mr = 0; int mc = 0; if (area[rl][cl] == '^') { if (x == 0) mr = -1; if (x == 1) mc = 1; if (x == 2) mr = 1; if (x == 3) mc = -1; } if (area[rl][cl] == '>') { if (x == 0) mc = 1; if (x == 1) mr = 1; if (x == 2) mc = -1; if (x == 3) mr = -1; } if (area[rl][cl] == 'v') { if (x == 0) mr = 1; if (x == 1) mc = -1; if (x == 2) mr = -1; if (x == 3) mc = 1; } if (area[rl][cl] == '<') { if (x == 0) mc = -1; if (x == 1) mr = -1; if (x == 2) mc = 1; if (x == 3) mr = 1; } while (true) { rl += mr; cl += mc; if (rl < 0 || cl < 0 || rl >= m || cl >= n) break; if (area[rl][cl] != '.' && area[rl][cl] != 'S' && area[rl][cl] != 'G') break; if (rl == r && cl == c) { tabrak = true; break; } } if (tabrak) break; } //cout << tabrak << endl; if (!tabrak) { if (area[r][c] == 'G') { ans = nn; break; } //cout << "yeah" << endl; q.push(mp((x + 1) % 4, mp(nn + 1, mp(r + 1, c)))); q.push(mp((x + 1) % 4, mp(nn + 1, mp(r - 1, c)))); q.push(mp((x + 1) % 4, mp(nn + 1, mp(r, c + 1)))); q.push(mp((x + 1) % 4, mp(nn + 1, mp(r, c - 1)))); } } else { first = false; q.push(mp(x + 1, mp(nn + 1, mp(r + 1, c)))); q.push(mp(x + 1, mp(nn + 1, mp(r, c + 1)))); q.push(mp(x + 1, mp(nn + 1, mp(r - 1, c)))); q.push(mp(x + 1, mp(nn + 1, mp(r, c - 1)))); } } if (ans == -1) cout << "impossible" << endl; else cout << ans << endl; } return 0; }
8a8e50c29876a28a0e32c6f609a42d4d8f4ea742
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_4484_last_repos.cpp
a035ebca3c64b35327e5e58ba3cb22f84ed9f16e
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
65
cpp
squid_repos_function_4484_last_repos.cpp
bool Store::Disk::doubleCheck(StoreEntry &) { return false; }
93918ba0bb3760c02ac9b7e9c1b23c331f417f22
9b4f4ad42b82800c65f12ae507d2eece02935ff6
/src/Manage/ThreadContextNull.cpp
5e6aedc32de246a459bdc96854049db87d3ff1c6
[]
no_license
github188/SClass
f5ef01247a8bcf98d64c54ee383cad901adf9630
ca1b7efa6181f78d6f01a6129c81f0a9dd80770b
refs/heads/main
2023-07-03T01:25:53.067293
2021-08-06T18:19:22
2021-08-06T18:19:22
393,572,232
0
1
null
2021-08-07T03:57:17
2021-08-07T03:57:16
null
UTF-8
C++
false
false
2,366
cpp
ThreadContextNull.cpp
#include "Stdafx.h" #include "MyMemory.h" #include "Text/MyString.h" #if defined(CPU_X86_64) #include "Manage/ThreadContextX86_64.h" Manage::ThreadContextX86_64::ThreadContextX86_64(UOSInt procId, UOSInt threadId, void *context) { this->procId = procId; this->threadId = threadId; this->context = context; } Manage::ThreadContextX86_64::~ThreadContextX86_64() { } OSInt Manage::ThreadContextX86_64::GetRegisterCnt() { return 0; } UTF8Char *Manage::ThreadContextX86_64::GetRegister(OSInt index, UTF8Char *buff, UInt8 *regVal, Int32 *regBitCount) { return 0; } void Manage::ThreadContextX86_64::ToString(Text::StringBuilderUTF *sb) { UTF8Char sbuff[64]; UTF8Char *sptr; UInt8 regBuff[16]; Int32 bitCnt; OSInt i = 0; OSInt j = this->GetRegisterCnt(); OSInt k; while (i < j) { if ((sptr = this->GetRegister(i, sbuff, regBuff, &bitCnt)) != 0) { sptr = Text::StrConcat(sptr, (const UTF8Char*)" = "); k = bitCnt >> 3; while (k-- > 0) { sptr = Text::StrHexByte(sptr, regBuff[k]); } sptr = Text::StrConcat(sptr, (const UTF8Char*)"\r\n"); sb->Append(sbuff); } i++; } } Manage::ThreadContext::ContextType Manage::ThreadContextX86_64::GetType() { return Manage::ThreadContext::CT_X86_64; } UOSInt Manage::ThreadContextX86_64::GetThreadId() { return this->threadId; } UOSInt Manage::ThreadContextX86_64::GetProcessId() { return this->procId; } OSInt Manage::ThreadContextX86_64::GetInstAddr() { return 0; } OSInt Manage::ThreadContextX86_64::GetStackAddr() { return 0; } OSInt Manage::ThreadContextX86_64::GetFrameAddr() { return 0; } void Manage::ThreadContextX86_64::SetInstAddr(OSInt instAddr) { } void Manage::ThreadContextX86_64::SetStackAddr(OSInt stackAddr) { } void Manage::ThreadContextX86_64::SetFrameAddr(OSInt frameAddr) { } Manage::ThreadContext *Manage::ThreadContextX86_64::Clone() { Manage::ThreadContextX86_64 *cont; NEW_CLASS(cont, Manage::ThreadContextX86_64(this->procId, this->threadId, this->context)); return cont; } Bool Manage::ThreadContextX86_64::GetRegs(Manage::Dasm::Dasm_Regs *regs) { return false; } Manage::Dasm *Manage::ThreadContextX86_64::CreateDasm() { return 0; } void *Manage::ThreadContextX86_64::GetContext() { return this->context; } #endif
19e606cd3bcec1a334973c72e822de3af2e34659
127469d91e0a53ea340d5c8ff3ca5f3b4e721d46
/src/GUAxes.cpp
3ebca4093e52d5a5807ce10e0a836668ffd7f6e9
[]
no_license
lcls-psana/PSQt
7b6e33bf2e4d99fc8372ca7284a28c33807e4187
274fc69d2bd869640da01b176094911c9f449315
refs/heads/master
2021-08-15T20:57:43.407279
2020-06-04T00:26:44
2020-06-04T00:26:44
82,349,695
0
0
null
null
null
null
UTF-8
C++
false
false
7,704
cpp
GUAxes.cpp
//--------------------------------------------------------------------- // File and Version Information: // $Id$ // // Author: Mikhail S. Dubrovin //--------------------------------------------------------------------- //-------------------------- #include "PSQt/GUAxes.h" //#include "PSQt/QGUtils.h" #include "PSQt/Logger.h" #include <QCloseEvent> #include <QResizeEvent> #include <QMouseEvent> #include <sstream> // for stringstream #include <iostream> // for std::cout //#include <fstream> // for std::ifstream(fname) //#include <math.h> // atan2 //#include <cstring> // for memcpy //using namespace std; // for cout without std:: namespace PSQt { //-------------------------- GUAxes::GUAxes( QWidget *parent , const float& xmin , const float& xmax , const float& ymin , const float& ymax , const unsigned& nxdiv1 , const unsigned& nydiv1 , const unsigned& nxdiv2 , const unsigned& nydiv2 , const unsigned pbits ) : QGraphicsView(parent) , m_pbits(pbits) , m_color(Qt::black) , m_pen(Qt::black, 2, Qt::SolidLine) , m_font() , m_ruler_hd(0) , m_ruler_hu(0) , m_ruler_vl(0) , m_ruler_vr(0) { m_pen.setCosmetic(true); if(m_pbits & 1) {std::cout << "GUAxes - ctor\n"; printMemberData();} pview()->setGeometry(100, 50, 700, 378); pview()->setMinimumSize(300,200); //this->setContentsMargins(-9,-9,-9,-9); m_scene = new QGraphicsScene(); pview()->setScene(m_scene); setLimits(xmin, xmax, ymin, ymax, nxdiv1, nydiv1, nxdiv2, nydiv2); if(m_pbits & 2) this->printTransform(); connectForTest(); } //-------------------------- void GUAxes::connectForTest() { // connections for internal test connect(this, SIGNAL(pressOnAxes(QMouseEvent*, QPointF)), this, SLOT(testSignalPressOnAxes(QMouseEvent*, QPointF))); connect(this, SIGNAL(releaseOnAxes(QMouseEvent*, QPointF)), this, SLOT(testSignalReleaseOnAxes(QMouseEvent*, QPointF))); //connect(this, SIGNAL(moveOnAxes(QMouseEvent*, QPointF)), // this, SLOT(testSignalMoveOnAxes(QMouseEvent*, QPointF))); } //-------------------------- void GUAxes::setLimits( const float& xmin , const float& xmax , const float& ymin , const float& ymax , const unsigned& nxdiv1 , const unsigned& nydiv1 , const unsigned& nxdiv2 , const unsigned& nydiv2 ) { m_xmin = xmin; m_xmax = xmax; m_ymin = ymin; m_ymax = ymax; m_nxdiv1 = nxdiv1; m_nydiv1 = nydiv1; m_nxdiv2 = nxdiv2; m_nydiv2 = nydiv2; this->updateTransform(); this->setAxes(); } //-------------------------- GUAxes::~GUAxes () { if (m_ruler_hd) delete m_ruler_hd; if (m_ruler_hu) delete m_ruler_hu; if (m_ruler_vl) delete m_ruler_vl; if (m_ruler_vr) delete m_ruler_vr; } //-------------------------- void GUAxes::updateTransform() { const QRect & geometryRect = pview()->geometry(); //std::stringstream ss; ss << "h:" << geometryRect.width() << " w:" << geometryRect.height(); //setWindowTitle(ss.str().c_str()); //std::cout << ss.str() << '\n'; float sx = (geometryRect.width()-150)/(m_xmax-m_xmin); float sy = -(geometryRect.height()-50)/(m_ymax-m_ymin); QTransform trans(sx, 0, 0, sy, 0, 0); pview()->setTransform(trans); // The transformation matrix tranforms the scene into view coordinates. //this->printTransform(); } //-------------------------- void GUAxes::setAxes() { m_scene_rect.setRect(m_xmin, m_ymin, m_xmax-m_xmin, m_ymax-m_ymin); m_scene->setSceneRect(m_scene_rect); //pview()->fitInView(m_scene_rect, Qt::IgnoreAspectRatio); //pview()->ensureVisible(m_scene_rect, 100, 100); //pview()->ensureVisible(m_scene_rect); //QGraphicsScene * scene = pview()->scene(); if (m_ruler_hd) delete m_ruler_hd; if (m_ruler_hu) delete m_ruler_hu; if (m_ruler_vl) delete m_ruler_vl; if (m_ruler_vr) delete m_ruler_vr; m_ruler_hd = new PSQt::GURuler(rview(),GURuler::HD,m_xmin,m_xmax,m_ymin,m_nxdiv1,m_nxdiv2,1,0,0,0,0,m_color,m_pen,m_font); m_ruler_hu = new PSQt::GURuler(rview(),GURuler::HU,m_xmin,m_xmax,m_ymax,m_nxdiv1,m_nxdiv2,0,0,0,0,0,m_color,m_pen,m_font); m_ruler_vl = new PSQt::GURuler(rview(),GURuler::VL,m_ymin,m_ymax,m_xmin,m_nydiv1,m_nydiv2,1,0,0,0,0,m_color,m_pen,m_font); m_ruler_vr = new PSQt::GURuler(rview(),GURuler::VR,m_ymin,m_ymax,m_xmax,m_nydiv1,m_nydiv2,0,0,0,0,0,m_color,m_pen,m_font); } //-------------------------- void GUAxes::printMemberData() { std::cout << "GUAxes::printMemberData():" << "\n xmin :" << m_xmin << "\n xmax :" << m_xmax << "\n ymin :" << m_ymin << "\n ymax :" << m_ymax << "\n nxdiv1:" << m_nxdiv1 << "\n nydiv1:" << m_nydiv1 << "\n nxdiv2:" << m_nxdiv2 << "\n nydiv2:" << m_nydiv2 << "\n pbits :" << m_pbits << '\n'; } //-------------------------- void GUAxes::printTransform() { QTransform trans = pview()->transform(); std::cout << "GUAxes::printTransform():" << "\n m11():" << trans.m11() << "\n m22():" << trans.m22() << "\n dx() :" << trans.dx() << "\n dy() :" << trans.dy() << '\n'; } //-------------------------- void GUAxes::closeEvent(QCloseEvent *event) { //QGraphicsView::closeEvent(event); //std::cout << "GUAxes::closeEvent(...): type = " << event -> type() << std::endl; } //-------------------------- void GUAxes::resizeEvent(QResizeEvent *event) { //m_frame -> setFrameRect (this->rect()); //m_frame->setGeometry(0, 0, event->size().width(), event->size().height()); //std::cout << "GUAxes::resizeEvent(...): w=" << event->size().width() // << " h=" << event->size().height() << '\n'; //setWindowTitle("Window is resized"); //pview()->fitInView(m_scene_rect, Qt::IgnoreAspectRatio); this->updateTransform(); } //-------------------------- QPointF GUAxes::pointOnAxes(QMouseEvent *e) { //const QPoint& poswin = e->pos(); QPointF sp = pview()->mapToScene(e->pos()); return sp; } //-------------------------- void GUAxes::mousePressEvent(QMouseEvent *e) { QPointF sp = pointOnAxes(e); emit pressOnAxes(e, sp); } //-------------------------- void GUAxes::mouseReleaseEvent(QMouseEvent *e) { QPointF sp = pointOnAxes(e); emit releaseOnAxes(e, sp); } //-------------------------- void GUAxes::mouseMoveEvent(QMouseEvent *e) { //QPointF sp = pointOnAxes(e); //emit moveOnAxes(e, sp); } //-------------------------- //-------------------------- //-------------------------- //-------------------------- void GUAxes::message(QMouseEvent *e, const QPointF& sp, const char* cmt) { std::stringstream ss; ss << _name_() << " " << cmt << " button: " << e->button() << " window x(), y() = " << e->x() << ", " << e->y() << " scene x(), y() = " << sp.x() << ", " << sp.y(); MsgInLog(_name_(), DEBUG, ss.str()); } //-------------------------- void GUAxes::testSignalPressOnAxes(QMouseEvent* e, QPointF p) { message(e, p, "press "); } //-------------------------- void GUAxes::testSignalReleaseOnAxes(QMouseEvent* e, QPointF p) { message(e, p, "release"); } //-------------------------- void GUAxes::testSignalMoveOnAxes(QMouseEvent* e, QPointF p) { message(e, p, "move "); } //-------------------------- //-------------------------- //-------------------------- } // namespace PSQt //--------------------------
59f4d36d75ee58a91c834a2286e87fc3a863c37c
cd72b19d2030f36f78dab52390d092ed3dc8005f
/lib/src/render/fillRenderer.hpp
55912662a1eb30ffed7d8bf749fbaf3aa1331d4e
[ "MIT", "DOC" ]
permissive
stitchEm/stitchEm
08c5a3ef95c16926c944c1835fdd4ab4b6855580
4a0e9fc167f10c7dde46394aff302927c15ce6cb
refs/heads/master
2022-11-27T20:13:45.741733
2022-11-22T17:26:07
2022-11-22T17:26:07
182,059,770
250
68
MIT
2022-11-22T17:26:08
2019-04-18T09:36:54
C++
UTF-8
C++
false
false
560
hpp
fillRenderer.hpp
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #ifndef GLYPHS_H_ #define GLYPHS_H_ #include "gpu/render/render.hpp" namespace VideoStitch { namespace Render { /** * @brief A renderer that fills the boundingbox. */ class FillRenderer { public: FillRenderer() {} Status draw(uint32_t* dst, int64_t dstWidth, int64_t dstHeight, int64_t left, int64_t top, int64_t right, int64_t bottom, uint32_t color, uint32_t bgcolor, cudaStream_t stream) const; }; } // namespace Render } // namespace VideoStitch #endif
a53724329289efe014a14251edcce5a62673da1f
3f90ac7a0e700e87c80e311b551bb30823b41ecb
/src/cheat/features/aimbot/autowall/autowall.cc
ac4226c949ed436392fb1e6293e8f4fce0ebacf3
[]
no_license
alphauc/polandhack
6192a630368ebbba228e9be519671b4034f6738f
853c70a29bb5384ab2256836febf4d1deeb93fa5
refs/heads/master
2020-04-19T20:46:33.545562
2019-01-30T22:29:00
2019-01-30T22:29:00
168,424,319
15
9
null
null
null
null
UTF-8
C++
false
false
16,850
cc
autowall.cc
#include "autowall.hh" namespace features::ragebot{ automatic_wall autowall; automatic_wall::Autowall_Return_Info automatic_wall::CalculateDamage( sdk::vec3 start, sdk::vec3 end, sdk::base_entity* from_entity, sdk::base_entity* to_entity, int specific_hitgroup ) { // default values for return info, in case we need to return abruptly Autowall_Return_Info return_info; return_info.damage = -1; return_info.hitgroup = -1; return_info.hit_entity = nullptr; return_info.penetration_count = 4; return_info.thickness = 0.f; return_info.did_penetrate_wall = false; Autowall_Info autowall_info; autowall_info.penetration_count = 4; autowall_info.start = start; autowall_info.end = end; autowall_info.current_position = start; autowall_info.thickness = 0.f; // direction utilities::math::angle_vectors( utilities::math::calculate_angle( start, end ), &autowall_info.direction ); // attacking entity if ( !from_entity ) from_entity = interfaces::entity_list->get_entity( interfaces::engine_client->get_local_player( ) ); if ( !from_entity ) return return_info; auto filter_player = sdk::trace_filter_one_entity( ); filter_player.pEntity = to_entity; auto filter_local = sdk::trace_filter( ); filter_local.skip = from_entity; // setup filters if ( to_entity ) autowall_info.filter = &filter_player; else autowall_info.filter = &filter_player; // weapon auto weapon = reinterpret_cast< sdk::base_weapon* >( interfaces::entity_list->get_entity( from_entity->active_weapon_handle( ) ) ); if ( !weapon ) return return_info; // weapon data auto weapon_info = weapon->weapon_data( ); if ( !weapon_info ) return return_info; // client class auto weapon_client_class = reinterpret_cast< sdk::base_entity* >( weapon )->client_class( ); if ( !weapon_client_class ) return return_info; // weapon range float range = min( weapon_info->range, ( start - end ).length( ) ); end = start + ( autowall_info.direction * range ); autowall_info.current_damage = weapon_info->damage; while ( autowall_info.current_damage > 0 && autowall_info.penetration_count > 0 ) { return_info.penetration_count = autowall_info.penetration_count; UTIL_TraceLine( autowall_info.current_position, end, MASK_SHOT | CONTENTS_GRATE, from_entity, &autowall_info.enter_trace ); UTIL_ClipTraceToPlayers( autowall_info.current_position, autowall_info.current_position + autowall_info.direction * 40.f, MASK_SHOT | CONTENTS_GRATE, autowall_info.filter, &autowall_info.enter_trace ); const float distance_traced = ( autowall_info.enter_trace.end - start ).length( ); autowall_info.current_damage *= pow( weapon_info->range_modifier, ( distance_traced / 500.f ) ); /// if reached the end if ( autowall_info.enter_trace.flFraction == 1.f ) { if ( to_entity && specific_hitgroup != -1 ) { ScaleDamage( to_entity, weapon_info, specific_hitgroup, autowall_info.current_damage ); return_info.damage = autowall_info.current_damage; return_info.hitgroup = specific_hitgroup; return_info.end = autowall_info.enter_trace.end; return_info.hit_entity = to_entity; } else { return_info.damage = autowall_info.current_damage; return_info.hitgroup = -1; return_info.end = autowall_info.enter_trace.end; return_info.hit_entity = nullptr; } break; } // if hit an entity if ( autowall_info.enter_trace.hitGroup > 0 && autowall_info.enter_trace.hitGroup <= 7 && autowall_info.enter_trace.m_pEnt ) { // checkles gg if ( ( to_entity && autowall_info.enter_trace.m_pEnt != to_entity ) || ( autowall_info.enter_trace.m_pEnt->team( ) == from_entity->team( ) ) ) { return_info.damage = -1; return return_info; } if ( specific_hitgroup != -1 ) ScaleDamage( autowall_info.enter_trace.m_pEnt, weapon_info, specific_hitgroup, autowall_info.current_damage ); else ScaleDamage( autowall_info.enter_trace.m_pEnt, weapon_info, autowall_info.enter_trace.hitGroup, autowall_info.current_damage ); // fill the return info return_info.damage = autowall_info.current_damage; return_info.hitgroup = autowall_info.enter_trace.hitGroup; return_info.end = autowall_info.enter_trace.end; return_info.hit_entity = autowall_info.enter_trace.m_pEnt; break; } // break out of the loop retard if ( !CanPenetrate( from_entity, autowall_info, weapon_info ) ) break; return_info.did_penetrate_wall = true; } return_info.penetration_count = autowall_info.penetration_count; return return_info; } float automatic_wall::GetThickness( sdk::vec3 start, sdk::vec3 end ) { float current_thickness = 0.f; sdk::vec3 direction; utilities::math::angle_vectors( utilities::math::calculate_angle( start, end ), &direction ); sdk::trace_world_only filter; sdk::trace_t enter_trace; sdk::trace_t exit_trace; sdk::ray_t ray; int pen = 0; while ( pen < 4 ) { ray.initialize( start, end ); interfaces::trace->TraceRay( ray, MASK_ALL, &filter, &enter_trace ); if ( enter_trace.flFraction == 1.f ) return current_thickness; start = enter_trace.end; if ( !TraceToExit( enter_trace, exit_trace, start, direction ) ) return current_thickness + 90.f; start = exit_trace.end; current_thickness += ( start - exit_trace.end ).length( ); pen++; } return current_thickness; } bool automatic_wall::CanPenetrate( sdk::base_entity* attacker, Autowall_Info& info, sdk::weapon_info* weapon_data ) { //typedef bool(__thiscall* HandleBulletPenetrationFn)(sdk::base_entity*, float&, int&, int*, sdk::trace_t*, sdk::vec3*, float, float, float, int, int, float, int*, sdk::vec3*, float, float, float*); //CBaseEntity *pLocalPlayer, float *flPenetration, int *SurfaceMaterial, char *IsSolid, trace_t *ray, sdk::vec3 *vecDir, int unused, float flPenetrationModifier, float flDamageModifier, int unused2, int weaponmask, float flPenetration2, int *hitsleft, sdk::vec3 *ResultPos, int unused3, int unused4, float *damage) typedef bool( __thiscall* HandleBulletPenetrationFn )( sdk::base_entity*, float*, int*, char*, sdk::trace_t*, sdk::vec3*, int, float, float, int, int, float, int*, sdk::vec3*, int, int, float* ); static HandleBulletPenetrationFn HBP = reinterpret_cast< HandleBulletPenetrationFn >( utilities::find_pattern( "client_panorama.dll", (PBYTE)"\x53\x8B\xDC\x83\xEC\x08\x83\xE4\xF8\x83\xC4\x04\x55\x8B\x6B\x04\x89\x6C\x24\x04\x8B\xEC\x83\xEC\x78\x56\x8B\x73\x34", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) ); auto enter_surface_data = interfaces::physic_props->surface_data( info.enter_trace.surface.surfaceProps ); if ( !enter_surface_data ) return true; char is_solid = 0; int material = enter_surface_data->game.material; int mask = 0x1002; // glass and shit gg if ( info.enter_trace.m_pEnt && !strcmp( "CBreakableSurface", info.enter_trace.m_pEnt->client_class( )->name ) ) *reinterpret_cast< byte* >( uintptr_t( info.enter_trace.m_pEnt + 0x27C ) ) = 2; is_autowalling = true; bool return_value = !HBP( attacker, &weapon_data->penetration, &material, &is_solid, &info.enter_trace, &info.direction, 0, enter_surface_data->game.flPenetrationModifier, enter_surface_data->game.flDamageModifier, 0, mask, weapon_data->penetration, &info.penetration_count, &info.current_position, 0, 0, &info.current_damage ); is_autowalling = false; return return_value; } void automatic_wall::ScaleDamage( sdk::base_entity* entity, sdk::weapon_info* weapon_info, int hitgroup, float& current_damage ) { //Cred. to N0xius for reversing this. //TODO: _xAE^; look into reversing this yourself sometime bool hasHeavyArmor = false; int armorValue = entity->armour( ); //Fuck making a new function, lambda beste. ~ Does the person have armor on for the hitbox checked? auto IsArmored = [ &entity, &hitgroup ]( )-> bool { sdk::base_entity* targetEntity = entity; switch ( hitgroup ) { case 1: return targetEntity->helmet( ); case 0: case 2: case 3: case 4: case 5: return true; default: return false; } }; switch ( hitgroup ) { case 1: current_damage *= hasHeavyArmor ? 2.f : 4.f; //Heavy Armor does 1/2 damage break; case 3: current_damage *= 1.25f; break; case 6: case 7: current_damage *= 0.75f; break; default: break; } if ( armorValue > 0 && IsArmored( ) ) { float bonusValue = 1.f, armorBonusRatio = 0.5f, armorRatio = weapon_info->armor_ratio / 2.f; //Damage gets modified for heavy armor users if ( hasHeavyArmor ) { armorBonusRatio = 0.33f; armorRatio *= 0.5f; bonusValue = 0.33f; } auto NewDamage = current_damage * armorRatio; if ( hasHeavyArmor ) NewDamage *= 0.85f; if ( ( ( current_damage - ( current_damage * armorRatio ) ) * ( bonusValue * armorBonusRatio ) ) > armorValue ) NewDamage = current_damage - ( armorValue / armorBonusRatio ); current_damage = NewDamage; } } bool automatic_wall::TraceToExit( sdk::trace_t& enterTrace, sdk::trace_t& exitTrace, sdk::vec3 startPosition, sdk::vec3 direction ) { /* Masks used: MASK_SHOT_HULL = 0x600400B CONTENTS_HITBOX = 0x40000000 MASK_SHOT_HULL | CONTENTS_HITBOX = 0x4600400B */ sdk::vec3 start, end; float maxDistance = 90.f, rayExtension = 4.f, currentDistance = 0; int firstContents = 0; while ( currentDistance <= maxDistance ) { //Add extra distance to our ray currentDistance += rayExtension; //Multiply the direction sdk::vec3 to the distance so we go outwards, add our position to it. start = startPosition + direction * currentDistance; if ( !firstContents ) firstContents = interfaces::trace->GetPointContents( start, MASK_SHOT_HULL | CONTENTS_HITBOX, nullptr ); /*0x4600400B*/ int pointContents = interfaces::trace->GetPointContents( start, MASK_SHOT_HULL | CONTENTS_HITBOX, nullptr ); if ( !( pointContents & MASK_SHOT_HULL ) || pointContents & CONTENTS_HITBOX && pointContents != firstContents ) /*0x600400B, *0x40000000*/ { //Let's setup our end position by deducting the direction by the extra added distance end = start - ( direction * rayExtension ); //Let's cast a ray from our start pos to the end pos UTIL_TraceLine( start, end, MASK_SHOT_HULL | CONTENTS_HITBOX, nullptr, &exitTrace ); //Let's check if a hitbox is in-front of our enemy and if they are behind of a solid wall if ( exitTrace.startSolid && exitTrace.surface.flags & SURF_HITBOX ) { UTIL_TraceLine( start, startPosition, MASK_SHOT_HULL, exitTrace.m_pEnt, &exitTrace ); if ( exitTrace.DidHit( ) && !exitTrace.startSolid ) { start = exitTrace.end; return true; } continue; } //Can we hit? Is the wall solid? if ( exitTrace.DidHit( ) && !exitTrace.startSolid ) { //Is the wall a breakable? If so, let's shoot through it. if ( IsBreakableEntity( enterTrace.m_pEnt ) && IsBreakableEntity( exitTrace.m_pEnt ) ) return true; if ( enterTrace.surface.flags & SURF_NODRAW || !( exitTrace.surface.flags & SURF_NODRAW ) && ( exitTrace.plane.normal.dot( direction ) <= 1.f ) ) { float multAmount = exitTrace.flFraction * 4.f; start -= direction * multAmount; return true; } continue; } if ( !exitTrace.DidHit( ) || exitTrace.startSolid ) { if ( enterTrace.DidHitNonWorldEntity( ) && IsBreakableEntity( enterTrace.m_pEnt ) ) { exitTrace = enterTrace; exitTrace.end = start + direction; return true; } } } } return false; } bool automatic_wall::HandleBulletPenetration( sdk::weapon_info* weaponData, sdk::trace_t& enterTrace, sdk::vec3& eyePosition, sdk::vec3 direction, int& possibleHitsRemaining, float& currentDamage, float penetrationPower, bool sv_penetration_type, float ff_damage_reduction_bullets, float ff_damage_bullet_penetration, float& current_thickness ) { //Because there's been issues regarding this- putting this here. if ( &currentDamage == nullptr ) throw std::invalid_argument( "currentDamage is null!" ); auto local_player = interfaces::entity_list->get_entity( interfaces::engine_client->get_local_player( ) ); if ( !local_player ) return false; sdk::trace_t exitTrace; sdk::base_entity* pEnemy = enterTrace.m_pEnt; sdk::surfacedata_t* enterSurfaceData = interfaces::physic_props->surface_data( enterTrace.surface.surfaceProps ); int enterMaterial = enterSurfaceData->game.material; float enterSurfPenetrationModifier = enterSurfaceData->game.flPenetrationModifier; float enterDamageModifier = enterSurfaceData->game.flDamageModifier; float thickness, modifier, lostDamage, finalDamageModifier, combinedPenetrationModifier; bool isSolidSurf = ( ( enterTrace.contents >> 3 ) & CONTENTS_SOLID ); bool isLightSurf = ( ( enterTrace.surface.flags >> 7 ) & SURF_LIGHT ); if ( possibleHitsRemaining <= 0 || ( !possibleHitsRemaining && !isLightSurf && !isSolidSurf && enterMaterial != CHAR_TEX_GRATE && enterMaterial != CHAR_TEX_GLASS ) || weaponData->penetration <= 0.f || !TraceToExit( enterTrace, exitTrace, enterTrace.end, direction ) && !( interfaces::trace->GetPointContents( enterTrace.end, MASK_SHOT_HULL, nullptr ) & MASK_SHOT_HULL ) ) return false; sdk::surfacedata_t* exitSurfaceData = interfaces::physic_props->surface_data( exitTrace.surface.surfaceProps ); int exitMaterial = exitSurfaceData->game.material; float exitSurfPenetrationModifier = exitSurfaceData->game.flPenetrationModifier; float exitDamageModifier = exitSurfaceData->game.flDamageModifier; //Are we using the newer penetration system? if ( sv_penetration_type ) { if ( enterMaterial == CHAR_TEX_GRATE || enterMaterial == CHAR_TEX_GLASS ) { combinedPenetrationModifier = 3.f; finalDamageModifier = 0.05f; } else if ( isSolidSurf || isLightSurf ) { combinedPenetrationModifier = 1.f; finalDamageModifier = 0.16f; } else if ( enterMaterial == CHAR_TEX_FLESH && ( local_player->team( ) == pEnemy->team( ) && ff_damage_reduction_bullets == 0.f ) ) //TODO: Team check config { //Look's like you aren't shooting through your teammate today if ( ff_damage_bullet_penetration == 0.f ) return false; //Let's shoot through teammates and get kicked for teamdmg! Whatever, atleast we did damage to the enemy. I call that a win. combinedPenetrationModifier = ff_damage_bullet_penetration; finalDamageModifier = 0.16f; } else { combinedPenetrationModifier = ( enterSurfPenetrationModifier + exitSurfPenetrationModifier ) / 2.f; finalDamageModifier = 0.16f; } //Do our materials line up? if ( enterMaterial == exitMaterial ) { if ( exitMaterial == CHAR_TEX_CARDBOARD || exitMaterial == CHAR_TEX_WOOD ) combinedPenetrationModifier = 3.f; else if ( exitMaterial == CHAR_TEX_PLASTIC ) combinedPenetrationModifier = 2.f; } //Calculate thickness of the wall by getting the length of the range of the trace and squaring thickness = ( exitTrace.end - enterTrace.end ).length_sqr( ); modifier = fmaxf( 1.f / combinedPenetrationModifier, 0.f ); current_thickness += thickness; //This calculates how much damage we've lost depending on thickness of the wall, our penetration, damage, and the modifiers set earlier lostDamage = fmaxf( ( ( modifier * thickness ) / 24.f ) + ( ( currentDamage * finalDamageModifier ) + ( fmaxf( 3.75f / penetrationPower, 0.f ) * 3.f * modifier ) ), 0.f ); //Did we loose too much damage? if ( lostDamage > currentDamage ) return false; //We can't use any of the damage that we've lost if ( lostDamage > 0.f ) currentDamage -= lostDamage; //Do we still have enough damage to deal? if ( currentDamage < 1.f ) return false; eyePosition = exitTrace.end; --possibleHitsRemaining; return true; } else //Legacy penetration system { combinedPenetrationModifier = 1.f; if ( isSolidSurf || isLightSurf ) finalDamageModifier = 0.99f; //Good meme :^) else { finalDamageModifier = fminf( enterDamageModifier, exitDamageModifier ); combinedPenetrationModifier = fminf( enterSurfPenetrationModifier, exitSurfPenetrationModifier ); } if ( enterMaterial == exitMaterial && ( exitMaterial == CHAR_TEX_METAL || exitMaterial == CHAR_TEX_WOOD ) ) combinedPenetrationModifier += combinedPenetrationModifier; thickness = ( exitTrace.end - enterTrace.end ).length_sqr( ); if ( sqrt( thickness ) <= combinedPenetrationModifier * penetrationPower ) { currentDamage *= finalDamageModifier; eyePosition = exitTrace.end; --possibleHitsRemaining; return true; } return false; } } }
f2890e0f0cc0cbf1d7415a4bfeca2af255bac45e
79ffba00f7bb09d3c4f428ab0d449a8d1f71b538
/Knight.h
0602289ffafd42ef65304633b7dabef9e6db8b98
[]
no_license
TMalicki/Alpacator-SFML
c933ceb3935aa9a315048520985f6f640640e56a
dbe72867727d1d797ea20031f6026f9e66aa9a7c
refs/heads/master
2020-12-20T17:58:30.402723
2020-07-30T14:24:04
2020-07-30T14:24:04
236,162,535
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
Knight.h
#ifndef KNIGHT_H #define KNIGHT_H #include <iostream> #include "Hero.h" using namespace std; class Knight : public Hero { private: public: Knight(string n, string prof = "Knight", int h = 120, int s = 5, int d = 10, int agil = 1, int stam = 3) : Hero(n, prof, h, s, d, agil, stam) {}; // dlaczego w liscie inicjalizacyjnej nie moge dodac np atrybutu strength!?!?!?!?! ~Knight() {}; virtual void getName() const { cout << name; }; void check() { cout << "Nothing"; } /* virtual void setStrength(int x) { strength = x; }; virtual int getStrength() const { return strength; }; virtual void setDefence(int x) { defence = x; }; virtual int getDefence() const { return defence; }; virtual void setAgillity(int x) { agillity = x; }; virtual int getAgillity() const { return agillity; }; virtual void setHp(int x) { hp = x; }; virtual int getHp() const { return hp; }; */ //int setStrength(); //void getStrength() const; }; #endif
041f0c2a865d3088a13e6d59f8a308636d6df6ac
6633da8501899ad0e926a42986326fb29513b67d
/src/network/ssf/layer/data_link/circuit_helpers.h
8b9278d073401d3d72a1851e370d6080d276a490
[ "BSD-3-Clause", "OpenSSL", "MIT", "BSL-1.0" ]
permissive
gdraperi/ssf
4218782e94b3d4c8a29270a505647c8d97a0a485
ee4aff98abc1fcebcab1c5cf77e213d04d9f9e29
refs/heads/develop
2021-08-25T16:47:28.529205
2017-11-17T14:32:52
2017-11-17T14:32:52
111,932,788
1
0
null
2017-11-24T15:30:16
2017-11-24T15:30:16
null
UTF-8
C++
false
false
2,791
h
circuit_helpers.h
#ifndef SSF_LAYER_DATA_LINK_CIRCUIT_HELPERS_H_ #define SSF_LAYER_DATA_LINK_CIRCUIT_HELPERS_H_ #include <list> #include <sstream> #include <string> #include <boost/asio/io_service.hpp> #include <boost/property_tree/ptree.hpp> #include "ssf/utils/map_helpers.h" #include "ssf/layer/parameters.h" #include "ssf/layer/data_link/circuit_endpoint_context.h" namespace ssf { namespace layer { namespace data_link { namespace detail { CircuitEndpointContext::ID get_local_id(); LayerParameters make_next_forward_node_ciruit_layer_parameters( const ParameterStack &next_node_full_stack); ParameterStack make_destination_node_parameter_stack(); CircuitEndpointContext make_circuit_context(boost::asio::io_service &io_service, const LayerParameters &parameters); } // detail class NodeParameterList { private: typedef std::list<ParameterStack> NodeList; public: void PushFrontNode(ParameterStack new_node_stack = ParameterStack()); ParameterStack &FrontNode(); const ParameterStack &FrontNode() const; void PopFrontNode(); void AddTopLayerToFrontNode(LayerParameters top_layer); void PushBackNode(ParameterStack new_node_stack = ParameterStack()); ParameterStack &BackNode(); const ParameterStack &BackNode() const; void PopBackNode(); void AddTopLayerToBackNode(LayerParameters top_layer); NodeList::iterator begin(); NodeList::iterator end(); NodeList::const_iterator begin() const; NodeList::const_iterator end() const; private: NodeList nodes_; }; ParameterStack make_acceptor_parameter_stack( std::string local_id, ParameterStack default_parameters, ParameterStack next_layer_parameters); ParameterStack make_forwarding_acceptor_parameter_stack( std::string local_id, ParameterStack default_parameters, ParameterStack next_layer_parameters); ParameterStack make_client_full_circuit_parameter_stack( std::string remote_id, const NodeParameterList &nodes); template <class NodeProtocol> NodeParameterList nodes_property_tree_to_node_list( const boost::property_tree::ptree &nodes_tree, bool connect, boost::system::error_code &ec) { NodeParameterList nodes; for (auto &node : nodes_tree) { ParameterStack node_stack; NodeProtocol::add_params_from_property_tree(&node_stack, node.second, connect, ec); if (ec) { return nodes; } nodes.PushBackNode(); auto node_stack_end_it = node_stack.rend(); for (auto param_node_it = node_stack.rbegin(); param_node_it != node_stack_end_it; ++param_node_it) { nodes.AddTopLayerToBackNode(*param_node_it); } } return nodes; } } // data_link } // layer } // ssf #endif // SSF_LAYER_DATA_LINK_CIRCUIT_HELPERS_H_
8dc36ae2a5bff6865aa414959350295da57a45b6
17e32121c8e8ffbe114ec438466afca7ed8f316b
/touhou/SDLEngine/ShooterInput.cpp
1a48db4dc7f29c1ec202814a55e1e768da4f0769
[ "MIT" ]
permissive
axt32/tohoxp
ee21a46de62f579f10a6927d2741c7bacb960c8b
1dee92da45f8adb2d6475154bd73f940d30e8cf3
refs/heads/master
2022-10-17T18:29:41.550294
2020-06-14T09:51:23
2020-06-14T09:51:23
272,163,237
0
0
null
null
null
null
UHC
C++
false
false
4,617
cpp
ShooterInput.cpp
#include "ShooterInput.h" ShooterInput :: ShooterInput() { for (int i = 0 ; i < MAXKEYCOUNT; i++) { PreviousKeyInput[i] = false; } FlushInput(); bGotFocus = false; } void ShooterInput :: InitInput() { SDL_StartTextInput(); } void ShooterInput :: FlushInput() { for (int i = 0; i < MAXKEYCOUNT; i++) { PreviousKeyInput[i] = KeyInput[i]; } for (int i = 0 ; i < MAXKEYCOUNT; i++) { KeyInput[i] = false; } } void ShooterInput :: TakeInput() { Uint32 LastTime = SDL_GetTicks(); while (SDL_PollEvent( &Event )) { switch (Event.type) { //시스템 이벤트 case SDL_QUIT: KeyInput[QUIT] = true; break; case SDL_WINDOWEVENT: switch (Event.window.event) { case SDL_WINDOWEVENT_CLOSE: { SDL_Window *window = SDL_GetWindowFromID(Event.window.windowID); if (window) { SDL_DestroyWindow(window); } KeyInput[WINDOW_CLOSE] = true; } break; case SDL_WINDOWEVENT_FOCUS_GAINED: KeyInput[WINDOW_FOCUS_GAINED] = true; bGotFocus = true; break; case SDL_WINDOWEVENT_FOCUS_LOST: KeyInput[WINDOW_FOCUS_LOST] = true; bGotFocus = false; case SDL_WINDOWEVENT_SIZE_CHANGED: bool debug; debug = false; break; } } } //그냥 윈도우 API의 입력함수로 쓴다. //왠만해선 SDL에서 자체제공하는 인터페이스를 사용하려고했는데 //SDL 2.0에서 이상하게 바뀌어서 예전처럼 입력처리가 안됨.. API를 써보니 성능차이도 없는것같고 //0x8000 마스크를 쓰지 않는다. 그 이유는, 프레임 딜레이 도중에 받았던 입력을 처리하기 위함이다. //이를 위해서, 모드 전환시마다 키 입력을 Reset 해줘야 한다. //(예컨대 Pause 메뉴 화면중에 공격키를 입력한 상태로 Pause를 끄면 공격이 한번 나가기 때문이다.) if ( bGotFocus == true ) { auto Check = [&] (int IN_KeyNum, KEY Result_Key) { if (GetAsyncKeyState(IN_KeyNum)) { KeyInput[Result_Key] = true; } }; Check(VK_ESCAPE, KEY_ESCAPE); Check(VK_F1, KEY_F1); Check(VK_F2, KEY_F2); Check(VK_F3, KEY_F3); Check(VK_F4, KEY_F4); Check(VK_F5, KEY_F5); Check(VK_F6, KEY_F6); Check(VK_F7, KEY_F7); Check(VK_F8, KEY_F8); Check(VK_F9, KEY_F9); Check(VK_F10, KEY_F10); Check(VK_F11, KEY_F11); Check(VK_F12, KEY_F12); Check(VK_OEM_3, KEY_TILDE); Check(VK_OEM_MINUS, KEY_MINUS); Check(VK_OEM_PLUS, KEY_PLUS); Check(VK_BACK, KEY_BACKSPACE); Check(VK_TAB, KEY_TAB); Check(VK_OEM_4, KEY_LEFTBRACKET); Check(VK_OEM_6, KEY_RIGHTBRACKET); Check(VK_OEM_5, KEY_WON); Check(VK_CAPITAL, KEY_CAPSLOCK); Check(VK_OEM_1, KEY_SEMICOLON); Check(VK_OEM_7, KEY_QUOTE); Check(VK_RETURN, KEY_RETURN); Check(VK_LSHIFT, KEY_LSHIFT); Check(VK_OEM_COMMA, KEY_COMMA); Check(VK_OEM_PERIOD, KEY_PERIOD); Check(VK_OEM_2, KEY_SLASH); Check(VK_RSHIFT, KEY_RSHIFT); Check(VK_LCONTROL, KEY_LCONTROL); Check(VK_LMENU, KEY_LALT); Check(VK_HANJA, KEY_HANJA); Check(VK_SPACE, KEY_SPACE); Check(VK_HANGUL, KEY_HANGUL); Check(VK_RMENU, KEY_RALT); Check(VK_RCONTROL, KEY_RCONTROL); Check(VK_HOME, KEY_HOME); Check(VK_END, KEY_END); Check(VK_INSERT, KEY_INSERT); Check(VK_PRIOR, KEY_PAGEUP); Check(VK_DELETE, KEY_DELETE); Check(VK_NEXT, KEY_PAGEDOWN); Check(VK_UP, KEY_UP); Check(VK_LEFT, KEY_LEFT); Check(VK_DOWN, KEY_DOWN); Check(VK_RIGHT, KEY_RIGHT); Check(VK_SNAPSHOT, KEY_PSCREEN); Check(VK_SCROLL, KEY_SCROLLLOCK); Check(VK_PAUSE, KEY_PAUSE); Check(VK_NUMLOCK, KEY_NUMLOCK); Check(VK_DIVIDE, KEY_NUMPADDIVIDE); Check(VK_MULTIPLY, KEY_NUMPADMULTIPLY); Check(VK_SUBTRACT, KEY_NUMPADSUBTRACT); Check(VK_ADD, KEY_NUMPADADD); Check(VK_DECIMAL, KEY_NUMPADDECIMAL); Check(VK_NUMPAD0, KEY_NUMPAD0); Check(VK_NUMPAD1, KEY_NUMPAD1); Check(VK_NUMPAD2, KEY_NUMPAD2); Check(VK_NUMPAD3, KEY_NUMPAD3); Check(VK_NUMPAD4, KEY_NUMPAD4); Check(VK_NUMPAD5, KEY_NUMPAD5); Check(VK_NUMPAD6, KEY_NUMPAD6); Check(VK_NUMPAD7, KEY_NUMPAD7); Check(VK_NUMPAD8, KEY_NUMPAD8); Check(VK_NUMPAD9, KEY_NUMPAD9); Check(VK_LWIN, KEY_LWIN); Check(VK_RWIN, KEY_RWIN); Check(VK_APPS, KEY_RCLICKMENU); //숫자 키 입력 for (int i = 0x30; i <= 0x39; i++) { Check(i, (KEY)(i - 0x30 + KEY_0)); } //알파벳 키 입력 for (int i = 0x41; i <= 0x5A; i++) { Check(i, (KEY)(i - 0x41 + KEY_A)); } } } bool ShooterInput :: GetPreviousInput (KEY IN_Key) { return PreviousKeyInput[IN_Key]; } bool ShooterInput :: GetInput(KEY IN_Key) { return KeyInput[IN_Key]; } const SDL_Event * ShooterInput :: GetEvent() { return &Event; }
07748593877c2f9dde83dfd39dd0aef6cba7e741
d3d6d2d6394c45fe8bb30ef502098e6c229d9797
/Assembler/Assembler.cpp
a9a91285f8ace7d299b953de49ff7679eeb98d41
[]
no_license
liwei1024/ca
51da4dbbb08e4f544eb2ed8c8692fcb5aed2d51f
ded158be0e016030f24513d3ab684ba3643b9f93
refs/heads/master
2020-04-15T11:08:29.934786
2019-03-19T10:51:51
2019-03-19T10:51:51
164,616,118
26
14
null
null
null
null
UTF-8
C++
false
false
169
cpp
Assembler.cpp
#include "Assembler.h" bool assembler::assembler(XEDPARSE *parse) { return (bool)XEDParseAssemble(parse); } bool assembler::autoAssembler(char * instr,bool x64) { }
55b88b2022c9841d6c03065ac1bb7e7a047cc6b9
f1ee65fbe1ffc43c2aac45e41515f1987eb534a4
/src/net/third_party/quiche/src/quiche/quic/core/frames/quic_ack_frequency_frame.cc
9d2fc31dad187d694ad4a6eb276251702b113e3d
[ "BSD-3-Clause" ]
permissive
klzgrad/naiveproxy
6e0d206b6f065b9311d1e12b363109f2d35cc058
8ef1cecadfd4e2b5d57e7ea2fa42d05717e51c2e
refs/heads/master
2023-08-20T22:42:12.511091
2023-06-04T03:54:34
2023-08-16T23:30:19
119,178,893
5,710
976
BSD-3-Clause
2023-08-05T10:59:59
2018-01-27T16:02:33
C++
UTF-8
C++
false
false
1,045
cc
quic_ack_frequency_frame.cc
// Copyright (c) 2020 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 "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include <cstdint> #include <limits> namespace quic { QuicAckFrequencyFrame::QuicAckFrequencyFrame( QuicControlFrameId control_frame_id, uint64_t sequence_number, uint64_t packet_tolerance, QuicTime::Delta max_ack_delay) : control_frame_id(control_frame_id), sequence_number(sequence_number), packet_tolerance(packet_tolerance), max_ack_delay(max_ack_delay) {} std::ostream& operator<<(std::ostream& os, const QuicAckFrequencyFrame& frame) { os << "{ control_frame_id: " << frame.control_frame_id << ", sequence_number: " << frame.sequence_number << ", packet_tolerance: " << frame.packet_tolerance << ", max_ack_delay_ms: " << frame.max_ack_delay.ToMilliseconds() << ", ignore_order: " << frame.ignore_order << " }\n"; return os; } } // namespace quic
6841e430d4aaacbbf20179325f71363caac14ed7
e1b592074c550149f43c1dce0a4d4ece26bce92c
/Graphs/all paths from source to target.cpp
49d75ee5087f2a9ac97ff9a132d9e07e120e98f4
[]
no_license
taruvar-mittal/DSA-Solutions
2155ccc170c372f92c60fa5acd3676ec4891baf9
2a23a688fc553d28d9beb7965c5b2b1db2f8f266
refs/heads/master
2023-08-17T07:14:46.680402
2021-09-25T15:57:04
2021-09-25T15:57:04
358,480,177
0
1
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
all paths from source to target.cpp
/* Leetcode 797. All Paths From Source to Target ques:- Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1, and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]). Example 1: Input: graph = [[1,2],[3],[3],[]] Output: [[0,1,3],[0,2,3]] Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. Example 2: Input: graph = [[4,3,1],[3,2,4],[3],[4],[]] Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]] Example 3: Input: graph = [[1],[]] Output: [[0,1]] Example 4: Input: graph = [[1,2,3],[2],[3],[]] Output: [[0,1,2,3],[0,2,3],[0,3]] Example 5: Input: graph = [[1,3],[2],[3],[]] Output: [[0,1,2,3],[0,3]] */ class Solution { public: vector<vector<int>> output; void dfs(vector<vector<int>> &graph, vector<bool> &visited, vector<int> &ans, int vertex, int n) { if (vertex >= n) return; visited[vertex] = true; ans.push_back(vertex); for (int i = 0; i < graph[vertex].size(); i++) { if (!visited[graph[vertex][i]]) dfs(graph, visited, ans, graph[vertex][i], n); } if (vertex == n - 1) output.push_back(ans); ans.pop_back(); visited[vertex] = false; } vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph) { int n = graph.size(); vector<bool> visited(n, false); vector<int> ans; dfs(graph, visited, ans, 0, n); return output; } };
5a6db65dd679678f459090e29c91866b89cdf832
942629fb731650dc6341463aabde18132881f7ff
/IfcPlusPlus/src/ifcpp/reader/ReaderUtil.cpp
88b66c139ed5c32311f51c1e550d08a433fabcef
[ "MIT" ]
permissive
shelltdf/ifcplusplus
335b7352ac3e4a0979be02d6a23289182a1940d7
120ef686c4002c1cc77e3808fe00b8653cfcabd7
refs/heads/master
2021-05-07T19:19:27.968924
2019-05-03T13:58:14
2019-05-03T13:58:14
184,751,293
1
1
MIT
2019-05-03T12:26:00
2019-05-03T12:26:00
null
UTF-8
C++
false
false
22,751
cpp
ReaderUtil.cpp
/* -*-c++-*- IfcQuery www.ifcquery.com * MIT License Copyright (c) 2017 Fabian Gerold 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. */ #define _USE_MATH_DEFINES #include <cmath> #ifdef WIN32 #include <windows.h> #endif #include <limits> #include "ifcpp/model/BuildingException.h" #include "ReaderUtil.h" #ifndef CP_UTF8 #define CP_UTF8 65001 #endif static short convertToHex(unsigned char mc) { short returnValue; if( mc >= '0' && mc <= '9' ) { returnValue = static_cast<short>(mc) - static_cast<short>('0'); } else if( mc >= 'A' && mc <= 'F' ) { returnValue = 10 + static_cast<short>(mc) - static_cast<short>('A'); } else if( mc >= 'a' && mc <= 'f' ) { returnValue = 10 + static_cast<short>(mc) - static_cast<short>('a'); } else { returnValue = 0; } return (returnValue); } static wchar_t Hex2Wchar(unsigned char h1, unsigned char h2 ) { wchar_t returnValue = (convertToHex(h1) << 4) + convertToHex(h2); return (returnValue); } static wchar_t Hex4Wchar(unsigned char h1, unsigned char h2, unsigned char h3, unsigned char h4 ) { wchar_t returnValue = (convertToHex(h1)<< 12) + (convertToHex(h2) << 8) +(convertToHex(h3) << 4) + convertToHex(h4); return (returnValue); } void checkOpeningClosingParenthesis( const wchar_t* ch_check ) { int num_opening=0; int num_closing=0; while( *ch_check != '\0' ) { if( *ch_check == '(' ) { ++num_opening; } else if( *ch_check == ')' ) { ++num_closing; } ++ch_check; } if( num_opening != num_closing ) { std::stringstream err; err << "checkOpeningClosingParenthesis: num_opening != num_closing : " << ch_check << std::endl; throw BuildingException( err.str(), __FUNC__ ); } } void findLeadingTrailingParanthesis( wchar_t* ch, wchar_t*& pos_opening, wchar_t*& pos_closing ) { int num_opening = 0; while( *ch != '\0' ) { if( *ch == '\'' ) { ++ch; // beginning of string, continue to end while( *ch != '\0' ) { if( *ch == '\'' ) { break; } ++ch; } ++ch; continue; } if( *ch == '(' ) { if( num_opening == 0 ) { pos_opening = ch; } ++num_opening; } else if( *ch == ')' ) { --num_opening; if( num_opening == 0 ) { pos_closing = ch; } } ++ch; } } void tokenizeList( std::wstring& list_str, std::vector<std::wstring>& list_items ) { if( list_str.empty() ) { return; } wchar_t* stream_pos = const_cast<wchar_t*>(list_str.c_str()); wchar_t* last_token = stream_pos; int numNestedLists = 0; while( *stream_pos != '\0' ) { if (*stream_pos == '(') { ++stream_pos; ++numNestedLists; continue; } else if (*stream_pos == ')') { ++stream_pos; --numNestedLists; continue; } else if( *stream_pos == '\'' ) { ++stream_pos; // beginning of string, continue to end while( *stream_pos != '\0' ) { if( *stream_pos == '\'' ) { break; } ++stream_pos; } ++stream_pos; continue; } if( *stream_pos == ',' && numNestedLists == 0) { std::wstring item( last_token, stream_pos-last_token ); list_items.push_back( item ); ++stream_pos; while( isspace(*stream_pos) ) { ++stream_pos; } last_token = stream_pos; if( *stream_pos == '\0' ) { throw BuildingException( "tokenizeList: *stream_pos == '\0'", __FUNC__ ); } continue; } ++stream_pos; } // pick up last element if( last_token != nullptr ) { if( last_token != stream_pos ) { std::wstring item( last_token, stream_pos-last_token ); list_items.push_back( item ); } } } void tokenizeEntityList( std::wstring& list_str, std::vector<int>& list_items ) { if( list_str.empty() ) { return; } wchar_t* stream_pos = const_cast<wchar_t*>(list_str.c_str()); while( *stream_pos != '\0' ) { // skip whitespace while( isspace( *stream_pos ) ) { ++stream_pos; } if( *stream_pos == '#' ) { ++stream_pos; // beginning of id wchar_t* begin_id = stream_pos; // proceed until end of integer ++stream_pos; while( *stream_pos != '\0' ) { if( isdigit( *stream_pos ) ) { ++stream_pos; } else { break; } } const int id = std::stoi( std::wstring( begin_id, stream_pos-begin_id ) ); list_items.push_back( id ); } else if( *stream_pos == '$' ) { // empty } else { std::stringstream err; err << "tokenizeEntityList: unexpected argument: " << list_str.c_str() << std::endl; throw BuildingException( err.str(), __FUNC__ ); } while( isspace( *stream_pos ) ) { ++stream_pos; } if( *stream_pos == ',' ) { ++stream_pos; //last_token = stream_pos; continue; } else { break; } } } void readIntegerList( const std::wstring& str, std::vector<int>& vec ) { const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == '(' ) { ++i; last_token = i; break; } ++i; } while( i<argsize ) { if( ch[i] == ',' ) { size_t str_length = i - last_token; if( str_length > 0 ) { vec.push_back(std::stoi(str.substr(last_token, i - last_token))); } last_token = i+1; } else if( ch[i] == ')' ) { size_t str_length = i - last_token; if( str_length > 0 ) { vec.push_back(std::stoi(str.substr(last_token, i - last_token))); } return; } ++i; } } void readIntegerList2D( const std::wstring& str, std::vector<std::vector<int> >& vec ) { // ((1,2,4),(3,23,039),(938,3,-3,6)) const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t num_par_open=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == ',' ) { if( num_par_open == 1 ) { std::vector<int> inner_vec; vec.push_back( inner_vec ); readIntegerList( str.substr( last_token, i-last_token ), inner_vec ); last_token = i+1; } } else if( ch[i] == '(' ) { ++num_par_open; } else if( ch[i] == ')' ) { --num_par_open; if( num_par_open == 0 ) { std::vector<int> inner_vec; vec.push_back( inner_vec ); readIntegerList( str.substr( last_token, i-last_token ), inner_vec ); return; } } ++i; } } void readRealList( const std::wstring& str, std::vector<double>& vec ) { const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == '(' ) { ++i; last_token = i; break; } ++i; } while( i<argsize ) { if( ch[i] == ',' ) { vec.push_back( std::stod( str.substr( last_token, i-last_token ) ) ); last_token = i+1; } else if( ch[i] == ')' ) { vec.push_back( std::stod( str.substr( last_token, i-last_token ) ) ); return; } ++i; } } void readRealList2D( const std::wstring& str, std::vector<std::vector<double> >& vec ) { // ((1.6,2.0,4.9382),(3.78,23.34,039.938367),(938.034,3.0,-3.45,6.9182)) const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t num_par_open=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == ',' ) { if( num_par_open == 1 ) { std::vector<double> inner_vec; vec.push_back(inner_vec); readRealList( str.substr( last_token, i-last_token ), vec.back() ); last_token = i; } } else if( ch[i] == '(' ) { ++num_par_open; last_token = i; } else if( ch[i] == ')' ) { --num_par_open; if( num_par_open == 0 ) { std::vector<double> inner_vec; vec.push_back(inner_vec); readRealList( str.substr( last_token, i-last_token ), vec.back() ); return; } } ++i; } } void readRealList3D( const std::wstring& str, std::vector<std::vector<std::vector<double> > >& vec ) { // ((1.6,2.0,4.9382),(3.78,23.34,039.938367),(938.034,3.0,-3.45,6.9182)) const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t num_par_open=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == ',' ) { if( num_par_open == 1 ) { std::vector<std::vector<double> > inner_vec; vec.push_back(inner_vec); readRealList2D( str.substr( last_token, i-last_token ), vec.back() ); last_token = i; } } else if( ch[i] == '(' ) { ++num_par_open; last_token = i; } else if( ch[i] == ')' ) { --num_par_open; if( num_par_open == 0 ) { std::vector<std::vector<double> > inner_vec; vec.push_back(inner_vec); readRealList2D( str.substr( last_token, i-last_token ), vec.back() ); return; } } ++i; } } void readBinary( const std::wstring& str, std::wstring& target ) { target = str; } void readBinaryString(const std::wstring& attribute_value, std::wstring& target) { if( attribute_value.size() < 2 ) { target = attribute_value; return; } if( attribute_value[0] == '"' && attribute_value[attribute_value.size() - 1] == '"' ) { target = attribute_value.substr(1, attribute_value.size() - 2); } } void readBinaryList( const std::wstring& str, std::vector<std::wstring>& vec ) { readStringList( str, vec ); } void readStringList( const std::wstring& str, std::vector<std::wstring>& vec ) { const wchar_t* ch = str.c_str(); const size_t argsize = str.size(); if( argsize == 0 ) { return; } size_t i=0; size_t last_token = 0; while( i<argsize ) { if( ch[i] == '(' ) { ++i; last_token = i; break; } ++i; } while( i<argsize ) { if( ch[i] == ',' ) { vec.push_back( str.substr( last_token, i-last_token ) ); last_token = i+1; } else if( ch[i] == ')' ) { vec.push_back( str.substr( last_token, i-last_token ) ); return; } ++i; } } void findEndOfString( char*& stream_pos ) { ++stream_pos; char* pos_begin = stream_pos; // beginning of string, continue to end while( *stream_pos != '\0' ) { if( *stream_pos == '\\' ) { if( *(stream_pos+1) == 'X' ) { if( *(stream_pos+2) == '0' || *(stream_pos+2) == '2' || *(stream_pos+2) == '4' ) { if( *(stream_pos+3) == '\\' ) { // ISO 10646 encoding, continue stream_pos += 4; continue; } } } if( *(stream_pos+1) == '\\' ) { // we have a double backslash, so just continue ++stream_pos; ++stream_pos; continue; } if( *(stream_pos+1) == '\'' ) { // quote is escaped ++stream_pos; ++stream_pos; continue; } } if( *stream_pos == '\'' ) { if( *(stream_pos+1) == '\'' ) { // two single quotes in string if( stream_pos != pos_begin ) { ++stream_pos; ++stream_pos; continue; } } ++stream_pos; // end of string break; } ++stream_pos; } } void findEndOfWString( wchar_t*& stream_pos ) { ++stream_pos; wchar_t* pos_begin = stream_pos; // beginning of string, continue to end while( *stream_pos != '\0' ) { if( *stream_pos == '\\' ) { if( *(stream_pos+1) == 'X' ) { if( *(stream_pos+2) == '0' || *(stream_pos+2) == '2' || *(stream_pos+2) == '4' ) { if( *(stream_pos+3) == '\\' ) { // ISO 10646 encoding, continue stream_pos += 4; continue; } } } if( *(stream_pos+1) == '\\' ) { // we have a double backslash, so just continue ++stream_pos; ++stream_pos; continue; } if( *(stream_pos+1) == '\'' ) { // quote is escaped ++stream_pos; ++stream_pos; continue; } } if( *stream_pos == '\'' ) { if( *(stream_pos+1) == '\'' ) { // two single quotes in string if( stream_pos != pos_begin ) { ++stream_pos; ++stream_pos; continue; } } ++stream_pos; // end of string break; } ++stream_pos; } } void decodeArgumentStrings( std::vector<std::string>& entity_arguments, std::vector<std::wstring>& args_out ) { for(auto & argument_str : entity_arguments) { const size_t arg_length = argument_str.length(); if( arg_length == 0 ) { continue; } std::wstring arg_str_new; arg_str_new.reserve(arg_length); char* stream_pos = const_cast<char*>(argument_str.c_str()); // ascii characters from STEP file while( *stream_pos != '\0' ) { if( *stream_pos == '\\' ) { if( *(stream_pos+1) == 'S' ) { if( *(stream_pos+2) == '\\' ) { if( *(stream_pos+3) != '\0' ) { if( *(stream_pos+4) == '\\' ) { if( *(stream_pos+5) == 'S' ) { if( *(stream_pos+6) == '\\' ) { if( *(stream_pos+7) != '\0' ) { char first = *(stream_pos+3); char second = *(stream_pos+7); wchar_t append_wchar = wchar_t(125 + first + second); arg_str_new += append_wchar; stream_pos += 8; continue; } } } else if( *(stream_pos+5) == 'Q' ) { if( *(stream_pos+6) == '\\' ) { if( *(stream_pos+7) != '\0' ) { char first = *(stream_pos+3); char second = *(stream_pos+7); wchar_t append_wchar = wchar_t(125 + first + second); arg_str_new += append_wchar; stream_pos += 8; continue; } } } } else { // next characters code value v shall be interpreted as v + 128 char first = *(stream_pos+3); wchar_t append_wchar = wchar_t(128 + first); arg_str_new += append_wchar; stream_pos += 4; continue; } } } } else if( *(stream_pos+1) == 'X' ) { if( *(stream_pos+2) == '\\' ) { wchar_t wc = Hex2Wchar(*(stream_pos+3), *(stream_pos+4)); //unsigned char char_ascii = wctob(wc); arg_str_new += wc; stream_pos += 5; continue; } else if( *(stream_pos+2) == '0' ) { if( *(stream_pos+3) == '\\' ) { stream_pos += 4; continue; } } else if( *(stream_pos+2) == '2' ) { if( *(stream_pos+3) == '\\' ) { // the following sequence of multiples of four hexadecimal characters shall be interpreted as encoding the // two-octet representation of characters from the BMP in ISO 10646 bool finished = false; stream_pos += 4; do { wchar_t wc = Hex4Wchar(*(stream_pos), *(stream_pos+1), *(stream_pos+2), *(stream_pos+3)); //unsigned char char_ascii = wctob(wc); arg_str_new += wc; stream_pos += 4; } while (( *stream_pos != '\0' ) && ( *stream_pos != '\\' )); continue; } } } else if( *(stream_pos+1) == 'N' ) { if( *(stream_pos+2) == '\\' ) { arg_str_new.append( L"\n" ); stream_pos += 3; continue; } } } char current_char = *stream_pos; arg_str_new += current_char; ++stream_pos; } args_out.push_back( arg_str_new ); } } //\brief split one string into a vector of argument strings // caution: when using OpenMP, this method runs in parallel threads void tokenizeEntityArguments( const std::string& argument_str, std::vector<std::string>& entity_arguments ) { char* stream_pos = const_cast<char*>(argument_str.c_str()); if( *stream_pos != '(' ) { return; } ++stream_pos; int num_open_braces = 1; char* last_token = stream_pos; while( *stream_pos != '\0' ) { if( *stream_pos == '\'' ) { findEndOfString( stream_pos ); continue; } if( *stream_pos == '(' ) { ++num_open_braces; } else if( *stream_pos == ',' ) { if( num_open_braces == 1 ) { if( *last_token == ',' ) { ++last_token; } char* begin_arg = last_token; // skip whitespace while( isspace( *begin_arg ) ) { ++begin_arg; } char* end_arg = stream_pos-1; entity_arguments.emplace_back( begin_arg, end_arg-begin_arg+1 ); last_token = stream_pos; } } else if( *stream_pos == ')' ) { --num_open_braces; if( num_open_braces == 0 ) { if( *last_token == ',' ) { ++last_token; } char* begin_arg = last_token; // skip whitespace while( isspace( *begin_arg ) ) { ++begin_arg; } int remaining_size = static_cast<int>(stream_pos - begin_arg); if( remaining_size > 0 ) { char* end_arg = stream_pos-1; entity_arguments.emplace_back( begin_arg, end_arg-begin_arg+1 ); } break; } } ++stream_pos; } } //\brief split one string into a vector of argument strings // caution: when using OpenMP, this method runs in parallel threads void tokenizeEntityArguments( const std::wstring& argument_str, std::vector<std::wstring>& entity_arguments ) { wchar_t* stream_pos = const_cast<wchar_t*>(argument_str.c_str()); if( *stream_pos != '(' ) { return; } ++stream_pos; int num_open_braces = 1; wchar_t* last_token = stream_pos; while( *stream_pos != '\0' ) { if( *stream_pos == '\'' ) { findEndOfWString( stream_pos ); continue; } if( *stream_pos == '(' ) { ++num_open_braces; } else if( *stream_pos == ',' ) { if( num_open_braces == 1 ) { if( *last_token == ',' ) { ++last_token; } wchar_t* begin_arg = last_token; // skip whitespace while( isspace( *begin_arg ) ) { ++begin_arg; } wchar_t* end_arg = stream_pos-1; entity_arguments.emplace_back( begin_arg, end_arg-begin_arg+1 ); last_token = stream_pos; } } else if( *stream_pos == ')' ) { --num_open_braces; if( num_open_braces == 0 ) { if( *last_token == ',' ) { ++last_token; } wchar_t* begin_arg = last_token; // skip whitespace while( isspace( *begin_arg ) ) { ++begin_arg; } int remaining_size = static_cast<int>(stream_pos - begin_arg); if( remaining_size > 0 ) { wchar_t* end_arg = stream_pos-1; entity_arguments.emplace_back( begin_arg, end_arg-begin_arg+1 ); } break; } } ++stream_pos; } } void tokenizeInlineArgument( std::wstring arg, std::wstring& keyword, std::wstring& inline_arg ) { if( arg.empty() ) { throw BuildingException( "arg.size() == 0", __FUNC__ ); } if( arg[0] == '$' ) { return; } if( arg[0] == '*' ) { return; } if( arg[0] == '#' ) { throw BuildingException( "tokenizeInlineArgument: argument begins with #, so it is not inline", __FUNC__ ); } wchar_t* stream_pos = const_cast<wchar_t*>(arg.c_str()); while(isspace(*stream_pos)){ ++stream_pos; } wchar_t* begin_keyword = stream_pos; while(isalnum(*stream_pos)){ ++stream_pos; } // get type name std::wstring key( begin_keyword, stream_pos-begin_keyword ); if( key.empty() ) { // single argument, for example .T. inline_arg = arg; return; } // proceed to '(' int numOpenBraces = 0; if( *stream_pos == '(' ) { ++stream_pos; ++numOpenBraces; } else { while( *stream_pos != '\0' ) { if( *stream_pos == '(' ) { ++stream_pos; ++numOpenBraces; break; } ++stream_pos; } } // proceed to ')' std::wstring inline_argument; wchar_t* inline_argument_begin = stream_pos; while( *stream_pos != '\0' ) { if( *stream_pos == '\'' ) { ++stream_pos; // inside string while( *stream_pos != '\0' ) { if( *stream_pos == '\'' ) { // check if tick is escaped wchar_t* tick_pos = stream_pos; bool tick_escaped = false; while( tick_pos != begin_keyword ) { --tick_pos; if( *tick_pos == '\\' ) { tick_escaped = !tick_escaped; continue; } break; } if( tick_escaped ) { ++stream_pos; continue; } // else tick marks the end of argument break; } ++stream_pos; } } if (*stream_pos == '(') { ++numOpenBraces; ++stream_pos; continue; } if( *stream_pos == ')' ) { --numOpenBraces; // skip whitespace while( isspace( *inline_argument_begin ) ) { ++inline_argument_begin; } if (numOpenBraces == 0) { wchar_t* end_arg = stream_pos - 1; inline_argument = std::wstring(inline_argument_begin, end_arg - inline_argument_begin + 1); break; } } ++stream_pos; } std::transform(key.begin(), key.end(), key.begin(), toupper); keyword = key; inline_arg = inline_argument; } void copyToEndOfStepString( char*& stream_pos, char*& stream_pos_source ) { char* pos_begin = stream_pos_source; findEndOfString( stream_pos_source ); size_t length = stream_pos_source - pos_begin; memcpy( stream_pos, pos_begin, (length)*sizeof( char) ); stream_pos += length; }
ed8f6d8dcf594e1ec96aa9cb4ebbdcb763c1e48a
4797932534f11408f701a79654072ee28623d0be
/HashTable/singlylinkedlist.h
5d6b1a889de7c392c1d3fc0084bb578e042b7c1f
[]
no_license
Stephen-Anderson-2000/Advanced-Software-Engineering
6d030e2b663370be5afbc243a69b72b2d749a4b4
8d61d618286ade254540bc723086938766d059c6
refs/heads/master
2023-05-11T12:13:29.171441
2021-05-28T21:11:51
2021-05-28T21:11:51
312,627,305
0
0
null
null
null
null
UTF-8
C++
false
false
1,716
h
singlylinkedlist.h
#ifndef SINGLYLINKEDLIST_H #define SINGLYLINKEDLIST_H template<typename K, typename I> struct SinglyLinkedList { using KeyType = K; using ItemType = I; SinglyLinkedList(); struct Node; Node* head; void insert(KeyType, ItemType); void insertRec(KeyType, ItemType, Node*); ItemType* lookup(KeyType); ItemType* lookupRec(KeyType, Node*); }; template<typename K, typename I> struct SinglyLinkedList<K, I>::Node { Node(K, I); K key; I item; struct Node* next = nullptr; }; template<typename K, typename I> SinglyLinkedList<K, I>::SinglyLinkedList() { this->head = nullptr; } template<typename K, typename I> void SinglyLinkedList<K, I>::insert(KeyType k, ItemType i) { insertRec(k, i, this->head); } template<typename K, typename I> void SinglyLinkedList<K, I>::insertRec(KeyType k, ItemType i, Node* currentNode) { if (currentNode == nullptr) { Node* newNode = new Node(k, i); currentNode = newNode; } else if (currentNode->key == k) { currentNode->item = i; } else { insert(k, i, currentNode->next); } } template<typename K, typename I> typename SinglyLinkedList<K, I>::ItemType* SinglyLinkedList<K, I>::lookup(KeyType k) { lookupRec(k, this->head); } template<typename K, typename I> typename SinglyLinkedList<K, I>::ItemType* SinglyLinkedList<K, I>::lookupRec(KeyType k, Node* currentNode) { if (currentNode != nullptr) { if (currentNode->key == k) { return currentNode; } else { lookup(k, currentNode->next); } } else { return nullptr; } } #endif // SINGLYLINKEDLIST_H
0e28c4578c31a3b292e84a03b9a42485a5d7a653
5e4be5370dd3e71354ac4c5bdff42c42dff54073
/main/i_session_delegate.hpp
ffbf14915dbde587745fddf49fbfefd9b4487ff9
[ "MIT" ]
permissive
jukorp/rollkit
8ea02b1db0f776ad9462f649bb34f1517fa6004e
04cdeba2fad804304a23c66673f58c400c891847
refs/heads/master
2020-03-26T18:35:05.638927
2018-08-10T03:58:44
2018-08-10T03:58:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
321
hpp
i_session_delegate.hpp
#ifndef I_SESSION_H_DELEGATE_HPP #define I_SESSION_H_DELEGATE_HPP #include "request.hpp" #include "i_session.hpp" class ISessionDelegate { public: ISessionDelegate() {}; virtual ~ISessionDelegate() {}; virtual void request_recv(Request& new_request, ISession* session) = 0; }; #endif // I_SESSION_DELEGATE_HPP
6c2c73f2ad10f5e9a8a9b6ee6ce32b27d0352dcf
6b5357388049b43be7b5fb3933ef883a147ec012
/RobotCommonLib/ISerializable.h
ea0e485e320e46e1de6acb73bfb0267f17f1686d
[]
no_license
akosnagy2/Diploma
eb1dc3c2c642aea22eb52ab00cda468c1789ce4c
00753e658347b4b8fddc7f3b1223b320ed53b4eb
refs/heads/master
2021-01-23T21:33:58.306157
2015-06-25T20:57:50
2015-06-25T20:57:50
24,590,168
1
2
null
null
null
null
UTF-8
C++
false
false
328
h
ISerializable.h
#pragma once #include <json/value.h> #include <iostream> class ISerializable { public: friend std::ostream& operator<<(std::ostream& os, ISerializable& obj); friend std::istream& operator>>(std::istream& is, ISerializable& obj); virtual Json::Value getJsonValue() = 0; virtual void setFromJson(Json::Value& value) = 0; };
6f850a23dbd528763f4bb881a3813154bf737ded
0e9e809421e6ffbef28fa1d638fd597a30bbe621
/fresh/whs.cpp
ab8b22fe5dd90fc52f8d719048eea65eae7f608e
[]
no_license
johnskie/CS_453_Lab_03
84db1ecb3e38cde066dc4ffb47920f6b652e2125
d75bb0e8c32d29144d869de197d1a658430697df
refs/heads/master
2021-01-10T09:57:01.339367
2015-11-24T11:26:17
2015-11-24T11:26:17
45,752,884
0
0
null
null
null
null
UTF-8
C++
false
false
2,018
cpp
whs.cpp
#include <fstream> #include <stdio.h> #include <string.h> #include <sstream> #include <stdlib.h> #include <iostream> #include "Process.h" #include <vector> #include "readin.h" using namespace std; /*vector<Process> readInFile(char* filename){ std::ifstream file(filename); std::string str; std::vector<Process> retval; int i = 0; while (std::getline(file, str)) { std::vector<int> string_list; if(i != 0){ istringstream ss(str); for(int word; ss >> word;){ string_list.push_back(word); } Process temp; temp.setPID(string_list.at(0)); temp.setArrivalTime(string_list.at(2)); temp.setBurstTime(string_list.at(1)); temp.setBurstRemaining(string_list.at(1)); temp.setLastTime(string_list.at(2)); temp.setIO(string_list.at(5)); temp.setPriority(string_list.at(3)); temp.setDeadline(string_list.at(4)); retval.push_back(temp); } i++; } for(int i = 0; i < retval.size();i++){ cout << retval.at(i).getPriority() << endl; } return retval; }*/ /*void MFQS::runProcess(Process *currentProcess, int q1, int curQuantum, int currentRemaining) { if (q1 == 0) { totalWait = c.getTime() - currentProcess->getArrivalTime(); } else { totalWait = totalWait + c.getTime() + currentProcess->getLastTime(); } endTime = startTime + curQuantum; // the endtime of a process is set to it's start time plus the current time quantum(i.e how long it ran) while (c.getTime() <= endTime && currentRemaining > 0) { c.incrementTime(); currentProcess->decrementTime(); } if (currentRemaining > 0) { currentProcess->setLastTime(endTime); queueList[q1 + 1].push(*currentProcess); } else { int diff = c.getTime() - currentProcess->getArrivalTime(); totalTurnaround = totalTurnaround + diff; } }*/
c04f5968d0a86a2a3e93847d3c8bdefcb0af7389
841f0a393aa42f9d2a420cc5a807bfd2729a45d7
/header/afd.h
942cb408f8e1c8ba903fdada8ceda609018def2d
[]
no_license
DanielPBL/tp_lfa
3796aff2589c7cf9309f9e33cd910ad988452c80
c875e573e1e1da857863bda61010a92c3a14d639
refs/heads/master
2020-12-31T06:09:08.744809
2016-05-29T14:23:24
2016-05-29T14:23:24
56,291,143
0
0
null
null
null
null
UTF-8
C++
false
false
1,004
h
afd.h
#ifndef __AFD_H__ #define __AFD_H__ #include "estado.h" #include "transicao.h" #include <string> #include <list> typedef struct ESTADO_COMPOSTO { Estado *e1; Estado *e2; Estado *comp; } EstadoComposto; enum Operacao { INTERSECAO, UNIAO }; class AFD { private: std::string nome; std::list<Estado*> estados; std::list<Transicao*> transicoes; Estado *inicial; std::list<Estado*> finais; public: AFD(std::string, Estado*); AFD(std::string, std::list<Estado*>, std::list<Transicao*>, Estado*, std::list<Estado*>); ~AFD(); bool possuiEstado(Estado*); void adicionaEstado(Estado*); void adicionaTransicao(Transicao*); Estado* realizaTransicao(Estado*, std::string); void gerarDot(bool); void setNome(std::string); std::string getNome(); std::list<Estado*> getEstados(); std::list<Transicao*> getTransicoes(); Estado* getInicial(); static AFD* intersecao(AFD*, AFD*); static AFD* uniao(AFD*, AFD*); private: static AFD* produto(AFD*, AFD*, Operacao); }; #endif // ifndef __AFD_H__
84760e5aa909f7d49aa28104a1ea4f1e1f66b46f
544df57d672532fd8f9595693f8e8cc00489aa0c
/series.cpp
c6f715fddefb2a8493407fa8ddc663e553322291
[]
no_license
moukraintsev/oop_project
05e4799b1075570dbfe76eecaac33eb86ba80a30
c1d8c825b5705c8d712202ac0d73fa30c2d98f7a
refs/heads/main
2023-01-30T15:05:41.995177
2020-12-14T12:49:15
2020-12-14T12:49:15
321,340,916
0
0
null
null
null
null
UTF-8
C++
false
false
2,160
cpp
series.cpp
#include "series.h" Series::Series() { this -> numberOfSeasons = 0; this -> numberOfEpisodes = 0; } Series::Series(const std::string &nameSource, const int &yearSource, const std::string &countrySource ,const std::string &durationSource, const bool &isViewedSource, const int &NumberOfSeasonsSource, const int &NumberOfEpisodesSource): Video(nameSource, yearSource, countrySource, durationSource,isViewedSource ) { if (NumberOfSeasonsSource > 0) this -> numberOfSeasons = NumberOfSeasonsSource; if (NumberOfEpisodesSource > 0) this -> numberOfEpisodes = NumberOfEpisodesSource; } Series::Series(const Series &sourceSeries) { this -> name = sourceSeries.getName(); this -> year = sourceSeries.getYear(); this -> duration = sourceSeries.getDuration(); this -> country = sourceSeries.getCountry(); this -> isViewed = sourceSeries.getView(); this -> numberOfSeasons = sourceSeries.getNumberOfSeasons(); this -> numberOfEpisodes = sourceSeries.getNumberOfEpisodes(); } const int &Series::getNumberOfSeasons() const { return this -> numberOfSeasons; } const int &Series::getNumberOfEpisodes() const { return this -> numberOfEpisodes; } void Series::setNumberOfSeasons(const int &newNmberOfSeasons) { if (newNmberOfSeasons > 0) this -> numberOfSeasons = newNmberOfSeasons; } void Series::setNumberOfEpisodes(const int &newNumberOfEpisodes) { if (newNumberOfEpisodes > 0) this -> numberOfEpisodes = newNumberOfEpisodes; } bool Series::operator == (Series *series) { if (this -> getName() == series -> getName() && this -> getYear() == series -> getYear() && this -> getCountry() == series -> getCountry() && this -> getDuration() == series -> getDuration() && this -> getNumberOfSeasons() == series -> getNumberOfSeasons() && this -> getNumberOfEpisodes() == series -> getNumberOfEpisodes()) { return true; } else { return false; } } VideoType Series::getType() const{ return series; }
ad4a2c322f3970b24182f6937db2d47beb4afbda
86d197c0e128dbc715771bdbab45f2000f0dc08f
/src/OpCodes.hpp
55bb9c42cff9542ebb9fda6b7f8633c8c865d236
[]
no_license
HarbingTarbl/Nemu
5fc9af4c1fb8580ca5f3e44d1ad378f84a5b2e6f
fd73c04e7455d300dc3deca57af30fbc024e7a8f
refs/heads/master
2021-01-02T22:57:08.772966
2014-04-22T02:02:01
2014-04-22T02:02:01
16,090,089
2
1
null
null
null
null
UTF-8
C++
false
false
2,688
hpp
OpCodes.hpp
#pragma once #ifndef _OPCODES_H #define _OPCODES_H #include <cstdint> class CPU; namespace InstructionTable { typedef void(*Callback)(CPU&); struct InstructionPack { Callback Pre; Callback Exec; uint8_t Size; uint8_t Cycles; const char* Name; }; const extern InstructionPack Table[256]; const InstructionPack* GetInstruction(uint8_t opcode); static void ADC(CPU& cpu); static void AND(CPU& cpu); static void ASL(CPU& cpu); static void BCC(CPU& cpu); static void BCS(CPU& cpu); static void BEQ(CPU& cpu); static void BIT(CPU& cpu); static void BMI(CPU& cpu); static void BNE(CPU& cpu); static void BPL(CPU& cpu); static void BRK(CPU& cpu); static void BVC(CPU& cpu); static void BVS(CPU& cpu); static void CLC(CPU& cpu); static void CLD(CPU& cpu); static void CLI(CPU& cpu); static void CLV(CPU& cpu); static void CMP(CPU& cpu); static void CPX(CPU& cpu); static void CPY(CPU& cpu); static void DEC(CPU& cpu); static void DEX(CPU& cpu); static void DEY(CPU& cpu); static void DCP(CPU& cpu); static void EOR(CPU& cpu); static void INC(CPU& cpu); static void INX(CPU& cpu); static void INY(CPU& cpu); static void ISB(CPU& cpu); static void JMP(CPU& cpu); static void JSR(CPU& cpu); static void LDA(CPU& cpu); static void LDX(CPU& cpu); static void LDY(CPU& cpu); static void LSR(CPU& cpu); static void LAX(CPU& cpu); static void NOP(CPU& cpu); static void ORA(CPU& cpu); static void PHA(CPU& cpu); static void PHP(CPU& cpu); static void PLA(CPU& cpu); static void PLP(CPU& cpu); static void ROL(CPU& cpu); static void ROR(CPU& cpu); static void RTI(CPU& cpu); static void RTS(CPU& cpu); static void RLA(CPU& cpu); static void RRA(CPU& cpu); static void SBC(CPU& cpu); static void SEC(CPU& cpu); static void SED(CPU& cpu); static void SEI(CPU& cpu); static void STA(CPU& cpu); static void STX(CPU& cpu); static void STY(CPU& cpu); static void SAX(CPU& cpu); static void SLO(CPU& cpu); static void SRE(CPU& cpu); static void TAX(CPU& cpu); static void TAY(CPU& cpu); static void TSX(CPU& cpu); static void TXA(CPU& cpu); static void TXS(CPU& cpu); static void TYA(CPU& cpu); }; namespace AddressingModes { using InstructionTable::Callback; static void ZP(CPU& cpu); static void ZPX(CPU& cpu); static void ZPY(CPU& cpu); static void ABS(CPU& cpu); static void ABX(CPU& cpu); static void ABY(CPU& cpu); static void IMP(CPU& cpu); static void ACC(CPU& cpu); static void IMM(CPU& cpu); static void REL(CPU& cpu); static void IND(CPU& cpu); static void IIX(CPU& cpu); static void IIY(CPU& cpu); static void NOP2(CPU& cpu); static void NOP3(CPU& cpu); }; #endif
ad1004652018b129d98d505d11155861f46a9273
abc4cd2f20e873ae23b969252813987ff028d0df
/Projects/project3/store.cpp
00d18a32c2b1e62f7dfc4e9dd8fe7ca430d20e67
[]
no_license
Reido50/CSE-232
7b291440d4c733336464bb4513aca28a5e978dd3
6bd6af37a4ed85d5d854b09fb64d2de27072eba2
refs/heads/master
2022-04-24T17:32:05.725968
2020-04-26T18:19:09
2020-04-26T18:19:09
233,287,864
0
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
store.cpp
#include "store.h" #include "item.h" #include<iostream> using std::ostream; using std::endl; #include<string> using std::string; #include<algorithm> using std::find_if; Store::Store(const Store& s){ name_ = s.name(); location_ = s.location(); items_ = s.items(); } long Store::getItemsSize(){ return static_cast<long>(items_.size()); } void Store::name(string n){ name_ = n; } void Store::location(string l){ location_ = l; } void Store::addItem(string n, long q, long p){ Item i(n, q, p); items_.push_back(i); } void Store::addItem(const Item& i){ items_.push_back(i); } ostream& operator<<(ostream& o, const Store& s){ o << "Name: " << s.name_ << endl << "Location: " << s.location_ << endl << "Items: " << endl; for(Item i : s.items_){ o << i << endl; } return o; }
8e6d193b739e5cdf0e4298ce7c4398a85b204b6e
f78d413c62a60b100f9412074a3eec9ce72af16c
/test/test_1.cpp
721ce053b53f89e1d31f65b605e6496786730b39
[ "MIT" ]
permissive
Galfurian/expar
7bdef526ee8f813b483361b86403fb661028855b
ad3db23c8b3b16b706374de11cc1969f61832690
refs/heads/main
2023-06-03T19:53:19.485582
2021-06-29T15:13:13
2021-06-29T15:13:13
380,176,326
0
0
null
null
null
null
UTF-8
C++
false
false
4,798
cpp
test_1.cpp
#include "expar/parser.hpp" #include <iostream> class ExpDebugPrinter : public expar::ExpBaseVisitor { public: void visit(expar::AstBinary &e) override { std::cout << "AstBinary["; if (e.left) e.left->accept(*this); else std::cout << "NULL"; std::cout << expar::operator_to_string(e.type); if (e.right) e.right->accept(*this); else std::cout << "NULL"; std::cout << "]"; } void visit(expar::AstUnary &e) override { std::cout << "AstUnary["; std::cout << expar::operator_to_string(e.type); if (e.right) e.right->accept(*this); else std::cout << "NULL"; std::cout << "]"; } void visit(expar::AstScope &e) override { std::cout << "AstScope["; if (e.type == expar::scp_round) std::cout << "("; else if (e.type == expar::scp_square) std::cout << "["; else if (e.type == expar::scp_curly) std::cout << "{"; if (e.content) e.content->accept(*this); else std::cout << "NULL"; if (e.type == expar::scp_round) std::cout << ")"; else if (e.type == expar::scp_square) std::cout << "]"; else if (e.type == expar::scp_curly) std::cout << "}"; std::cout << "]"; } void visit(expar::AstFunction &e) override { std::cout << "AstFunction["; std::cout << e.name << "("; for (auto it : e.content) { if (it) it->accept(*this); else std::cout << "NULL"; } std::cout << ")"; std::cout << "]"; } void visit(expar::AstVariable &e) override { std::cout << "AstVariable["; std::cout << e.name; std::cout << "]"; } void visit(expar::AstNumber &e) override { std::cout << "AstNumber["; std::cout << e.value; std::cout << "]"; } }; class ExpPrinter : public expar::ExpBaseVisitor { public: void visit(expar::AstBinary &e) override { if (e.left) e.left->accept(*this); else std::cout << "NULL"; std::cout << expar::operator_to_string(e.type); if (e.right) e.right->accept(*this); else std::cout << "NULL"; } void visit(expar::AstUnary &e) override { std::cout << expar::operator_to_string(e.type); if (e.right) e.right->accept(*this); else std::cout << "NULL"; } void visit(expar::AstScope &e) override { if (e.type == expar::scp_round) std::cout << "("; else if (e.type == expar::scp_square) std::cout << "["; else if (e.type == expar::scp_curly) std::cout << "{"; if (e.content) e.content->accept(*this); else std::cout << "NULL"; if (e.type == expar::scp_round) std::cout << ")"; else if (e.type == expar::scp_square) std::cout << "]"; else if (e.type == expar::scp_curly) std::cout << "}"; } void visit(expar::AstFunction &e) override { std::cout << e.name << "("; for (size_t i = 0; i < e.content.size(); ++i) { if (e.content[i]) e.content[i]->accept(*this); else std::cout << "NULL"; if (i < (e.content.size() - 1)) std::cout << ", "; } std::cout << ")"; } void visit(expar::AstVariable &e) override { std::cout << e.name; } void visit(expar::AstNumber &e) override { std::cout << e.value; } }; ExpDebugPrinter debug_printer; ExpPrinter printer; void Test(const std::string &text) { auto node = expar::parser::parse(text); printf("%-30s ", text.c_str()); if (node) { std::cout << " OK "; node->accept(printer); std::cout << " --> "; node->accept(debug_printer); } else { std::cout << " FAILED"; } std::cout << "\n"; } int main(int argc, char *argv[]) { Test("a = b"); Test("1+2+3+4"); Test("1*2*3*4"); Test("1-2-3-4"); Test("1/2/3/4"); Test("1*2+3*4"); Test("1+2*3+4"); Test("(1+2)*(3+4)"); Test("1+(2*3)*(4+5)"); Test("1+(2*3)/4+5"); Test("5/(4+3)/2"); Test("1 + 2.5"); Test("125"); Test("-1"); Test("-1+(-2)"); Test("-1+(-2.0)"); Test(" 1*2,5"); Test(" 1*2.5e2"); Test("M1 + 2.5"); Test("1 + 2&5"); Test("1 * 2.5.6"); Test("1 ** 2.5"); Test("1 / 2.5"); Test("A(1, 2, 3)"); }
395d1d5647bd5bd4d26be17a353952fdb0773cc8
389129460c5e453ac882f02fc601c239ba66cbc5
/Classes/OpenLayer.cpp
493addcb538024b0117dfbd2869044a9c4d28f50
[]
no_license
wangjunchi/pong
2eca1e771383920abf2a33c8af370344b5b6e7df
716de1a6ae86d14620cb0dfc34ea40beacbbc951
refs/heads/master
2020-03-07T14:12:39.666681
2018-04-02T12:49:16
2018-04-02T12:49:16
127,521,190
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
cpp
OpenLayer.cpp
#include "OepenLayer.h" bool OpenLayer::init() { Size winsize = Director::getInstance()->getWinSize(); Label *label = Label::createWithSystemFont("Pong!", "", 48); label->setPosition(Vec2(winsize.width / 2, winsize.height*0.8)); this->addChild(label); Label *labelStart = Label::createWithSystemFont("Start", "", 24); MenuItemLabel * menuItem = MenuItemLabel::create(labelStart, CC_CALLBACK_1(OpenLayer::menuCallBack, this)); menuItem->setTag(101); menuItem->setPosition(Vec2(winsize.width / 2, winsize.height*0.55)); Label *labelHelp = Label::createWithSystemFont("Help", "", 24); MenuItemLabel *menuItem_3 = MenuItemLabel::create(labelHelp, CC_CALLBACK_1(OpenLayer::menuCallBack,this)); menuItem_3->setTag(103); menuItem_3->setPosition(winsize.width / 2, winsize.height*0.4); Label *labelQuit = Label::createWithSystemFont("Quit","", 24); MenuItemLabel * menuItem_2 = MenuItemLabel::create(labelQuit, CC_CALLBACK_1(OpenLayer::menuCallBack, this)); menuItem_2->setTag(102); menuItem_2->setPosition(Vec2(winsize.width / 2, winsize.height*0.25)); auto menu = Menu::create(menuItem, menuItem_2, menuItem_3,NULL); menu->setPosition(Point::ZERO); this->addChild(menu); return true; } void OpenLayer::menuCallBack(Ref * pSender) { switch (((MenuItem*)pSender)->getTag()) { case 101: tsm->goToGameScene(); break; case 102: { Director::getInstance()->end(); exit(0); } break; case 103: { tsm->goToHelpScene(); break; } default: break; } }
7a2c70fce473f1c16f9320f6a83173083f471462
4b9b8e3a6807df68023b71926036817eabb0c575
/Decorator/Decorator Pattern/Updated/AddBlackSugar.cpp
42e204548bfb318f58031de9a035aa57c991eed2
[]
no_license
duongbaochan/Group3-19APCS1-CS202-Project
5a62e5cbdbf07e0c0d6ce7f8adcb891eb2bf4e87
25551c1254cafcad474a112c5f36d6b6a7ba9bc6
refs/heads/master
2023-02-14T02:23:30.545543
2021-01-09T01:13:08
2021-01-09T01:13:08
313,612,688
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
AddBlackSugar.cpp
#include "AddBlackSugar.h" //Concrete Decorator AddBlackSugar::AddBlackSugar(MilkTea* base_milk_tea) : AddTopping(base_milk_tea) {} string AddBlackSugar::serve() { return milk_tea->serve() + " + Black Sugar"; } unsigned long long int AddBlackSugar::price() { return milk_tea->price() + 2000; }
a5e3953bad6fdbf6af598d109cf7caca9f36726d
c794c764f56868eff07c5ab821eced2dc3e8ae15
/source/arduino/bobina/Command.h
7f1300e39c657c02e861dc16910be3f8f257672d
[]
no_license
cjsatuforc/Bobina
905039f611f8c0f934711eacf9417ecb8f27d23e
fb7597f2f98daedb8162af8d10e18846979e72cd
refs/heads/master
2020-04-04T16:21:01.245417
2016-09-05T15:38:20
2016-09-05T15:38:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
538
h
Command.h
#ifndef COMMAND_H #define COMMAND_H /* * Builtin Commands */ #define NO_COMMAND 0 #define MOVE_ON 1 #define MOVE_BACK 2 #define MOVE_RIGHT 3 #define MOVE_LEFT 4 #define TEST_MOTORS 5 /* * Commands mode */ #define AUTOMATIC_MODE 99 #define MANUAL_MODEq 88 /** * Sends commands to the Robot. It can be * automatic or manual */ class Command{ public: /* * Reciece Serial data and return * the corresponding command */ int proccess(); /* * */ bool setMode(int mode); private: bool automatic; }; #endif
c73ed3917b16b37124e9269f2852bbd01511681e
746b47dc3c71be2bfa24ae5fa35014a2e45084be
/icode.cc
41fbcb755e249bc5554af67e3c2173e6cb95cd14
[]
no_license
sahilsaiyad/Compiler
b6b631000d3515c29d8066b5410a03dc28246593
26205d03066a9499770290a5bcce017e4bef173f
refs/heads/master
2022-02-22T23:19:32.688593
2022-02-05T09:44:01
2022-02-05T09:44:01
201,766,823
0
0
null
null
null
null
UTF-8
C++
false
false
10,525
cc
icode.cc
Instruction_Descriptor::Instruction_Descriptor (Tgt_Op op, string nam, string mnn, string ics, Icode_Format icf, Assembly_Format af){ inst_op = op; mnemonic = mnn; ic_symbol = ics; /* symbol for printing in intermediate code */ name = nam; ic_format = icf; /* format for printing in intemediate code */ assem_format = af; } Instruction_Descriptor::Instruction_Descriptor (){} Tgt_Op Instruction_Descriptor::get_op(){ return inst_op; } string Instruction_Descriptor::get_name(){ return name; } string Instruction_Descriptor::get_mnemonic(){ return mnemonic; } string Instruction_Descriptor::get_ic_symbol(){ return ic_symbol; } Icode_Format Instruction_Descriptor::get_ic_format(){ return ic_format; } Assembly_Format Instruction_Descriptor::get_assembly_format(){ return assem_format; } void Instruction_Descriptor::print_instruction_descriptor(ostream & file_buffer){ } Register_Descriptor* Ics_Opd::get_reg(){} Mem_Addr_Opd::Mem_Addr_Opd(Symbol_Table_Entry & se){ symbol_entry = &se; } Mem_Addr_Opd & Mem_Addr_Opd::operator = (const Mem_Addr_Opd & rhs){ symbol_entry = rhs.symbol_entry; return *this; } void Mem_Addr_Opd::print_ics_opd(ostream & file_buffer){ file_buffer<<symbol_entry->get_variable_name(); } void Mem_Addr_Opd::print_asm_opd(ostream & file_buffer){ Table_Scope symbol_scope = symbol_entry->get_symbol_scope(); if (symbol_scope == local) { int offset = symbol_entry->get_start_offset(); file_buffer << offset << "($fp)"; } else file_buffer << symbol_entry->get_variable_name(); } Register_Addr_Opd::Register_Addr_Opd(Register_Descriptor * rd){ register_description = rd; } Register_Descriptor * Register_Addr_Opd::get_reg(){ return register_description; } Register_Addr_Opd& Register_Addr_Opd::operator = (const Register_Addr_Opd& rhs){ register_description = rhs.register_description; return *this; } void Register_Addr_Opd::print_ics_opd(ostream & file_buffer){ file_buffer << register_description->get_name(); } void Register_Addr_Opd::print_asm_opd(ostream & file_buffer){ file_buffer << "$" << register_description->get_name(); } template<> Const_Opd<int>::Const_Opd (int n){ num = n; } template<> Const_Opd<double>::Const_Opd (double n){ num = n; } template<> Const_Opd<int> & Const_Opd<int>::operator = (const Const_Opd<int> &rhs) { num = rhs.num; return *this; } template<> Const_Opd<float> & Const_Opd<float>::operator = (const Const_Opd<float> &rhs) { num = rhs.num; return *this; } template<> void Const_Opd<int>::print_ics_opd(ostream & file_buffer){ file_buffer << num; } template<> void Const_Opd<double>::print_ics_opd(ostream & file_buffer){ file_buffer << num; } template<> void Const_Opd<int>::print_asm_opd(ostream & file_buffer){ file_buffer << num; } template<> void Const_Opd<double>::print_asm_opd(ostream & file_buffer){ file_buffer << num; } Instruction_Descriptor & Icode_Stmt::get_op(){ return op_desc; } Ics_Opd * Icode_Stmt::get_opd1(){} Ics_Opd * Icode_Stmt::get_opd2(){} Ics_Opd * Icode_Stmt::get_result(){} void Icode_Stmt::set_opd1(Ics_Opd * io){} void Icode_Stmt::set_opd2(Ics_Opd * io){} void Icode_Stmt::set_result(Ics_Opd * io){} Print_IC_Stmt::Print_IC_Stmt(){ op_desc = *(machine_desc_object.spim_instruction_table[print]); } Print_IC_Stmt::~Print_IC_Stmt(){} void Print_IC_Stmt::print_icode(ostream & file_buffer){ file_buffer<<"\t"<<op_desc.get_name()<<endl; } void Print_IC_Stmt::print_assembly(ostream & file_buffer){ file_buffer<<"\t"<<op_desc.get_mnemonic()<<endl; } Move_IC_Stmt::Move_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o, Ics_Opd * r){ opd1 = o; result = r; op_desc = *(machine_desc_object.spim_instruction_table[inst_op]); } Instruction_Descriptor & Move_IC_Stmt::get_inst_op_of_ics(){ return op_desc; } Ics_Opd * Move_IC_Stmt::get_opd1(){ return opd1; } void Move_IC_Stmt::set_opd1(Ics_Opd * io){ opd1 = io; } Ics_Opd * Move_IC_Stmt::get_result(){ return result; } void Move_IC_Stmt::set_result(Ics_Opd * io){ result = io; } Move_IC_Stmt& Move_IC_Stmt::operator = (const Move_IC_Stmt & rhs) { op_desc = rhs.op_desc; opd1 = rhs.opd1; result = rhs.result; return *this; } void Move_IC_Stmt::print_icode(ostream & file_buffer){ string opname = op_desc.get_name(); Icode_Format icf = op_desc.get_ic_format(); if (icf == i_r_op_o1) { file_buffer << "\t" << opname << ": \t"; result->print_ics_opd(file_buffer); file_buffer << " <- "; opd1->print_ics_opd(file_buffer); file_buffer << "\n"; } else { printf("CS316 error\n"); exit(0); } } void Move_IC_Stmt::print_assembly(ostream & file_buffer){ string opmne = op_desc.get_mnemonic(); Assembly_Format asf = op_desc.get_assembly_format(); if (asf == a_op_r_o1) { file_buffer << "\t" << opmne << " "; result->print_asm_opd(file_buffer); file_buffer << ", "; opd1->print_asm_opd(file_buffer); file_buffer << "\n"; } else if (asf == a_op_o1_r) { file_buffer << "\t" << opmne << " "; opd1->print_asm_opd(file_buffer); file_buffer << ", "; result->print_asm_opd(file_buffer); file_buffer << "\n"; } else { printf("CS316 error\n"); exit(0); } } Compute_IC_Stmt::Compute_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o1, Ics_Opd * o2, Ics_Opd * r){ opd1 = o1; opd2 = o2; result = r; op_desc = *(machine_desc_object.spim_instruction_table[inst_op]); } Instruction_Descriptor & Compute_IC_Stmt::get_inst_op_of_ics(){ return op_desc; } Ics_Opd * Compute_IC_Stmt::get_opd1(){ return opd1; } void Compute_IC_Stmt::set_opd1(Ics_Opd * io){ opd1 = io; } Ics_Opd * Compute_IC_Stmt::get_opd2(){ return opd2; } void Compute_IC_Stmt::set_opd2(Ics_Opd * io){ opd2 = io; } Ics_Opd * Compute_IC_Stmt::get_result(){ return result; } void Compute_IC_Stmt::set_result(Ics_Opd * io){ result = io; } void Compute_IC_Stmt::print_icode(ostream & file_buffer){ string opname = op_desc.get_name(); Icode_Format icf = op_desc.get_ic_format(); if (icf == i_r_o1_op_o2) { file_buffer << "\t" << opname << ": \t"; result->print_ics_opd(file_buffer); file_buffer << " <- "; opd1->print_ics_opd(file_buffer); file_buffer << " , "; opd2->print_ics_opd(file_buffer); file_buffer << "\n"; } else if (icf == i_r_op_o1) { file_buffer << "\t" << opname << ": \t"; result->print_ics_opd(file_buffer); file_buffer << " <- "; opd1->print_ics_opd(file_buffer); file_buffer << "\n"; } else { printf("CS316 error\n"); exit(0); } } void Compute_IC_Stmt::print_assembly(ostream & file_buffer){ string opmne = op_desc.get_mnemonic(); Assembly_Format asf = op_desc.get_assembly_format(); if (asf == a_op_r_o1_o2) { file_buffer << "\t" << opmne << " "; result->print_asm_opd(file_buffer); file_buffer << ", "; opd1->print_asm_opd(file_buffer); file_buffer << ", "; opd2->print_asm_opd(file_buffer); file_buffer << "\n"; } else if (asf == a_op_o1_o2_r) { file_buffer << "\t" << opmne << " "; opd1->print_asm_opd(file_buffer); file_buffer << ", "; opd2->print_asm_opd(file_buffer); file_buffer << ", "; result->print_asm_opd(file_buffer); file_buffer << "\n"; } else if (asf == a_op_r_o1) { file_buffer << "\t" << opmne << " "; result->print_asm_opd(file_buffer); file_buffer << ", "; opd1->print_asm_opd(file_buffer); file_buffer << "\n"; } else if (asf == a_op_o1_r) { file_buffer << "\t" << opmne << " "; opd1->print_asm_opd(file_buffer); file_buffer << ", "; result->print_asm_opd(file_buffer); file_buffer << "\n"; } else { printf("CS316 error\n"); exit(0); } } Control_Flow_IC_Stmt::Control_Flow_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o1, string l){ opd1 = o1; label = l; op_desc = *(machine_desc_object.spim_instruction_table[inst_op]); } Instruction_Descriptor & Control_Flow_IC_Stmt::get_inst_op_of_ics(){ return op_desc; } Ics_Opd * Control_Flow_IC_Stmt::get_opd1(){ return opd1; } void Control_Flow_IC_Stmt::set_opd1(Ics_Opd * io){ opd1 = io; } string Control_Flow_IC_Stmt::get_label(){ return label; } void Control_Flow_IC_Stmt::set_label(string l){ label = l; } Control_Flow_IC_Stmt& Control_Flow_IC_Stmt::operator=(const Control_Flow_IC_Stmt& rhs) { opd1 = rhs.opd1; label = rhs.label; op_desc = rhs.op_desc; return *this; } void Control_Flow_IC_Stmt::print_icode(ostream & file_buffer){ string op = op_desc.get_name(); Icode_Format icf = op_desc.get_ic_format(); if (icf == i_op_o1_o2_st) { file_buffer << "\t" << op << ": \t"; opd1->print_ics_opd(file_buffer); file_buffer << " , zero"; file_buffer << " : goto " << label << "\n"; } else if (icf == i_op_st) file_buffer << "\tgoto " << label << "\n"; else { printf("CS316 error\n"); exit(0); } } void Control_Flow_IC_Stmt::print_assembly(ostream & file_buffer){ string op = op_desc.get_mnemonic(); Assembly_Format af = op_desc.get_assembly_format(); if(af == a_op_o1_o2_st) { file_buffer << "\t" << op << " "; opd1->print_asm_opd(file_buffer); file_buffer << ", "; file_buffer << "$zero, "; file_buffer << label << "\n"; } else if (af == a_op_st) file_buffer << "\tj " << label << "\n"; } Label_IC_Stmt::Label_IC_Stmt(Tgt_Op inst_op, string l){ label = l; this->op_desc = *(machine_desc_object.spim_instruction_table[inst_op]); } Instruction_Descriptor & Label_IC_Stmt::get_inst_op_of_ics(){ return op_desc; } string Label_IC_Stmt::get_label(){ return label; } void Label_IC_Stmt::set_label(string l){ label = l; } void Label_IC_Stmt::print_icode(ostream & file_buffer){ string opname = op_desc.get_name(); Icode_Format icf = op_desc.get_ic_format(); if (icf == i_op_st) file_buffer << "\n" << label << ": \t\n"; else printf("CS316 error\n"); } void Label_IC_Stmt::print_assembly(ostream & file_buffer){ string opmne = op_desc.get_mnemonic(); Assembly_Format asf = op_desc.get_assembly_format(); if (asf == a_op_st) file_buffer << "\n" << label << ": \t\n"; else printf("CS316 error\n"); } Code_For_Ast::Code_For_Ast(){} Code_For_Ast::Code_For_Ast(list<Icode_Stmt *> & ic_l, Register_Descriptor * reg){ ics_list = ic_l; result_register = reg; } void Code_For_Ast::append_ics(Icode_Stmt & ics){ ics_list.push_back(&ics); } list<Icode_Stmt *> & Code_For_Ast::get_icode_list() { return ics_list; } Register_Descriptor * Code_For_Ast::get_reg() { return result_register; } void Code_For_Ast::set_reg(Register_Descriptor * reg){ result_register = reg; } Code_For_Ast& Code_For_Ast::operator=(const Code_For_Ast& rhs) { ics_list = rhs.ics_list; result_register = rhs.result_register; return *this; }
f8a5aebf8a68cadcea6204ceef540b4e5d142c9f
e24b9f5970e7b128df0212276e1679f3d4a0c046
/src/led.cpp
6f036b7254168cda0745bf0ac8ed83cacdb3ddac
[]
no_license
Ficik/esp8266-led-strip
5e6647315e214f21714692c89819405e8706f7c7
bd0df2dffa17632b37360b590aed42c1ce213b30
refs/heads/master
2021-04-06T01:00:03.316411
2018-03-11T14:47:58
2018-03-11T14:47:58
124,766,622
0
0
null
null
null
null
UTF-8
C++
false
false
2,724
cpp
led.cpp
#include "led.h" #define COLOR_TAIL 16 #define COLOR_STEP 16 // COLOR_TAIL * COLOR_STEP >= 255 CHSV currentColor = CHSV(0, 0, 255); CHSV lastColor = currentColor; CHSV previousColor = CHSV(0, 0, 0); char state = 1; int changePosition = 0; int isChromaOn = 1; int hue = 0; CRGBArray<NUM_LEDS> leds; // ws2811 void approxColor(int i, CHSV lastColor, CHSV currentColor, int step) { fract8 frac = min(255, COLOR_STEP * (step + 1)); CHSV color = CHSV(0, 0, 0); color.hue = lerp8by8(lastColor.hue, currentColor.hue, frac); color.sat = lerp8by8(lastColor.sat, currentColor.sat, frac); color.val = lerp8by8(lastColor.val, currentColor.val, frac); // Serial.print("Color "); // Serial.print(color.hue); // Serial.print(", "); // Serial.print(color.sat); // Serial.print(", "); // Serial.print(color.val); // Serial.print(" step "); // Serial.print(step); // Serial.print(" frac "); // Serial.print(frac); // Serial.print(" to "); // Serial.println(i); leds[i] = color; } void ledSetup() { FastLED.addLeds<WS2811, LED_DATA_PIN, BRG>(leds, NUM_LEDS) .setCorrection(TypicalSMD5050); fill_solid(leds, NUM_LEDS, CRGB::Black); FastLED.show(); }; void changeColor() { if (changePosition == (NUM_LEDS/2) + 1 + COLOR_TAIL) { previousColor = currentColor; return; } int middle = NUM_LEDS / 2; for (int i=0;i < min(COLOR_TAIL, changePosition+1); i++) { approxColor(min(NUM_LEDS - 1, middle + changePosition - i ), previousColor, currentColor, i); approxColor(max(0, middle - changePosition + i), previousColor, currentColor, i); } changePosition += 1; FastLED.setTemperature(Candle); FastLED.show(); FastLED.delay(15); } void ledLoop() { if (isChromaOn) { leds.fill_rainbow(hue, 255 / NUM_LEDS); hue += 1; FastLED.delay(5); FastLED.show(); } else { changeColor(); } } void setLedState(int val) { state = val; if (state == 0) { currentColor = CHSV(currentColor.hue, currentColor.sat, 0); } if (state == 1) { currentColor = lastColor; } changePosition = 0; isChromaOn = 0; } void setColor(int h, int s, int v) { currentColor = CHSV((uint8_t)(h * 255/360.0), (uint8_t)(s * 255.0/100), (uint8_t)(v * 255.0/100)); lastColor = currentColor; changePosition = 0; isChromaOn = 0; } void setLedBrightness(int val) { currentColor = CHSV(currentColor.hue, currentColor.sat, (uint8_t)(val * 255.0/100)); if (currentColor.value > 0) { lastColor = currentColor; } changePosition = 0; isChromaOn = 0; } void setChroma() { isChromaOn = 1; }
84c2d8e913db7b0456a96a9976798be850117206
fea74fe7df1e5d5cc5ef170b5f8fb53339e11d6d
/automation/main.cpp
94561284b679222a8bca6e89b3bdcd434ac551f8
[]
no_license
osanir/somecodes
0db2e7e8fb6f4abe23388377c478edc5426bc2a2
9f2b0f546531bb6735f498cdebcbf2ddd9fe060d
refs/heads/master
2020-08-02T17:56:58.520459
2019-09-28T07:16:06
2019-09-28T07:16:06
211,455,696
1
0
null
null
null
null
UTF-8
C++
false
false
161
cpp
main.cpp
#include <iostream> #include "club.h" using namespace std; int main(){ Club myClub; myClub.open_db(); myClub.show_menu(); myClub.close_db(); }
aa4042c8adf6686e1139c540842ed43da11bfcea
578350453e9325b26ee64307c81d56ed08ee711d
/src/linux/ServoInterface/ServoInterface.cpp
5d00881573bb2d01ab78f59b7f142850f5c07c50
[]
no_license
x-sven/himbeere
69ea0a9f1411824ce37b3e5cfebd3bb41bcb7eb2
f5b345891bedcf4635443d6943ff1dc8b278db88
refs/heads/master
2020-05-17T15:47:42.610146
2015-08-23T10:43:16
2015-08-23T10:43:16
8,897,883
1
1
null
null
null
null
UTF-8
C++
false
false
3,483
cpp
ServoInterface.cpp
#include "ServoInterface.h" #include "../../src/crc16/crc16.h" ServoInterface::ServoInterface(Stream *stream): num_channel_max(7), m_stream(NULL), reciever_state(0), reciever_couter(0), rx_channel(NULL) { rx_channel = (uint16_t*)malloc(num_channel_max*sizeof(uint16_t)); memset(rx_buffer, 0, 14); memset(rx_channel, 0, 7); if(NULL != stream) { begin(stream); } } void ServoInterface::begin(Stream *stream) { if(NULL != stream) { m_stream = stream; } } bool ServoInterface::update(void) { uint8_t bytedata = 0; int16_t numc = 0; bool ret_val=false; numc = m_stream->available(); if(0 < numc ) { // printf("Number bytes: %d \n",numc); fflush(stdout); for (int16_t i=0; i < numc; i++) { bytedata = m_stream->read(); // printf("%d (%d)",bytedata, reciever_state); switch(reciever_state) { case 0: if(bytedata==(uint8_t)0xff) reciever_state=1; else { reciever_state=0; reciever_couter=0; } break; case 1: if(bytedata==0xfe) reciever_state=2; else { reciever_state=0; reciever_couter=0; } break; case 2: if(reciever_couter%2==0) { rx_channel[reciever_couter/2]=bytedata<<8; } else { rx_channel[(unsigned int)(reciever_couter/2+0.5)] |= bytedata; } rx_buffer[reciever_couter]=bytedata; reciever_couter++; // if(bytedata==0xfe ) // { // reciever_couter=0; // reciever_state=0; // } // if(bytedata==0xff) // { // reciever_couter=0; // reciever_state=1; // } if(reciever_couter>13) // 6x2 + 2 bytes in rx_channel (+1 weil 1x reciever_couter++) { // printf("\n"); // printf("%d: %d %d %d %d %d %d %d\n",reciever_couter, rx_channel[0],rx_channel[1],rx_channel[2],rx_channel[3],rx_channel[4],rx_channel[5], rx_channel[6]); reciever_couter=0; reciever_state=0; // TODO (sven#1#): CRC check here? // const unsigned char* p_data = (unsigned char*)&rx_channel[0]; if(rx_channel[6] != crcFast(rx_buffer,12)) { printf("CRC error! (%d != %d)\n", rx_channel[6], crcFast(rx_buffer,12)); } ret_val=true; } break; default: ; }//switch case }//for(numc) }//if() return ret_val; } uint16_t ServoInterface::get_channel(uint8_t channel) { if(0 <= channel) // && channel < num_ch_max { return(rx_channel[channel]); } else { printf("Error in gert_channel()!\n"); return(0); } } ServoInterface::~ServoInterface() { if(NULL != rx_channel) { free(rx_channel); } }
92ac57bf11333a15bf8ae2fba53547a7695481b4
31a97191e9583f367d7b992aefd54a84417b6e89
/ctdl/daycontongbangk.cpp
e09c07663654f2218704616c60d5712f8afc54df
[]
no_license
Keybinhoainam/codecpp
97200e0f585d46724ac4a02b2647d16e7c305715
7f5c00cc4299b0122878c8550caa7a49d01ddcf9
refs/heads/main
2023-07-13T17:10:44.983890
2021-08-24T14:22:57
2021-08-24T14:22:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
daycontongbangk.cpp
#include<bits/stdc++.h> using namespace std; int check; void kt(int n,int k,int a[],long long tong,int b[],int t,map<int,bool> c,int bd) { if(tong==k) { check=1; cout<<"["; for(int i=0;i<t;i++) { if(i<t-1)cout<<b[i]<<" "; else cout<<b[i]; } cout<<"] "; } for(int i=bd;i<n;i++) { if(tong+a[i]<=k) { b[t]=a[i]; kt(n,k,a,tong+a[i],b,t+1,c,i+1); c[a[i]]=0; } else { if(tong+a[i]>k)break; } } } int main() { int T; cin>>T; while(T--) { int n,k; cin>>n>>k; int a[n],b[n]; for(int i=0;i<n;i++)cin>>a[i]; sort(a,a+n); check=0; map<int,bool> c; kt(n,k,a,0,b,0,c,0); if(check==0)cout<<-1; cout<<endl; } }
36779303aaa1a2ade83a5883ace5fe360adf6a51
9fb456a0f1cc77d148a9c5334c084c2a65630592
/cornellbox/Eyeo2012/Catalog/src/Star.cpp
249bb94cce12cef1dd11dc2c5d88c83a293f2604
[ "Apache-2.0" ]
permissive
eighteight/CinderEight
4deba73910eb3e02d2f881da303205159a77f052
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
refs/heads/master
2021-06-19T14:46:18.448625
2021-01-16T20:55:22
2021-01-16T20:55:22
16,152,693
6
1
null
null
null
null
UTF-8
C++
false
false
2,478
cpp
Star.cpp
// // Star.cpp // StarMap // // Created by Robert Hodgin on 11/26/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #include "Star.h" #include "cinder/CinderMath.h" #include "cinder/Rand.h" #include "cinder/gl/gl.h" #include "cinder/Text.h" #include "cinder/app/AppBasic.h" using namespace ci; Star::Star( Vec3f pos, float appMag, float absMag, float color, std::string name, std::string spectrum, const Font &fontS, const Font &fontM ) : mPos( pos ), mApparentMag( appMag ), mAbsoluteMag( absMag ), mColor( color ), mName( name ) { mInitPos = mPos; mDistToMouse = 1000.0f; mIsSelected = false; mRadius = ( 10.0f - mAbsoluteMag ) * 0.025f; mRadiusMulti = 1.0f; // not implemented yet if( mName.length() > 1 && appMag < 6.0f ){ TextLayout layout; layout.clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); layout.setFont( fontM ); layout.setColor( Color( 1.0f, 1.0f, 1.0f ) ); layout.addLine( name ); layout.setFont( fontS ); layout.setLeadingOffset( 3 ); layout.addLine( spectrum ); mNameTex = gl::Texture( layout.render( true, false ) ); mSphere.setCenter( mPos ); mSphere.setRadius( mRadius ); } } void Star::update( const Camera &cam, float scale ) { mPos = mInitPos * scale; mSphere.setCenter( mPos ); mScreenPos = cam.worldToScreen( mPos, app::getWindowWidth(), app::getWindowHeight() ); mDistToCam = -cam.worldToEyeDepth( mPos ); mDistToCamPer = math<float>::min( mDistToCam * 0.01f, 1.0f ); mScreenRadius = cam.getScreenRadius( mSphere, app::getWindowWidth(), app::getWindowHeight() ); } void Star::drawName( const Vec2f &mousePos, float power, float alpha ) { if( mDistToCam > 0.0f && mNameTex ){ float per = constrain( 1.0f - mDistToCam * 0.0000375f, 0.0f, 1.0f ); per *= per * per; Vec2f dirToMouse = mScreenPos - mousePos; mDistToMouse = dirToMouse.length(); if( mDistToMouse < 40.0f ) per += 1.0f - mDistToMouse/40.0f; if( mIsSelected ) per = 1.0f; if( per > 0.05f ){ gl::color( ColorA( power, power, power, per * alpha ) ); mNameTex.enableAndBind(); gl::draw( mNameTex, mScreenPos + Vec2f( mScreenRadius + 35.0f, -28.0f ) ); mNameTex.disable(); gl::color( ColorA( power, power, power, per * 0.4f * alpha ) ); Vec2f p1 = mScreenPos; Vec2f p2 = p1 + Vec2f( mScreenRadius + 35.0f, -13.0f ); Vec2f p3 = mScreenPos + Vec2f( mScreenRadius + 35.0f + mNameTex.getWidth(), -13.0f ); gl::drawLine( p1, p2 ); gl::drawLine( p2, p3 ); } } }
5131f0485b7301f2aeb73a13e14146e14bf4dc13
67ed24f7e68014e3dbe8970ca759301f670dc885
/win10.19042/SysWOW64/xwreg.dll.cpp
9d09c463ba211e986bae9b51ff5182ee721ca87f
[]
no_license
nil-ref/dll-exports
d010bd77a00048e52875d2a739ea6a0576c82839
42ccc11589b2eb91b1aa82261455df8ee88fa40c
refs/heads/main
2023-04-20T21:28:05.295797
2021-05-07T14:06:23
2021-05-07T14:06:23
401,055,938
1
0
null
2021-08-29T14:00:50
2021-08-29T14:00:49
null
UTF-8
C++
false
false
206
cpp
xwreg.dll.cpp
#pragma comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\SysWOW64\\xwreg.DllCanUnloadNow\"") #pragma comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\SysWOW64\\xwreg.DllGetClassObject\"")
d6198cf68980f6d9366507ada44011adfca3664e
9422bca38b8aae235f344334dd2fc031d124f406
/verify/aoj/DSL_1_A.test.cpp
5530969755cee1b875d35ca89ea1d8d7d2bf4dd7
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
debabrota1604/CPtips_cplib
ce2c24c2ae7d9c416c9d8b41ab7e4d3370ff998c
3c8eda6155237cc987bba0e8bf7509f366d63ba3
refs/heads/master
2023-03-19T17:13:22.746275
2021-02-21T13:58:52
2021-02-21T13:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
DSL_1_A.test.cpp
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_1_A" #include "template.cpp" #include "data-structure/union-find.cpp" #include "util/fast-io.cpp" int main() { int n = IN, q = IN; UnionFind uf(n); rep(q) { int c = IN, x = IN, y = IN; if (c == 0) uf.merge(x, y); else OUT((int)uf.same(x, y)); } }
d78d768b857b100cbdb4c93b705ae73fc2e16aa6
7147c899790036e20743abc82abd5e02a0617fc0
/client/GraphTool.cpp
506ddaad01b5dc8ea69275a1422cb9810faa3aca
[]
no_license
ckcks12/SafeDesk
a33b92d1540206aa4c9dc9fcf6d6e60ffa00d525
7d5ed72f2eef089b3ae54ccece90e33ab06a68db
refs/heads/master
2021-01-21T04:11:30.826591
2016-11-15T15:44:36
2016-11-15T15:44:36
66,625,956
3
1
null
null
null
null
UTF-8
C++
false
false
1,509
cpp
GraphTool.cpp
// // Created by lec on 2016. 11. 2.. // #include "GraphTool.h" //template<typename T> //Mat GraphTool::drawGraph(vector<T> vec, int width, int height, Scalar color) { // Mat mat(Size(width, height), CV_8UC3); // T max = 0; // for( size_t i=0; i<vec.size(); i++ ) // { // if( vec[i] >= max ) // max = vec[i]; // } // // int step = (int)floor(width / vec.size()); // int x1 = 0; // int y1 = height - (int)((vec[0] / max) * height); // line(mat, Point(x1, y1), Point(x1, y1), color, 2); // // // for( size_t i=0; i<vec.size(); i++ ) // { // int y2 = height - (int)((vec[i] / max) * height); // int x2 = x1 + step; // line(mat, Point(x1, y1), Point(x2, y2), color, 2); // x1 = x2; // y1 = y2; // } // // return mat; //} Mat GraphTool::drawGraph(vector<double> vec, int width, int height, Scalar color) { Mat mat(Size(width, height), CV_8UC3, Scalar(0, 0, 0)); double max = 0; for( size_t i=0; i<vec.size(); i++ ) { if( vec[i] >= max ) max = vec[i]; } int step = (int)floor(width / vec.size()); int x1 = 0; int y1 = height - (int)((vec[0] / max) * height); line(mat, Point(x1, y1), Point(x1, y1), color, 2); for( size_t i=0; i<vec.size(); i++ ) { int y2 = height - (int)((vec[i] / max) * height); int x2 = x1 + step; line(mat, Point(x1, y1), Point(x2, y2), color, 2); x1 = x2; y1 = y2; } return mat; }
ff743cf660a85349df18e269a524a1f28c162305
f529d03f30c39c8a82cff5320863094bef74732b
/amazon246/Clock_angle.cpp
d6f4c5f7bd7fbe72d68104a33a599e6035b54a4b
[]
no_license
ashutosh28/DS_ALGO
c99971414bdd39963f123c8b7a0ee9bff21d98c4
370a211dcc5d3ff1921adb571b9c622613a10608
refs/heads/master
2021-01-19T00:38:42.982581
2017-04-04T14:48:26
2017-04-04T14:48:26
87,192,728
0
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
Clock_angle.cpp
//============================================================================ // Name : Clock_angle.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cmath> #include <vector> #include <map> #include <algorithm> using namespace std; class test { }; struct test1 { }; class test_drived: public test { }; double angleBetHrAndMinHand(int hr, int min) { double angle; double hrangle,minangle; if(hr == 12) { hr = 0; } if(min == 60) { min = 0; hr += 1; } hrangle = hr*30 + 0.5*(min); minangle = min*6; angle = abs(hrangle - minangle); return angle; } int main() { int hr,min; cout<<"Enter hr and min: "; cin>>hr>>min; cout<<"Angle is: "<<angleBetHrAndMinHand(hr,min); cout<<endl<<sizeof(test)<<endl<<sizeof(test1); test t; test1 t1; cout<<endl<<sizeof(t)<<endl<<sizeof(t1); test *t2 = new test(); test1 *t3 = new test1(); int *i; cout<<endl<<sizeof(t2)<<endl<<sizeof(t3)<<endl<<sizeof(int)<<endl<<sizeof(test_drived); return 0; }
5d320b4e259575c9c0ec281a4d0bc972f93f43d5
c32ee8ade268240a8064e9b8efdbebfbaa46ddfa
/Libraries/m2sdk/ue/game/vehicle/S_WheelInitData.h
5b313adb7bffe62f59aa2af206e68b99b14230e4
[]
no_license
hopk1nz/maf2mp
6f65bd4f8114fdeb42f9407a4d158ad97f8d1789
814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8
refs/heads/master
2021-03-12T23:56:24.336057
2015-08-22T13:53:10
2015-08-22T13:53:10
41,209,355
19
21
null
2015-08-31T05:28:13
2015-08-22T13:56:04
C++
UTF-8
C++
false
false
597
h
S_WheelInitData.h
// auto-generated file (rttidump-exporter by h0pk1nz) #pragma once #include <ue/game/crashobject/S_AddDeformPartsInitData.h> namespace ue { namespace game { namespace vehicle { /** ue::game::vehicle::S_WheelInitData (VTable=0x01E65200) */ struct S_WheelInitData : public ue::game::crashobject::S_AddDeformPartsInitData { public: virtual void vfn_0001_AD61BC7B() = 0; virtual void vfn_0002_AD61BC7B() = 0; virtual void vfn_0003_AD61BC7B() = 0; virtual void vfn_0004_AD61BC7B() = 0; virtual void vfn_0005_AD61BC7B() = 0; }; } // namespace vehicle } // namespace game } // namespace ue
13341b7c13d6ee6948a3e1282d01bc314971ebf4
72c82550fc7c547894df97f71933418f176dfa7d
/main.cpp
5be099a5e458f47ac52c901d70a4c0c7ea8d285b
[]
no_license
PuKoren/opengl-b-splines
054690ff01ab9372ef8b00ea7526d8f77c488226
b98c4ccb01c0ba1d247a220ce9d1588a2ae86cb7
refs/heads/master
2016-09-06T00:48:45.485542
2013-05-21T08:00:03
2013-05-21T08:00:03
9,568,785
2
0
null
null
null
null
UTF-8
C++
false
false
2,903
cpp
main.cpp
#include <stdio.h> #include <string.h> #include <GL/freeglut.h> #include "Application.h" #include "config.h" void displayText(float x, float y, int r, int g, int b, const char *string); void keyboard(unsigned char key, int x, int y); void keyboardSpecialKeys(int key, int x, int y); void mouse(int button, int state, int x, int y); void mouseMotion(int x, int y); void mousePassiveMotion(int x, int y); void display(); void resize(int width, int height); Application a; int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(window_width,window_height); glutCreateWindow("BSplines - OpenGL"); glMatrixMode(GL_PROJECTION); gluOrtho2D(0, window_width, 0, window_height); glutKeyboardFunc(&keyboard); glutSpecialFunc(&keyboardSpecialKeys); glutMouseFunc(&mouse); glutMotionFunc(&mouseMotion); glutPassiveMotionFunc(&mousePassiveMotion); glutDisplayFunc(&display); glutReshapeFunc(&resize); glutMainLoop(); glutExit(); return EXIT_SUCCESS; } void keyboard(unsigned char key, int x, int y){ a.keyboard(key); } void keyboardSpecialKeys(int key, int x, int y){ a.keyboardSpecial(key); } void mouse(int button, int state, int x, int y){ a.mouse(button, state, x, y); } void mouseMotion(int x, int y){ a.mouseMotion(x, y); } void mousePassiveMotion(int x, int y){ a.mouseMotion(x, y); } void displayText(float x, float y, int r, int g, int b, const char *string) { int j = strlen( string ); glColor3ub(r, g, b); glRasterPos2f(x, window_height - y - 13); for( int i = 0; i < j; i++ ) { glutBitmapCharacter( GLUT_BITMAP_HELVETICA_12, string[i] ); } } void display(){ glClearColor(0.05f, 0.05f, 0.05f, 1.f); glClear(GL_COLOR_BUFFER_BIT); a.draw(); displayText(0, 0, 78, 205, 196, "Welcome to the B-Spline drawer !"); displayText(0, 12, 200, 200, 200, "Left mouse button: place control points and move them"); displayText(0, 24, 200, 200, 200, "Right mouse button: delete a control point"); displayText(0, 36, 200, 200, 200, "Middle mouse button: move all control points"); displayText(0, 48, 200, 200, 200, "+/-: to change Spline Degree"); displayText(0, 60, 200, 200, 200, "Arrows: to move every control points"); displayText(0, 72, 200, 200, 200, "R: rotate or stop rotate around your current mouse position"); displayText(0, 84, 200, 200, 200, "Space: show/hide lines between control points"); displayText(0, 96, 200, 200, 200, "Suppr: reset the viewport"); char notice[50]; sprintf(notice, "Current degree: %d", a.getDegree()); displayText(0, window_height/2, 100, 100, 100, notice); glutSwapBuffers(); } void resize(int width, int height) { window_width = width; window_height = height; glViewport(0, 0, window_width, window_height); }
1de244ce2378de992c72d71310eaea7e5c7f31cd
3bb233c305fa678255d740bfa54cd885e63db2ba
/5º Semestre/Laboratório de Projeto de Algoritmos/Tarefas/AS03_Altura.cpp
7ee95a24b8b571286d69af070423e010f805bf20
[]
no_license
rithienatan/PUCMG-CC
124cb7d72508522cfebb5727bc4394eac67c1cd1
dece46c8d5e37dca6536bd964ec189a258ec333d
refs/heads/master
2022-06-13T09:43:16.554384
2022-06-07T19:31:45
2022-06-07T19:31:45
207,550,174
3
1
null
null
null
null
UTF-8
C++
false
false
1,576
cpp
AS03_Altura.cpp
/** * @author Rithie Natan Carvalhaes Prado * Matricula: 541488 * @version 0.1.0 * * Função de complexidade: * quicksort: n log(n) * main: n * (n + quicksort + n) = n²log(n) + 2n² * * O(n²log(n)) */ /*----- includes -----*/ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> using namespace std; void quicksort(int values[], int began, int end) { int i, j, pivo, aux; i = began; j = end-1; pivo = values[(began + end) / 2]; while(i <= j) { while(values[i] < pivo && i < end) { i++; } while(values[j] > pivo && j > began) { j--; } if(i <= j) { aux = values[i]; values[i] = values[j]; values[j] = aux; i++; j--; } } if(j > began) quicksort(values, began, j+1); if(i < end) quicksort(values, i, end); }//end quicksort int main() { int quantEntrada; int quantidadePessoas = 0; int alturas; cin >> quantEntrada; for(int i = 0; i < quantEntrada; i++) { //alocar quantidade de elementos no vetor cin >> quantidadePessoas; int *cidade = (int*) malloc(quantidadePessoas * sizeof(int)); //inserir elementos for(int j = 0; j < quantidadePessoas ; j++) {cin >> cidade[j];} quicksort(cidade, 0, quantidadePessoas); //mostrar elementos for(int j = 0; j < quantidadePessoas ; j++) {cout << cidade[j]; cout << " ";} cout << endl; free(cidade); }//end for return 0; }//end main()
fdd2520212b78fa1e8002d6907089b30cd49458e
bf361141e8af9ede987ea3faa89017cfc2c5e183
/src/storage/storage.cc
08af99621b40f4384f3e73e3dd108405d1fd77b5
[ "Apache-2.0" ]
permissive
xiangliu886/mxnet
4ad3ace7c887c8e8ce8771a49df884e4f106ecfd
f778bfe930c7f3c7043a7e98535abb9d82bae6ad
refs/heads/master
2021-01-17T23:00:07.742295
2015-09-30T14:26:05
2015-09-30T14:26:05
43,232,809
1
0
null
2015-09-27T03:28:20
2015-09-27T03:28:17
null
UTF-8
C++
false
false
3,248
cc
storage.cc
/*! * Copyright (c) 2015 by Contributors */ #include <mxnet/storage.h> #include <mshadow/tensor.h> #include <dmlc/logging.h> #include <array> #include <mutex> #include <memory> #include "storage_manager.h" #include "naive_storage_manager.h" #include "pooled_storage_manager.h" #include "cpu_device_storage.h" #include "gpu_device_storage.h" #include "pinned_memory_storage.h" #include "../common/cuda_utils.h" #include "../common/utils.h" namespace mxnet { // consider change storage as a pure abstract class struct Storage::Impl { static constexpr size_t kPoolThreshold = 4096 * 1024 * 1024ul; static constexpr size_t kMaxNumberOfDevices = Context::kMaxDevType + 1; static constexpr size_t kMaxNumberOfDeviceIDs = Context::kMaxDevID + 1; template <class DeviceStorage> using CurrentStorageManager = storage::PooledStorageManager<DeviceStorage, kPoolThreshold>; static void ActivateDevice(Context ctx) { switch (ctx.dev_type) { case Context::kCPU: break; case Context::kGPU: case Context::kCPUPinned: #if MXNET_USE_CUDA CUDA_CALL(cudaSetDevice(ctx.dev_id)); #else // MXNET_USE_CUDA LOG(FATAL) << "Please compile with CUDA enabled"; #endif // MXNET_USE_CUDA break; default: LOG(FATAL) << "Unimplemented device"; } } std::array<std::array<std::unique_ptr<storage::StorageManager>, kMaxNumberOfDeviceIDs>, kMaxNumberOfDevices> storage_managers; std::mutex m; }; // struct Storage::Impl Storage::Handle Storage::Alloc(size_t size, Context ctx) { // space already recycled, ignore request Handle hd; hd.ctx = ctx; hd.size = size; { std::lock_guard<std::mutex> lock{impl_->m}; auto&& device = impl_->storage_managers.at(ctx.dev_type); auto&& device_id_it = device.at(ctx.dev_id); // Allocate device if necessary. if (!device_id_it) { switch (ctx.dev_type) { case Context::kCPU: { device_id_it = common::MakeUnique< Storage::Impl::CurrentStorageManager< storage::CPUDeviceStorage>>(); break; } case Context::kCPUPinned: { device_id_it = common::MakeUnique< Storage::Impl::CurrentStorageManager< storage::PinnedMemoryStorage>>(); break; } case Context::kGPU: { device_id_it = common::MakeUnique<Storage::Impl::CurrentStorageManager< storage::GPUDeviceStorage>>(); break; } default: LOG(FATAL) << "Unimplemented device"; } } Impl::ActivateDevice(ctx); hd.dptr = device_id_it->Alloc(size); } return hd; } void Storage::Free(Storage::Handle handle) { std::lock_guard<std::mutex> lock{impl_->m}; Impl::ActivateDevice(handle.ctx); impl_->storage_managers.at(handle.ctx.dev_type) .at(handle.ctx.dev_id) ->Free(handle.dptr, handle.size); } Storage::~Storage() = default; std::shared_ptr<Storage> Storage::_GetSharedRef() { static std::shared_ptr<Storage> inst(new Storage()); return inst; } Storage* Storage::Get() { static Storage *ptr = _GetSharedRef().get(); return ptr; } Storage::Storage() : impl_{new Impl{}} {} } // namespace mxnet
2eab2e69e40507e160611b88224a64a52a9c32f0
1e0ecf70b6ea487de3fa985bb2c2699773aeee3f
/C++/Retired_Code/Lexathon-MIPS.cpp
48728eec198692908d1faa89ef839c7fe5f74a94
[]
no_license
kevincvanhorn/lexathon-mips
8700426e780774afc7e9d22a69fc70717541cb1d
7981a66d1117e767fc1e753c969552e0b1866fa5
refs/heads/master
2020-05-01T03:47:37.069578
2016-12-02T04:46:48
2016-12-02T04:46:48
68,539,851
0
0
null
2016-12-01T22:55:00
2016-09-18T18:35:30
Assembly
UTF-8
C++
false
false
6,921
cpp
Lexathon-MIPS.cpp
//Author(s): Kevin van Horn // Nishant Gurrapadi // Thach Ngo //Prof: Nhut Nguyen //Assignment: Lexathon Project //Class: CS3340.501/ Computer Architecture //Due: 1 December, 2016 #include <iostream> #include <fstream> #include <iomanip> #include <random> #include <string> using namespace std; // Lexathon is a word game where you must find as many word // of four or more letters in the alloted time // Each word must contain the central letter exactly once, // and other tiles can be used once // You start each game with 60 seconds // Finding a new word increases time by 20 seconds // The game ends when: // -Time runs out, or // -You give up // Scores are determined by both the percentage of words found // and how quickly words are found // so find as many words as quickly as possible. void printMenu(); void printInstructions(); void randomizeBoard(char gameTable[]); void printBoard(char gameTable[]); void startGame(char gameTable[]); bool checkMiddle(char gameTable[], char input[], int inputLength); int checkDictionary(char input[], int inputLength); const int ARRAY_SIZE = 9; int main() { printMenu(); system("pause"); return 0; } // Display menu void printMenu() { // Variable holds user input int choice; // Array holds random letters for board char gameTable[ARRAY_SIZE]; // Menu cout << "Welcome to Lexathon!\n\n"; cout << "1) Start the game\n"; cout << "2) Instructions\n"; cout << "3) Exit\n"; // Input choice cin >> choice; while (choice != 3) { if (choice == 1) { startGame(gameTable); } else if (choice == 2) { printInstructions(); } else if (choice == 3) { break; } cout << "1) Start the game\n"; cout << "2) Instructions\n"; cout << "3) Exit\n"; cin >> choice; } } // Print out instructions void printInstructions() { cout << "Lexathon is a word game where you must find as many word\n" << "of four or more letters in the alloted time\n\n"; cout << "Each word must contain the central letter exactly once,\n" << "and other tiles can be used once\n\n"; cout << "You start each game with 60 seconds\n" << "Finding a new word increases time by 20 seconds\n\n"; cout << "The game ends when:\n" << "-Time runs out, or\n" << "-You give up\n\n"; cout << "Scores are determined by both the percentage of words found\n" << "and how quickly words are found.\n" << "so find as many words as quickly as possible.\n\n"; return; } // Generate random letters for table void randomizeBoard(char gameTable[]) { for (int index = 0; index < ARRAY_SIZE; ++index) { gameTable[index] = 65 + rand() % 26; if (index + 1 % 3 == 0) { cout << endl; } } } // Print board void printBoard(char gameTable[]) { int line = 1; for (int i = 0; i < ARRAY_SIZE; ++i) { cout << "| " << gameTable[i] << " | "; if ( line % 3 == 0) { cout << "\n"; } ++line; } } // Starts the game void startGame(char gameTable[]) { char playerAnswer[9]; // array holds player input int score = 0; // variable hold player score randomizeBoard(gameTable); do { // initialize array for (int i = 0; i < sizeof(playerAnswer); ++i) { playerAnswer[i] = '0'; } // print board printBoard(gameTable); cout << "Score: " << score << endl; cout << "1) Instructions" << endl << "2) Shuffle" << endl << "3) Give Up" << endl << "Enter word:" << endl; // get player's answer cin >> playerAnswer; // if 1 entered into menu print instructions if (playerAnswer[0] == '1') { printInstructions(); } // if 2 entered shuffle board else if (playerAnswer[0] == '2') { randomizeBoard(gameTable); } // find answer's length int index = 0; int inputLength = 0; while (playerAnswer[index] != '0') { ++inputLength; ++index; cout << inputLength - 1; } inputLength = inputLength - 1; cout << "Input length is " << inputLength << endl; cout << "Player's answer is: " << playerAnswer[0] << playerAnswer[1] << endl; cout << endl; // Check if middle letter was used bool inputIsValid = checkMiddle(gameTable, playerAnswer, inputLength); // If input valid add to score, else try again if (inputIsValid == true) { score = score + checkDictionary(playerAnswer, inputLength); } else if(inputIsValid == false) { cout << endl << "Invalid Answer. Middle letter not used. Try again." << endl << endl; } } while (playerAnswer[0] != '3'); } // check if middle tile was used bool checkMiddle(char gameTable[], char playerAnswer[], int inputLength) { // Table Positions // 0 1 2 // 3 4 5 // 6 7 8 // check if middle letter is in the player's answer int tablePosition = 4; int index = 0; while(index < inputLength) { if (gameTable[tablePosition] != toupper(playerAnswer[index])) { ++index; } else if (gameTable[tablePosition] == toupper(playerAnswer[index])) { return true; } } return false; } int checkDictionary(char input[], int inputLength) { const string FILE_NAME = "Dictionary.txt"; // create input stream object ifstream inputFile; // string to hold words string dictionaryWord; cout << "Answer you entered is" << endl; for (int i = 0; i < inputLength; i++) { cout << input[i]; } cout << endl; system("pause"); // open file for reading if (!inputFile.fail()) { inputFile.open(FILE_NAME); cout << "Dictionary opened" << endl; cout << "Player Answer Length: " << inputLength << endl << endl; while (inputFile >> dictionaryWord) { int i = 0; cout << dictionaryWord << endl; while (i < inputLength) { if (tolower(input[i]) == dictionaryWord[i]) { cout << dictionaryWord[i]; ++i; } else { break; } cout << endl; } if (i == inputLength) // if (i == inputLength && i == sizeof(dictionaryWord) - 1) { cout << "Word found:" << dictionaryWord << endl << "Here, have some points" << endl << "+500" << endl << endl; return 500; } } cout << "Word not found" << endl << endl; } else { cout << "Error file not detected."; } return 0; }
b257c119881eb9dd8bb8e8ca502060d50dc7bd66
b10479a8b9187f885f1486a9fb6aaba368872b59
/Parser.hpp
c7e51544710edc87477b85cb3539d959e9d2b881
[]
no_license
dronperminov/RPNCalculator
898f059084d481ad9133903a8d834b89a8e6f658
db2f77b0fab6ef8d0e3a02f302967b15baf0f31f
refs/heads/master
2020-08-12T07:09:36.446239
2019-10-13T09:39:19
2019-10-13T09:39:19
214,713,388
0
0
null
null
null
null
UTF-8
C++
false
false
1,874
hpp
Parser.hpp
#pragma once #include <iostream> #include <string> #include <vector> class Parser { std::string expr; // строка выражения bool IsOperator(char c) const; bool IsBracket(char c) const; bool IsLetter(char c) const; bool IsDigit(char c) const; bool IsLetterOrDigit(char c) const; public: Parser(const std::string &expr); std::vector<std::string> Parse(); }; bool Parser::IsOperator(char c) const { return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%'; } bool Parser::IsBracket(char c) const { return c == '(' || c == ')'; } bool Parser::IsLetter(char c) const { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } bool Parser::IsDigit(char c) const { return c >= '0' && c <= '9'; } bool Parser::IsLetterOrDigit(char c) const { return IsLetter(c) || IsDigit(c); } Parser::Parser(const std::string &expr) { this->expr = expr; } std::vector<std::string> Parser::Parse() { std::vector<std::string> lexemes; size_t i = 0; while (i < expr.length()) { if (IsOperator(expr[i]) || IsBracket(expr[i]) || expr[i] == ',') { lexemes.push_back(std::string(1, expr[i])); i++; } else if (IsLetter(expr[i])) { std::string identifier = ""; while (i < expr.length() && IsLetterOrDigit(expr[i])) { identifier += expr[i]; i++; } lexemes.push_back(identifier); } else if (IsDigit(expr[i])) { std::string number = ""; int points = 0; while (i < expr.length() && (IsDigit(expr[i]) || expr[i] == '.')) { if (expr[i] == '.') { points++; if (points > 1) throw std::string("Invalid float number"); } number += expr[i]; i++; } lexemes.push_back(number); } else if (expr[i] == ' ') { i++; } else throw std::string("Unknown character"); } if (lexemes.size() == 0) throw std::string("Expression is empty"); return lexemes; }
de5cad3e1aa1ae988763d936f48caa78710113b8
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_compute_container_flat_set.hpp
5faefb12fef50977ee08643e1479894cba505dba
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
48
hpp
boost_compute_container_flat_set.hpp
#include <boost/compute/container/flat_set.hpp>
a2fbe3ec06acc1a2797003e82ceca896949976f1
390241b7131e0d7652b5fba9884e8bfe5aa08f83
/MainUI/Logical/SettingSub/TextSettingLogic.h
38e9bc3875ce26d6cdc0fcefb58a9eb57ca7b62f
[]
no_license
hongzhuxuke/VlsClient
718762b2fdd0494753fd5193ac83a51f19271c3d
64c4eb7f8aa62d875cb8aa7727ec538f551e627f
refs/heads/master
2022-12-23T17:50:47.136684
2020-09-25T07:31:44
2020-09-25T07:31:44
296,022,926
0
1
null
null
null
null
GB18030
C++
false
false
683
h
TextSettingLogic.h
#ifndef __TEXT_SETTING_LOGIC__H_INCLUDE__ #define __TEXT_SETTING_LOGIC__H_INCLUDE__ #pragma once class TextSettingDlg; class TextSettingLogic { public: TextSettingLogic(void); ~TextSettingLogic(void); public: BOOL Create(); void Destroy(); // 处理消息 void DealMessage(DWORD adwMessageID, void* apData, DWORD adwLen); public: // 处理Click控制 void DealClickControl(void* apData, DWORD adwLen); // 处理修改文本 void DealModifyText(void* apData, DWORD adwLen); private: void CreateTextUI(); //添加文字 void AddText(); private: TextSettingDlg* m_pTextSettingDlg; }; #endif //__TEXT_SETTING_LOGIC__H_INCLUDE__
e2420500907af23b9862d42d9e165b01c2e70899
c9fec000e3e16b7b94079ca9ae39eb9a4dc3e384
/tp2/clientThread.h
d8630d16838cda2c3a73a2ce6d064561d028f871
[]
no_license
jpraymond/ift2245
212f934f5bcd7f4e0e72385efca2300ae215cbb6
188dddc0525eda466a337fc14ae36b52cae57f65
refs/heads/master
2021-03-24T12:25:17.473157
2015-04-22T17:59:20
2015-04-22T17:59:20
30,256,074
1
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
clientThread.h
#ifndef CLIENTTHREAD_H #define CLIENTTHREAD_H #include <string> //POSIX library for threads #include <pthread.h> #include <unistd.h> class ClientThread { public: int ID; static int portNumber; static int numClients; static int numResources; static int numRequests; ClientThread(); ~ClientThread(); void createAndStartThread(); static void additionalInitialization(); static int sendRequest(int clientID, int requestID, int socketFD, int *&requestQuantities); static void waitUntilServerFinishes(); static void printAndSaveResults(const char* fileName); static int readConfigurationFile(const char *fileName); static void readMaxFromFile(); private: // Maximum number of instances of each resource type // that each client MAY need static int **Max; static int **allocatedResources; // Results variables static int countAccepted; // Result counter for total acepted requests static int countOnWait; // Result counter for total request denied and put to wait static int countInvalid; // Result counter for total invalid requests static int countClientsDispatched; // Result counter for total clients correctly finished static int countClientsProcessed; // Qui ont envoye toutes leurs requetes. static pthread_mutex_t mutexCountAccepted; static pthread_mutex_t mutexCountOnWait; static pthread_mutex_t mutexCountInvalid; static pthread_mutex_t mutexCountClientsDispatched; static pthread_mutex_t mutexCountClientsProcessed; static int count; // Common counter of created ClienThread to asign an ID pthread_t pt_tid; // The thread identifier pthread_attr_t pt_attr; // Set of thread identifiers //Function that will be called by every client thread static void *clientThreadCode(void * param); static void randomAllocations(int clientID, int allocations[]); static void randomReleases(int clientID, int releases[]); static bool allocationPossible(int clientID); static bool releasePossible(int clientID); static int sum(int integers[], int length); }; #endif // CLIENTTHREAD_H
1f4ef0f4de89c58224eafb566d69218ca1687693
09fb445742ff40791b0f49958c7af22dc9291c37
/pageRank_hls/amdpool/pageRank.cpp
4b0c636274362213cfda9a0cd763949bffe38122
[]
no_license
xiaotan2/meng-reconfigurable-computing
a87dbaf577ea4065602730220b06a48d73b56049
6c42101f2905ba7143b4c74bc804f692bf805ae9
refs/heads/master
2020-04-06T06:58:35.682020
2016-08-01T04:56:29
2016-08-01T04:56:29
42,365,460
1
0
null
null
null
null
UTF-8
C++
false
false
1,643
cpp
pageRank.cpp
//========================================================================= // pageRank.cpp //========================================================================= // @brief : A PAGERANK implementation of sine and cosine functions. #include <hls_stream.h> #include <iostream> #include "pageRank.h" //----------------------------------- // dut function (top module) //----------------------------------- // @param[in] : strm_in - input stream // @param[out] : strm_out - output stream void dut ( hls::stream<bit32_t> &strm_in, hls::stream<bit32_t> &strm_out ) { bit32_t sum, a, b; // ------------------------------------------------------ // Input processing // ------------------------------------------------------ // Read the two input 32-bit words (low word first) a = strm_in.read(); b = strm_in.read(); // ------------------------------------------------------ // Call PAGERANK // ------------------------------------------------------ pageRank( sum, a, b ); // ------------------------------------------------------ // Output processing // ------------------------------------------------------ // Write out the cos value (low word first) strm_out.write( sum ); } //----------------------------------- // pageRank function //----------------------------------- // @param[in] : a - operand 1, 32 bit uint // @param[in] : b - operand 2, 32 bit uint // @param[out] : c - sum, 32 bit uint void pageRank(bit32_t &sum, bit32_t a, bit32_t b) { sum = a + b; // std::cout << "a = " << a << "\n" << // "b = " << b << "\n" << // "s = " << sum << "\n"; }
de4dc1d85b38bdfe04e4022c9ba68158367b7f81
daa23f97a52485eabc1d548f3323c13eaaf9b89d
/interface/FullVector.h
53399e7c066eab328ef47eab9b19ba9e04ee4fcc
[ "Apache-2.0" ]
permissive
felicepantaleo/helix-fitting
40c76e5dfe9c3f301f5caf2cc10bb81ab5efe56f
d1540156430f0e4ea85a9fd0e0f08e3447f0ec3f
refs/heads/master
2020-12-24T06:37:32.525886
2016-11-11T10:56:54
2016-11-11T10:56:54
73,467,198
1
0
null
null
null
null
UTF-8
C++
false
false
1,768
h
FullVector.h
/*! * \file FullVector.h * \brief FullVector = StateVector + covariance matrix * * 5x5 covariance matrix added. * Space for storing residuals is provided also. * * \author Wolfgang Waltenberger * \date Thu 05 Jul 2001 15:15:46 CEST */ #ifndef FullVector_H #define FullVector_H #include "DetElement.h" #include "defines.h" #include "Plane.h" #include "StateVector.h" #include <CLHEP/config/iostream.h> #include "CLHEP/config/CLHEP.h" #include "CLHEP/Matrix/SymMatrix.h" #ifdef GL #include <Inventor/nodes/SoSelection.h> #endif class FullVector : public StateVector { private: HepSymMatrix _CMSCov, _DelphiCov; bool useCMSCov, useDelphiCov; void CMS2DelphiCov(); void Delphi2CMSCov(); #ifdef GL void drawonCyl( SoSelection *, const string &, HepDouble ); void drawonDis( SoSelection *, const string &, HepDouble ); #endif public: FullVector ( const DetElement & ); FullVector ( const DetElement & , HepDouble , HepDouble , HepDouble , \ HepDouble , HepDouble ); FullVector (); /// Inserts parameter from a Plane into our /// FullVector. /// \param cov get covariance matrix also? // /* void getPlane ( RealPlane , DetElement ); void getPlane ( RealPlane , DetElement, HepDouble r ); */ void setDelphiCov ( const HepSymMatrix & ); void setCMSCov ( const HepSymMatrix & ); HepSymMatrix DelphiCov (); HepSymMatrix CMSCov (); void writeCMS(); void writeDelphi(); #ifdef GL HepSymMatrix track_cov; void GLdraw( SoSelection * , HepDouble lngth ); void GLdraw( SoSelection * , HepDouble, HepDouble, HepDouble , HepDouble ); void GLdraw( SoSelection * , const string & , HepDouble ); void GLdraw( SoSelection * , const string & , HepDouble, \ HepDouble, HepDouble , HepDouble ); string getInfo ( int ) ; #endif }; #endif
3abddd6696e6eef6cf4977f779c295233cf4982a
b02410b3e3b1cbe56cd5d434e6284e6ee0f93f6f
/External Iterator/External Iterator/List.cpp
35cc7fd886d845db7804f1f31ff98d835db29e04
[]
no_license
blake27182/CS2420
37529065fda4a9f0689712e8662471118ef1b57a
dc4a59aefb283df7e579c42e28b57be66d60841c
refs/heads/master
2022-02-24T11:26:38.029563
2019-09-11T17:26:02
2019-09-11T17:26:02
198,278,597
0
0
null
null
null
null
UTF-8
C++
false
false
1,893
cpp
List.cpp
#include "List.h" void List::deallocator(Node* cursor){ if(cursor->next == nullptr){ delete cursor; } else { deallocator(cursor->next); delete cursor; } } List::~List(){ deallocator(head); } List::List(){ head = nullptr; tail = nullptr; } Iterator List::begin(){ return Iterator(head); } Iterator List::end(){ return Iterator(tail->next); } void List::push_back(const int &value){ Node* temp = new Node(value); if (tail){ tail->next = temp; tail = temp; } else { tail = temp; head = temp; } } void List::push_front(const int &value){ Node* temp = new Node(value); temp->next = head; head = temp; if (!tail){ tail = temp; } } int List::size(){ Node* cursor = head; int si = 0; while (cursor->next != nullptr) { si++; cursor = cursor->next; } return ++si; } void List::PrintList(){ Node *cursor = head; while (cursor) { std::cout << cursor->data << " "; cursor = cursor->next; } } void List::remove(const int &value){ while(head->data == value){ DeleteHead(); } Node* precursor = head; while(precursor->next){ while(precursor->next && precursor->next->data == value){ DeleteNotHead(precursor); } if (precursor->next) precursor = precursor->next; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Precondition: precursor must be at least // one space behind tail //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void List::DeleteNotHead(Node* precursor){ Node* temp = precursor->next; if (precursor->next == tail) tail = precursor; precursor->next = precursor->next->next; delete temp; } void List::DeleteHead(){ Node* temp = head; head = head->next; delete temp; }
cc8e9b381bba8a4d5e0c3e641d9a4d47cd6cfdab
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge/convert_tf_quant_types_test.cc
1f21ab98c8746a52b2b26cd3badde9b6decbef48
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
4,223
cc
convert_tf_quant_types_test.cc
/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <gtest/gtest.h> #include "absl/strings/string_view.h" #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/Pass/PassManager.h" // from @llvm-project #include "mlir/Support/LogicalResult.h" // from @llvm-project #include "tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge/passes.h" #include "tensorflow/compiler/mlir/register_common_dialects.h" #include "tensorflow/compiler/mlir/tensorflow/utils/serialize_mlir_module_utils.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/monitoring/cell_reader.h" #include "tensorflow/tsl/platform/statusor.h" namespace mlir { namespace stablehlo { namespace { using ::mlir::DialectRegistry; using ::mlir::MLIRContext; using ::mlir::ModuleOp; using ::mlir::OwningOpRef; using ::tensorflow::monitoring::testing::CellReader; static constexpr char kMetricsName[] = "/tensorflow/core/tf2xla/tf_quant_op_count"; class LegalizeTfTypesTest : public ::testing::Test { protected: void CreateModule(const char* module_string) { DialectRegistry mlir_registry; RegisterCommonToolingDialects(mlir_registry); context_.appendDialectRegistry(mlir_registry); TF_ASSERT_OK( tensorflow::DeserializeMlirModule(module_string, &context_, &module_)); pm_ = std::make_unique<mlir::PassManager>(&context_); pm_->addNestedPass<mlir::func::FuncOp>( mlir::stablehlo::CreateConvertTFQuantTypesPass()); } mlir::LogicalResult Run() { return pm_->run(module_.get()); } private: MLIRContext context_; OwningOpRef<ModuleOp> module_; std::unique_ptr<mlir::PassManager> pm_; }; TEST_F(LegalizeTfTypesTest, RecordsStreamzQuantOps) { static constexpr char kMlirModuleStr[] = R"( module attributes {tf.versions = {bad_consumers = [], min_consumer = 0 : i32, producer = 268 : i32}} { func.func @main(%arg0: tensor<3x3x!tf_type.qint8>, %arg1: tensor<3x3x!tf_type.qint8>) -> tensor<6x3x!tf_type.qint8> { %axis = "tf.Const"() { value = dense<0> : tensor<i64> } : () -> tensor<i64> %1 = "tf.ConcatV2"(%arg0, %arg1, %axis) : (tensor<3x3x!tf_type.qint8>, tensor<3x3x!tf_type.qint8>, tensor<i64>) -> tensor<6x3x!tf_type.qint8> func.return %1 : tensor<6x3x!tf_type.qint8> } })"; CreateModule(kMlirModuleStr); CellReader<int64_t> reader(kMetricsName); auto result = Run(); EXPECT_TRUE(result.succeeded()); EXPECT_EQ(reader.Delta("tf.ConcatV2"), 1); EXPECT_EQ(reader.Delta("func.return"), 1); EXPECT_EQ(reader.Delta("func.func"), 0); } TEST_F(LegalizeTfTypesTest, RecordsStreamzNoQuantOps) { static constexpr char kMlirModuleStr[] = R"( module attributes {tf.versions = {bad_consumers = [], min_consumer = 0 : i32, producer = 268 : i32}} { func.func @main(%arg0: tensor<3x3xf32>, %arg1: tensor<3x3xf32>) -> tensor<6x3xf32> { %axis = "tf.Const"() { value = dense<0> : tensor<i64> } : () -> tensor<i64> %1 = "tf.ConcatV2"(%arg0, %arg1, %axis) : (tensor<3x3xf32>, tensor<3x3xf32>, tensor<i64>) -> tensor<6x3xf32> func.return %1 : tensor<6x3xf32> } })"; CreateModule(kMlirModuleStr); CellReader<int64_t> reader(kMetricsName); auto result = Run(); EXPECT_TRUE(result.succeeded()); EXPECT_EQ(reader.Delta("tf.ConcatV2"), 0); EXPECT_EQ(reader.Delta("func.return"), 0); EXPECT_EQ(reader.Delta("func.func"), 0); } } // namespace } // namespace stablehlo } // namespace mlir
eda74350dbba4bb422853b6d0aaf04aae49ecade
e83488c383a71a4e20ab39374a953bb016d025cf
/AtCoder/Brown/ABC157C.cpp
5b1d8eb1eb8f5feb3df9a39e5c9a3b167935214e
[]
no_license
uechoco/CompetitionProgramming
1cf41971b03ad47fd05a83b582bb2915d600d99b
e922f25d29f95f7f9c22a41bfa98dc5979b4890f
refs/heads/master
2023-01-06T17:07:53.403586
2020-11-03T13:30:57
2020-11-03T13:30:57
268,006,857
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
ABC157C.cpp
#include <bits/stdc++.h> using namespace std; // syntax sugar: `for (int i = 0; i < N; ++i)` #define rep(i, N) for (int i = 0; i < (int)(N); ++i) // syntax sugar: `for (int i = 0; i < N; ++i)` #define REP(type, name, beginValue, endCondValue) \ for (type name = beginValue; name < endCondValue; ++name) // syntax sugar: 多次元vector #define VECTOR_DIM3(T, name, d1, d2, d3, initValue) \ std::vector<std::vector<std::vector<T>>> name(d1, std::vector<std::vector<T>>(d2, std::vector<int>(d3, initValue))); #define VECTOR_DIM2(T, name, d1, d2, initValue) \ std::vector<std::vector<T>> name(d1, std::vector<T>(d2, initValue)); #define VECTOR_DIM1(T, name, d1, initValue) \ std::vector<T> name(d1, initValue); #define ll long long #define ld long double // ABC157 C - Guess The Number int main(){ int n, m; // 1 <= N <= 3, 0 <= M <= 5 cin >> n >> m; vector<int> digits(n, 0); unordered_map<int, int> inputs; // s, c bool canCreate = true; rep(i,m) { int s, c; cin >> s >> c; const auto itr = inputs.find(s); if (n != 1 && s == 1 && c == 0) { canCreate = false; // 左から1桁が0はNG } if (itr != inputs.end() && itr->second != c) { canCreate = false; // 同じ桁に異なる数値 } inputs[s] = c; digits[s-1] = c; } if (!canCreate) { cout << -1 << endl; return 0; } if (n >= 2 && digits[0] == 0) { digits[0] = 1; } rep(i,n) { cout << digits[i]; } cout << endl; return 0; }
b402937327724d8d8164c360a82badb9e2b0669c
dc6550b7f51cdfec7e0769dabec21ee21cec56f1
/tests/cpp/data/test_sparse_page_raw_format.cc
7226558808999f7f1cc29ecfb32f263e0db28f85
[ "Apache-2.0" ]
permissive
huaxz1986/xgboost
748527f5d8a05054ac7d6ab3629c5cfd28b50671
962a20693fd5e6266618edeef6c43b35e42fa675
refs/heads/master
2023-06-11T02:19:29.836548
2023-06-05T00:05:38
2023-06-05T00:05:38
131,370,480
3
4
null
2018-04-28T03:51:00
2018-04-28T03:51:00
null
UTF-8
C++
false
false
2,301
cc
test_sparse_page_raw_format.cc
/** * Copyright 2021-2023, XGBoost contributors */ #include <gtest/gtest.h> #include <xgboost/data.h> // for CSCPage, SortedCSCPage, SparsePage #include <memory> // for allocator, unique_ptr, __shared_ptr_ac... #include <string> // for char_traits, operator+, basic_string #include "../../../src/data/sparse_page_writer.h" // for CreatePageFormat #include "../helpers.h" // for RandomDataGenerator #include "dmlc/filesystem.h" // for TemporaryDirectory #include "dmlc/io.h" // for SeekStream, Stream #include "gtest/gtest_pred_impl.h" // for Test, AssertionResult, ASSERT_EQ, TEST #include "xgboost/context.h" // for Context namespace xgboost { namespace data { template <typename S> void TestSparsePageRawFormat() { std::unique_ptr<SparsePageFormat<S>> format{CreatePageFormat<S>("raw")}; Context ctx; auto m = RandomDataGenerator{100, 14, 0.5}.GenerateDMatrix(); ASSERT_TRUE(m->SingleColBlock()); dmlc::TemporaryDirectory tmpdir; std::string path = tmpdir.path + "/sparse.page"; S orig; { // block code to flush the stream std::unique_ptr<dmlc::Stream> fo{dmlc::Stream::Create(path.c_str(), "w")}; for (auto const &page : m->GetBatches<S>(&ctx)) { orig.Push(page); format->Write(page, fo.get()); } } S page; std::unique_ptr<dmlc::SeekStream> fi{dmlc::SeekStream::CreateForRead(path.c_str())}; format->Read(&page, fi.get()); for (size_t i = 0; i < orig.data.Size(); ++i) { ASSERT_EQ(page.data.HostVector()[i].fvalue, orig.data.HostVector()[i].fvalue); ASSERT_EQ(page.data.HostVector()[i].index, orig.data.HostVector()[i].index); } for (size_t i = 0; i < orig.offset.Size(); ++i) { ASSERT_EQ(page.offset.HostVector()[i], orig.offset.HostVector()[i]); } ASSERT_EQ(page.base_rowid, orig.base_rowid); } TEST(SparsePageRawFormat, SparsePage) { TestSparsePageRawFormat<SparsePage>(); } TEST(SparsePageRawFormat, CSCPage) { TestSparsePageRawFormat<CSCPage>(); } TEST(SparsePageRawFormat, SortedCSCPage) { TestSparsePageRawFormat<SortedCSCPage>(); } } // namespace data } // namespace xgboost
0fa05f6fbfa251df23bc11fac7fde1fc10ec91bb
d69210f40e45bec837e34c0b4ed46a6bdbf06d1b
/include/Misc/FrameRateCalculator.h
07818ee9f8186c4f83e6e26da83d8e92772aa31e
[ "MIT" ]
permissive
jambolo/Misc
5871ffb3dc6490fd191a9b6c6c3e0fb4fe16e0b3
0b2779c9bb1954294a722bddd51dc2ad5e449a1c
refs/heads/master
2021-01-11T11:45:11.631294
2020-12-08T23:57:25
2020-12-08T23:57:25
76,819,398
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
h
FrameRateCalculator.h
#if !defined(MISC_FRAMERATECALCULATOR_H_INCLUDED) #define MISC_FRAMERATECALCULATOR_H_INCLUDED #pragma once #include <chrono> //! A class that keeps track of the frame rate. class FrameRateCalculator { public: //! Constructor. FrameRateCalculator(); //! Updates the state and computes the new frame rate values. void update(std::chrono::high_resolution_clock::time_point t); //! Returns the frame rate for the previous frame. float rate() const { return frameRate_; } //! Returns the average frame rate over the previous second. //! //! @note This value is updated every second (at most). float average() const { return averageFrameRate_; } private: std::chrono::high_resolution_clock::time_point oldTime_; // Time of the previous update std::chrono::high_resolution_clock::time_point oldTime2_; // Time of the previous 1-second update int nFrames_; // Number of frames since the previous 1-second update float frameRate_; // Frame rate of the previous frame float averageFrameRate_; // Frame rate over the previous second }; #endif // !defined(MISC_FRAMERATECALCULATOR_H_INCLUDED)
d0a1dea9d86e55d2e9e9362fafbff5a13bd60e53
04314015734eccb309857652e73944be8996fedc
/src/ExternLibs/fox/src/FXArrowButton.cpp
7b614530f5e91fbea3409460e2d4bf7ac69f50c5
[]
no_license
onexianjian/tsiu
0ed1c2df3f39a445e039d1ac8752a189dbfe21e9
7f37d79588d3655ec52f7cfd04019e332b5bcdf7
refs/heads/master
2020-05-20T09:22:21.261314
2015-06-11T06:41:18
2015-06-11T06:41:18
185,498,769
1
0
null
2019-05-08T00:38:11
2019-05-08T00:38:11
null
UTF-8
C++
false
false
17,283
cpp
FXArrowButton.cpp
/******************************************************************************** * * * A r r o w B u t t o n O b j e c t * * * ********************************************************************************* * Copyright (C) 1998,2006 by Jeroen van der Zijp. All Rights Reserved. * ********************************************************************************* * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * ********************************************************************************* * $Id: FXArrowButton.cpp,v 1.50 2006/01/22 17:58:17 fox Exp $ * ********************************************************************************/ #include "xincs.h" #include "fxver.h" #include "fxdefs.h" #include "fxkeys.h" #include "FXHash.h" #include "FXThread.h" #include "FXStream.h" #include "FXString.h" #include "FXSize.h" #include "FXPoint.h" #include "FXRectangle.h" #include "FXSettings.h" #include "FXRegistry.h" #include "FXApp.h" #include "FXDCWindow.h" #include "FXArrowButton.h" /* Notes: - Automatic mode works by simply hovering cursor over arrow button; it is used for scrolling menus. - Possible interactions between auto mode and manual pressing.. */ // Justification #define JUSTIFY_MASK (JUSTIFY_HZ_APART|JUSTIFY_VT_APART) // Arrow styles #define ARROW_MASK (ARROW_UP|ARROW_DOWN|ARROW_LEFT|ARROW_RIGHT|ARROW_AUTO|ARROW_REPEAT|ARROW_AUTOGRAY|ARROW_AUTOHIDE|ARROW_TOOLBAR) using namespace FX; /*******************************************************************************/ namespace FX { // Map FXDEFMAP(FXArrowButton) FXArrowButtonMap[]={ FXMAPFUNC(SEL_PAINT,0,FXArrowButton::onPaint), FXMAPFUNC(SEL_UPDATE,0,FXArrowButton::onUpdate), FXMAPFUNC(SEL_ENTER,0,FXArrowButton::onEnter), FXMAPFUNC(SEL_LEAVE,0,FXArrowButton::onLeave), FXMAPFUNC(SEL_TIMEOUT,FXArrowButton::ID_AUTO,FXArrowButton::onAuto), FXMAPFUNC(SEL_TIMEOUT,FXArrowButton::ID_REPEAT,FXArrowButton::onRepeat), FXMAPFUNC(SEL_LEFTBUTTONPRESS,0,FXArrowButton::onLeftBtnPress), FXMAPFUNC(SEL_LEFTBUTTONRELEASE,0,FXArrowButton::onLeftBtnRelease), FXMAPFUNC(SEL_QUERY_TIP,0,FXArrowButton::onQueryTip), FXMAPFUNC(SEL_QUERY_HELP,0,FXArrowButton::onQueryHelp), FXMAPFUNC(SEL_UNGRABBED,0,FXArrowButton::onUngrabbed), FXMAPFUNC(SEL_KEYPRESS,0,FXArrowButton::onKeyPress), FXMAPFUNC(SEL_KEYRELEASE,0,FXArrowButton::onKeyRelease), FXMAPFUNC(SEL_KEYPRESS,FXArrowButton::ID_HOTKEY,FXArrowButton::onHotKeyPress), FXMAPFUNC(SEL_KEYRELEASE,FXArrowButton::ID_HOTKEY,FXArrowButton::onHotKeyRelease), FXMAPFUNC(SEL_COMMAND,FXArrowButton::ID_SETHELPSTRING,FXArrowButton::onCmdSetHelp), FXMAPFUNC(SEL_COMMAND,FXArrowButton::ID_GETHELPSTRING,FXArrowButton::onCmdGetHelp), FXMAPFUNC(SEL_COMMAND,FXArrowButton::ID_SETTIPSTRING,FXArrowButton::onCmdSetTip), FXMAPFUNC(SEL_COMMAND,FXArrowButton::ID_GETTIPSTRING,FXArrowButton::onCmdGetTip), }; // Object implementation FXIMPLEMENT(FXArrowButton,FXFrame,FXArrowButtonMap,ARRAYNUMBER(FXArrowButtonMap)) // For deserialization FXArrowButton::FXArrowButton(){ flags|=FLAG_ENABLED; arrowColor=0; arrowSize=9; state=FALSE; fired=FALSE; } // Make a text button FXArrowButton::FXArrowButton(FXComposite* p,FXObject* tgt,FXSelector sel,FXuint opts,FXint x,FXint y,FXint w,FXint h,FXint pl,FXint pr,FXint pt,FXint pb): FXFrame(p,opts,x,y,w,h,pl,pr,pt,pb){ flags|=FLAG_ENABLED; target=tgt; message=sel; arrowColor=getApp()->getForeColor(); arrowSize=9; state=FALSE; fired=FALSE; } // Get default size FXint FXArrowButton::getDefaultWidth(){ return padleft+padright+arrowSize+(border<<1); } FXint FXArrowButton::getDefaultHeight(){ return padtop+padbottom+arrowSize+(border<<1); } // Enable the window void FXArrowButton::enable(){ if(!(flags&FLAG_ENABLED)){ FXFrame::enable(); update(); } } // Disable the window void FXArrowButton::disable(){ if(flags&FLAG_ENABLED){ FXFrame::disable(); update(); } } // Set button state void FXArrowButton::setState(FXbool s){ if(state!=s){ state=s; update(); } } // If window can have focus bool FXArrowButton::canFocus() const { return true; } // Implement auto-hide or auto-gray modes long FXArrowButton::onUpdate(FXObject* sender,FXSelector sel,void* ptr){ if(!FXFrame::onUpdate(sender,sel,ptr)){ if(options&ARROW_AUTOHIDE){if(shown()){hide();recalc();}} if(options&ARROW_AUTOGRAY){disable();} } return 1; } // Press automatically long FXArrowButton::onAuto(FXObject*,FXSelector,void*){ setState(TRUE); getApp()->addTimeout(this,ID_REPEAT,getApp()->getScrollSpeed()); flags&=~FLAG_UPDATE; fired=FALSE; return 1; } // Entered button long FXArrowButton::onEnter(FXObject* sender,FXSelector sel,void* ptr){ FXFrame::onEnter(sender,sel,ptr); if(isEnabled()){ if(flags&FLAG_PRESSED){ setState(TRUE); } else if(options&ARROW_AUTO){ if(options&ARROW_REPEAT) getApp()->addTimeout(this,ID_AUTO,getApp()->getScrollDelay()); } if(options&ARROW_TOOLBAR) update(); } return 1; } // Left button long FXArrowButton::onLeave(FXObject* sender,FXSelector sel,void* ptr){ FXFrame::onLeave(sender,sel,ptr); if(isEnabled()){ if(flags&FLAG_PRESSED){ setState(FALSE); } else if(options&ARROW_AUTO){ setState(FALSE); if(options&ARROW_REPEAT) getApp()->removeTimeout(this,ID_AUTO); flags|=FLAG_UPDATE; fired=FALSE; } if(options&ARROW_TOOLBAR) update(); } return 1; } // Pressed mouse button long FXArrowButton::onLeftBtnPress(FXObject*,FXSelector,void* ptr){ handle(this,FXSEL(SEL_FOCUS_SELF,0),ptr); flags&=~FLAG_TIP; if(isEnabled() && !(flags&FLAG_PRESSED)){ grab(); if(target && target->tryHandle(this,FXSEL(SEL_LEFTBUTTONPRESS,message),ptr)) return 1; setState(TRUE); getApp()->removeTimeout(this,ID_AUTO); if(options&ARROW_REPEAT) getApp()->addTimeout(this,ID_REPEAT,getApp()->getScrollDelay()); flags|=FLAG_PRESSED; flags&=~FLAG_UPDATE; fired=FALSE; return 1; } return 0; } // Released mouse button long FXArrowButton::onLeftBtnRelease(FXObject*,FXSelector,void* ptr){ FXbool click=(!fired && state); if(isEnabled() && (flags&FLAG_PRESSED)){ ungrab(); flags|=FLAG_UPDATE; flags&=~FLAG_PRESSED; fired=FALSE; getApp()->removeTimeout(this,ID_REPEAT); if(target && target->tryHandle(this,FXSEL(SEL_LEFTBUTTONRELEASE,message),ptr)) return 1; setState(FALSE); if(click && target) target->tryHandle(this,FXSEL(SEL_COMMAND,message),(void*)(FXuval)1); return 1; } return 0; } // Lost the grab for some reason long FXArrowButton::onUngrabbed(FXObject* sender,FXSelector sel,void* ptr){ FXFrame::onUngrabbed(sender,sel,ptr); setState(FALSE); getApp()->removeTimeout(this,ID_REPEAT); flags&=~FLAG_PRESSED; flags|=FLAG_UPDATE; fired=FALSE; return 1; } // Repeat a click automatically long FXArrowButton::onRepeat(FXObject*,FXSelector,void*){ getApp()->addTimeout(this,ID_REPEAT,getApp()->getScrollSpeed()); if(state && target) target->tryHandle(this,FXSEL(SEL_COMMAND,message),(void*)(FXuval)1); fired=TRUE; return 1; } // Key Press long FXArrowButton::onKeyPress(FXObject*,FXSelector,void* ptr){ FXEvent* event=(FXEvent*)ptr; flags&=~FLAG_TIP; if(isEnabled() && !(flags&FLAG_PRESSED)){ if(target && target->tryHandle(this,FXSEL(SEL_KEYPRESS,message),ptr)) return 1; if(event->code==KEY_space || event->code==KEY_KP_Space){ setState(TRUE); getApp()->removeTimeout(this,ID_AUTO); if(options&ARROW_REPEAT) getApp()->addTimeout(this,ID_REPEAT,getApp()->getScrollDelay()); flags|=FLAG_PRESSED; flags&=~FLAG_UPDATE; fired=FALSE; return 1; } } return 0; } // Key Release long FXArrowButton::onKeyRelease(FXObject*,FXSelector,void* ptr){ FXEvent* event=(FXEvent*)ptr; FXbool click=(!fired && state); if(isEnabled() && (flags&FLAG_PRESSED)){ if(target && target->tryHandle(this,FXSEL(SEL_KEYRELEASE,message),ptr)) return 1; if(event->code==KEY_space || event->code==KEY_KP_Space){ setState(FALSE); flags|=FLAG_UPDATE; flags&=~FLAG_PRESSED; fired=FALSE; getApp()->removeTimeout(this,ID_REPEAT); if(click && target) target->tryHandle(this,FXSEL(SEL_COMMAND,message),(void*)(FXuval)1); return 1; } } return 0; } // Hot key combination pressed long FXArrowButton::onHotKeyPress(FXObject*,FXSelector,void* ptr){ flags&=~FLAG_TIP; handle(this,FXSEL(SEL_FOCUS_SELF,0),ptr); if(isEnabled() && !(flags&FLAG_PRESSED)){ setState(TRUE); getApp()->removeTimeout(this,ID_AUTO); if(options&ARROW_REPEAT) getApp()->addTimeout(this,ID_REPEAT,getApp()->getScrollDelay()); flags|=FLAG_PRESSED; flags&=~FLAG_UPDATE; fired=FALSE; } return 1; } // Hot key combination released long FXArrowButton::onHotKeyRelease(FXObject*,FXSelector,void*){ FXbool click=(!fired && state); if(isEnabled() && (flags&FLAG_PRESSED)){ setState(FALSE); flags|=FLAG_UPDATE; flags&=~FLAG_PRESSED; fired=FALSE; getApp()->removeTimeout(this,ID_REPEAT); if(click && target) target->tryHandle(this,FXSEL(SEL_COMMAND,message),(void*)(FXuval)1); } return 1; } // Set help using a message long FXArrowButton::onCmdSetHelp(FXObject*,FXSelector,void* ptr){ setHelpText(*((FXString*)ptr)); return 1; } // Get help using a message long FXArrowButton::onCmdGetHelp(FXObject*,FXSelector,void* ptr){ *((FXString*)ptr)=getHelpText(); return 1; } // Set tip using a message long FXArrowButton::onCmdSetTip(FXObject*,FXSelector,void* ptr){ setTipText(*((FXString*)ptr)); return 1; } // Get tip using a message long FXArrowButton::onCmdGetTip(FXObject*,FXSelector,void* ptr){ *((FXString*)ptr)=getTipText(); return 1; } // We were asked about tip text long FXArrowButton::onQueryTip(FXObject* sender,FXSelector sel,void* ptr){ if(FXWindow::onQueryTip(sender,sel,ptr)) return 1; if((flags&FLAG_TIP) && !tip.empty()){ sender->handle(this,FXSEL(SEL_COMMAND,ID_SETSTRINGVALUE),(void*)&tip); return 1; } return 0; } // We were asked about status text long FXArrowButton::onQueryHelp(FXObject* sender,FXSelector sel,void* ptr){ if(FXWindow::onQueryHelp(sender,sel,ptr)) return 1; if((flags&FLAG_HELP) && !help.empty()){ sender->handle(this,FXSEL(SEL_COMMAND,ID_SETSTRINGVALUE),(void*)&help); return 1; } return 0; } // Handle repaint long FXArrowButton::onPaint(FXObject*,FXSelector,void* ptr){ FXEvent *ev=(FXEvent*)ptr; FXDCWindow dc(this,ev); FXPoint points[3]; FXint xx,yy,ww,hh,q; // With borders if(options&(FRAME_RAISED|FRAME_SUNKEN)){ // Toolbar style if(options&ARROW_TOOLBAR){ // Enabled and cursor inside, and up if(isEnabled() && underCursor() && !state){ dc.setForeground(backColor); dc.fillRectangle(border,border,width-border*2,height-border*2); if(options&FRAME_THICK) drawDoubleRaisedRectangle(dc,0,0,width,height); else drawRaisedRectangle(dc,0,0,width,height); } // Enabled and cursor inside and down else if(isEnabled() && state){ dc.setForeground(hiliteColor); dc.fillRectangle(border,border,width-border*2,height-border*2); if(options&FRAME_THICK) drawDoubleSunkenRectangle(dc,0,0,width,height); else drawSunkenRectangle(dc,0,0,width,height); } // Disabled or unchecked or not under cursor else{ dc.setForeground(backColor); dc.fillRectangle(0,0,width,height); } } // Normal style else{ // Draw sunken if enabled and pressed if(isEnabled() && state){ dc.setForeground(hiliteColor); dc.fillRectangle(border,border,width-border*2,height-border*2); if(options&FRAME_THICK) drawDoubleSunkenRectangle(dc,0,0,width,height); else drawSunkenRectangle(dc,0,0,width,height); } // Draw in up state if disabled or up else{ dc.setForeground(backColor); dc.fillRectangle(border,border,width-border*2,height-border*2); if(options&FRAME_THICK) drawDoubleRaisedRectangle(dc,0,0,width,height); else drawRaisedRectangle(dc,0,0,width,height); } } } // No borders else{ if(isEnabled() && state){ dc.setForeground(hiliteColor); dc.fillRectangle(0,0,width,height); } else{ dc.setForeground(backColor); dc.fillRectangle(0,0,width,height); } } // Compute size of the arrows.... ww=width-padleft-padright-(border<<1); hh=height-padtop-padbottom-(border<<1); if(options&(ARROW_UP|ARROW_DOWN)){ q=ww|1; if(q>(hh<<1)) q=(hh<<1)-1; ww=q; hh=q>>1; } else{ q=hh|1; if(q>(ww<<1)) q=(ww<<1)-1; ww=q>>1; hh=q; } if(options&JUSTIFY_LEFT) xx=padleft+border; else if(options&JUSTIFY_RIGHT) xx=width-ww-padright-border; else xx=(width-ww)/2; if(options&JUSTIFY_TOP) yy=padtop+border; else if(options&JUSTIFY_BOTTOM) yy=height-hh-padbottom-border; else yy=(height-hh)/2; if(state){ ++xx; ++yy; } if(isEnabled()) dc.setForeground(arrowColor); else dc.setForeground(shadowColor); // NB Size of arrow should stretch if(options&ARROW_UP){ points[0].x=xx+(ww>>1); points[0].y=yy-1; points[1].x=xx; points[1].y=yy+hh; points[2].x=xx+ww; points[2].y=yy+hh; dc.fillPolygon(points,3); } else if(options&ARROW_DOWN){ points[0].x=xx+1; points[0].y=yy; points[1].x=xx+ww-1; points[1].y=yy; points[2].x=xx+(ww>>1); points[2].y=yy+hh; dc.fillPolygon(points,3); } else if(options&ARROW_LEFT){ points[0].x=xx+ww; points[0].y=yy; points[1].x=xx+ww; points[1].y=yy+hh-1; points[2].x=xx; points[2].y=yy+(hh>>1); dc.fillPolygon(points,3); } else if(options&ARROW_RIGHT){ points[0].x=xx; points[0].y=yy; points[1].x=xx; points[1].y=yy+hh-1; points[2].x=xx+ww; points[2].y=yy+(hh>>1); dc.fillPolygon(points,3); } return 1; } // Set arrow style void FXArrowButton::setArrowStyle(FXuint style){ FXuint opts=(options&~ARROW_MASK) | (style&ARROW_MASK); if(options!=opts){ options=opts; update(); } } // Get arrow style FXuint FXArrowButton::getArrowStyle() const { return (options&ARROW_MASK); } // Set default arrow size void FXArrowButton::setArrowSize(FXint size){ if(size!=arrowSize){ arrowSize=size; recalc(); } } // Set text color void FXArrowButton::setArrowColor(FXColor clr){ if(clr!=arrowColor){ arrowColor=clr; update(); } } // Set text justify style void FXArrowButton::setJustify(FXuint style){ FXuint opts=(options&~JUSTIFY_MASK) | (style&JUSTIFY_MASK); if(options!=opts){ options=opts; update(); } } // Get text justify style FXuint FXArrowButton::getJustify() const { return (options&JUSTIFY_MASK); } // Save object to stream void FXArrowButton::save(FXStream& store) const { FXFrame::save(store); store << arrowColor; store << arrowSize; } // Load object from stream void FXArrowButton::load(FXStream& store){ FXFrame::load(store); store >> arrowColor; store >> arrowSize; } // Kill the timer FXArrowButton::~FXArrowButton(){ getApp()->removeTimeout(this,ID_AUTO); getApp()->removeTimeout(this,ID_REPEAT); } }
2b88d28ecf84344d3ec6225d142493b9a9c69a4a
a92708d28a0ec6ddf083ae42a47e35f2121f0eba
/foundation/graphic/lite/frameworks/ui/include/font/ui_muti_font_manager.h
671afa4facc1fbfd7d25e432a074416f0ffdde17
[ "Apache-2.0" ]
permissive
km1042412/my-OHOS
322eca402c28eb68272c58214243ecb8a0960b3c
3c74564d9c6c3b33b836c6a3cd1a6dbc6d4bc18e
refs/heads/main
2023-03-28T05:36:56.244181
2021-03-16T06:25:01
2021-03-16T06:25:01
348,194,410
1
0
null
null
null
null
UTF-8
C++
false
false
3,485
h
ui_muti_font_manager.h
/* * Copyright (c) 2020 Huawei Device 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 UI_MUTI_FONT_MANAGER_H #define UI_MUTI_FONT_MANAGER_H #include "graphic_config.h" #if ENABLE_MUTI_FONT namespace OHOS { class UIMutiFontManager { public: UIMutiFontManager(const UIMutiFontManager&) = delete; UIMutiFontManager& operator=(const UIMutiFontManager&) = delete; UIMutiFontManager(UIMutiFontManager&&) noexcept = delete; UIMutiFontManager& operator=(UIMutiFontManager&&) noexcept = delete; /** * @brief Get the Instance object * * @return UIMutiFontManager* */ static UIMutiFontManager* GetInstance() { static UIMutiFontManager instance; return &instance; } void ClearSearchFontList(); int8_t SetSearchFontList(uint8_t fontListId, uint8_t* fontIds, uint8_t size); int8_t GetSearchFontList(uint8_t fontListId, uint8_t** fontIds); bool IsNeedShaping(char* text, uint8_t& ttfId); uint8_t GetShapingFontId(char* text, uint8_t fontId, uint8_t& ttfId); private: /** * @brief Construct a new UIMutiFontManager object * */ UIMutiFontManager(); /** * @brief Destroy the UIMutiFontManager object * */ ~UIMutiFontManager(); int8_t AddNewFont(uint8_t fontListId, uint8_t* fontIds, int8_t size, uint8_t fontId); int8_t UpdateFont(uint8_t fontListId, uint8_t* fontIds, uint8_t size); int8_t IsShapingLetter(uint32_t unicode, uint8_t& ttfId) { // arbic if (unicode <= 0x06FF && unicode >= 0x0600) { ttfId = arbicTtfId_; return true; } // thai if (unicode <= 0x0E7F && unicode >= 0x0E00) { ttfId = thaiTtfId_; return true; } // Devanagari if (unicode <= 0x097F && unicode >= 0x0900) { ttfId = devanagariTtfId_; return true; } // Hebrew if (unicode <= 0x05FF && unicode >= 0x0590) { ttfId = hebrewTtfId_; return true; } // Myanmar if (unicode <= 0x109F && unicode >= 0x1000) { ttfId = myanmarTtfId_; return true; } return false; } struct FontIdNode { uint8_t* fontIds = nullptr; int8_t size = 0; }; static constexpr uint8_t MAX_LIST_NUM = 20; static constexpr uint8_t DEFAULT_SHAPING_ID = 1; static constexpr const char* ARABIC_LANG = "Arabic"; static constexpr const char* THAI_LANG = "Thai"; static constexpr const char* MYAN_LANG = "Myanmar"; static constexpr const char* DVCARI_LANG = "Devanagari"; static constexpr const char* HBREW_LANG = "Hebrew"; uint8_t arbicTtfId_; uint8_t thaiTtfId_; uint8_t myanmarTtfId_; uint8_t devanagariTtfId_; uint8_t hebrewTtfId_; uint8_t topIndex_; uint8_t* fontIdIndex_; FontIdNode fontNodes_[MAX_LIST_NUM]; }; } // namespace OHOS #endif #endif
8d1fe86ff0d018a12af8e522b5ffddbec4bbf598
796fce2ea689d64583ca0011f934886d6ad9b5bb
/Classes/BattleBuilding.cpp
97ba6874c3885a9ee076353eedf4048a11c31c4a
[]
no_license
hackerlank/cocgame
7fcd0b0e3bb5d3fab7c780a7250637d086ac8d84
390370cfb126e6cc7191bff85ba2dcc2e38a4652
refs/heads/master
2020-06-14T23:25:04.333232
2013-11-10T13:37:18
2013-11-10T13:37:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
BattleBuilding.cpp
#include "BattleBuilding.h" #include "GameUtil.h" CCBattleBuilding::CCBattleBuilding() :isEnemy(false) ,isDying(false) ,isCastle(false) ,fSpeed(0) ,fRange(480) ,nDamage(2) ,nHP(1000) ,nOriginHP(1000) { } CCBattleBuilding::~CCBattleBuilding() { } CCBattleBuilding* CCBattleBuilding::create(const char *pszFileName) { CCBattleBuilding *pobSprite = new CCBattleBuilding(); if (pobSprite && pobSprite->initWithFile(pszFileName)) { pobSprite->autorelease(); return pobSprite; } CC_SAFE_DELETE(pobSprite); return NULL; } bool CCBattleBuilding::initWithFile(const char *pszFilename) { if( CCSprite::initWithFile(pszFilename) == false) return false; return true; } void CCBattleBuilding::setDamage(int nDamage) { nHP -= nDamage; if(nHP <= 0) { nHP = 0; isDying = true; } } float CCBattleBuilding::positionX() { float fX = this->getPositionX(); CCSize size = this->getContentSize(); if(isEnemy) fX -= size.width/2; else fX += size.width/2; return fX; }
da16b30f85ab33b95c1fd0e82f5a15191d1fc083
753679167aa71bd60ec7a87892291ecd60cea9c3
/UpDate OS Scheduling/FCFS.cpp
5479e785f0b1c04dd94d2064e09772350307f6ab
[]
no_license
SumonKantiDey/Univ-Lab-Work
fcdfaa4ad2fa02549df183f88b8503f212b71c04
d4a6c9b043ae56eb51bfa642f2a63d673a53290d
refs/heads/master
2021-01-22T01:54:28.885605
2018-06-23T21:26:27
2018-06-23T21:26:27
81,015,557
0
0
null
2017-02-05T19:16:26
2017-02-05T19:16:26
null
UTF-8
C++
false
false
1,604
cpp
FCFS.cpp
#include<bits/stdc++.h> using namespace std; string pp[10]; int B[10],A[10],TBr[10],C[10],TAT[10],W[10]; int main() { cout << "First Come First-Served Scheduling"<<"\n"; cout <<">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"<<"\n"; cout <<"Number of process \n"; int n,ww = 0; cin >> n; for(int i = 1; i <= n; i++){ cin >> pp[i-1] >> B[i] >> A[i]; TBr[i] = B[i]; } int p; for(int i = 1; i <= n; i++){ if(A[i+1] > TBr[i]) { p = A[i+1] - B[i]; p += TBr[i+1] + B[i]; TBr[i + 1] = p; } else{ TBr[i+1] += TBr[i]; } } // for(int i = 1; i <= n; i++){ // cout << TBr[i]<< endl; // } for(int i = 1; i <= n; i++){ TAT[i] = TBr[i] - A[i]; } for(int i = 1; i <= n; i++){ W[i] = TAT[i] - B[i]; } // cout << " Tranced time " << endl; // for(int i = 1; i <= n; i++){ // cout << TAT[i]<< endl; // } // cout << "Waiting Timr" << endl; // for(int i = 1; i <= n; i++){ // cout << W[i]<< endl; // } cout << "Process " << "BrustTime " << "ArrivalTime " << "CompliationTime "<<"TrunciatTime " <<"WainingTime "<<"\n"; for(int i = 1; i <=n; i++){ ww += W[i]; cout <<" "<< pp[i-1] << "\t "<< B[i] << "\t\t"<< A[i] << "\t\t" << TBr[i]<< "\t"<< TAT[i] << "\t\t" << W[i] <<endl; } cout << "Average waiting Time = " << double(ww) / double(n) << endl; } /* 5 p1 4 0 p2 3 1 p3 1 2 p4 2 3 p5 5 4 3 p1 24 0 p2 3 0 p3 3 0 3 p1 2 0 p2 1 3 p3 6 5 4 p1 4 0 p2 9 2 p3 8 4 p4 3 3 */
e1c25647d28e8440266e648c514a478edea26f1f
b93d253b0fd1229597518cbfa62f0900b5689b24
/test/common/minimize_composed_function_test.cpp
5db4f99c51946568f999d45f86ad7e076007f5eb
[ "BSD-2-Clause" ]
permissive
praveenmunagapati/charge
3e95e58e13dc16d998cf59bd7b58fcf7cd86ef1c
85e35f7a6c8b8c161ecd851124d1363d5a450573
refs/heads/master
2020-04-13T16:39:17.330291
2017-12-26T14:51:24
2017-12-26T14:51:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,192
cpp
minimize_composed_function_test.cpp
#include "common/minimize_composed_function.hpp" #include "../helper/function_comparator.hpp" #include "../helper/function_printer.hpp" #include <catch.hpp> using namespace charge; using namespace charge::common; TEST_CASE("Combine linear and PWL function") { LimitedHypOrLinFunction f{1, 2, LinearFunction{-0.5, 5}}; auto capacity = 5; PiecewieseDecLinearFunction pwf{{ {0, 2, LinearFunction(-1, capacity - 0)}, {2, 6, LinearFunction(-0.5, capacity - 1)}, {6, 10, LinearFunction(-0.25, capacity - 2.75)}, }}; StatefulPiecewieseDecLinearFunction g{pwf}; REQUIRE(f(1) == pwf(0.5)); auto[delta, h] = compose_minimal(f, g); REQUIRE(h(1) == f(1)); REQUIRE(h(1) == pwf(0.5)); REQUIRE(h(2) == pwf(1.5)); REQUIRE(h(3) == pwf(2.5)); REQUIRE(h(4) == pwf(3.5)); REQUIRE(h(5) == pwf(4.5)); REQUIRE(h(6) == pwf(5.5)); REQUIRE(h(7) == pwf(6.5)); REQUIRE(h(8) == pwf(7.5)); REQUIRE(h(9) == pwf(8.5)); REQUIRE(h(10) == pwf(9.5)); REQUIRE(h(10.5) == pwf(10)); } TEST_CASE("Combine linear and PWL function, charging does not pay off") { LimitedHypOrLinFunction f{5, 7, LinearFunction{-0.51, 5.05}}; auto capacity = 5; PiecewieseDecLinearFunction pwf{{ {0, 2, LinearFunction(-1, capacity - 0)}, {2, 6, LinearFunction(-0.5, capacity - 1)}, {6, 10, LinearFunction(-0.25, capacity - 2.75)}, }}; StatefulPiecewieseDecLinearFunction g{pwf}; // f'(5) = -0.51 // pwf'(3) = -0.5 // -> does not pay off to charge REQUIRE(f(5) == Approx(pwf(3))); auto[delta, solution] = compose_minimal(f, g); REQUIRE(solution.functions.size() == 0); } TEST_CASE("Combine hyperbolic and PWL function, five candidates") { LimitedHypOrLinFunction f{3, 8, HyperbolicFunction{64, 0, -1}}; const auto &f_hyp = static_cast<const HyperbolicFunction &>(*f); const auto deriv_f = [&](double x) { return -2 * f_hyp.a / std::pow(x - f_hyp.b, 3); }; const auto inv_deriv_f = [&](double alpha) { return f_hyp.b + std::cbrt(-2 * f_hyp.a / alpha); }; REQUIRE(deriv_f(3) == Approx(-4.7407407407)); REQUIRE(deriv_f(4) == -2); REQUIRE(deriv_f(5) == -1.024); REQUIRE(deriv_f(6) == Approx(-0.5925925926)); REQUIRE(deriv_f(7) == Approx(-0.3731778426)); REQUIRE(deriv_f(8) == -0.25); REQUIRE(f(3) == Approx(6.111111)); REQUIRE(f(4) == Approx(3)); REQUIRE(f(5) == Approx(1.56)); REQUIRE(f(6) == Approx(0.77778)); REQUIRE(f(7) == Approx(0.30612244897959173)); REQUIRE(f(8) == Approx(0)); auto capacity = 10; // Using a linear approximation of f we can construct the worst-case // where each sub function needs to be considered as a possible starting // point for charging. auto slope_0 = (f(3) - capacity) / 3; auto slope_1 = f(4) - f(3); auto slope_2 = f(5) - f(4); auto slope_3 = f(6) - f(5); auto slope_4 = f(7) - f(6); auto slope_5 = f(8) - f(7); REQUIRE(slope_1 > deriv_f(3)); REQUIRE(slope_1 < deriv_f(4)); REQUIRE(slope_2 > deriv_f(4)); REQUIRE(slope_2 < deriv_f(5)); REQUIRE(slope_3 > deriv_f(5)); REQUIRE(slope_3 < deriv_f(6)); REQUIRE(slope_4 > deriv_f(6)); REQUIRE(slope_4 < deriv_f(7)); REQUIRE(slope_5 > deriv_f(7)); REQUIRE(slope_5 < deriv_f(8)); REQUIRE(inv_deriv_f(slope_1) == Approx(3.45222f)); REQUIRE(inv_deriv_f(slope_2) == Approx(4.46289f)); REQUIRE(inv_deriv_f(slope_3) == Approx(5.46966f)); REQUIRE(inv_deriv_f(slope_4) == Approx(6.47433f)); REQUIRE(inv_deriv_f(slope_5) == Approx(7.47776f)); PiecewieseDecLinearFunction pwf{{ {0, 3, LinearFunction(slope_0, capacity)}, {3, 4, LinearFunction(slope_1, f(3) - slope_1 * 3)}, {4, 5, LinearFunction(slope_2, f(4) - slope_2 * 4)}, {5, 6, LinearFunction(slope_3, f(5) - slope_3 * 5)}, {6, 7, LinearFunction(slope_4, f(6) - slope_4 * 6)}, {7, 8, LinearFunction(slope_5, f(7) - slope_5 * 7)}, }}; REQUIRE(pwf(3) == Approx(f(3))); REQUIRE(pwf(4) == Approx(f(4))); REQUIRE(pwf(5) == Approx(f(5))); REQUIRE(pwf(6) == Approx(f(6))); REQUIRE(pwf(7) == Approx(f(7))); REQUIRE(pwf(8) == Approx(f(8))); StatefulPiecewieseDecLinearFunction g{pwf}; auto[delta, solution] = compose_minimal(f, g); PiecewieseDecHypOrLinFunction reference{ {{3.45221749599, 3.89261195827, LinearFunction{-3.11111111111, -0.107388041731, 15.4444444444}}, {3.89261195827, 4.89261195827, LinearFunction{-1.44, -0.107388041731, 8.76}}, {4.89261195827, 5.89261195827, LinearFunction{-0.782222222222, -0.107388041731, 5.47111111111}}, {5.89261195827, 6.89261195827, LinearFunction{-0.471655328798, -0.107388041731, 3.60770975057}}, {6.89261195827, 7.89261195827, LinearFunction{-0.30612244898, -0.107388041731, 2.44897959184}}}}; CHECK(ApproxFunction(reference) == solution); } TEST_CASE("Combine constant and PWL function") { LimitedHypOrLinFunction f{1, 1, ConstantFunction{4.5}}; auto capacity = 5; PiecewieseDecLinearFunction pwf{{ {0, 2, LinearFunction(-1, capacity - 0)}, {2, 6, LinearFunction(-0.5, capacity - 1)}, {6, 10, LinearFunction(-0.25, capacity - 2.75)}, }}; StatefulPiecewieseDecLinearFunction g{pwf}; REQUIRE(f(1) == pwf(0.5)); auto[delta, h] = compose_minimal(f, g); REQUIRE(h(1) == f(1)); REQUIRE(h(1) == pwf(0.5)); REQUIRE(h(2) == pwf(1.5)); REQUIRE(h(3) == pwf(2.5)); REQUIRE(h(4) == pwf(3.5)); REQUIRE(h(5) == pwf(4.5)); REQUIRE(h(6) == pwf(5.5)); REQUIRE(h(7) == pwf(6.5)); REQUIRE(h(8) == pwf(7.5)); REQUIRE(h(9) == pwf(8.5)); REQUIRE(h(10) == pwf(9.5)); REQUIRE(h(10.5) == pwf(10)); } // Same test case as for the non-convex output TEST_CASE("Combine hyperbolic and PWL function with five convex solutions") { LimitedHypOrLinFunction f{3, 8, HyperbolicFunction{64, 0, -1}}; const auto &f_hyp = static_cast<const HyperbolicFunction &>(*f); const auto deriv_f = [&](double x) { return -2 * f_hyp.a / std::pow(x - f_hyp.b, 3); }; const auto inv_deriv_f = [&](double alpha) { return f_hyp.b + std::cbrt(-2 * f_hyp.a / alpha); }; auto capacity = 10; // Using a linear approximation of f we can construct the worst-case // where each sub function needs to be considered as a possible starting // point for charging. auto slope_0 = (f(3) - capacity) / 3; auto slope_1 = f(4) - f(3); auto slope_2 = f(5) - f(4); auto slope_3 = f(6) - f(5); auto slope_4 = f(7) - f(6); auto slope_5 = f(8) - f(7); PiecewieseDecLinearFunction pwf{{ {0, 3, LinearFunction(slope_0, capacity)}, {3, 4, LinearFunction(slope_1, f(3) - slope_1 * 3)}, {4, 5, LinearFunction(slope_2, f(4) - slope_2 * 4)}, {5, 6, LinearFunction(slope_3, f(5) - slope_3 * 5)}, {6, 7, LinearFunction(slope_4, f(6) - slope_4 * 6)}, {7, 8, LinearFunction(slope_5, f(7) - slope_5 * 7)}, }}; StatefulPiecewieseDecLinearFunction g{pwf}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, g, std::back_inserter(solutions)); PiecewieseSolution reference_1{ {{3.45221749599, 7.89261195827, LinearFunction{0, 0, 3.45221749599}}}, {{{3.45221749599, 3.89261195827, LinearFunction{-3.11111111111, -0.107388041731, 15.4444444444}}, {3.89261195827, 4.89261195827, LinearFunction{-1.44, -0.107388041731, 8.76}}, {4.89261195827, 5.89261195827, LinearFunction{-0.782222222222, -0.107388041731, 5.47111111111}}, {5.89261195827, 6.89261195827, LinearFunction{-0.471655328798, -0.107388041731, 3.60770975057}}, {6.89261195827, 7.89261195827, LinearFunction{-0.30612244898, -0.107388041731, 2.44897959184}}}}}; PiecewieseSolution reference_2{ {{4.46288633388, 7.91655172304, LinearFunction{0, 0, 4.46288633388}}}, {{{4.46288633388, 4.91655172304, LinearFunction{-1.44, -0.0834482769561, 8.76}}, {4.91655172304, 5.91655172304, LinearFunction{-0.782222222222, -0.0834482769561, 5.47111111111}}, {5.91655172304, 6.91655172304, LinearFunction{-0.471655328798, -0.0834482769561, 3.60770975057}}, {6.91655172304, 7.91655172304, LinearFunction{-0.30612244898, -0.0834482769561, 2.44897959184}}}}}; PiecewieseSolution reference_3{ {{5.46965551376, 7.93175506592, LinearFunction{0, 0, 5.46965551376}}}, {{{5.46965551376, 5.93175506592, LinearFunction{-0.782222151756, -0.068244934082, 5.47111082077}}, {5.93175506592, 6.93175506592, LinearFunction{-0.471655368805, -0.068244934082, 3.60770988464}}, {6.93175506592, 7.93175506592, LinearFunction{-0.306122422218, -0.068244934082, 2.44897937775}}}}}; PiecewieseSolution reference_4{ {{6.47433328629, 7.94227027893, LinearFunction{0, 0, 6.47433328629}}}, {{{6.47433328629, 6.94227027893, LinearFunction{-0.471655368805, -0.0577297210693, 3.60770988464}}, {6.94227027893, 7.94227027893, LinearFunction{-0.306122422218, -0.0577297210693, 2.44897937775}}}}}; PiecewieseSolution reference_5{ {{7.47776126862, 7.94997549057, LinearFunction{0, 0, 7.47776126862}}}, {{{7.47776126862, 7.94997549057, LinearFunction{-0.306122422218, -0.0500245094299, 2.44897937775}}}}}; CHECK(solutions.size() == 5); CHECK(ApproxFunction(std::get<1>(solutions[0])) == std::get<1>(reference_1)); CHECK(ApproxFunction(std::get<1>(solutions[1])) == std::get<1>(reference_2)); CHECK(ApproxFunction(std::get<1>(solutions[2])) == std::get<1>(reference_3)); CHECK(ApproxFunction(std::get<1>(solutions[3])) == std::get<1>(reference_4)); CHECK(ApproxFunction(std::get<1>(solutions[4])) == std::get<1>(reference_5)); CHECK(ApproxFunction(std::get<0>(solutions[0])) == std::get<0>(reference_1)); CHECK(ApproxFunction(std::get<0>(solutions[1])) == std::get<0>(reference_2)); CHECK(ApproxFunction(std::get<0>(solutions[2])) == std::get<0>(reference_3)); CHECK(ApproxFunction(std::get<0>(solutions[3])) == std::get<0>(reference_4)); CHECK(ApproxFunction(std::get<0>(solutions[4])) == std::get<0>(reference_5)); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(f(delta_1(h_1.min_x())) == Approx(h_1(h_1.min_x()))); CHECK(0 == Approx(h_1(h_1.max_x()))); auto & [ delta_2, h_2 ] = solutions[1]; CHECK(f(delta_2(h_2.min_x())) == Approx(h_2(h_2.min_x()))); CHECK(0 == Approx(h_2(h_2.max_x()))); auto & [ delta_3, h_3 ] = solutions[2]; CHECK(f(delta_3(h_3.min_x())) == Approx(h_3(h_3.min_x()))); CHECK(0 == Approx(h_3(h_3.max_x()))); auto & [ delta_4, h_4 ] = solutions[3]; CHECK(f(delta_4(h_4.min_x())) == Approx(h_4(h_4.min_x()))); CHECK(0 == Approx(h_4(h_4.max_x()))); auto & [ delta_5, h_5 ] = solutions[4]; CHECK(f(delta_5(h_5.min_x())) == Approx(h_5(h_5.min_x()))); CHECK(0 == Approx(h_5(h_5.max_x()))); } TEST_CASE("Regression test of linking to linear function with better slope", "[minimal compose]") { PiecewieseDecHypOrLinFunction lhs{ {{1479.6498021832708, 1508.0545022488018, LinearFunction{-33.333333, 51875.366170315174}}, {1508.0545022488018, 1509.6078191325887, HyperbolicFunction{59502.382604, 1463.008313, 1577.559577}}, {1509.6078191325887, 1518.3274208221796, HyperbolicFunction{95174.45446, 1455.110309, 1572.915411}}, {1518.3274208221796, 1519.778984471895, HyperbolicFunction{73.74026, 1512.521166, 1594.543118}}, {1519.778984471895, 1523.9688983996118, HyperbolicFunction{383.058819, 1507.209243, 1593.518556}}}}; PiecewieseDecLinearFunction pwf{ {{0.000000, 527.811766, LinearFunction{-6.062767, 0.000000, 4000.000000}}, {527.811766, 565.552943, LinearFunction{-5.299252, 527.811766, 800.000000}}, {565.552943, 617.035296, LinearFunction{-3.884826, 565.552943, 600.000000}}, {617.035296, 692.800001, LinearFunction{-2.639752, 617.035296, 400.000000}}, {692.800001, 917.270587, LinearFunction{-0.890985, 692.800001, 200.000000}}}}; StatefulPiecewieseDecLinearFunction cf{pwf}; std::vector<PiecewieseSolution> solutions; compose_minimal(lhs, cf, std::back_inserter(solutions)); CHECK(solutions.size() == 1); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(h_1.min_x() == Approx(1508.0545022488018)); CHECK(h_1(h_1.min_x()) == Approx(lhs(1508.0545022488018))); } TEST_CASE("Regression test from FPC dijkstra test - 1", "[minimal compose]") { PiecewieseDecHypOrLinFunction f{ {{1.450953, 10.000000, HyperbolicFunction{4000.000000, 0.000000, 100.000000}}}}; PiecewieseDecLinearFunction g{ {{0.000000, 4.000000, LinearFunction{-400.000000, 0.000000, 2000.000000}}, {4.000000, 12.000000, LinearFunction{-50.000000, 4.000000, 400.000000}}}}; StatefulPiecewieseDecLinearFunction stateful_g{g}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, stateful_g, std::back_inserter(solutions)); CHECK(solutions.size() == 2); auto & [ delta_1, h_1 ] = solutions[0]; auto & [ delta_2, h_2 ] = solutions[1]; CHECK(h_1.min_x() == Approx(2.7144176166)); CHECK(h_1(h_1.min_x()) == Approx(f(h_1.min_x()))); CHECK(h_2.min_x() == Approx(5.4288352332)); CHECK(h_2(h_2.min_x()) == Approx(f(h_2.min_x()))); CHECK(h_2(h_2.max_x()) == Approx(0.0)); } TEST_CASE("Regression test from FPC dijkstra test - 2", "[minimal compose]") { PiecewieseDecHypOrLinFunction f{ {{1.000000, 1.000000, LinearFunction{0.000000, 0.000000, 500.000000}}}}; PiecewieseDecLinearFunction g{ {{0.000000, 4.000000, LinearFunction{-400.000000, 0.000000, 2000.000000}}, {4.000000, 12.000000, LinearFunction{-50.000000, 4.000000, 400.000000}}}}; StatefulPiecewieseDecLinearFunction stateful_g{g}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, stateful_g, std::back_inserter(solutions)); CHECK(solutions.size() == 1); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(h_1.min_x() == Approx(1)); CHECK(h_1(h_1.min_x()) == Approx(f(h_1.min_x()))); CHECK(h_1(h_1.max_x()) == Approx(0.0)); } TEST_CASE("Regression test from FPC dijkstra test - 3", "[minimal compose]") { PiecewieseDecHypOrLinFunction f{ {{1.000000, 1.000000, LinearFunction{0.000000, 0.000000, 100.000000}}}}; PiecewieseDecLinearFunction g{ {{0.000000, 4.000000, LinearFunction{-400.000000, 0.000000, 2000.000000}}, {4.000000, 12.000000, LinearFunction{-50.000000, 4.000000, 400.000000}}}}; StatefulPiecewieseDecLinearFunction stateful_g{g}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, stateful_g, std::back_inserter(solutions)); CHECK(solutions.size() == 1); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(h_1.min_x() == Approx(1)); CHECK(h_1(h_1.min_x()) == Approx(f(h_1.min_x()))); CHECK(h_1(h_1.max_x()) == Approx(0.0)); } TEST_CASE("Composition ciritical point is not global minimum") { PiecewieseDecHypOrLinFunction lhs{ {{500, 700, LinearFunction{-6.333333, 0, 7075.36617031517}}, {700, 1450, LinearFunction{-3.333333, 0, 4975.366170315174}}}}; PiecewieseDecLinearFunction pwf{ {{0.000000, 527.811766, LinearFunction{-6.062767, 0.000000, 4000.000000}}, {527.811766, 565.552943, LinearFunction{-5.299252, 527.811766, 800.000000}}, {565.552943, 617.035296, LinearFunction{-3.884826, 565.552943, 600.000000}}, {617.035296, 692.800001, LinearFunction{-2.639752, 617.035296, 400.000000}}, {692.800001, 917.270587, LinearFunction{-0.890985, 692.800001, 200.000000}}}}; StatefulPiecewieseDecLinearFunction cf{pwf}; std::vector<PiecewieseSolution> solutions; compose_minimal(lhs, cf, std::back_inserter(solutions)); CHECK(solutions.size() == 2); auto & [ delta_1, h_1 ] = solutions[0]; auto & [ delta_2, h_2 ] = solutions[1]; CHECK(h_1.min_x() == Approx(700)); CHECK(h_1(h_1.min_x()) == Approx(lhs(h_1.min_x()))); CHECK(h_1(h_1.max_x()) == Approx(0.0).epsilon(0.001)); CHECK(h_2.min_x() == Approx(1450)); CHECK(h_2(h_2.min_x()) == Approx(lhs(h_2.min_x()))); CHECK(h_2(h_2.max_x()) == Approx(0.0).epsilon(0.001)); } TEST_CASE("Luxev node 3840 - Regression 1", "[compose_minimal]") { PiecewieseDecHypOrLinFunction f{ {{831.943906, 864.307012, HyperbolicFunction{25678788.073262, 576.634952, 1352.872133}}, {864.307012, 879.998096, HyperbolicFunction{48529213.479193, 508.642451, 1279.531867}}, {879.998096, 931.851598, HyperbolicFunction{55737980.421740, 491.096831, 1262.905327}}, {931.851598, 1007.950644, HyperbolicFunction{35859796.038277, 551.356371, 1302.132407}}, {1007.950644, 1060.210259, HyperbolicFunction{3441082.167333, 798.912181, 1395.391151}}, {1060.210259, 1157.167342, HyperbolicFunction{4746667.229624, 769.339010, 1389.687088}}}}; PiecewieseDecLinearFunction g{ {{0.000000, 96.000000, LinearFunction{-33.333333, 0.000000, 4000.000000}}}}; StatefulPiecewieseDecLinearFunction cf{g}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, cf, std::back_inserter(solutions)); CHECK(solutions.size() == 1); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(h_1.min_x() == Approx(831.9439)); CHECK(h_1(h_1.min_x()) == Approx(f(h_1.min_x()))); CHECK(h_1(h_1.max_x()) == Approx(800).epsilon(0.001)); } TEST_CASE("Luxev node 3840 - Regression 2", "[compose_minimal]") { PiecewieseDecHypOrLinFunction f{ {{959.982878, 1060.411220, HyperbolicFunction{266953356.627944, 581.089945, 2140.473477}}, {1060.411220, 1100.512812, HyperbolicFunction{289895401.647429, 567.734525, 2108.098250}}, {1100.512812, 1141.250370, HyperbolicFunction{307187111.879935, 557.345359, 2088.183152}}, {1141.250370, 1144.398619, HyperbolicFunction{330251.111271, 1081.433645, 2896.870850}}, {1144.398619, 1149.013667, HyperbolicFunction{1873616.521263, 1032.099116, 2831.603168}}, {1149.013667, 1160.454977, HyperbolicFunction{2444966.698858, 1021.252369, 2818.886466}}, {1160.454977, 1178.669793, HyperbolicFunction{3449568.608434, 1004.327988, 2803.545820}}, {1178.669793, 1181.196292, HyperbolicFunction{20.504422, 1174.880045, 2915.609229}}}}; PiecewieseDecLinearFunction g{ {{0.000000, 96.000000, LinearFunction{-33.333333, 0.000000, 4000.000000}}}}; StatefulPiecewieseDecLinearFunction cf{g}; std::vector<PiecewieseSolution> solutions; compose_minimal(f, cf, std::back_inserter(solutions)); CHECK(solutions.size() == 1); auto & [ delta_1, h_1 ] = solutions[0]; CHECK(h_1.min_x() == Approx(959.982878)); CHECK(h_1(h_1.min_x()) == Approx(f(h_1.min_x()))); CHECK(h_1(h_1.max_x()) == Approx(800).epsilon(0.001)); }
c7854389bef589e35252b977c5c2b29ca001371a
9fa46c7489fba285740fe0b0fd1acd330e469c79
/map.cpp
84ba50c57191e179f0b54362c32244528cfa852e
[]
no_license
NexusGrid/Sibir
44b72ac6efb290ae77819595bcc9a6917070fa3b
34bbad3e4ab2de6494033a3cee517e423afa4068
refs/heads/master
2020-03-16T00:15:06.953181
2018-05-28T00:13:31
2018-05-28T00:13:31
132,287,035
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
map.cpp
#include "map.h" #include <iostream> void map::setLength(int x) { mapLength = x; } void map::setHeight(int x) { mapHeight = x; } int map::getLength() { return mapLength; } int map::getHeight() { return mapHeight; } map::map() { mapLength = 20; mapHeight = 20; } map::~map() { } void map::initMap() { for(int i = 0; i < map::getHeight(); i++) { for(int j = 0 ; j < map::getLength(); j++) { screen[i][j] = ' '; } } } void map::printMap() { for(int i = 0; i < map::getHeight(); i++) { for(int j = 0 ; j < map::getLength(); j++) { std::cout << screen[i][j]; } std::cout << std::endl; } }
48855d9faa18f23d5b8845277350509570717b4f
76b2f3df691fa986d66f8e496ef87feec5f3eb25
/WakeMEup/Codes/RX_TX_WebServer/RX_TX_WebServer.ino
9107841c7dcd7aa6915518c1dc14e77a8ef62fad
[]
no_license
udareechk/Projects
45cfb0fbb789dbb71ccc64980a4640f7fd402353
46476c689e314698deca7513e5908f9c3790aa78
refs/heads/master
2021-01-12T10:52:27.329733
2017-08-31T13:33:25
2017-08-31T13:33:25
72,740,044
0
0
null
null
null
null
UTF-8
C++
false
false
5,457
ino
RX_TX_WebServer.ino
#include <ESP8266WiFi.h> #include <WiFiClient.h> // size of buffer used to capture HTTP requests #define REQ_BUF_SZ 90 // size of buffer that stores the incoming string #define TXT_BUF_SZ 50 const char* ssid = "WiFi iData_469C"; const char* password = "12345678"; WiFiServer server(80); const int ledPin = D12; // the pin that the LED is attached to const int configPin = D5; //int incomingByte; // a variable to read incoming serial data into //Variables to be sent to Mega char setHours = 11, setMins = 48, setMonths = 4, setDays = 22; int setYears = 2017; char alarmHour = 19, alarmMin = 15; char volume = 15; char snoozeHour, snoozeMin, snoozeTime = 1; String HTTP_req[REQ_BUF_SZ] = {}; // buffered HTTP request stored as null terminated string char req_index = 0; // index into HTTP_req buffer char txt_buf[TXT_BUF_SZ] = {0}; // buffer to save text to //Functions void webServerInit(); void webServerLoop(); bool readPinState(int pin); void handleSubmit(); void sendConfigData(); // sets every element of str to 0 (clears array) void StrClear(char *str, char length) { for (int i = 0; i < length; i++) { str[i] = 0; } } void setup() { // initialize serial communication: Serial.begin(9600); // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); pinMode(configPin, INPUT); digitalWrite(ledPin, LOW); digitalWrite(configPin, LOW); webServerInit(); } void loop() { //if(readPinState(configPin)){ if(digitalRead(configPin) == HIGH){ // webServerInit(); //digitalWrite(ledPin, HIGH); webServerLoop(); // digitalWrite(ledPin, LOW); } } void webServerInit(){ // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL : "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void webServerLoop(){ // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); while(!client.available()){ delay(1); } String request; // Read the first line of the request request = client.readStringUntil('\r\n'); Serial.println(request); client.flush(); // // Match the request int value = LOW; if (request.indexOf("/ALARM=ON") != -1) { int index = request.indexOf("/ALARM=ON"); Serial.println(index); Serial.println(request); request.concat( index = request.indexOf("HTTP"); Serial.println("HTTP index: "); Serial.println(index); // digitalWrite(ledPin, HIGH); // Serial.end(); // Serial.begin(11500); // Serial.print('H'); // delay(10000); // Serial.end(); value = HIGH; } if (request.indexOf("/ALARM=OFF") != -1){ digitalWrite(ledPin, LOW); // Serial.end(); // Serial.begin(11500); // Serial.print('L'); // delay(10000); // Serial.end(); value = LOW; } // if (request.indexOf("/submit") != -1){ //// handleSubmit(); // // } // server.on("/submit", handleSubmit); // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<head>"); client.println("<title>WakeMEup</title>"); client.println("</head>"); client.println("<body>"); client.println("<h1>WakeMEup</h1>"); client.println("<p>Alarm State:</p>"); if(value == HIGH) { client.print("ON"); } else { client.print("OFF"); } client.println("<br><br>"); client.println("Click <a href=\"/ALARM=ON\">here</a> turn the ALARM on pin 13 ON<br>"); client.println("Click <a href=\"/ALARM=OFF\">here</a> turn the ALARM on pin 13 OFF<br>"); client.println("<form action = \"/submit\" method = \"POST\">First name:<br><input type=\"text\" name=\"firstname\"><br></form>"); client.println("</html>"); delay(1); Serial.println("Client disconnected"); Serial.println(""); // client.stop(); // sendConfigData(); } bool readPinState(int pin){ return (digitalRead(pin) == HIGH); } void sendConfigData(){ Serial.end(); Serial.begin(11500); Serial.print(setHours); delay(5000); Serial.print(setMins); delay(5000); Serial.print(setMonths); delay(5000); Serial.print(setDays); delay(5000); Serial.print(setYears); delay(5000); Serial.print(alarmHour); delay(5000); Serial.print(alarmMin); delay(5000); Serial.print(volume); delay(5000); Serial.print(snoozeHour); delay(5000); Serial.print(snoozeMin); delay(5000); Serial.print(snoozeTime); delay(5000); Serial.end(); Serial.begin(9600); } // // void handleSubmit(){ // if (server.args() > 0 ) { // for ( uint8_t i = 0; i < server.args(); i++ ) { // if (server.argName(i) == "firstname") { // // Serial.println(server.arg(i)); // // do something here with value from server.arg(i); // } // } //} // }
d80f620e47a2a9fc07836a30c6846b348b894e30
39064b3c6307323d9b3e5c0e287622bd0c2b25bf
/LittleGame/idlist.h
16ccdc24c89431c72e51340abdc2f9406d318158
[]
no_license
yukyduky/LittleGame
b8cf0a298208bca56b0ef832bbc7288c42618516
f02a57a8bd3106e065163fccc4189e4264d4d895
refs/heads/master
2021-05-12T02:02:54.926686
2018-03-15T10:40:56
2018-03-15T10:40:56
117,570,550
1
0
null
null
null
null
UTF-8
C++
false
false
3,609
h
idlist.h
#pragma once #ifndef IDLIST_H #define IDLIST_H #include <list> #include <vector> #include <unordered_map> #include <queue> #include <functional> template<class T> class idlist { private: std::list<size_t> m_AvailableIDs; std::priority_queue<size_t, std::vector<size_t>, std::greater<size_t>> m_AvailableIndexes; std::unordered_map<size_t, size_t> m_IDToIndex; std::unordered_map<size_t, size_t> m_IndexToID; std::vector<typename T> m_Container; size_t m_NrOfElements; public: idlist(); idlist(const size_t size); size_t push(typename T element); void remove(const size_t id); void reserve(const size_t size); size_t capacity(); void clear(); T& getElementByID(const size_t id); bool empty(); size_t size(); T* data(); size_t peekNextID(); T& operator[](size_t id); }; template<class T> inline idlist<T>::idlist() : m_NrOfElements(0) { } template<class T> inline idlist<T>::idlist(const size_t size) : idlist() { this->resize(size); } template<class T> inline size_t idlist<T>::push(typename T element) { size_t index = m_NrOfElements; size_t id = index; if (m_AvailableIDs.empty()) { m_Container.push_back(element); m_IDToIndex.insert(m_IDToIndex.end(), std::pair<size_t, size_t>(id, index)); m_IndexToID.insert(m_IndexToID.end(), std::pair<size_t, size_t>(index, id)); } else { id = m_AvailableIDs.front(); m_AvailableIDs.pop_front(); index = m_AvailableIndexes.top(); m_AvailableIndexes.pop(); m_Container[index] = element; m_IDToIndex[id] = index; m_IndexToID[index] = id; } m_NrOfElements++; return id; } template<class T> inline void idlist<T>::remove(const size_t id) { size_t lastIndex = m_NrOfElements - 1; if (lastIndex == 0) { m_IDToIndex.erase(id); m_IndexToID.erase(lastIndex); m_AvailableIDs.push_front(id); m_AvailableIndexes.push(lastIndex); m_NrOfElements--; } else if (lastIndex != static_cast<size_t>(-1)) { // Get the index of the id to remove size_t holeIndex = m_IDToIndex.at(id); m_Container[holeIndex] = m_Container[lastIndex]; m_IDToIndex[m_IndexToID[lastIndex]] = holeIndex; m_IndexToID[holeIndex] = m_IndexToID[lastIndex]; m_IDToIndex.erase(id); m_IndexToID.erase(lastIndex); m_AvailableIDs.push_front(id); m_AvailableIndexes.push(lastIndex); m_NrOfElements--; } } template<class T> inline void idlist<T>::reserve(const size_t size) { m_Container.resize(size); m_IDToIndex.reserve(size); m_IndexToID.reserve(size); for (size_t i = m_NrOfElements + m_AvailableIDs.size(); i < size; i++) { m_AvailableIDs.push_back(i); m_AvailableIndexes.push(i); } } template<class T> inline size_t idlist<T>::capacity() { return m_Container.capacity(); } template<class T> inline void idlist<T>::clear() { m_Container.clear(); m_IDToIndex.clear(); m_IndexToID.clear(); m_AvailableIDs.clear(); for (size_t i = 0; i < m_AvailableIndexes.size(); i++) { m_AvailableIndexes.pop(); } m_NrOfElements = 0; } template<class T> inline T& idlist<T>::getElementByID(const size_t id) { return m_Container[m_IDToIndex.at(id)]; // TODOYE: Throw own exception } template<class T> inline bool idlist<T>::empty() { return m_IDToIndex.empty(); } template<class T> inline size_t idlist<T>::size() { return m_NrOfElements; } template<class T> inline T* idlist<T>::data() { return m_Container.data(); } template<class T> inline size_t idlist<T>::peekNextID() { return m_AvailableIDs.front(); } template<class T> inline T& idlist<T>::operator[](size_t index) { if (index >= m_NrOfElements) { throw("idlist - Subscript out of range"); } return m_Container[index]; } #endif
a70082ccecd311ce6d0d1f5374df020d7c0e859d
46f157b7257a89cec68132ec69c6443f5b7469a7
/ModelViewer/SubgridPage.h
a12b4191716f897fbd6f149aeb24ac2fa808feaa
[]
no_license
Phylian/modelview
08cbce6866df6fd3fcf888e7393fcf92af4d1a24
36e02312d46bbba7c72f02be6209a74b1a2afc15
refs/heads/master
2021-06-25T02:55:44.926109
2017-08-24T23:53:15
2017-08-24T23:53:15
100,531,819
0
0
null
null
null
null
UTF-8
C++
false
false
2,038
h
SubgridPage.h
#if !defined(AFX_SUBGRIDPAGE_H__C4133468_03FF_11D4_8108_00C04F61038F__INCLUDED_) #define AFX_SUBGRIDPAGE_H__C4133468_03FF_11D4_8108_00C04F61038F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // SubgridPage.h : header file // ///////////////////////////////////////////////////////////////////////////// // CSubgridPage dialog class CMvDoc; class CGridDlg; class CSubgridPage : public CPropertyPage { DECLARE_DYNCREATE(CSubgridPage) // Construction public: CSubgridPage(); ~CSubgridPage(); void Reinitialize(); void Activate(BOOL b); BOOL CustomUpdateData(BOOL b); void Apply(); CMvDoc *m_pDoc; CGridDlg *m_Parent; BOOL m_ExchangeData; BOOL m_ActivateSubgrid; int m_ilow; int m_ihigh; int m_jlow; int m_jhigh; int m_klow; int m_khigh; int m_imax; int m_jmax; int m_kmax; BOOL m_IsActive; BOOL m_2D; BOOL m_IrregularMesh; BOOL m_LayeredMesh; // Dialog Data //{{AFX_DATA(CSubgridPage) enum { IDD = IDD_SUBGRID }; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CSubgridPage) public: virtual BOOL OnSetActive(); protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CSubgridPage) virtual BOOL OnInitDialog(); afx_msg void OnActivateSubgrid(); afx_msg void OnDeltaposIlowSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposIhighSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposJlowSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposJhighSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposKlowSpin(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDeltaposKhighSpin(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SUBGRIDPAGE_H__C4133468_03FF_11D4_8108_00C04F61038F__INCLUDED_)
6f4aab59447dff06684c329b748455b632f7f62a
ae56ce265c64cfcabf9c8b2d8aaf3be0edf8ed4f
/lab01-05/src/ntree.h
e3f114308edcdcde9edf6aea7ab9287b9c0cb36d
[]
no_license
rod98/MAI_OOP
0af6cc682ed19c088cdf97921a0f7f88efd23e5c
be113661bb93e70de9bfde17dd7649a7ab68e127
refs/heads/master
2020-04-17T15:47:31.182605
2019-01-20T22:17:41
2019-01-20T22:17:41
166,713,403
0
0
null
null
null
null
UTF-8
C++
false
false
726
h
ntree.h
#ifndef NTREE_H #define NTREE_H #include <memory> #include "trap.h" template<class T> class Ntree { public: Ntree(); Ntree(std::shared_ptr<T>& val); Ntree(std::shared_ptr<T>&& val); ~Ntree(); void add(std::shared_ptr<T>& val, int *path); void add(std::shared_ptr<T>&& val, int *path); void del(int *path); std::shared_ptr<T> get_val(int *path); std::ostream& print(std::ostream& os, int depth); Ntree<T> *getNext(); Ntree<T> *getLast(); template<class A> friend std::ostream& operator<<(std::ostream& os, Ntree<A> &t); private: void add_child( std::shared_ptr<T>& val ); Ntree **ch; Ntree *par; int noc; int rsz; int crn; std::shared_ptr<T> val; }; #endif
aa12178a671273ef75bc561a4338c12ae6a5599a
417836b8bca49dfbd0f55fcc616161fb97b87ba7
/ my-simple-code/src/mysdk/database/mysql/QueryResult.cc
3cb2704b76a513dc72a0905ac0aec159647a41b6
[]
no_license
befollow/cppGameFrame
636c729d4fe4b44b36e4d2190773b0a4ec0e0ea1
c494a489e0cdde7e95712fd543b709cb33586bb4
refs/heads/master
2020-03-20T08:51:16.215723
2015-03-19T06:44:49
2015-03-19T06:44:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
947
cc
QueryResult.cc
#include <mysdk/database/mysql/QueryResult.h> using namespace mysdk; ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount): m_rowCount(rowCount), m_fieldCount(fieldCount), m_result(result), m_fields(fields) { m_currentRow = new Field[m_fieldCount]; assert(m_currentRow); } ResultSet::~ResultSet() { cleanUp(); } bool ResultSet::nextRow() { MYSQL_ROW row; if (!m_result) { return false; } row = mysql_fetch_row(m_result); if (!row) { cleanUp(); return false; } for (uint32 i = 0; i < m_fieldCount; i++) { m_currentRow[i].setStructuredValue(row[i], m_fields[i].type); } return true; } void ResultSet::cleanUp() { if (m_currentRow) { delete[] m_currentRow; m_currentRow = NULL; } if (m_result) { mysql_free_result(m_result); m_result = NULL; } }
2f4365a36d5f7943e01368f842e024a196a78f9b
287a97cf97fd9f3108452789e9537522c064ff97
/_old/template_v1/数学/lucas_std.cpp
414051cbe3a4d56885f50166fe61c9599c08fa43
[]
no_license
mollnn/XCPCHandbook
4e083c872f8ddcf83bd9cc2132d7c2f62af1f303
acc6f07521bf59927ba762ba953c0e4ea647cc42
refs/heads/main
2023-03-31T11:25:34.593525
2021-04-02T05:08:18
2021-04-02T05:08:18
331,952,549
0
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
lucas_std.cpp
// Lucas std // input n,m,p // output C(m,n+m) mod p // p is a prime, O(p*log(n)/log(p)) #include<bits/stdc++.h> #define N 100010 using namespace std; typedef long long ll; ll a[N]; int p; ll pow(ll y,int z,int p){ y%=p;ll ans=1; for(int i=z;i;i>>=1,y=y*y%p)if(i&1)ans=ans*y%p; return ans; } ll C(ll n,ll m){ if(m>n)return 0; return ((a[n]*pow(a[m],p-2,p))%p*pow(a[n-m],p-2,p)%p); } ll Lucas(ll n,ll m){ if(!m)return 1; return C(n%p,m%p)*Lucas(n/p,m/p)%p; } int main(){ cin>>T; while(T--){ cin>>n>>m>>p; a[0]=1; for(int i=1;i<=p;i++)a[i]=(a[i-1]*i)%p; cout<<Lucas(n+m,n)<<endl; } }
ea031b8012083a64ee0341b06820dd08cedd50e4
a7764174fb0351ea666faa9f3b5dfe304390a011
/src/RWStepRepr/RWStepRepr_RWCompoundRepresentationItem.cxx
cab5229eed22fc7ef404c060e8a217c5ba29595c
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
cxx
RWStepRepr_RWCompoundRepresentationItem.cxx
#include <RWStepRepr_RWCompoundRepresentationItem.ixx> #include <TCollection_HAsciiString.hxx> #include <StepRepr_HArray1OfRepresentationItem.hxx> #include <StepRepr_RepresentationItem.hxx> RWStepRepr_RWCompoundRepresentationItem::RWStepRepr_RWCompoundRepresentationItem () { } void RWStepRepr_RWCompoundRepresentationItem::ReadStep (const Handle(StepData_StepReaderData)& data, const Standard_Integer num, Handle(Interface_Check)& ach, const Handle(StepRepr_CompoundRepresentationItem)& ent) const { // --- Number of Parameter Control --- if (!data->CheckNbParams(num,2,ach,"compound_representation_item")) return; // --- inherited field : name --- Handle(TCollection_HAsciiString) aName; //szv#4:S4163:12Mar99 `Standard_Boolean stat1 =` not needed data->ReadString (num,1,"name",ach,aName); // --- own field : item_element Handle(StepRepr_HArray1OfRepresentationItem) aItems; Handle(StepRepr_RepresentationItem) anent2; Standard_Integer nsub2; if (data->ReadSubList (num,2,"item_element",ach,nsub2)) { Standard_Integer nb2 = data->NbParams(nsub2); aItems = new StepRepr_HArray1OfRepresentationItem (1, nb2); for (Standard_Integer i2 = 1; i2 <= nb2; i2 ++) { if (data->ReadEntity(nsub2, i2,"representation_item", ach, STANDARD_TYPE(StepRepr_RepresentationItem), anent2)) aItems->SetValue(i2, anent2); } } ent->Init (aName,aItems); } void RWStepRepr_RWCompoundRepresentationItem::WriteStep (StepData_StepWriter& SW, const Handle(StepRepr_CompoundRepresentationItem)& ent) const { // --- inherited field : name --- SW.Send(ent->Name()); // --- own field : items --- SW.OpenSub(); for (Standard_Integer i2 = 1; i2 <= ent->NbItemElement(); i2 ++) { SW.Send(ent->ItemElementValue(i2)); } SW.CloseSub(); } void RWStepRepr_RWCompoundRepresentationItem::Share (const Handle(StepRepr_CompoundRepresentationItem)& ent, Interface_EntityIterator& iter) const { Standard_Integer i, nb = ent->NbItemElement(); for (i = 1; i <= nb; i ++) iter.AddItem (ent->ItemElementValue(i)); }
e871052e712e4c0d64f025fc6c69b39e7da5da3a
2292df0f8b4670bb979b92b4e797fb31686be083
/面向对象基本案例/main.cpp
7252f07c1a89d3d655ab405694ac9da30e4d48d5
[]
no_license
LiuYiZhou95/LeetCode
25877207a15283d9aa1885d3be6eb428aebedfca
2bcbdac2b5fed4f46fff30951cabc2ddbbc45ffe
refs/heads/master
2020-08-27T19:47:43.276752
2019-10-25T07:24:54
2019-10-25T07:24:54
217,474,743
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
main.cpp
// // main.cpp // 面向对象基本案例 // // Created by B612 on 2019/10/18. // Copyright © 2019年 action.zhou. All rights reserved. // #include <iostream> #include "Audience.h" #include "Comedy.h" int main(int argc, const char * argv[]) { // insert code here... Audience * audience=new Audience(); Comedy* comedy=new Comedy(); audience->watch(comedy); return 0; }
daed7a793b48c6ee5bad4084136799c36c30a4bb
5a44b5f9712ae3cead027d735bc5568a6c132679
/testing/old_openFoam/openFoam1/shallow/shallow50/0.1/p
56844c5d2ac965f135d37a5fd96d92c70f9d08eb
[]
no_license
georgenewman10/cfd
d12e86198ac8e8bf7345a0fc20311c0b94bbeda0
1d8faa9d852545f16920c2b02273a68af9db19ae
refs/heads/master
2022-01-06T00:26:14.191816
2019-05-23T14:54:09
2019-05-23T14:54:09
170,887,037
0
1
null
null
null
null
UTF-8
C++
false
false
8,867
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6.0 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.1"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 800 ( 1.8784e-08 -0.00221548 -0.00536856 -0.00839047 -0.0106144 -0.0117257 -0.0116283 -0.0103461 -0.00795553 -0.00454782 -0.000209346 0.00498736 0.0109868 0.0177505 0.0252554 0.0334914 0.0424601 0.0521738 0.0626541 0.0739284 0.0860255 0.0989687 0.112768 0.127408 0.14284 0.158961 0.175601 0.192503 0.209314 0.225578 0.240745 0.254204 0.265329 0.273561 0.278504 0.280034 0.278425 0.274458 0.269532 0.265712 0.00217588 -0.000109914 -0.00260059 -0.00476901 -0.00628487 -0.00691925 -0.00657426 -0.00523667 -0.00293483 0.000286589 0.00437987 0.00930169 0.0150174 0.0215019 0.0287382 0.0367171 0.045437 0.0549031 0.0651263 0.0761201 0.0878962 0.100459 0.113797 0.127879 0.142638 0.157962 0.17368 0.189551 0.205252 0.220377 0.234452 0.246958 0.257378 0.265264 0.270316 0.272469 0.271983 0.269472 0.265749 0.261924 0.00540006 0.00223424 -0.000346961 -0.0022267 -0.00341215 -0.00378081 -0.00327234 -0.00188065 0.000380003 0.00348681 0.00741445 0.0121398 0.0176438 0.0239113 0.0309304 0.0386929 0.047195 0.0564373 0.0664237 0.0771587 0.0886441 0.100875 0.113831 0.127476 0.141741 0.156519 0.171649 0.18691 0.202006 0.216567 0.23016 0.242307 0.252529 0.260404 0.265636 0.268133 0.268091 0.265971 0.26208 0.256899 0.00862872 0.00424084 0.00117396 -0.000757327 -0.00186304 -0.00212237 -0.00152646 -9.74392e-05 0.00214392 0.00518122 0.00900077 0.0135918 0.0189451 0.0250518 0.0319029 0.0394902 0.0478079 0.0568524 0.0666221 0.077116 0.088331 0.100259 0.112881 0.126164 0.140049 0.154444 0.169209 0.184149 0.198996 0.213411 0.226978 0.239229 0.249675 0.257858 0.263424 0.266196 0.266272 0.26398 0.259258 0.25224 0.0110401 0.0053881 0.0017236 -0.000383984 -0.00151245 -0.00173354 -0.00108928 0.000367025 0.00260196 0.00559958 0.0093529 0.0138584 0.0191123 0.0251083 0.0318379 0.0392912 0.0474583 0.0563305 0.0659004 0.0761621 0.0871102 0.098737 0.11103 0.123964 0.1375 0.151567 0.166056 0.180806 0.195585 0.210085 0.223909 0.236584 0.247586 0.256392 0.262546 0.265745 0.265965 0.263405 0.257718 0.248861 0.0120086 0.00514068 0.000859565 -0.00146824 -0.00266028 -0.00286955 -0.00218472 -0.000689227 0.00157032 0.00457575 0.00832252 0.0128097 0.0180345 0.0239898 0.0306645 0.0380439 0.0461118 0.0548523 0.0642516 0.0742997 0.0849898 0.0963175 0.108279 0.120865 0.134057 0.147818 0.162077 0.176717 0.191552 0.206313 0.220626 0.234012 0.245903 0.255687 0.262773 0.266691 0.267255 0.264524 0.257909 0.247283 0.0110248 0.00300985 -0.00185951 -0.00439526 -0.00563593 -0.00581005 -0.00504908 -0.00346439 -0.00111503 0.00197679 0.00580504 0.0103672 0.0156578 0.0216653 0.0283723 0.0357564 0.0437922 0.0524552 0.061725 0.0715873 0.0820349 0.0930684 0.104694 0.116924 0.129766 0.14322 0.157262 0.171831 0.186798 0.201945 0.216935 0.231292 0.244406 0.255563 0.264008 0.269061 0.270318 0.267661 0.260245 0.247891 0.00764053 -0.00146229 -0.00685865 -0.00953252 -0.0107413 -0.0107923 -0.00985967 -0.0080813 -0.00552901 -0.00223126 0.00180131 0.00656154 0.012038 0.0182116 0.0250554 0.0325362 0.040618 0.0492675 0.0584573 0.0681691 0.0783961 0.0891442 0.100433 0.112295 0.124769 0.137897 0.151709 0.166208 0.181337 0.196944 0.212747 0.228294 0.242951 0.255904 0.266214 0.27294 0.275399 0.273214 0.265205 0.251115 0.00142347 -0.00873988 -0.0145718 -0.0172444 -0.018259 -0.0180144 -0.0167345 -0.0145867 -0.011658 -0.00798527 -0.00358559 0.00152706 0.00733303 0.0138032 0.020899 0.0285758 0.0367876 0.0454923 0.0546567 0.064259 0.0742935 0.0847725 0.0957291 0.107217 0.119307 0.132086 0.145643 0.160051 0.175334 0.191429 0.208132 0.225047 0.241542 0.256727 0.269474 0.278539 0.282879 0.281737 0.273444 0.257574 -0.0080938 -0.0193377 -0.0254681 -0.0278975 -0.0284374 -0.0276093 -0.0257015 -0.0229201 -0.0193708 -0.0150995 -0.0101301 -0.00448395 0.00181071 0.00871463 0.0161789 0.0241492 0.0325716 0.0413982 0.0505911 0.0601274 0.0700031 0.0802382 0.0908789 0.102 0.113705 0.126124 0.139405 0.153695 0.16911 0.18569 0.203338 0.221752 0.240349 0.258202 0.274014 0.286218 0.293316 0.294014 0.285905 0.268213 -0.0214934 -0.033891 -0.040088 -0.0418625 -0.0414677 -0.0396059 -0.0366556 -0.0328718 -0.0283806 -0.0232354 -0.0174632 -0.0110889 -0.00414597 0.00332063 0.0112564 0.0196026 0.0283021 0.0373049 0.0465725 0.056083 0.0658369 0.075862 0.0862182 0.0970007 0.108342 0.120415 0.133423 0.147588 0.16312 0.180174 0.198788 0.218794 0.239718 0.260663 0.280219 0.296503 0.307483 0.311131 0.303936 0.284445 -0.0396114 -0.0532675 -0.0590954 -0.0595103 -0.0574473 -0.0538788 -0.0493043 -0.0440336 -0.0382078 -0.0318764 -0.0250584 -0.0177713 -0.0100431 -0.00191466 0.00656348 0.0153364 0.0243511 0.0335613 0.0429325 0.0524476 0.062114 0.0719693 0.0820868 0.0925808 0.103611 0.115387 0.128164 0.142233 0.157897 0.175435 0.195036 0.216711 0.240159 0.264608 0.288635 0.310099 0.326399 0.33456 0.329462 0.308395 -0.0638091 -0.0787514 -0.0833416 -0.0811902 -0.0763149 -0.0700709 -0.0630967 -0.0557442 -0.0481427 -0.0403096 -0.0322298 -0.0238905 -0.0152945 -0.00646166 0.00257499 0.0117758 0.0211004 0.0305134 0.0399896 0.0495212 0.0591251 0.0688505 0.0787847 0.0890597 0.0998593 0.111425 0.124056 0.138106 0.153967 0.17204 0.192681 0.216114 0.24228 0.270648 0.299931 0.327873 0.351354 0.366262 0.365228 0.343313 -0.0965372 -0.112348 -0.113915 -0.107146 -0.0977235 -0.0874697 -0.0771274 -0.067027 -0.0572177 -0.0476249 -0.0381505 -0.0287132 -0.0192605 -0.00976848 -0.000235488 0.00932644 0.0188989 0.0284636 0.03801 0.047543 0.0570921 0.0667191 0.0765252 0.0866588 0.0973243 0.10879 0.121394 0.135544 0.151713 0.170424 0.192206 0.217519 0.24662 0.279342 0.314748 0.350724 0.383831 0.408754 0.41518 0.394394 -0.142528 -0.157253 -0.152081 -0.137268 -0.120778 -0.1048 -0.0900002 -0.0765213 -0.0641915 -0.0527367 -0.0418982 -0.0314713 -0.0213104 -0.0113225 -0.00145403 0.00832123 0.0180136 0.0276267 0.0371671 0.0466547 0.0561322 0.0656739 0.0753938 0.085454 0.0960763 0.107552 0.12025 0.134629 0.151237 0.170711 0.193756 0.221092 0.253352 0.290882 0.333352 0.379213 0.425178 0.464993 0.484936 0.470305 -0.211063 -0.218408 -0.198964 -0.170627 -0.14365 -0.119971 -0.09971 -0.0824698 -0.0676059 -0.0544789 -0.0425652 -0.0314729 -0.0209264 -0.0107424 -0.00080557 0.00895359 0.0185754 0.0280853 0.0375061 0.0468707 0.0562328 0.0656764 0.0753245 0.0853496 0.0959863 0.107544 0.12042 0.135115 0.152244 0.172555 0.196928 0.226366 0.261942 0.30466 0.355129 0.412982 0.475985 0.537835 0.581941 0.585291 -0.320294 -0.302817 -0.254961 -0.20513 -0.163445 -0.130123 -0.103839 -0.0830034 -0.0660999 -0.0519084 -0.0395301 -0.028334 -0.0178938 -0.00793208 0.0017254 0.0111847 0.0205092 0.0297391 0.0389069 0.0480524 0.057234 0.0665394 0.0760949 0.0860777 0.0967298 0.108372 0.121422 0.136413 0.154018 0.175086 0.200669 0.232067 0.27086 0.318882 0.378095 0.450176 0.535325 0.629041 0.715228 0.762503 -0.512488 -0.419165 -0.316106 -0.23496 -0.174785 -0.130996 -0.0994091 -0.076242 -0.0586013 -0.0445022 -0.0326255 -0.0221064 -0.0123918 -0.00313804 0.00586237 0.0147303 0.0235344 0.0323145 0.0411006 0.0499283 0.0588515 0.0679526 0.0773531 0.0872266 0.0978131 0.109435 0.122515 0.137603 0.155408 0.176847 0.203115 0.235782 0.276947 0.329425 0.397005 0.484556 0.596766 0.735152 0.89696 1.05126 -0.903153 -0.571331 -0.354533 -0.235147 -0.160138 -0.111083 -0.0791984 -0.0578121 -0.0425381 -0.0307968 -0.021059 -0.0123995 -0.00426631 0.00365883 0.0115505 0.0194973 0.0275377 0.0356849 0.0439453 0.052333 0.0608823 0.0696569 0.0787601 0.0883475 0.0986412 0.109945 0.122661 0.137319 0.154613 0.175453 0.201052 0.233075 0.273893 0.327033 0.398052 0.4958 0.632701 0.828148 1.13532 1.5725 -1.61159 -0.716833 -0.31373 -0.168752 -0.0988585 -0.0595555 -0.0377181 -0.0250379 -0.0167098 -0.0103559 -0.00477805 0.000658494 0.0062806 0.0122372 0.0185765 0.025291 0.0323454 0.0396938 0.047294 0.0551191 0.0631665 0.0714655 0.0800852 0.0891459 0.0988324 0.109406 0.121218 0.134734 0.150565 0.16951 0.192626 0.221356 0.25778 0.305141 0.369109 0.460605 0.601201 0.843949 1.36346 2.37679 ) ; boundaryField { movingWall { type zeroGradient; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
82ac7e63c3ee8d3264de49fc13f4f909be92492b
a5a04c9377fa7d405788045ea4d3ae49eaa74ec5
/src/bl_program.cpp
c6533db815ff494a09530bada72ddec406207d9d
[]
no_license
bonnefoa/bull
895256852b0f06d5c749252f4e2b59724a1007d5
8ffb35819bd3f6dc42dff75c221e8ca84f34cfc7
refs/heads/master
2020-03-30T17:22:49.790294
2013-07-12T08:02:27
2013-07-12T08:02:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
bl_program.cpp
#include "bl_program.h" #include <stdio.h> #include <bl_util.h> #include <bl_log.h> void BlProgram::loadProgram() { if (programId == 0) { programId = glCreateProgram(); INFO("Initialized program with id %d\n", programId); } else { for(unsigned int i = 0; i < shaders.size(); i++) { glDetachShader(programId, (*shaders[i]).shaderId); } } GLint programOk; for(unsigned int i = 0; i < shaders.size(); i++){ GLuint shaderId = (*shaders[i]).loadShader(); if(shaderId==0) { exit(1); } glAttachShader(programId, shaderId); } glLinkProgram(programId); glGetProgramiv(programId, GL_LINK_STATUS, &programOk); if(!programOk) { INFO("Failed to link shader program:\n"); showInfoLog(programId, glGetProgramiv, glGetProgramInfoLog); glDeleteProgram(programId); } } BlProgram::~BlProgram(void) { INFO("Deleting program %i\n", programId); glDeleteProgram(programId); for (std::vector<BlShader*>::iterator it = shaders.begin(); it != shaders.end(); ++it) { delete (*it); } }
daf3a94598bdc1bdc27551a10b37609f744bd26f
987de44706784422b68b9e38623dc053e312f721
/main.cpp
26dcb56c02f130a299939db34ef7aa01f047af33
[]
no_license
YMYmiemie/taobao
e93a8ace4690ab496a13e5fbb2c06b92a1af057c
591d3c790278436574689f083db9ac8fd8c562d2
refs/heads/master
2020-04-21T08:47:21.548868
2019-02-26T07:52:40
2019-02-26T07:52:40
169,429,665
0
0
null
null
null
null
GB18030
C++
false
false
2,500
cpp
main.cpp
#pragma once #include"admin.h" #include<iostream> using namespace std; int main() { int n(0); cout << "欢迎进入网点购物管理系统" << endl; cout << "==========================================" << endl; cout << "1.用户登录 2.用户注册 3.管理员登录 4.退出" << endl; cout << "==========================================" << endl; cout << "输入操作:"; cin >> n; while (n != 4) { if (n == 1) { User user1; if (user1.userID_cheak()){ int n = 0; cout << "========================================================================================" << endl; cout << "0.注销登陆 1.查看商品 2.商品搜索 3.添加商品至购物车 4.删除购物车商品 5.查看购物车 6.结账" << endl; cout << "========================================================================================" << endl; cout << "输入操作:"; cin >> n; while (n != 0) { if (n == 1) { user1.view_store_list(); } else if (n == 2) { user1.search_goods(); } else if (n == 3) { user1.add_shop_list(); } else if (n == 4) { user1.drop_shop_list(); } else if (n == 5) { user1.view_shop_list(); } else if (n == 6) { user1.pay(); } else { cout << "操作非法!" << endl; } cout << "输入操作:"; cin >> n; } } } else if (n == 2) { User user2; user2.userID_create(); } else if (n == 3) { Admin admin1; if (admin1.IDcheak()) { int n = 0; cout << "======================================================================" << endl; cout << "0.注销登陆 1.查询商品 2.增加商品 3.删除商品 4.修改商品 5.售货清单" << endl; cout << "======================================================================" << endl; cout << "输入操作:"; cin >> n; while (n != 0) { if (n == 1) { admin1.output_store_list(); } else if (n == 2) { admin1.input_goods(); } else if (n == 3) { admin1.drop_goods(); } else if (n == 4) { admin1.modify_goods(); } else if (n == 5) { admin1.output_sold_list(); } else { cout << "操作数错误!" << endl; } cout << "输入操作:"; cin >> n; } } } } return 0; }
04793c369401acd43fffe40c240abe71ca886aac
87636ec4189f02435221d4705386383445511001
/brown-ros-pkg-read-only/experimental/rlrobot/icreate_nav/src/.svn/text-base/rlglue_icreate_env_codec.cpp.svn-base
0debc296c847e6e87fe3c56bdaff26b26c940948
[]
no_license
mainchuh/ROSMAV
349bfc6b2bff4869b17a357ccdc44177aefd174e
8988d98c45b6599ddc38dcc2f1e0c7d8b1f27f36
refs/heads/master
2021-01-21T15:57:29.119669
2013-05-13T13:05:57
2013-05-13T13:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,847
rlglue_icreate_env_codec.cpp.svn-base
/** This is a copy of RL_client_environment for the irobot_createa couple of specific calls filled in. To customize the codec, just look for places where default calls are happening, like: env_init, env_start, env_step, etc, etc.. and then write a bit of code to emulate the same behavior using whatever project you are hooking into. All of the inserted code is commented. All of the previous code in here has been commented out like:*/ /* CUT-FOR-CUSTOMIZATION: env_init();*/ #include <assert.h> /* assert */ #include <unistd.h> /* sleep */ #include <stdio.h> /* fprintf */ #include <stdlib.h> /* calloc, getenv, exit */ #include <string.h> /* strlen */ /* I'm sorry about using strlen. */ #include <ctype.h> /* isdigit */ #include <netdb.h> /* gethostbyname */ #include <arpa/inet.h> /* inet_ntoa */ //#include <rlglue/Environment_common.h> //#include <rlglue/network/RL_network.h> /* Our project specific include */ #include "../include/icreate_glue.h" /* Include the utility methods*/ //#include <rlglue/utils/C/RLStruct_util.h> /* State variable for TheGame that is not exposed with function calls */ //using namespace std; /* GLOBAL VARIABLES FOR RL-GLUE methods (global for convenience) */ /* TO DO: Move to a Reward function file*/ //#define GOAL_LOWX 0 //#define GOAL_HIGHX 1 //#define GOAL_LOWY 0 //#define GOAL_HIGHY 1 //double GOAL_LOWX=3.3; //double GOAL_HIGHX=3.6; //double GOAL_LOWY=0; //double GOAL_HIGHY=.5; //double GOAL_LOWYAW=2; //double GOAL_HIGHYAW=3.5; double GOAL_LOWX=0; double GOAL_HIGHX=1; double GOAL_LOWY=3; double GOAL_HIGHY=4; double GOAL_LOWYAW=1; double GOAL_HIGHYAW=1.7; static const char* kUnknownMessage = "Unknown Message: %s\n"; static action_t theAction = {0}; static rlBuffer theBuffer = {0}; static char* theInMessage = 0; static unsigned int theInMessageCapacity = 0; /*Added as a global variable because now we must allocate and fill up the data structures instead of the environment.*/ static observation_t globalObservation = {0}; static void onEnvInit(int theConnection) { /* CUT-FOR-CUSTOMIZATION: char* theTaskSpec = 0;*/ unsigned int theTaskSpecLength = 0; unsigned int offset = 0; static char* theTaskSpec="VERSION RL-Glue-3.0 PROBLEMTYPE episodic DISCOUNTFACTOR 1 OBSERVATIONS DOUBLES (2 -2.0 10.0) (-2.0 2.0) ACTIONS INTS (0 3) REWARDS (-1.0 10.0) EXTRA iRobotCreate (C/C++) by Sarah Osentoski."; if (theTaskSpec!=NULL) { theTaskSpecLength = strlen(theTaskSpec);//.length(); printf("TaskSpecLength %d\n", theTaskSpecLength); } /* Prepare the buffer for sending data back to the server */ rlBufferClear(&theBuffer); offset = rlBufferWrite(&theBuffer, offset, &theTaskSpecLength, 1, sizeof(int)); if (theTaskSpecLength > 0) { offset = rlBufferWrite(&theBuffer, offset, theTaskSpec, theTaskSpecLength, sizeof(char)); } } static void onEnvStart(int theConnection, ros::Rate loop_rate) { /* CUT-FOR-CUSTOMIZATION: observation_t globalObservation = {0}; */ static observation_t this_observation; /*alocate space to store the observation*/ /*TODO needs to be changed to take a variable number of vars*/ allocateRLStruct(&this_observation, 0, 3, 0); unsigned int offset = 0; /* Call the start environment and get new variables */ /*TODO also needs to be changed to not be variable specific*/ position_tracker::Position ros_observation=start_environment(loop_rate); this_observation.doubleArray[0]=ros_observation.x; this_observation.doubleArray[1]=ros_observation.y; this_observation.doubleArray[2]=ros_observation.theta; /*send to RL-glue*/ __RL_CHECK_STRUCT(&this_observation) rlBufferClear(&theBuffer); offset = rlCopyADTToBuffer(&this_observation, &theBuffer, offset); printf("onEnvStart \n"); } static void onEnvStep(int theConnection, ros::Rate loop_rate, ros::ServiceClient client) { static reward_observation_terminal_t ro;// = {0}; unsigned int offset = 0; /* Create an integer variable to hold the action from the agent*/ int theIntAction=0; printf("onEnvStep\n"); offset = rlCopyBufferToADT(&theBuffer, offset, &theAction); __RL_CHECK_STRUCT(&theAction); assert(theAction.numInts==1); assert(theAction.intArray[0]>=0); assert(theAction.intArray[0]<4); /*I know to only expect 1 integer action*/ theIntAction=theAction.intArray[0]; /*This is our hook into the robot */ printf("about to go in\n"); position_tracker::Position tempobs=take_step(theIntAction, loop_rate, client); printf("finished\n"); ro=convertObservation(tempobs); ro.reward=calculateReward(tempobs); ro.terminal=checkTerminal(tempobs); __RL_CHECK_STRUCT(ro.observation) rlBufferClear(&theBuffer); offset = 0; offset = rlBufferWrite(&theBuffer, offset, &ro.terminal, 1, sizeof(int)); offset = rlBufferWrite(&theBuffer, offset, &ro.reward, 1, sizeof(double)); offset = rlCopyADTToBuffer(ro.observation, &theBuffer, offset); } static void onEnvCleanup(int theConnection) { /*No game specific cleanup to do*/ /* CUT-FOR-CUSTOMIZATION: env_cleanup();*/ rlBufferClear(&theBuffer); /* Clean up globalObservation global we created*/ clearRLStruct(&globalObservation); clearRLStruct(&theAction); /*It's ok to free null pointers, so this is safe */ free( theInMessage); theInMessage = 0; theInMessageCapacity = 0; } static void onEnvMessage(int theConnection) { unsigned int inMessageLength = 0; unsigned int outMessageLength = 0; char *inMessage=0; /*We set this to a string constant instead of null*/ char *outMessage="sample custom codec integration has no messages!"; unsigned int offset = 0; offset = 0; offset = rlBufferRead(&theBuffer, offset, &inMessageLength, 1, sizeof(int)); if (inMessageLength >= theInMessageCapacity) { inMessage = (char*)calloc(inMessageLength+1, sizeof(char)); free(theInMessage); theInMessage = inMessage; theInMessageCapacity = inMessageLength; } if (inMessageLength > 0) { offset = rlBufferRead(&theBuffer, offset, theInMessage, inMessageLength, sizeof(char)); } /*Make sure to null terminate the string */ theInMessage[inMessageLength]='\0'; /* CUT-FOR-CUSTOMIZATION: outMessage = env_message(theInMessage);*/ if (outMessage != NULL) { outMessageLength = strlen(outMessage); } /* we want to start sending, so we're going to reset the offset to 0 so we write the the beginning of the buffer */ rlBufferClear(&theBuffer); offset = 0; offset = rlBufferWrite(&theBuffer, offset, &outMessageLength, 1, sizeof(int)); if (outMessageLength > 0) { offset = rlBufferWrite(&theBuffer, offset, outMessage, outMessageLength, sizeof(char)); } } void runEnvironmentEventLoop(int theConnection, ros::Rate loop_rate, ros::ServiceClient client) { int envState = 0; printf("In event loop \n"); do { rlBufferClear(&theBuffer); rlRecvBufferData(theConnection, &theBuffer, &envState); printf("envstate %d\n", envState); printf("envInit %d, EnvStart %d, kEnvStep %d, kEnvCleanup %d, \n",kEnvInit, kEnvStart, kEnvStep, kEnvCleanup); switch(envState) { case kEnvInit: onEnvInit(theConnection); break; case kEnvStart: onEnvStart(theConnection, loop_rate); break; case kEnvStep: onEnvStep(theConnection, loop_rate, client); break; case kEnvCleanup: onEnvCleanup(theConnection); break; case kEnvMessage: onEnvMessage(theConnection); break; case kRLTerm: break; default: fprintf(stderr, kUnknownMessage, envState); exit(0); break; }; rlSendBufferData(theConnection, &theBuffer, envState); } while (envState != kRLTerm); } /*This used to be the main method, I've renamed it and cut a bunch of stuff out*/ int setup_rlglue_network() { int theConnection = 0; struct hostent *host_ent; char *host = kLocalHost; short port = kDefaultPort; char *envptr =0; host = getenv("RLGLUE_HOST"); if (host == 0) { host = kLocalHost; } envptr = getenv("RLGLUE_PORT"); if (envptr != 0) { port = strtol(envptr, 0, 10); if (port == 0) { port = kDefaultPort; } } if (isalpha(host[0])) { /*This method is apparently deprecated, we should update at some point*/ host_ent = gethostbyname(host); if(host_ent==0){ fprintf(stderr,"Couldn't find IP address for host: %s\n",host); exit(55); } host = inet_ntoa(*(struct in_addr*)host_ent->h_addr_list[0]); } // fprintf(stdout, "RL-Glue C Environment Codec Version %s, Build %s\n\tConnecting to host=%s on port=%d...\n", VERSION,__rlglue_get_codec_svn_version(),host, port); //fflush(stdout); printf("RL-Glue sample env custom codec integration.\n"); /* Allocate what should be plenty of space for the buffer - it will dynamically resize if it is too small */ rlBufferCreate(&theBuffer, 4096); printf("RL-glue about to wait for connection \n"); theConnection = rlWaitForConnection(host, port, kRetryTimeout); printf("\tSample custom env codec :: Connected\n"); rlBufferClear(&theBuffer); rlSendBufferData(theConnection, &theBuffer, kEnvironmentConnection); return theConnection; } void teardown_rlglue_network(int theConnection){ rlClose(theConnection); rlBufferDestroy(&theBuffer); } /****** Helper Functions ****/ reward_observation_terminal_t convertObservation(position_tracker::Position observation){ static observation_t this_observation; static reward_observation_terminal_t this_reward_observation; allocateRLStruct(&this_observation, 0, 3, 0); this_reward_observation.observation=&this_observation; this_reward_observation.observation->doubleArray[0]=observation.x; this_reward_observation.observation->doubleArray[1]=observation.y; this_reward_observation.observation->doubleArray[2]=observation.theta; return this_reward_observation; } double calculateReward(position_tracker::Position observation){ double distance; if(observation.x>=GOAL_LOWX && observation.x<=GOAL_HIGHX && observation.y>=GOAL_LOWY && observation.y <= GOAL_HIGHY && fabs(observation.theta) <=GOAL_HIGHYAW && fabs(observation.theta)>=GOAL_LOWYAW) return 10; else { distance=sqrt(pow((GOAL_HIGHX-observation.x), 2)+pow((GOAL_HIGHY-observation.y), 2)); return -1*distance; } } bool checkTerminal(position_tracker::Position observation){ if(observation.x>=GOAL_LOWX && observation.x<=GOAL_HIGHX && observation.y>=GOAL_LOWY && observation.y <= GOAL_HIGHY && fabs(observation.theta) <=GOAL_HIGHYAW && fabs(observation.theta)>=GOAL_LOWYAW) { // cout << "terminal position" << endl; return true; } else return false; }
c3207baa47de5d293e9596502f7b39527bd2df8b
1cb7eb93e807642d756cc5e67bdd143ee1b786e7
/cc/test-chart-modify.cc
cd3870c3e47560870143a869b3fa03bbc8c80fcb
[ "MIT" ]
permissive
acorg/acmacs-chart-2
fcd7f6be003f6a8050b634c5bf63ddef6dee3092
b584c0c8c63b72f552078583bac87d48436f0780
refs/heads/master
2022-09-12T10:29:03.726010
2022-08-31T07:55:20
2022-08-31T07:55:20
108,879,170
0
0
null
null
null
null
UTF-8
C++
false
false
37,548
cc
test-chart-modify.cc
#include <iostream> #include <unistd.h> #include <cstdlib> #include <array> #include "acmacs-base/argc-argv.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/temp-file.hh" #include "acmacs-base/enumerate.hh" #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/chart-modify.hh" #include "acmacs-chart-2/factory-export.hh" static void test_chart_modify_no_changes(acmacs::chart::ChartP chart, const argc_argv& args, report_time report); static void test_modify_titers(acmacs::chart::ChartP chart, const argc_argv& args, report_time report); static void test_dont_care_for_antigen(acmacs::chart::ChartP chart, size_t aAntigenNo, const argc_argv& args, report_time report); static void test_dont_care_for_serum(acmacs::chart::ChartP chart, size_t aSerumNo, const argc_argv& args, report_time report); static void test_multiply_by_for_antigen(acmacs::chart::ChartP chart, size_t aAntigenNo, double aMult, const argc_argv& args, report_time report); static void test_multiply_by_for_serum(acmacs::chart::ChartP chart, size_t aSerumNo, double aMult, const argc_argv& args, report_time report); static void test_remove_antigens(acmacs::chart::ChartP chart, const acmacs::Indexes& indexes, const argc_argv& args, report_time report); static void test_remove_sera(acmacs::chart::ChartP chart, const acmacs::Indexes& indexes, const argc_argv& args, report_time report); static void test_insert_antigen(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report); static void test_insert_serum(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report); static void test_insert_remove_antigen(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report); static void test_insert_remove_serum(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report); static void test_extensions(acmacs::chart::ChartP chart, const argc_argv& args, report_time report); enum class compare_titers { no, yes }; static void compare_antigens(acmacs::chart::ChartP chart_source, size_t source_ag_no, acmacs::chart::AntigenP source_antigen, acmacs::chart::ChartP chart_imported, size_t imported_ag_no, compare_titers ct); static void compare_sera(acmacs::chart::ChartP chart_source, size_t source_sr_no, acmacs::chart::SerumP source_serum, size_t source_number_of_antigens, acmacs::chart::ChartP chart_imported, size_t imported_sr_no, size_t imported_number_of_antigens, compare_titers ct); // ---------------------------------------------------------------------- int main(int argc, char* const argv[]) { int exit_code = 0; try { argc_argv args(argc, argv, {{"--full", false, "full output"}, {"--time", false, "report time of loading chart"}, {"-h", false}, {"--help", false}, {"-v", false}, {"--verbose", false}}); if (args["-h"] || args["--help"] || args.number_of_arguments() != 1) { std::cerr << "Usage: " << args.program() << " [options] <chart-file>\n" << args.usage_options() << '\n'; exit_code = 1; } else { const auto report = do_report_time(args["--time"]); auto chart = acmacs::chart::import_from_file(args[0], acmacs::chart::Verify::None, report); const std::array<size_t, 5> antigens_to_test{{0, 1, chart->number_of_antigens() / 2, chart->number_of_antigens() - 2, chart->number_of_antigens() - 1}}; const std::array<size_t, 5> sera_to_test{{0, 1, chart->number_of_sera() / 2, chart->number_of_sera() - 2, chart->number_of_sera() - 1}}; test_chart_modify_no_changes(chart, args, report); if (chart->titers()->number_of_layers() == 0) { std::cout << " test_modify_titers\n"; test_modify_titers(chart, args, report); std::cout << " test_dont_care_for_antigen\n"; for (auto ag_no : antigens_to_test) test_dont_care_for_antigen(chart, ag_no, args, report); std::cout << " test_dont_care_for_serum\n"; for (auto sr_no : sera_to_test) test_dont_care_for_serum(chart, sr_no, args, report); std::cout << " test_multiply_by_for_antigen\n"; for (auto ag_no : antigens_to_test) { test_multiply_by_for_antigen(chart, ag_no, 2.0, args, report); test_multiply_by_for_antigen(chart, ag_no, 0.5, args, report); } std::cout << " test_multiply_by_for_serum\n"; for (auto sr_no : sera_to_test) { test_multiply_by_for_serum(chart, sr_no, 2.0, args, report); test_multiply_by_for_serum(chart, sr_no, 0.5, args, report); } std::cout << " test_insert_antigen\n"; for (auto ag_no : antigens_to_test) { test_insert_antigen(chart, ag_no, args, report); test_insert_antigen(chart, ag_no + 1, args, report); test_insert_remove_antigen(chart, ag_no, args, report); test_insert_remove_antigen(chart, ag_no + 1, args, report); } std::cout << " test_insert_serum\n"; for (auto sr_no : sera_to_test) { test_insert_serum(chart, sr_no, args, report); test_insert_serum(chart, sr_no + 1, args, report); test_insert_remove_serum(chart, sr_no, args, report); test_insert_remove_serum(chart, sr_no + 1, args, report); } } std::cout << " test_remove_antigens\n"; for (auto ag_no : antigens_to_test) test_remove_antigens(chart, {ag_no}, args, report); std::cout << " test_remove_sera\n"; for (auto sr_no : sera_to_test) test_remove_sera(chart, {sr_no}, args, report); std::cout << " test_extensions\n"; test_extensions(chart, args, report); } } catch (std::exception& err) { std::cerr << "ERROR: " << err.what() << '\n'; exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- void test_chart_modify_no_changes(acmacs::chart::ChartP chart, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.info_modify(); chart_modify.antigens_modify(); chart_modify.sera_modify(); chart_modify.titers_modify(); chart_modify.forced_column_bases_modify(acmacs::chart::MinimumColumnBasis{}); const auto plain = acmacs::chart::export_factory(*chart, acmacs::chart::export_format::ace, args.program(), report); const auto modified = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); if (plain != modified) { if (args["--full"]) { std::cout << "======== PLAIN ============" << plain << '\n'; std::cout << "======== MODIFIED ============" << modified << '\n'; } else { acmacs::file::temp plain_file{".ace"}, modified_file{".ace"}; if (write(plain_file, plain.data(), plain.size()) < 0) throw std::runtime_error("write plain_file failed!"); if (write(modified_file, modified.data(), modified.size()) < 0) throw std::runtime_error("write modified_file failed!"); if (std::system(("/usr/bin/diff -B -b --ignore-matching-lines='\"?created\"' " + static_cast<std::string>(plain_file) + " " + static_cast<std::string>(modified_file)).data())) throw std::runtime_error("diff failed!"); } throw std::runtime_error("different!"); } } // test_chart_modify_no_changes // ---------------------------------------------------------------------- void test_modify_titers(acmacs::chart::ChartP chart, const argc_argv& args, report_time report) { struct ME { size_t ag_no, sr_no; const char* titer; }; const std::array<ME, 4> test_data{{{0, 1, "11"}, {0, 2, "12"}, {1, 1, "21"}, {1, 2, "<22"}}}; acmacs::chart::ChartModify chart_modify{chart}; auto& titers = chart_modify.titers_modify(); for (const auto& new_t : test_data) titers.titer(new_t.ag_no, new_t.sr_no, acmacs::chart::Titer{new_t.titer}); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto titers_source{chart->titers()}, titers_modified{imported->titers()}; const auto tim_source = titers_source->titers_existing(), tim_modified = titers_modified->titers_existing(); auto ti_source = tim_source.begin(), ti_modified = tim_modified.begin(); for (; ti_source != tim_source.end(); ++ti_source, ++ti_modified) { if (ti_source->antigen != ti_modified->antigen || ti_source->serum != ti_modified->serum) throw std::runtime_error{fmt::format("test_modify_titers: titer iterator mismatch: [{}] vs. [{}]", *ti_source, *ti_modified)}; if (auto found = std::find_if(test_data.begin(), test_data.end(), [ag_no=ti_source->antigen, sr_no=ti_source->serum](const auto& entry) { return ag_no == entry.ag_no && sr_no == entry.sr_no; }); found != test_data.end()) { if (ti_source->titer == ti_modified->titer) throw std::runtime_error{fmt::format("test_modify_titers: unexpected titer match: [{}] vs. [{}]", *ti_source, *ti_modified)}; if (ti_modified->titer != acmacs::chart::Titer{found->titer}) throw std::runtime_error{fmt::format("titer mismatch: [{}] vs. [{}]", found->titer, *ti_modified)}; } else if (ti_source->titer != ti_modified->titer) throw std::runtime_error{fmt::format("test_modify_titers: titer mismatch: [{}] vs. [{}]", *ti_source, *ti_modified)}; } if (ti_modified != tim_modified.end()) throw std::runtime_error("test_modify_titers: titer iterator end mismatch"); } // test_modify_titers // ---------------------------------------------------------------------- void test_dont_care_for_antigen(acmacs::chart::ChartP chart, size_t aAntigenNo, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.titers_modify().dontcare_for_antigen(aAntigenNo); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto titers_source{chart->titers()}, titers_modified{imported->titers()}; for (auto ti_source : titers_source->titers_existing()) { if (ti_source.antigen == aAntigenNo) { if (!titers_modified->titer(ti_source.antigen, ti_source.serum).is_dont_care()) throw std::runtime_error{fmt::format("test_dont_care_for_antigen: unexpected titer: [{}], expected: *", ti_source)}; } else if (titers_modified->titer(ti_source.antigen, ti_source.serum) != ti_source.titer) throw std::runtime_error(fmt::format("test_dont_care_for_antigen: titer mismatch: [{} {}] vs. {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum))); } } // test_dont_care_for_antigen // ---------------------------------------------------------------------- void test_dont_care_for_serum(acmacs::chart::ChartP chart, size_t aSerumNo, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.titers_modify().dontcare_for_serum(aSerumNo); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto titers_source{chart->titers()}, titers_modified{imported->titers()}; for (auto ti_source : titers_source->titers_existing()) { if (ti_source.serum == aSerumNo) { if (!titers_modified->titer(ti_source.antigen, ti_source.serum).is_dont_care()) throw std::runtime_error{fmt::format("test_dont_care_for_serum: unexpected titer: [{}], expected: *", ti_source)}; } else if (titers_modified->titer(ti_source.antigen, ti_source.serum) != ti_source.titer) throw std::runtime_error(fmt::format("test_dont_care_for_serum: titer mismatch: [{} {}] vs. {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum))); } } // test_dont_care_for_serum // ---------------------------------------------------------------------- void test_multiply_by_for_antigen(acmacs::chart::ChartP chart, size_t aAntigenNo, double aMult, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.titers_modify().multiply_by_for_antigen(aAntigenNo, aMult); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto titers_source = chart->titers(), titers_modified = imported->titers(); for (auto ti_source : titers_source->titers_existing()) { if (ti_source.antigen == aAntigenNo && !ti_source.titer.is_dont_care()) { const auto expected_value = static_cast<size_t>(std::lround(static_cast<double>(ti_source.titer.value()) * aMult)); if (titers_modified->titer(ti_source.antigen, ti_source.serum).value() != expected_value) throw std::runtime_error(fmt::format("test_multiply_by_for_antigen: unexpected titer: [ag:{} sr:{} t:{}], expected: {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum), expected_value)); } else if (titers_modified->titer(ti_source.antigen, ti_source.serum) != ti_source.titer) throw std::runtime_error(fmt::format("test_multiply_by_for_antigen: titer mismatch: [{} {}] vs. {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum))); } } // test_multiply_by_for_antigen // ---------------------------------------------------------------------- void test_multiply_by_for_serum(acmacs::chart::ChartP chart, size_t aSerumNo, double aMult, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.titers_modify().multiply_by_for_serum(aSerumNo, aMult); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto titers_source{chart->titers()}, titers_modified{imported->titers()}; for (auto ti_source : titers_source->titers_existing()) { if (ti_source.serum == aSerumNo && !ti_source.titer.is_dont_care()) { const auto expected_value = static_cast<size_t>(std::lround(static_cast<double>(ti_source.titer.value()) * aMult)); if (titers_modified->titer(ti_source.antigen, ti_source.serum).value() != expected_value) throw std::runtime_error(fmt::format("test_multiply_by_for_serum: unexpected titer: [ag:{} sr:{} t:{}], expected: {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum), std::to_string(expected_value))); } else if (titers_modified->titer(ti_source.antigen, ti_source.serum) != ti_source.titer) throw std::runtime_error(fmt::format("test_multiply_by_for_serum: titer mismatch: [{} {}] vs. {}", ti_source.antigen, ti_source.serum, *titers_modified->titer(ti_source.antigen, ti_source.serum))); } } // test_multiply_by_for_serum // ---------------------------------------------------------------------- void test_remove_antigens(acmacs::chart::ChartP chart, const acmacs::Indexes& indexes, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.remove_antigens(acmacs::ReverseSortedIndexes(indexes)); // for (auto ag_no : acmacs::range(chart_modify.number_of_antigens())) { // std::cerr << "plot_style orig: " << std::setw(2) << (ag_no + 1) << ' ' << chart->plot_spec()->style(ag_no + 1) << '\n'; // std::cerr << "plot_style mod: " << std::setw(2) << ag_no << ' ' << chart_modify.plot_spec()->style(ag_no) << '\n' << '\n'; // } const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); try { auto antigens_source = chart->antigens(), antigens_imported = imported->antigens(); auto sera_source = chart->sera(), sera_imported = imported->sera(); auto titers_source = chart->titers(), titers_imported = imported->titers(); auto projections_source = chart->projections(), projections_imported = imported->projections(); auto plot_spec_source = chart->plot_spec(), plot_spec_imported = imported->plot_spec(); size_t imported_ag_no = 0; for (auto[source_ag_no, source_antigen] : acmacs::enumerate(*antigens_source)) { if (std::find(indexes.begin(), indexes.end(), source_ag_no) == indexes.end()) { compare_antigens(chart, source_ag_no, source_antigen, imported, imported_ag_no, compare_titers::yes); ++imported_ag_no; } } if (imported_ag_no != imported->number_of_antigens()) throw std::runtime_error("invalid resulting imported_ag_no"); for (auto[source_sr_no, source_serum] : acmacs::enumerate(*sera_source)) compare_sera(chart, source_sr_no, source_serum, antigens_source->size(), imported, source_sr_no, antigens_imported->size(), compare_titers::no); } catch (std::exception& err) { // const std::string prefix = fs::exists("/r/ramdisk-id") ? "/r/" : "/tmp/"; // acmacs::file::write(prefix + "a.ace", exported, acmacs::file::force_compression::yes); throw std::runtime_error(fmt::format("test_remove_antigens: {}\n indexes:{}", err, indexes)); } } // test_remove_antigens // ---------------------------------------------------------------------- void test_remove_sera(acmacs::chart::ChartP chart, const acmacs::Indexes& indexes, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.remove_sera(acmacs::ReverseSortedIndexes(indexes)); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); try { auto antigens_source = chart->antigens(), antigens_imported = imported->antigens(); auto sera_source = chart->sera(), sera_imported = imported->sera(); auto titers_source = chart->titers(), titers_imported = imported->titers(); auto projections_source = chart->projections(), projections_imported = imported->projections(); auto plot_spec_source = chart->plot_spec(), plot_spec_imported = imported->plot_spec(); for (auto[source_ag_no, source_antigen] : acmacs::enumerate(*antigens_source)) compare_antigens(chart, source_ag_no, source_antigen, imported, source_ag_no, compare_titers::no); size_t imported_sr_no = 0; for (auto[source_sr_no, source_serum] : acmacs::enumerate(*sera_source)) { if (std::find(indexes.begin(), indexes.end(), source_sr_no) == indexes.end()) { compare_sera(chart, source_sr_no, source_serum, antigens_source->size(), imported, imported_sr_no, antigens_imported->size(), compare_titers::yes); ++imported_sr_no; } } if (imported_sr_no != imported->number_of_sera()) throw std::runtime_error("invalid resulting imported_sr_no"); } catch (std::exception& err) { // const std::string prefix = fs::exists("/r/ramdisk-id") ? "/r/" : "/tmp/"; // acmacs::file::write(prefix + "a.ace", exported, acmacs::file::force_compression::yes); throw std::runtime_error(fmt::format("test_remove_sera: {}\n indexes:{}", err, indexes)); } } // test_remove_sera // ---------------------------------------------------------------------- void test_insert_antigen(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report) { std::string exported; try { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.insert_antigen(before); exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); auto antigens_source = chart->antigens(), antigens_imported = imported->antigens(); auto sera_source = chart->sera(), sera_imported = imported->sera(); auto titers_source = chart->titers(), titers_imported = imported->titers(); auto projections_source = chart->projections(), projections_imported = imported->projections(); auto plot_spec_source = chart->plot_spec(), plot_spec_imported = imported->plot_spec(); auto check_inserted = [&](size_t imported_ag_no) { if (auto new_name = (*antigens_imported)[imported_ag_no]->name_full(); new_name.empty()) throw std::runtime_error("inserted antigen has no name"); for (auto sr_no : acmacs::range(sera_source->size())) { if (!titers_imported->titer(imported_ag_no, sr_no).is_dont_care()) throw std::runtime_error{AD_FORMAT("inserted antigen has titer: sr_no:{} titer:{}", sr_no, *titers_imported->titer(imported_ag_no, sr_no))}; } for (auto projection : *projections_imported) { if (auto imp = projection->layout()->at(imported_ag_no); imp.exists()) throw std::runtime_error{AD_FORMAT("inserted antigen has coordinates: {}", imp)}; } }; size_t imported_ag_no = 0; for (auto [source_ag_no, source_antigen] : acmacs::enumerate(*antigens_source)) { if (source_ag_no == before) { check_inserted(imported_ag_no); ++imported_ag_no; } else { compare_antigens(chart, source_ag_no, source_antigen, imported, imported_ag_no, compare_titers::yes); } ++imported_ag_no; } if (imported_ag_no == before) { check_inserted(imported_ag_no); ++imported_ag_no; } if (imported_ag_no != imported->number_of_antigens()) throw std::runtime_error{AD_FORMAT("invalid resulting imported_ag_no: {}, expected: ", imported_ag_no, imported->number_of_antigens())}; for (auto [source_sr_no, source_serum] : acmacs::enumerate(*sera_source)) compare_sera(chart, source_sr_no, source_serum, antigens_source->size(), imported, source_sr_no, antigens_imported->size(), compare_titers::no); } catch (std::exception& err) { // const std::string prefix = fs::exists("/r/ramdisk-id") ? "/r/" : "/tmp/"; // acmacs::file::write(prefix + "a.ace", exported, acmacs::file::force_compression::yes); throw std::runtime_error(fmt::format("test_insert_antigen: {}\n before:{}", err, before)); } } // test_insert_antigen // ---------------------------------------------------------------------- void test_insert_serum(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.insert_serum(before); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); try { auto antigens_source = chart->antigens(), antigens_imported = imported->antigens(); auto sera_source = chart->sera(), sera_imported = imported->sera(); auto titers_source = chart->titers(), titers_imported = imported->titers(); auto projections_source = chart->projections(), projections_imported = imported->projections(); auto plot_spec_source = chart->plot_spec(), plot_spec_imported = imported->plot_spec(); auto check_inserted = [&](size_t imported_sr_no) { if (auto new_name = (*sera_imported)[imported_sr_no]->name_full(); new_name.empty()) throw std::runtime_error("inserted serum has no name"); for (auto ag_no : acmacs::range(antigens_source->size())) { if (!titers_imported->titer(ag_no, imported_sr_no).is_dont_care()) throw std::runtime_error{AD_FORMAT("inserted serum has titer: ag_no:{} titer:{}", ag_no, *titers_imported->titer(ag_no, imported_sr_no))}; } for (auto projection : *projections_imported) { if (auto imp = projection->layout()->at(imported_sr_no + antigens_source->size()); imp.exists()) throw std::runtime_error{AD_FORMAT("inserted serum has coordinates: ", imp)}; } }; for (auto [source_ag_no, source_antigen] : acmacs::enumerate(*antigens_source)) compare_antigens(chart, source_ag_no, source_antigen, imported, source_ag_no, compare_titers::no); size_t imported_sr_no = 0; for (auto [source_sr_no, source_serum] : acmacs::enumerate(*sera_source)) { if (source_sr_no == before) { check_inserted(imported_sr_no); ++imported_sr_no; } else { compare_sera(chart, source_sr_no, source_serum, antigens_source->size(), imported, imported_sr_no, antigens_imported->size(), compare_titers::yes); } ++imported_sr_no; } if (imported_sr_no == before) { check_inserted(imported_sr_no); ++imported_sr_no; } if (imported_sr_no != imported->number_of_sera()) throw std::runtime_error("invalid resulting imported_sr_no: " + acmacs::to_string(imported_sr_no) + ", expected: " + acmacs::to_string(imported->number_of_sera())); } catch (std::exception& err) { // const std::string prefix = fs::exists("/r/ramdisk-id") ? "/r/" : "/tmp/"; // acmacs::file::write(prefix + "a.ace", exported, acmacs::file::force_compression::yes); throw std::runtime_error(std::string("test_insert_serum: ") + err.what() + "\n before:" + acmacs::to_string(before)); } } // test_insert_serum // ---------------------------------------------------------------------- inline std::string equality_report(const acmacs::PointStyle& s1, const acmacs::PointStyle& s2) { return fmt::format("shown:{} fill:{} outline:{} outline_width:{} size:{} rotation:{} aspect:{} shape:{} label:{} label_text:{}", s1.shown() == s2.shown(), s1.fill() == s2.fill(), s1.outline() == s2.outline(), s1.outline_width() == s2.outline_width(), s1.size() == s2.size(), s1.rotation() == s2.rotation(), s1.aspect() == s2.aspect(), s1.shape() == s2.shape(), s1.label() == s2.label(), s1.label_text() == s2.label_text()); } // ---------------------------------------------------------------------- void compare_antigens(acmacs::chart::ChartP chart_source, size_t source_ag_no, acmacs::chart::AntigenP source_antigen, acmacs::chart::ChartP chart_imported, size_t imported_ag_no, compare_titers ct) { auto antigens_imported = chart_imported->antigens(); auto projections_source = chart_source->projections(), projections_imported = chart_imported->projections(); auto plot_spec_source = chart_source->plot_spec(), plot_spec_imported = chart_imported->plot_spec(); if (*source_antigen != *(*antigens_imported)[imported_ag_no]) throw std::runtime_error("antigen mismatch: orig:" + std::to_string(source_ag_no) + " vs. imported:" + std::to_string(imported_ag_no)); if (ct == compare_titers::yes) { auto titers_source = chart_source->titers(), titers_imported = chart_imported->titers(); for (auto sr_no : acmacs::range(chart_source->number_of_sera())) { if (titers_source->titer(source_ag_no, sr_no) != titers_imported->titer(imported_ag_no, sr_no)) throw std::runtime_error(fmt::format("titer mismatch: sr_no:{} orig: {} {}, imported: {} {}", sr_no, source_ag_no, *titers_source->titer(source_ag_no, sr_no), imported_ag_no, *titers_imported->titer(imported_ag_no, sr_no))); } } for (auto[p_no, projection] : acmacs::enumerate(*projections_source)) { if (auto src = projection->layout()->at(source_ag_no), imp = (*projections_imported)[p_no]->layout()->at(imported_ag_no); src != imp) throw std::runtime_error(fmt::format("antigen coordinates mismatch: orig:{} {} vs. imported:", source_ag_no, src, imported_ag_no, imp)); } if (auto src = plot_spec_source->style(source_ag_no), imp = plot_spec_imported->style(imported_ag_no); src != imp) throw std::runtime_error(fmt::format("antigen plot style mismatch:\n orig:{} {}\n imported:{} {}\n report: {}", source_ag_no, src, imported_ag_no, imp, equality_report(src, imp))); } // void compare_antigens // ---------------------------------------------------------------------- void compare_sera(acmacs::chart::ChartP chart_source, size_t source_sr_no, acmacs::chart::SerumP source_serum, size_t source_number_of_antigens, acmacs::chart::ChartP chart_imported, size_t imported_sr_no, size_t imported_number_of_antigens, compare_titers ct) { auto sera_imported = chart_imported->sera(); auto projections_source = chart_source->projections(), projections_imported = chart_imported->projections(); auto plot_spec_source = chart_source->plot_spec(), plot_spec_imported = chart_imported->plot_spec(); if (*source_serum != *(*sera_imported)[imported_sr_no]) throw std::runtime_error("serum mismatch: " + std::to_string(source_sr_no) + " vs. " + std::to_string(imported_sr_no)); if (ct == compare_titers::yes) { auto titers_source = chart_source->titers(), titers_imported = chart_imported->titers(); for (auto ag_no : acmacs::range(source_number_of_antigens)) { if (titers_source->titer(ag_no, source_sr_no) != titers_imported->titer(ag_no, imported_sr_no)) throw std::runtime_error(fmt::format("titer mismatch: ag_no:{} orig: {} {}, imported: {} {}", ag_no, source_sr_no, *titers_source->titer(ag_no, source_sr_no), imported_sr_no, *titers_imported->titer(ag_no, imported_sr_no))); } } const auto point_no_source = source_sr_no + source_number_of_antigens, point_no_imported = imported_sr_no + imported_number_of_antigens; for (auto[p_no, projection] : acmacs::enumerate(*projections_source)) { if (auto src = projection->layout()->at(point_no_source), imp = (*projections_imported)[p_no]->layout()->at(point_no_imported); src != imp) throw std::runtime_error(fmt::format("serum coordinates mismatch: orig:{} {} vs. imported:", source_sr_no, src, imported_sr_no, imp)); } if (auto src = plot_spec_source->style(point_no_source), imp = plot_spec_imported->style(point_no_imported); src != imp) throw std::runtime_error(fmt::format("serum plot style mismatch:\n orig:{} {}\n imported:{} {}\n report: {}", source_sr_no, src, imported_sr_no, imp, equality_report(src, imp))); } // compare_sera // ---------------------------------------------------------------------- void test_insert_remove_antigen(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.insert_antigen(before); chart_modify.remove_antigens(acmacs::ReverseSortedIndexes(std::vector<size_t>{before})); const auto source_exported = acmacs::chart::export_factory(*chart, acmacs::chart::export_format::text, args.program(), report); const auto modified_exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::text, args.program(), report); if (source_exported != modified_exported) { acmacs::file::write("/tmp/source.txt", source_exported, acmacs::file::force_compression::no); acmacs::file::write("/tmp/modified.txt", modified_exported, acmacs::file::force_compression::no); throw std::runtime_error(fmt::format("test_insert_remove_antigen: exported chart difference, diff /tmp/source.txt /tmp/modified.txt\n before: {}", before)); } } // test_insert_remove_antigen // ---------------------------------------------------------------------- void test_insert_remove_serum(acmacs::chart::ChartP chart, size_t before, const argc_argv& args, report_time report) { acmacs::chart::ChartModify chart_modify{chart}; chart_modify.insert_serum(before); chart_modify.remove_sera(acmacs::ReverseSortedIndexes(acmacs::Indexes{before})); const auto source_exported = acmacs::chart::export_factory(*chart, acmacs::chart::export_format::text, args.program(), report); const auto modified_exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::text, args.program(), report); if (source_exported != modified_exported) { acmacs::file::write("/tmp/source.txt", source_exported, acmacs::file::force_compression::no); acmacs::file::write("/tmp/modified.txt", modified_exported, acmacs::file::force_compression::no); throw std::runtime_error(fmt::format("test_insert_remove_serum:: exported chart difference, (no ediff!) diff /tmp/source.txt /tmp/modified.txt\n before: {}", before)); } } // test_insert_remove_serum // ---------------------------------------------------------------------- void test_extensions(acmacs::chart::ChartP chart, const argc_argv& args, report_time report) { { acmacs::chart::ChartModify chart_modify{chart}; if (const auto& ext1 = chart_modify.extension_field("test-chart-modify"); !ext1.is_const_null()) throw std::runtime_error("test_extensions: initial test-chart-modify value is not const_null"); if (const auto& ext2 = chart_modify.extension_field_modify("test-chart-modify"); !ext2.is_const_null()) throw std::runtime_error("test_extensions: initial modifiy test-chart-modify value is not const_null"); } { acmacs::chart::ChartModify chart_modify{chart}; const rjson::value test_value_1{rjson::object{{"A", 1}, {"B", 2.1}, {"C", "D"}}}; chart_modify.extension_field_modify("test-chart-modify-1", test_value_1); const rjson::value test_value_2{rjson::object{{"E", rjson::array{11, "F", 12.12}}}}; chart_modify.extension_field_modify("test-chart-modify-2", test_value_2); // std::cerr << "EXT: " << chart_modify.extension_fields() << '\n'; // std::cerr << "EXT1: " << chart_modify.extension_field("test-chart-modify-1") << '\n'; // std::cerr << "EXT2: " << chart_modify.extension_field("test-chart-modify-2") << '\n'; if (const auto& r1 = chart_modify.extension_field("test-chart-modify-1"); r1 != test_value_1) throw std::runtime_error("test_extensions: r1 != test_value_1"); if (const auto& r2 = chart_modify.extension_field("test-chart-modify-2"); r2 != test_value_2) throw std::runtime_error("test_extensions: r2 != test_value_2"); // replace const rjson::value test_value_3{rjson::array{rjson::object{{"G", "GG"}}, "HHHH", 123.123}}; chart_modify.extension_field_modify("test-chart-modify-2", test_value_3); // std::cerr << "EXT: " << chart_modify.extension_fields() << '\n'; if (const auto& r3 = chart_modify.extension_field("test-chart-modify-2"); r3 != test_value_3) throw std::runtime_error("test_extensions: r3 != test_value_3"); const auto exported = acmacs::chart::export_factory(chart_modify, acmacs::chart::export_format::ace, args.program(), report); auto chart_imported = acmacs::chart::import_from_data(exported, acmacs::chart::Verify::None, report); // std::cerr << "EXT imported: " << chart_imported->extension_fields() << '\n'; if (const auto& r4 = chart_imported->extension_field("test-chart-modify-2"); r4 != test_value_3) throw std::runtime_error("test_extensions: r4 != test_value_3"); } } // test_extensions // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
3de156738b8a8dbb9940275c0e6fce0ef5893181
8899da7ed2494e87d502cccdc3884a2b3e0e671e
/VideoSmokeDetection/VasIO.cpp
80072065332b00dcd190b29bde7a53b639c0530a
[]
no_license
powerlic/VSD
552f9c228528c028dd85147e1e07a8c1c6196534
c5e5056804c08410e4c58a1fe8fbc415e836c1fc
refs/heads/master
2021-01-01T18:19:06.287153
2017-07-25T11:55:42
2017-07-25T11:55:42
98,299,661
3
0
null
null
null
null
UTF-8
C++
false
false
2,116
cpp
VasIO.cpp
#include"stdafx.h" #include "VasIO.h" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> namespace vas { using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; bool ReadProtoFromTextFile(const char *file_name, Message*proto) { int fd = _open(file_name, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << file_name; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; _close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = _open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; _close(fd); } /*void TestProto() { VasService vas_services; const char *file_name = "..\\proto\\service_list.prototxt"; ReadProtoFromTextFile(file_name, &vas_services); for (size_t i = 0; i < vas_services.service_paramter_size(); i++) { ServiceParameter service_para = vas_services.service_paramter(i); DecodeParameter decode_para = service_para.decode_parameter(); DetectParameter detect_para = service_para.detect_parameter(); if (decode_para.has_dst_width()) { std::cout << decode_para.dst_height()<<std::endl; } if (decode_para.has_decode_method()) { std::cout << decode_para.decode_method() << std::endl; } BgParameter bg_para = detect_para.bg_parameter(); BgGuassianParameter bg_guassian_para = bg_para.guassian_parameter(); std::cout << bg_guassian_para.num_history() << std::endl; for (size_t j = 0; j < detect_para.reg_type_size(); j++) { std::cout << detect_para.reg_type(j) << std::endl; } } }*/ }
43eab0650a06981ef7fff04ba82a0f307b36eef0
60c1712c4b41fe624d2093b7a743f27c2d539cd0
/hackerrank/equal_stacks.cpp
66f08842d0f0d07ef4a1cf33da8c752e2cf1818f
[]
no_license
agkee/competitive_programming
a67e46ac6288c6c0566028a1080d1513f83149bd
9feb3599d9d96bc1d53972834c5ed51f4f651d36
refs/heads/master
2023-01-07T07:00:13.988752
2020-10-30T04:03:25
2020-10-30T04:03:25
255,014,174
0
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
equal_stacks.cpp
#include <vector> using namespace std; int equalStacks(vector<int> h1, vector<int> h2, vector<int> h3) { int sum1 =0 , sum2=0, sum3=0; for(int h: h1) sum1 += h; for(int h: h2) sum2 += h; for(int h: h3) sum3 += h; reverse(h1.begin(), h1.end()); reverse(h2.begin(), h2.end()); reverse(h3.begin(), h3.end()); while (sum1 != sum2 || sum2 != sum3) { if (sum1 >= sum2 && sum1 >= sum3) { sum1 -= h1.back(); h1.pop_back(); } else if (sum2 >= sum1 && sum2 >= sum3) { sum2 -= h2.back(); h2.pop_back(); } else { sum3 -= h3.back(); h3.pop_back(); } } return sum1; }
b9536175d9e0eac1ac33d28c7d5f3da8f46e8f91
a0423109d0dd871a0e5ae7be64c57afd062c3375
/Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Common.Blitter.h
d7872db63c37acfdb1c52d16aa7832eac8aa5eec
[ "Apache-2.0" ]
permissive
marferfer/SpinOff-LoL
1c8a823302dac86133aa579d26ff90698bfc1ad6
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
refs/heads/master
2020-03-29T20:09:20.322768
2018-10-09T10:19:33
2018-10-09T10:19:33
150,298,258
0
0
null
null
null
null
UTF-8
C++
false
false
2,841
h
Fuse.Common.Blitter.h
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Common/1.9.0/Blitter.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Float2.h> #include <Uno.Object.h> #include <Uno.Runtime.Implement-476e2792.h> namespace g{namespace Fuse{namespace Common{struct Blitter;}}} namespace g{namespace Uno{namespace Graphics{struct SamplerState;}}} namespace g{namespace Uno{namespace Graphics{struct Texture2D;}}} namespace g{namespace Uno{namespace Graphics{struct VertexBuffer;}}} namespace g{namespace Uno{struct Float3x3;}} namespace g{namespace Uno{struct Float4;}} namespace g{namespace Uno{struct Float4x4;}} namespace g{namespace Uno{struct Rect;}} namespace g{ namespace Fuse{ namespace Common{ // internal sealed class Blitter :6 // { uType* Blitter_typeof(); void Blitter__ctor__fn(Blitter* __this); void Blitter__Blit_fn(Blitter* __this, ::g::Uno::Graphics::Texture2D* texture, ::g::Uno::Graphics::SamplerState* samplerState, bool* preMultiplied, ::g::Uno::Rect* textureRect, ::g::Uno::Float3x3* textureTransform, ::g::Uno::Rect* localRect, ::g::Uno::Float4x4* localToClipTransform, ::g::Uno::Float4* color, int32_t* cullFace); void Blitter__Blit1_fn(Blitter* __this, ::g::Uno::Graphics::Texture2D* texture, ::g::Uno::Rect* rect, ::g::Uno::Float4x4* localToClipTransform, float* opacity, bool* flipY, int32_t* cullFace); void Blitter__Fill_fn(Blitter* __this, ::g::Uno::Rect* localRect, ::g::Uno::Float4x4* localToClipTransform, ::g::Uno::Float4* color); void Blitter__init_DrawCalls_fn(Blitter* __this); void Blitter__New1_fn(Blitter** __retval); struct Blitter : uObject { static uSStrong<Blitter*> Singleton_; static uSStrong<Blitter*>& Singleton() { return Blitter_typeof()->Init(), Singleton_; } uStrong< ::g::Uno::Graphics::VertexBuffer*> Blit_v_254ef0e5_1_8_1; uStrong<uArray*> Blit_verts_254ef0e5_1_7_5; uStrong< ::g::Uno::Graphics::VertexBuffer*> Fill_v_181ef612_1_8_1; ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall _draw_254ef0e5; ::g::Uno::Runtime::Implementation::ShaderBackends::OpenGL::GLDrawCall _draw_181ef612; void ctor_(); void Blit(::g::Uno::Graphics::Texture2D* texture, ::g::Uno::Graphics::SamplerState samplerState, bool preMultiplied, ::g::Uno::Rect textureRect, ::g::Uno::Float3x3 textureTransform, ::g::Uno::Rect localRect, ::g::Uno::Float4x4 localToClipTransform, ::g::Uno::Float4 color, int32_t cullFace); void Blit1(::g::Uno::Graphics::Texture2D* texture, ::g::Uno::Rect rect, ::g::Uno::Float4x4 localToClipTransform, float opacity, bool flipY, int32_t cullFace); void Fill(::g::Uno::Rect localRect, ::g::Uno::Float4x4 localToClipTransform, ::g::Uno::Float4 color); void init_DrawCalls(); static Blitter* New1(); }; // } }}} // ::g::Fuse::Common
b244b3143bdb9cc1d3eeb9751d7573ce82cbde12
ecf336b92bd77b279942ddc4b326f4620b1076c6
/Server/Client.h
d44e4648ce705f675b063c5f0a444729107a9092
[]
no_license
Sp00nyMan/Chat
fddde87b42e7a9168b21a0249ef60659d9c48cf0
ebc3ee80addd08d587e374ab91ef0325de4875e4
refs/heads/master
2022-04-12T13:01:40.689144
2020-03-26T16:18:37
2020-03-26T16:18:37
250,224,719
0
0
null
null
null
null
UTF-8
C++
false
false
254
h
Client.h
#include <string> class Client { public: long int id; std::string name; int socket; Client(const std::string& name, long int id, int socket) { this->name = name; this->id = id; this->socket = socket; } };
771f15d716dee58b4b23a94224ea7584b9ebaf5b
783e25073c359443fbd3feb6744cf4440e3194e5
/hw3/GenScatterHierarchy.h
56656fbd179526b8897dd89f07b4c8c4fc26563f
[]
no_license
alfekka/metaprog
964a0b8a60393b6a3c418ebdd963f89d7405835c
c2032ffe80fccb47d7730951d07c2f4b996321eb
refs/heads/master
2020-09-07T14:52:16.667730
2019-11-25T00:26:49
2019-11-25T00:26:49
220,816,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
h
GenScatterHierarchy.h
// // Created by mila on 10.11.2019. // #pragma once #include "listt.h" template <class TList, template <class> class Unit> class GenScatterHierarchy; template <class Head, class ... Tail, template <class> class Unit> class GenScatterHierarchy<TypeList<Head, Tail ...>, Unit>: public GenScatterHierarchy<class TypeList<Head, Tail ...>::head , Unit>, public GenScatterHierarchy<class TypeList<Head, Tail ...>::tail, Unit> { public: using TList = TypeList<Head, Tail ...>; using LeftBase = GenScatterHierarchy<class TypeList<Head, Tail ...>::head, Unit>; using RightBase = GenScatterHierarchy<class TypeList<Head, Tail ...>::tail, Unit>; template <typename A> struct Rebind { using Result = Unit<A>; }; }; template <class Type, template <class> class Unit> class GenScatterHierarchy: public Unit<Type> { public: using LeftBase = Unit<Type>; template <typename T> struct Rebind { using Result = Unit<T>; }; }; template <template <class> class Unit> class GenScatterHierarchy<NullType, Unit> { template <typename A> struct Rebind { using Result = Unit<A>; }; }; template <class A, class H> typename H::template Rebind<A>::Result& Field(H& obj) { return obj; }
a9376a9bc9b1b76cdb8d2b46805af4907a5b5300
b1a78fa0f8f60c665301e22cd341a622086275a1
/include/lgl/Texture2D.h
a883fa91b97a67c1a87a481b6229c56be62baff1
[]
no_license
kyungminkim7/learn_opengl
359e7e6bcc643b79c416ba9833e7109971b90426
a4ad69c1faaab0f49f6928e5cbd4b9fdb67293cf
refs/heads/master
2021-12-04T06:03:56.606073
2021-10-08T03:12:36
2021-10-08T03:12:36
144,912,381
0
0
null
null
null
null
UTF-8
C++
false
false
241
h
Texture2D.h
#pragma once #include <memory> #include <string> namespace lgl { class Texture2D { public: explicit Texture2D(const std::string &pathname); void bind(); private: std::shared_ptr<unsigned int> texture; }; } // namespace lgl
ab8097d3f1575f4ea40b4f3f3c67ab247b16e895
bc32feaf4022092bb0de69e2263174297d0aa49e
/constructor_overloading.cpp
d62c7e2a395bab179e5006df8567e3e2715d6dd4
[]
no_license
aanantt/C_program
595d4a81e700ddf3573a7e73decea9e44536cdeb
38178527411bcd88c5947f858bb7571ec9cfc817
refs/heads/main
2023-05-19T14:52:14.938205
2021-06-06T18:16:33
2021-06-06T18:16:33
374,432,555
2
1
null
null
null
null
UTF-8
C++
false
false
709
cpp
constructor_overloading.cpp
#include<iostream> using namespace std; class deposit{ int principal; int time; float rate; float total_amt; public: deposit(); deposit(int p, int t, float r); void calc_amt(void); void display(void); }; deposit::deposit(){ principal=time=rate=0.0; } deposit::deposit(int p, int t,float r ){ principal=p; time=t; rate=r; } void deposit::calc_amt(void) { total_amt=principal+(principal*time*rate)/100; } void deposit::display(){ cout<<"\n principal amount:"<<principal; cout<<"\n period of investment"<<time; cout<<"\n rate of interest"<<rate; cout<<"\n total amount"<<total_amt<<"\n"; } int main() { deposit d1; deposit d2(440,2,0.07f); d1.calc_amt(); d2.calc_amt(); d1.display();
d3385586d994c5a5774b52b819b294bbd91d5eed
ff31b52ee8e08e5386ac38d13359b328d2b907c5
/GAME/Actors/Player/PlayerAnimations/PlayerAnimations.cpp
c9fefc7e930c5d01060909f1a7245caf8b17a97e
[]
no_license
kychka/sfml-game-test.reborn
c1194d250fdf1234145fcedf668f199359c14f38
b3b1946e93264c7a04a457e167bac0c1a48d3121
refs/heads/master
2021-01-10T08:01:53.186911
2016-03-03T19:16:45
2016-03-03T19:16:45
51,251,717
9
5
null
2016-03-03T19:16:45
2016-02-07T15:07:16
C++
UTF-8
C++
false
false
230
cpp
PlayerAnimations.cpp
#include "PlayerAnimations.h" PlayerAnimations::PlayerAnimations() { } PlayerAnimations::~PlayerAnimations() { } void PlayerAnimations::init() { animations.emplace( Entity::ANIM_JUMP, std::make_shared<JumpAnimation>() ); }
171ecbebdd144df58752c8e6f7c57de732058041
edb8292c3ed53b9e81eab4a1ef66f6b234c21a1f
/Code/EntityItem.h
07794f43a3ec29dbc9f2785daafc74b315102ebd
[]
no_license
Exploratory-Studios/Fear-Of-The-Dark
6bdacbea391c0034bee6e27e09ee5019dfaf2f4f
05c3faa4e0863ad15ccaec482e23eda181a3d163
refs/heads/master
2023-06-30T13:18:53.787366
2023-06-14T16:53:55
2023-06-14T16:53:55
98,566,800
4
1
null
2019-04-07T01:44:12
2017-07-27T18:07:35
C++
UTF-8
C++
false
false
524
h
EntityItem.h
#pragma once #include "Entity.h" #include "Item.h" class EntityItem : public Entity { public: EntityItem(glm::vec2 pos, unsigned int layer, unsigned int id); EntityItem(glm::vec2 pos, unsigned int layer, EntityIDs id); virtual ~EntityItem(); void init(); void init(SaveDataTypes::EntityItemData& data); virtual bool collideWithOther(Entity* other) override; /// Getters Item* getItem(); unsigned int getItemID() { return m_itemId; } protected: // Item unsigned int m_itemId = (unsigned int)-1; };
44190c32c7fa5300c71db88f7eaba7a81485d23b
5f1724bcf33b4d4223e26f003dc8d2fbfc5bbcca
/exp 3/code.ino
f2819bd17bb5affc2c850d059fb5fecc2bfc478f
[]
no_license
tiwariaditya-cu/BEEE_CU19
da88422eb1d28a7d15ec3fbba68a653e38b95e3f
b930938d8c57c0856d15ac29d92b4f201295ce87
refs/heads/master
2020-07-28T09:58:43.841470
2019-11-03T18:08:03
2019-11-03T18:08:03
209,387,276
0
0
null
null
null
null
UTF-8
C++
false
false
434
ino
code.ino
void setup() { for(int x = 10; x <= 13; x++){ pinMode(x, OUTPUT); } } void loop() { for(int x = 10; x <14; x++){ allLEDsOff(); if(x!=13){ digitalWrite(x, HIGH); digitalWrite(x+1, HIGH); delay(200); } else digitalWrite(x, HIGH); digitalWrite(x-3, HIGH); delay(200); allLEDsOff(); } } void allLEDsOff(void){ for(int x = 10; x<=14; x++){ digitalWrite(x, LOW); } delay(100); }
25ff80aa8dff7f6efb0a902f8cc4beb9c7c622e0
c35afc59d4065bcfb3376af51464455082a7ccd9
/src/AOAReciver.h
bb3022d66bfc5ba1476772e22ea061f817c96df2
[ "Apache-2.0" ]
permissive
zoseliu/SerialPort
df7cc9ccf6f4565081304d87505a9f3459907bd8
e2c6fbf92c5f1156c33d9611336e9c15761cc174
refs/heads/master
2020-03-19T01:04:24.387860
2018-05-31T03:36:42
2018-05-31T03:36:42
135,520,431
0
1
null
null
null
null
UTF-8
C++
false
false
329
h
AOAReciver.h
/* * AOAReciver.h * * Created on: May 25, 2018 * Author: leon */ #ifndef AOARECIVER_H_ #define AOARECIVER_H_ #include "LocationFrame.h" class AOAReciver { private: unsigned char lastKeys; bool open; public: AOAReciver(); void onReceiveData(unsigned char *mFrame); ~AOAReciver(); }; #endif /* AOARECIVER_H_ */
e47dc75e7c2ec499e2758b49fff34e7cf31f27f4
96e63fc690bc12d3d95a947a3f5ed52b7c7d79dc
/project_3/Code/main.cpp
ec85bbece06bebf0cd659ae61b3f13e5674bb8c8
[]
no_license
AlexYinHan/Compiler_Projects
baacd1b7025f6cb34e069e5695122f92fb367e02
63f41b6076a07a1d3ab480c208e7c947cf3ab3f2
refs/heads/master
2020-04-16T09:53:41.645579
2019-01-29T10:30:10
2019-01-29T10:30:10
165,481,219
0
0
null
null
null
null
UTF-8
C++
false
false
1,003
cpp
main.cpp
#include "common.h" #include "parseCommon.h" #include "SemanticAnalyzer.h" Node* treeRoot = NULL; SyntaxErrorFlag syntaxErrorFlag = NO_SYNTAX_ERROR; LexErrorFlag lexErrorFlag = NO_LEX_ERROR; int main(int argc, char** argv) { if(argc <= 1) { return 1; } FILE* f = fopen(argv[1], "r"); if(!f) { perror(argv[1]); return 1; } yyrestart(f); yyparse(); if(lexErrorFlag == NO_LEX_ERROR && syntaxErrorFlag == NO_SYNTAX_ERROR) { #ifdef DEBUG Node::printTree(treeRoot); #endif SemanticAnalyzer semanticAnalyzer; semanticAnalyzer.getSymbolTable()->setSupportNestedScope(false); // nested scope not supported for inter code yet semanticAnalyzer.analyse(treeRoot); if(semanticAnalyzer.getSemanticErrorFlag() == NO_SEMANTIC_ERROR) { InterCodeTranslater IRT(semanticAnalyzer.getSymbolTable()); IRT.translate(treeRoot); if(argc >= 3) { IRT.output(argv[2]); } else { IRT.output(); } } } Node::deleteTree(treeRoot); return 0; }
d51026233588c9afd74ac4022128512c3a15e69e
b0069cfa317b9281f064a7fbd9d1463c33ee1ac4
/Firestore/core/src/util/path.h
27fe6907088e97a592843590210d855a41e8d190
[ "Swift-exception", "MIT", "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
firebase/firebase-ios-sdk
5bb2b5ef2be28c993e993517059452ddb8bee1e6
1dc90cdd619c5e8493df4a01138e2d87e61bc027
refs/heads/master
2023-08-29T23:15:28.905909
2023-08-29T21:49:41
2023-08-29T21:49:41
89,033,556
5,048
1,594
Apache-2.0
2023-09-14T21:11:30
2017-04-22T00:26:50
Objective-C
UTF-8
C++
false
false
6,138
h
path.h
/* * Copyright 2018 Google * * 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 FIRESTORE_CORE_SRC_UTIL_PATH_H_ #define FIRESTORE_CORE_SRC_UTIL_PATH_H_ #include <string> #include <utility> #include "Firestore/core/src/util/string_apple.h" #include "absl/strings/string_view.h" namespace firebase { namespace firestore { namespace util { /** * An immutable native pathname string. Paths can be absolute or relative. Paths * internally maintain their filesystem-native encoding. * * The intent of the API is that high-level code generally just uses UTF-8- * encoded string-literals or strings for the segments and constructs a * filesystem-native Path using APIs like Path::JoinUtf8. * * Lower level code may need to construct derived Paths from values obtained * from the filesystem that already are in the right encoding. */ class Path { public: #if defined(_WIN32) using char_type = wchar_t; #else using char_type = char; #endif using string_type = std::basic_string<char_type>; static constexpr size_t npos = static_cast<size_t>(-1); /** * Creates a new Path from a UTF-8-encoded pathname. */ static Path FromUtf8(absl::string_view utf8_pathname); #if defined(_WIN32) /** * Creates a new Path from a UTF-16-encoded pathname. */ // absl::wstring_view does not exist :-(. static Path FromUtf16(const wchar_t* begin, size_t size); #endif #if defined(__OBJC__) /** * Creates a new Path from the given NSString pathname. */ static Path FromNSString(NSString* path) { return FromUtf8(MakeString(path)); } #endif Path() = default; const string_type& native_value() const { return pathname_; } const char_type* c_str() const { return pathname_.c_str(); } bool empty() const { return pathname_.empty(); } size_t size() const { return pathname_.size(); } #if defined(_WIN32) std::string ToUtf8String() const; #else const std::string& ToUtf8String() const; #endif // defined(_WIN32) #if defined(__OBJC__) NSString* ToNSString() const { return MakeNSString(native_value()); } #endif /** * Returns a new Path containing the unqualified trailing part of this path, * e.g. "c" for "/a/b/c". */ Path Basename() const; /** * Returns a new Path containing the parent directory of this path, e.g. * "/a/b" for "/a/b/c". * * Note: * * Trailing slashes are treated as a separator between an empty path * segment and the dirname, so the Dirname of "/a/b/c/" is "/a/b/c". * * Runs of more than one slash are treated as a single separator, so * the Dirname of "/a/b//c" is "/a/b". * * Paths are not canonicalized, so the Dirname of "/a//b//c" is "/a//b". */ Path Dirname() const; /** * Returns true if this Path is an absolute path. */ bool IsAbsolute() const; /** * Returns true if this pathname's last component has the given file * extension. * * @param ext The file extension (including leading dot). */ bool HasExtension(const Path& ext) const; /** * Returns a new Path with the given UTF-8 encoded path segment appended, * as if by calling `Append(Path::FromUtf8(path))`. */ Path AppendUtf8(absl::string_view path) const; Path AppendUtf8(const char* path, size_t size) const { return AppendUtf8(absl::string_view{path, size}); } #if defined(_WIN32) Path AppendUtf16(const wchar_t* path, size_t size) const { Path result{*this}; result.MutableAppendSegment(path, size); return result; } #endif /** * Returns the paths separated by path separators. * * @param base If base is of type std::string&& the result is moved from this * value. Otherwise the first argument is copied. * @param paths The rest of the path segments. */ template <typename P1, typename... PA> static Path JoinUtf8(P1&& base, const PA&... paths) { Path result = Path::FromUtf8(base); result.MutableAppendUtf8(paths...); return result; } friend bool operator==(const Path& lhs, const Path& rhs); friend bool operator!=(const Path& lhs, const Path& rhs) { return !(lhs == rhs); } private: explicit Path(string_type&& native_pathname) : pathname_{std::move(native_pathname)} { } /** * If `path` is relative, appends it to `*this`. If `path` is absolute, * replaces `*this`. */ template <typename... P> void MutableAppend(const Path& path, const P&... rest) { MutableAppendSegment(path.c_str(), path.size()); MutableAppend(rest...); } void MutableAppend() { // Recursive base case; nothing to do. } void MutableAppendSegment(const char_type* path, size_t size); /** * If `path` is relative, appends it to `*this`. If `path` is absolute, * replaces `*this`. */ template <typename P1, typename... P> void MutableAppendUtf8(const P1& path, const P&... rest) { MutableAppendUtf8Segment(path); MutableAppendUtf8(rest...); } void MutableAppendUtf8Segment(absl::string_view path); void MutableAppendUtf8Segment(const Path& path) { // Allow existing Paths to be passed to Path::JoinUtf8. MutableAppendSegment(path.c_str(), path.size()); } void MutableAppendUtf8() { // Recursive base case; nothing to do. } /** * Returns a copy of the given path. * * This non-public variant of FromUtf8 allows JoinUtf8 to take a Path as its * first argument. */ static Path FromUtf8(const Path& path) { return path; } string_type pathname_; }; } // namespace util } // namespace firestore } // namespace firebase #endif // FIRESTORE_CORE_SRC_UTIL_PATH_H_
92ec57e469135f31dad3a5fce558ae1e1e5b7799
1fa349ea3a835bd0bf421514080751aea352796d
/ChildrenOfOsi/ChildrenOfOsi/ConversationLogObj.cpp
18e2930668174f022c2b26d120cfd58db95b53a0
[]
no_license
EronLake/Children-of-Ase
10208f9d728a0bbc9c9bbb2a0d601e0b4f20f864
e12e0182104927bb4f2d5824515e72cd1a5b5a91
refs/heads/master
2022-11-29T00:15:23.377916
2020-08-13T21:10:02
2020-08-13T21:10:02
78,604,222
3
0
null
2017-06-28T20:28:32
2017-01-11T04:58:42
C++
UTF-8
C++
false
false
1,208
cpp
ConversationLogObj.cpp
#include "ConversationLogObj.h" #include "ConversationPoint.h" #include "stdafx.h" #include "ConversationPoint.h" ConversationLogObj::ConversationLogObj() { who = 0; conv_point = nullptr; number_of_times_said = 0; Memory* mem = nullptr; topic = std::make_pair(0, mem); } ConversationLogObj::~ConversationLogObj() { } int ConversationLogObj::get_who() { return who; } ConversationPoint* ConversationLogObj::get_conv_point() { return conv_point; } std::pair<int, Memory*> ConversationLogObj::get_topic() { return topic; } int ConversationLogObj::get_number_of_times_said() { return number_of_times_said; } void ConversationLogObj::set_who(int person) { who = person; } void ConversationLogObj::set_conv_point(ConversationPoint* con_point) { conv_point = con_point; } void ConversationLogObj::set_topic(int person, Memory* mem) { //doing this instead of using push_back() function in here because //I initialize the topic vector in the class constructor by //pushing back 0 and a nullptr topic.first = person; topic.second = mem; } void ConversationLogObj::update_number_of_times_said() { ++number_of_times_said; }
463f6e9be46f3802c3d8a7928cfbb0633987d9d8
c427c20feaa857327f32c7e3ec2c69e90b478281
/MyCpp/MyPro/MyNet/MyNet.h
b5480da08b2173825b55e402f980d30df05760c4
[]
no_license
chenhuidong/MyGit
039dc4cf356c458eac6c69617b47407f5e353ff4
93f92110a0696562765e0a6c424193f05b81c124
refs/heads/master
2020-04-03T23:29:40.094276
2019-03-28T09:31:36
2019-03-28T09:31:36
33,935,620
3
0
null
null
null
null
UTF-8
C++
false
false
2,003
h
MyNet.h
#ifndef __MY_LIB_MY_NET_H_ #define __MY_LIB_MY_NET_H_ #include "MyStdAfx.h" #include "MyTR.h" #include <boost/asio.hpp> #include <boost/bind.hpp> using namespace boost; using namespace boost::asio; #include "student.pb.h" namespace MMyLib { typedef boost::shared_ptr<ip::tcp::socket> sock_pt; class MySessionBase { public: MySessionBase(boost::asio::io_service& ios); virtual ~MySessionBase(); virtual void start() = 0; virtual void write_handler(const boost::system::error_code& ec) = 0; virtual void read_handler(const boost::system::error_code& ec, boost::shared_ptr<vector<char> > str) = 0; public: sock_pt m_oSocket; }; class MyServSession1: public MySessionBase, public boost::enable_shared_from_this<MyServSession1> { public: MyServSession1(boost::asio::io_service& io_service); virtual ~MyServSession1(); void start(); void write_handler(const boost::system::error_code& ec); void read_handler(const boost::system::error_code& ec, boost::shared_ptr<vector<char> > str); }; class MyCltSession1: public MySessionBase, public boost::enable_shared_from_this<MyCltSession1> { public: MyCltSession1(boost::asio::io_service& io_service); virtual ~MyCltSession1(); void start(); void write_handler(const boost::system::error_code& ec); void read_handler(const boost::system::error_code& ec, boost::shared_ptr<vector<char> > str); }; class MyServer { public: MyServer(io_service& in_oIos); virtual ~MyServer(); void start(); template <typename T> void accept_handler(boost::shared_ptr<T> new_session, const boost::system::error_code& ec) { if (ec) return; new_session->start(); start(); } private: boost::asio::io_service& m_oIos; ip::tcp::acceptor m_oAcceptor; }; class MyClient { public: MyClient(io_service& in_oIos); virtual ~MyClient(); void start(); void conn_handler(boost::shared_ptr<MyCltSession1> new_session, const boost::system::error_code& ec); private: boost::asio::io_service& m_oIos; ip::tcp::endpoint m_oEp; }; }; #endif
9597c0502d8ee72407fcd7c8b0d464de9b90b2b3
c33f5ff31cbb46c3a151abf0752e9d9f9267099d
/mainwindow.cpp
e06e0a74d050f63ec594e088e984046f5cdf61df
[]
no_license
BluePerception/BluesPub
d72db669c3fa6bdceaa4000baaa6bfb7f1fc885b
f26fb20f2c46c53e5b6c1b3933221e1c1cc263c2
refs/heads/master
2021-06-27T06:27:10.265644
2017-09-16T09:36:23
2017-09-16T09:36:23
103,062,008
4
0
null
null
null
null
UTF-8
C++
false
false
470
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <iostream> using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), actualview(0){ ui->setupUi(this); } MainWindow::~MainWindow(){ delete ui; } void MainWindow::change(QWidget* m){ if (actualview) { setCentralWidget(0); actualview->hide(); } actualview = m; setCentralWidget(actualview); actualview->show(); }