hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9f915e83118f6cf2fd3b289f69af404bc8725906
1,172
cpp
C++
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
1
2020-09-30T10:36:06.000Z
2020-09-30T10:36:06.000Z
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
24_dynamic_1/5_coin_change.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; // d=array of denominations // sample // 4 2 // 1 2 // output // 3 int coin_change(int n, int *d,int num_den, int **storage){ if(n<0){ return 0; } if(n==0){ return 1; } if(num_den==0){ return 0; } if(storage[n][num_den]>-1){ return storage[n][num_den]; } int first = coin_change(n-d[0],d,num_den,storage); int second = coin_change(n,d+1,num_den-1,storage); storage[n][num_den]=first+second; return first+second; } int main(){ int n; //rupees cin>>n; int num_den; //no of den of coins cin>>num_den; int *d=new int[num_den]; for(int i=0;i<num_den;i++){ cin>>d[i]; } int **storage=new int*[n+1]; for(int i=0;i<=n;i++){ storage[i]=new int[num_den+1]; } for(int i=0;i<=n;i++){ for(int j=0;j<=num_den;j++){ storage[i][j]=-1; } } // for(int i=0;i<n;i++){ // for(int j=0;j<num_den;j++){ // cout<<storage[i][j]<<" "; // } // cout<<"\n"; // } cout<<coin_change(n,d,num_den,storage)<<endl; }
20.928571
58
0.503413
meyash
7a04d2c5b41a20c8832eda458453611fbf05fec6
4,891
cc
C++
src/plat-win/drivers/windows_nvme_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/plat-win/drivers/windows_nvme_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/plat-win/drivers/windows_nvme_driver.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
/** * @file windows_nvme_driver.cc * @author Joseph Lee <development@jc-lab.net> * @date 2020/07/23 * @copyright Copyright (C) 2020 jc-lab.\n * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ #include "windows_nvme_driver.h" #include "driver_utils.h" #include "windows_nvme_ioctl.h" #include "scsi_driver.h" namespace jcu { namespace dparm { namespace plat_win { namespace drivers { class WindowsNvmeDriverHandle : public WindowsDriverHandle { private: std::string device_path_; HANDLE handle_; public: std::string getDriverName() const override { return "WindowsNvmeDriver"; } WindowsNvmeDriverHandle(const char *path, HANDLE handle, windows10::TStorageQueryWithBuffer *nptwb) : device_path_(path), handle_(handle) { driving_type_ = kDrivingNvme; nvme_identify_device_buf_.insert( nvme_identify_device_buf_.end(), &nptwb->buffer[0], &nptwb->buffer[sizeof(nptwb->buffer)]); } HANDLE getHandle() const override { return handle_; } void close() override { if (handle_ && (handle_ != INVALID_HANDLE_VALUE)) { ::CloseHandle(handle_); handle_ = nullptr; } } const std::string &getDevicePath() const override { return device_path_; } DparmResult doSecurityCommand(uint8_t protocol, uint16_t com_id, int rw, void *buffer, uint32_t len, int timeout) override { return ScsiDriver::doSecurityCommandImpl(handle_, protocol, com_id, rw, buffer, len, timeout); } bool driverHasSpecificNvmeGetLogPage() const override { return true; } DparmResult doNvmeGetLogPage(uint32_t nsid, uint8_t log_id, bool rae, uint32_t data_len, void *data) override { windows10::TStorageQueryWithBuffer nptwb; DWORD dwReturned = 0; int werr = 0; ZeroMemory(&nptwb, sizeof(nptwb)); nptwb.protocol_specific.ProtocolType = ProtocolTypeNvme; nptwb.protocol_specific.DataType = NVMeDataTypeLogPage; nptwb.protocol_specific.ProtocolDataRequestValue = log_id; nptwb.protocol_specific.ProtocolDataRequestSubValue = 0; nptwb.protocol_specific.ProtocolDataRequestSubValue2 = 0; nptwb.protocol_specific.ProtocolDataOffset = sizeof(nptwb.protocol_specific); nptwb.protocol_specific.ProtocolDataLength = (sizeof(nptwb.buffer) > data_len) ? data_len : sizeof(nptwb.buffer); nptwb.query.PropertyId = StorageAdapterProtocolSpecificProperty; nptwb.query.QueryType = PropertyStandardQuery; if (!DeviceIoControl(handle_, IOCTL_STORAGE_QUERY_PROPERTY, &nptwb, sizeof(nptwb), &nptwb, sizeof(nptwb), &dwReturned, NULL)) { werr = (int) ::GetLastError(); return { DPARME_SYS, werr }; } memcpy(data, nptwb.buffer, nptwb.protocol_specific.ProtocolDataLength); return { DPARME_OK, 0 }; } }; DparmReturn<std::unique_ptr<WindowsDriverHandle>> WindowsNvmeDriver::open(const char *path) { std::string strpath(path); std::basic_string<TCHAR> drive_path(strpath.cbegin(), strpath.cend()); int werr = 0; HANDLE drive_handle; do { drive_handle = CreateFile( drive_path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if (!drive_handle || (drive_handle == INVALID_HANDLE_VALUE)) { werr = (int) ::GetLastError(); break; } windows10::TStorageQueryWithBuffer nptwb; DWORD dwReturned = 0; ZeroMemory(&nptwb, sizeof(nptwb)); nptwb.protocol_specific.ProtocolType = ProtocolTypeNvme; nptwb.protocol_specific.DataType = NVMeDataTypeIdentify; nptwb.protocol_specific.ProtocolDataRequestValue = NVME_IDENTIFY_CNS_CONTROLLER; nptwb.protocol_specific.ProtocolDataRequestSubValue = 0; nptwb.protocol_specific.ProtocolDataOffset = sizeof(nptwb.protocol_specific); nptwb.protocol_specific.ProtocolDataLength = sizeof(nptwb.buffer); nptwb.query.PropertyId = StorageAdapterProtocolSpecificProperty; nptwb.query.QueryType = PropertyStandardQuery; if (!DeviceIoControl(drive_handle, IOCTL_STORAGE_QUERY_PROPERTY, &nptwb, sizeof(nptwb), &nptwb, sizeof(nptwb), &dwReturned, NULL)) { werr = (int) ::GetLastError(); break; } std::unique_ptr<WindowsNvmeDriverHandle> driver_handle(new WindowsNvmeDriverHandle(path, drive_handle, &nptwb)); return {DPARME_OK, 0, 0, std::move(driver_handle)}; } while (0); if (drive_handle && (drive_handle != INVALID_HANDLE_VALUE)) { ::CloseHandle(drive_handle); } return {DPARME_SYS, werr}; } DparmReturn<std::unique_ptr<WindowsDriverHandle>> WindowsNvmeDriver::open(const WindowsPhysicalDrive& drive_info) { return this->open(drive_info.physical_disk_path.c_str()); } } // namespace dparm } // namespace plat_win } // namespace dparm } // namespace jcu
33.047297
126
0.721734
jc-lab
7a0912953604c5a3096fe228d4e161be1c38cbb0
10,236
cpp
C++
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
4
2017-06-20T10:05:31.000Z
2019-05-04T14:25:23.000Z
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
null
null
null
helperFunctions.cpp
JoshVorick/LipReader
126212bc7e50316146a3b8f5551e5c475af67eae
[ "Apache-2.0" ]
3
2015-08-18T11:04:55.000Z
2018-07-25T12:56:01.000Z
#include "opencv2/opencv.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/nonfree/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/nonfree/nonfree.hpp" #include <fstream> using namespace cv; using namespace std; const double ANGLE_W = .3; const double SIZE_W = .3; const double DIST_W = .4; #define FEATURE_THRESHHOLD 120 #define FRAME_BLUR 1 enum { NONE, FF, OO, JJ, MM, TH }; #define NUM_SOUNDS 6 // Compare key points by location // Sorts top to bottom and left to right (I think) bool compKeyPointsLocY(KeyPoint a, KeyPoint b) { if (a.pt.y < b.pt.y) return true; if (a.pt.y == b.pt.y && a.pt.x < b.pt.x) return true; return false; } // Compare key points by location // Sorts left to right and top to bottom(I think) bool compKeyPointsLocX(KeyPoint a, KeyPoint b) { if (a.pt.x < b.pt.x) return true; if (a.pt.x == b.pt.x && a.pt.y < b.pt.y) return true; return false; } // Compare key points based on size // Biggest first, smallest last bool compKeyPointsSize(KeyPoint a, KeyPoint b) { return a.size > b.size; } // Compare key points based on angle // Biggest first, smallest last bool compKeyPointsAngle(KeyPoint a, KeyPoint b) { return a.angle > b.angle; } /* std::vector<float> convertToFloatArray(std::vector<KeyPoint> pts) { // Trim down to the 80 biggest features if (pts.size() > 20) { std::sort(pts.begin(), pts.end(), compKeyPointsSize); pts.erase(pts.begin() + 20, pts.end()); } //Sort by location to try and standardize their order std::sort(pts.begin(), pts.end(), compKeyPointsLoc); std::vector<float> arr; for(int i=0; i<pts.size(); i++) { arr.push_back( pts[i].pt.x ); arr.push_back( pts[i].pt.y ); arr.push_back( pts[i].size ); arr.push_back( pts[i].angle ); } //Make the vector 80 long if it isn't already while (arr.size() < 80) { arr.push_back(0); } return arr; } */ // Calculates the distance between two features float distFeature(KeyPoint a, KeyPoint b) { return (a.pt.x - b.pt.x)*(a.pt.x - b.pt.x) + (a.pt.y - b.pt.y)*(a.pt.y - b.pt.y); } // This functiion takes in the new features and // tries to align them with the old ones so that // features[0][0] and features [1][0] will be consecutive // frames of the same feature std::vector<KeyPoint> alignNewFeatures(std::vector<KeyPoint> oldF, std::vector<KeyPoint> newF) { std::vector<KeyPoint> outF; for (int i=0; i < oldF.size(); i++) { float minDist = 1000; KeyPoint closest; int indexClosest = -1; // Find which feature from 'newF' is closest to this feature for (int j=0; j < newF.size(); j++) { if (distFeature(newF[j], oldF[i]) < minDist) { minDist = distFeature(newF[j], oldF[i]); closest = newF[j]; indexClosest = j; } } // If closest is close enough (such that it's probably the same feature) // Add it to the output vector and remove it from newF if (minDist < 20) { outF.push_back(closest); newF.erase(newF.begin() + indexClosest); } else if (oldF[i].size == 0 && indexClosest > -1) { // If it was a placeholder feature last frame outF.push_back(closest); newF.erase(newF.begin() + indexClosest); } else { // Otherwise set this feature to the correct location, but 0 size KeyPoint k(oldF[i].pt, 0); outF.push_back(k); } } //Throw all the new features (ones that weren't in last frame) into open spots (where size has been 0 for two frames) for (int i=0; i<oldF.size(); i++) { if (oldF[i].size == 0 && outF[i].size == 0 && newF.size() > 0) { outF[i] = newF[0]; newF.erase(newF.begin()); } } for (int i=0; i<newF.size(); i++) { outF.push_back(newF[i]); } return outF; } // Trims the features that aren't apparent thoughout most frames // THe threshhold is the percent of frames features must persist in std::vector<std::vector<KeyPoint> > trimBadFeatures(std::vector<std::vector<KeyPoint> > arr, double threshhold) { std::vector<std::vector<KeyPoint> > outF; if (arr.size() < 1) return outF; // First make it a nice rectangle by adding filler points // This makes trimming it easier/neater int maxLen = arr[arr.size() - 1].size(); for (int i=0; i < arr.size(); i++) { while (arr[i].size() < maxLen) { KeyPoint k(0,0,0); arr[i].push_back(k); } } // Now we start firguring which features to keep for (int j=0; j < maxLen; j++) { // Loop through one feature across all its frames to see if it persists int numAppearances = 0; KeyPoint kp = arr[0][j]; for (int i=0; i < arr.size(); i++) { if (distFeature(kp, arr[i][j]) < 20 && arr[i][j].size > 0) { numAppearances++; } kp = arr[i][j]; } // If the feature is a good one, add it to the output if (numAppearances > arr.size() * threshhold){ for (int i=0; i < arr.size(); i++) { if (outF.size() <= i) { std::vector<KeyPoint> kpArr; kpArr.push_back(arr[i][j]); outF.insert(outF.begin(), kpArr); } else { outF[i].push_back(arr[i][j]); } } } } return outF; } // Sorts the array while keeping features aligned // Yes I know its an insertion sort. // If that bothers you, make a Pull Request std::vector<std::vector<KeyPoint> > sortFeatures(std::vector<std::vector<KeyPoint> > arr) { std::vector<std::vector<KeyPoint> > outF; if (arr.size() < 1 || arr[0].size() < 1) return outF; // Initialize output vector to be right number of frames for (int i=0; i < arr.size(); i++) { std::vector<KeyPoint> kpArr; outF.push_back(kpArr); } // Find element that should go last, add it, repeat while (arr[0].size() > 0) { int indexOfMin = 0; KeyPoint smallest = arr[0][0]; // Find which is smallest for (int i=0; i < arr[0].size(); i++) { if (arr[0][i].pt.x < smallest.pt.x || (arr[0][i].pt.x == smallest.pt.x && arr[0][i].pt.y < smallest.pt.y)) { indexOfMin = i; smallest = arr[0][i]; } } // Insert elements into 'outF' and remove them from 'arr' for (int i=0; i < arr.size(); i++) { outF[i].push_back(arr[i][indexOfMin]); arr[i].erase(arr[i].begin() + indexOfMin); } } return outF; } // Returns how dissimilar two points are // Based on location, size, and angle int calcDiff(KeyPoint a, KeyPoint b) { int dist = distFeature(a, b); int ds = abs(a.size - b.size); int da = abs(cos(a.angle) - cos(b.angle)); // Using cosine makes it so that 179 and -179 are close together return dist + ds + da*10; } // Returns % accuracy of feed more or less // Uses |(theoretical - actual) / theoretical| double calcPerformance(KeyPoint lib, KeyPoint feed) { double dist = calcDiff(lib, feed) / 20; double size, angle; if (lib.size != 0) size = abs(lib.size - feed.size) / lib.size; else size = dist; if (lib.angle != -1) angle = abs(lib.angle - feed.angle) / lib.angle; else angle = dist; return ANGLE_W*angle + SIZE_W*size + DIST_W*(1 - dist); } // Compare two matrices of features to see how similar they are double compareFeatures(std::vector<std::vector<KeyPoint> > lib, std::vector<std::vector<KeyPoint> > feed) { #if 0 int diff = 0; // Keeps track of how similar the two vectors are int numWrong = 0; //Keeps track of features that aren't in both // Resize feed to be the same number of frames as lib if (feed.size() > lib.size()) { feed.erase(feed.begin(), feed.begin() + (feed.size() - lib.size() - 1)); } if (lib.size() < 1 || feed.size() < 1) return 10000000; // Iterate through one array // Find the distance feedetween each feature and its closest counterpart for (int i=0; i < lib.size() && i < feed.size(); i++) { for (int j=0; j < lib[i].size(); j++) { // Find nearest feature from other array int distMin = 10000; KeyPoint nearest(0,0,0); for (int k=0; k < feed[i].size(); k++) { if (distFeature(lib[i][j], feed[i][k]) < distMin){ distMin = distFeature(lib[i][j], feed[i][k]); nearest = feed[i][k]; } } if (distMin > 30) diff += calcDiff(lib[i][j], nearest); else numWrong++; } } return diff; #else double performance = 0; double maxPerformance = 0; // Resize feed to be the same number of frames as lib if (feed.size() > lib.size()) { feed.erase(feed.begin(), feed.begin() + (feed.size() - lib.size())); } if (lib.size() < 1 || feed.size() < 1) return 0; // Iterate through one array // Find the distance feedetween each feature and its closest counterpart for (int i=0; i < lib.size() && i < feed.size(); i++) { for (int j=0; j < lib[i].size(); j++) { // Find nearest feature from other array int distMin = 10000; KeyPoint nearest(0,0,0); for (int k=0; k < feed[i].size(); k++) { if (distFeature(lib[i][j], feed[i][k]) < distMin){ distMin = distFeature(lib[i][j], feed[i][k]); nearest = feed[i][k]; } } if (distMin < 20) performance += calcPerformance(lib[i][j], nearest); maxPerformance++; } } return performance / maxPerformance; #endif } Mat combineImages(std::vector<Mat> images) { assert(images.size() >= 1); double weight = 1. / images.size(); Mat outImage = weight * images[0]; for (int i=1; i < images.size(); i++) { outImage += weight * images[i]; } return outImage; } void whichSound(double diffs[]) { // Find what the highest value is double highest = 0; for (int i=0; i < NUM_SOUNDS; i++) { if (diffs[i] > highest) highest = diffs[i]; } // Now figure out which letter has that value if (highest == diffs[NONE]) { printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM_~______\n"); } else if (highest == diffs[FF]) { printf("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__F_____\n"); } else if (highest == diffs[OO]) { printf("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO___O____\n"); } else if (highest == diffs[JJ]) { printf("JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ____J___\n"); } else if (highest == diffs[MM]) { printf("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM_____M__\n"); } else if (highest == diffs[TH]) { printf("THTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTHTH______TH\n"); } //printf("NONE: %.3f FF: %.3f OO: %.3f JJ: %.3f MM: %.3f TH: %.3f\n", diffs[NONE], diffs[FF], diffs[OO], diffs[JJ], diffs[MM], diffs[TH]); }
30.105882
139
0.648789
JoshVorick
7a0c65a7178771a71e152c0fe5e1d767fdc3287d
4,617
cpp
C++
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
1
2019-09-01T05:40:51.000Z
2019-09-01T05:40:51.000Z
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
null
null
null
src/lcd.cpp
calhighrobotics/2017-2018-vex-in-the-zone
bc41f47971a601dc896a1054edd0eca5c5b10d1b
[ "MIT" ]
null
null
null
// contains the code that controls the LCD screen #include "main.hpp" // what port the LCD screen goes into #define LCD_PORT uart1 // amount of milliseconds between each LCD update #define LCD_POLL_SPEED 100ul // the different types of things the LCD can do enum LoopState { // select the autonomous program AUTON_SELECT, // display primary/backup battery voltage DISPLAY_BATTERY, // control the lift from the LCD LIFT_CONTROL }; // tracks the state of the buttons class ButtonState { public: ButtonState(FILE* lcdPort): lcdPort(lcdPort), current(0), previous(0) {} // polls all the lcd buttons void poll() { previous = current; current = lcdReadButtons(lcdPort); } // checks if a button was pressed bool pressed(unsigned int button) const { return current & button; } // checks if a button was just pressed bool justPressed(unsigned int button) const { return pressed(button) && !(previous & button); } private: FILE* lcdPort; unsigned int current; unsigned int previous; }; // corresponds to state_t enum // takes a reference to the ButtonState, returns what the LoopState should be // changed to static LoopState autonSelect(const ButtonState& buttons); static LoopState displayBattery(const ButtonState& buttons); static LoopState liftControl(const ButtonState& buttons); // declared in main.hpp void lcd::controller(void*) { lcdInit(LCD_PORT); lcdClear(LCD_PORT); lcdSetBacklight(LCD_PORT, false); // the action that should be taken, kinda like a state machine LoopState loopState = LIFT_CONTROL; // tells loop functions what buttons are being pressed ButtonState buttons(LCD_PORT); // used for timing cyclic delays unsigned long time = millis(); while (true) { buttons.poll(); // do a different loop action based on loopState switch (loopState) { case AUTON_SELECT: loopState = autonSelect(buttons); break; case DISPLAY_BATTERY: loopState = displayBattery(buttons); break; case LIFT_CONTROL: loopState = liftControl(buttons); break; } // wait a bit before receiving input again taskDelayUntil(&time, LCD_POLL_SPEED); } } LoopState autonSelect(const ButtonState& buttons) { // so we don't have to type "auton::" 5 billion times using namespace auton; // used for printing the name of an autonomous program static const char* autonNames[AUTONID_MAX + 1] = { "Nothing", "Forward+Backward", "MG+Cone Left", "MG+Cone Right", "Score Stationary" }; // see if the left/right buttons were just pressed bool left = buttons.justPressed(LCD_BTN_LEFT); bool right = buttons.justPressed(LCD_BTN_RIGHT); // if left, go up the autonNames list if (left && !right) { autonid = (AutonID) (autonid - 1); if (autonid < AUTONID_MIN || autonid > AUTONID_MAX) { // go back to the end of the list autonid = AUTONID_MAX; } } // if right, go down the autonNames list else if (!left && right) { autonid = (AutonID) (autonid + 1); if (autonid < AUTONID_MIN || autonid > AUTONID_MAX) { // go back to the start of the list autonid = AUTONID_MIN; } } lcdSetText(LCD_PORT, 1, ROBOT_NAME " will do:"); lcdSetText(LCD_PORT, 2, autonNames[autonid]); // if auton selected or enabled by comp switch, start displaying battery if (buttons.justPressed(LCD_BTN_CENTER)) { return DISPLAY_BATTERY; } return AUTON_SELECT; } LoopState displayBattery(const ButtonState& buttons) { lcdPrint(LCD_PORT, 1, "Primary: %.1fV", powerLevelMain() / 1000.0f); lcdPrint(LCD_PORT, 2, "Backup: %.1fV", powerLevelBackup() / 1000.0f); if (buttons.justPressed(LCD_BTN_CENTER)) { return LIFT_CONTROL; } return DISPLAY_BATTERY; } LoopState liftControl(const ButtonState& buttons) { lcdPrint(LCD_PORT, 1, "lift pos = %.1f", motor::getLiftPos()); lcdSetText(LCD_PORT, 2, "v ^"); if (buttons.pressed(LCD_BTN_LEFT)) { motor::setLift(-127); } else if (buttons.pressed(LCD_BTN_RIGHT)) { motor::setLift(127); } else if (!isJoystickConnected(1)) { motor::setLift(0); } if (buttons.justPressed(LCD_BTN_CENTER)) { return AUTON_SELECT; } return LIFT_CONTROL; }
27.319527
77
0.633745
calhighrobotics
7a0db341149b2c2e860b1eb16612ac80ea171d69
3,086
hpp
C++
src/ibeo_8l_sdk/src/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
tomcamp0228/ibeo_ros2
ff56c88d6e82440ae3ce4de08f2745707c354604
[ "MIT" ]
1
2020-06-19T11:01:49.000Z
2020-06-19T11:01:49.000Z
include/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
null
null
null
include/ibeosdk/datablocks/snippets/ScalaFpgaRawHeader.hpp
chouer19/enjoyDriving
e4a29e6cad7d3b0061d59f584cce7cdea2a55351
[ "MIT" ]
2
2020-06-19T11:01:48.000Z
2020-10-29T03:07:14.000Z
//====================================================================== /*! \file ScalaFpgaRawHeader.hpp * * \copydoc Copyright * \author kd * \date Sep 17, 2015 *///------------------------------------------------------------------- #ifndef IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN #define IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN //====================================================================== #include <ibeosdk/misc/WinCompatibility.hpp> #include <ibeosdk/datablocks/snippets/Snippet.hpp> #include <ibeosdk/inttypes.hpp> #include <ibeosdk/misc/deprecatedwarning.hpp> #include <istream> #include <ostream> //====================================================================== namespace ibeosdk { //====================================================================== class ScalaFpgaRawHeader : public Snippet { public: static std::streamsize getSerializedSize_static() { return 16; } public: ScalaFpgaRawHeader(); virtual ~ScalaFpgaRawHeader(); public: //! Equality predicate bool operator==(const ScalaFpgaRawHeader& other) const; bool operator!=(const ScalaFpgaRawHeader& other) const; public: virtual std::streamsize getSerializedSize() const { return getSerializedSize_static(); } virtual bool deserialize(std::istream& is); virtual bool serialize(std::ostream& os) const; public: uint16_t getScanCounter() const { return m_scanCounter; } uint16_t getMinApdOffset() const { return m_minApdOffset; } uint16_t getMaxApdOffset() const { return m_maxApdOffset; } uint16_t getFrequencyInteger() const { return m_frequencyInteger; } uint16_t getFrequencyFractional() const { return m_frequencyFractional; } IBEOSDK_DEPRECATED uint16_t getFreqencyFractional() const { return m_frequencyFractional; } uint16_t getDeviceId() const { return m_deviceId; } public: void setScanCounter(const uint16_t scanCounter) { m_scanCounter = scanCounter; } IBEOSDK_DEPRECATED void setMminApdOffset(const uint16_t minApdOffset) {m_minApdOffset = minApdOffset; } void setMinApdOffset(const uint16_t minApdOffset) {m_minApdOffset = minApdOffset; } void setMaxApdOffset(const uint16_t maxApdOffset) { m_maxApdOffset = maxApdOffset; } void setFrequencyInteger(const uint16_t freqInteger) { m_frequencyInteger = freqInteger; } void setFrequencyFractional(const uint16_t freqFrac) { m_frequencyFractional = freqFrac; } IBEOSDK_DEPRECATED void setFreqencyFractional(const uint16_t freqFrac) { m_frequencyFractional = freqFrac; } void setDeviceId(const uint16_t deviceId) { m_deviceId = deviceId; } public: static const uint16_t blockId; protected: uint16_t m_scanCounter; uint16_t m_minApdOffset; uint16_t m_maxApdOffset; uint16_t m_frequencyInteger; uint16_t m_frequencyFractional; uint16_t m_deviceId; uint16_t m_reservedHeader7; }; // ScalaFpgaRawHeader //====================================================================== } // namespace ibeosdk //====================================================================== #endif // IBEOSDK_SCALAFPGARAWHEADER_HPP_SEEN //======================================================================
33.912088
109
0.647116
tomcamp0228
7a0dc5f049adc357bed1eabd0e3353c4c1f7adb5
1,680
cpp
C++
src/experiments/babybot/armcontrol/YARPGravityEstimator.cpp
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
src/experiments/babybot/armcontrol/YARPGravityEstimator.cpp
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
src/experiments/babybot/armcontrol/YARPGravityEstimator.cpp
robotology-legacy/yarp1
21434f5b776edea201b39a9644552dca59339dbc
[ "Artistic-1.0-Perl" ]
null
null
null
#include "YARPGravityEstimator.h" YARPGravityEstimator::YARPGravityEstimator(int par): _leastSquares(par, 1.0) { _parSize = par; _parameters.Resize(_parSize); _input.Resize(_parSize); _k1 = 0.0; _k2 = 1.0; _deltaK1 = 1.0/__querySize; YMatrix SP0(_parSize, _parSize); SP0 = 0.0; for(int i = 1; i<=_parSize; i++) SP0(i,i) = 1.0; YVector ST0(_parSize); ST0 = 0.0; _leastSquares.Reset(); _leastSquares.SetInitialState(SP0, ST0); } YARPGravityEstimator::~YARPGravityEstimator() { } int YARPGravityEstimator::save(const YARPString &filename) { _lock(); YMatrix p0(_parSize,_parSize); YVector par(_parSize); p0 = _leastSquares.GetP (); par = _parameters; int steps = _leastSquares.GetSteps(); // end of the shared part _unlock(); FILE *fp = fopen(filename.c_str(), "wt"); if (fp == NULL) return YARP_FAIL; fprintf(fp, "%d\n", steps); int i; for(i = 1; i<=_parSize; i++) fprintf (fp, "%lf\n", par(i)); for (i = 1; i <= _parSize; i++) for (int j = 1; j <= _parSize; j++) fprintf (fp, "%lf ", p0 (i, j)); fprintf (fp, "\n"); fclose(fp); return YARP_OK; } int YARPGravityEstimator::load(const YARPString &filename) { _lock(); FILE *fp = fopen(filename.c_str(), "r"); int nsteps; YVector t0(_parSize); YMatrix p0(_parSize,_parSize); fscanf (fp, "%d\n", &nsteps); int i,j; for(i = 0; i < _parSize; i++) fscanf (fp, "%lf\n", t0.data()+i); for (i = 0; i < _parSize; i++) for (j = 0; j < _parSize; j++) fscanf (fp, "%lf ", p0.data()[i] + j); fscanf (fp, "\n"); // set data. _leastSquares.SetInitialState (p0, t0); _leastSquares.SetSteps (nsteps); _parameters = t0; fclose (fp); _unlock(); return YARP_OK; }
18.666667
58
0.632738
robotology-legacy
7a1035590685403ce70b496c3e2ead8986d64c4f
923
cpp
C++
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
src/robot/auto/AutoModeRunner.cpp
roboFiddle/7405M_TowerTakeover_Code
e16ffab17964ff61a25eac2074da78d0d7577caa
[ "MIT" ]
null
null
null
// // Created by alexweiss on 8/14/19. // #include "AutoModeRunner.hpp" namespace auton { AutoModeRunner::AutoModeRunner() { thread_ = new pros::Task(AutoModeRunner::runAuton, this, TASK_PRIORITY_DEFAULT, TASK_STACK_DEPTH_DEFAULT, "AUTO RUNNER"); thread_->suspend(); } void AutoModeRunner::setAutoMode(std::shared_ptr<AutoModeBase> new_auto_mode) { mode_ = new_auto_mode; } void AutoModeRunner::start() { if(mode_) thread_->resume(); } void AutoModeRunner::stop() { if(mode_) thread_->suspend(); } std::shared_ptr<AutoModeBase> AutoModeRunner::getAutoMode() { return mode_; } void AutoModeRunner::runAuton(void* param) { AutoModeRunner* instance = static_cast<AutoModeRunner*>(param); instance->mode_->run(); while(1) pros::Task::delay(50); }; AutoModeRunner::AutoModeRunnerManager AutoModeRunner::instance; }
24.945946
83
0.668472
roboFiddle
7a182ec33426d72818a4bc08ef7e208dd9e30e9a
1,704
cpp
C++
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
superline/producer/superline_client.cpp
Jim-CodeHub/superline
cc6c979371d1e392691b099804bb34d00e63ba4a
[ "Apache-2.0" ]
null
null
null
/**----------------------------------------------------------------------------------------------------------------- * @file subscriber_client.cpp * @brief Send message to superline server, Implement with POSX.1 semaphore and shared memory * * Copyright (c) 2019-2019 Jim Zhang 303683086@qq.com *------------------------------------------------------------------------------------------------------------------ */ #include <superline/producer/superline_client.hpp> using namespace NS_SUPERLINE; /* -------------------------------------------------------------------------------------------------------------------- * * FUNCTIONS IMPLEMENT * -------------------------------------------------------------------------------------------------------------------- */ /** * @brief Send data to superline server (consumer) * @param[in] data * @param[in] size - size of the data * @param[out] None * @return None * @note 1. The client will block if superline has already full * 2. *** EACH DATA SIZE SHALL NOT LARGER THAN BLOCK SIZE **/ void superline_client::send( const void *data, int size ) { P(_shminfo.sem_0_spc); /**< Wating for free space on superline */ P(_shminfo.sem_wrmtx); /**< Multi-process mutex lock */ int _size = (size > _shminfo.m_head->_size)?(_shminfo.m_head->_size):(size); memmove(_shminfo.offset + _shminfo.m_head->wr_inx * _shminfo.m_head->_size, data, _size); _shminfo.m_head->wr_inx += 1; _shminfo.m_head->wr_inx %= (_shminfo.m_head->blocks); /**< Loop write */ V(_shminfo.sem_wrmtx); /**< Multi-process mutext unlock */ V(_shminfo.sem_1_spc); /**< Acc non-free space for superline */ return; }
34.77551
116
0.484155
Jim-CodeHub
7a188b7ccb884ffb7f1c2a4ef903d4997b126b47
37
cpp
C++
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
5
2021-10-19T18:30:43.000Z
2022-03-19T22:02:02.000Z
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
12
2022-03-09T13:40:21.000Z
2022-03-31T12:47:48.000Z
SystemResource/Source/Image/PNG/Chunk/PNGLastModificationTime.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
null
null
null
#include "PNGLastModificationTime.h"
18.5
36
0.837838
BitPaw
7a1ab207cf7cbc87f628177aa6044698027cb90e
1,489
cpp
C++
Drawing-program/Class/aboutScene.cpp
sindre0830/Drawing-Recognition
19eb92103182ddc23428171f74842b980352d5df
[ "MIT" ]
null
null
null
Drawing-program/Class/aboutScene.cpp
sindre0830/Drawing-Recognition
19eb92103182ddc23428171f74842b980352d5df
[ "MIT" ]
122
2021-09-01T10:19:25.000Z
2021-12-09T20:57:26.000Z
Drawing-program/Class/aboutScene.cpp
sindre0830/Drawing-Recognition
19eb92103182ddc23428171f74842b980352d5df
[ "MIT" ]
null
null
null
/** * @file Scene.cpp * @author Maren Sk�restuen Grindal * @version 0.1 * @date 2021-12-05 * * @copyright Copyright (c) 2021 Sindre Eiklid, Rickard Loland, Maren Sk�restuen Grindal */ #include "./Header/aboutScene.h" /* external libraries */ #include <GLFW/glfw3.h> /** * Constructor. */ AboutScene::AboutScene() { heading = new Font("../External/Fonts/CaveatBrush-Regular.ttf", 100); float x1 = getWidth() / 2.f - 60.f, y1 = 200.f, x2 = x1 + 140.f, y2 = y1 + 50.f; Rect rect = { x1, y2, x1, y1, x2, y1, x2, y2 }; NavButton* nav = new NavButton("Main menu", menu, rect, YELLOW); navigation.push_back(nav); } /** * Deconstructor. */ AboutScene::~AboutScene() { delete heading; } /** * Draw the about scene on screen. */ void AboutScene::draw() { Scene::draw(); // Render title RGB txtColor = colors.find(YELLOW)->second; heading->RenderText("About", getWidth() / 2.f - 80.f, getHeight() - 200.f, 1.f, glm::vec3(txtColor.r, txtColor.g, txtColor.b)); // Render about text text->RenderText("You have 60 seconds to draw the words that show up on the screen.", getWidth() / 2.f - 360.f, getHeight() / 2.f + 50.f, 1.f, glm::vec3(0, 0, 0)); text->RenderText("For each drawing the game guesses what are, you will get a point.", getWidth() / 2.f - 360.f, getHeight() / 2.f - 50.f, 1.f, glm::vec3(0, 0, 0)); }
26.589286
99
0.572868
sindre0830
7a1b20619b66ea7e98af60ef3644e1f1899e607d
921
hpp
C++
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
null
null
null
include/zisa/math/triangular_rule.hpp
1uc/ZisaFVM
75fcedb3bece66499e011228a39d8a364b50fd74
[ "MIT" ]
1
2021-08-24T11:52:51.000Z
2021-08-24T11:52:51.000Z
// SPDX-License-Identifier: MIT // Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval #ifndef TRIANGULAR_RULE_H_V7Y5S #define TRIANGULAR_RULE_H_V7Y5S #include <zisa/config.hpp> #include <zisa/math/barycentric.hpp> #include <zisa/math/max_quadrature_degree.hpp> #include <zisa/memory/array.hpp> namespace zisa { struct TriangularRule { array<double, 1> weights; array<Barycentric2D, 1> points; TriangularRule(int_t n_points); TriangularRule(const TriangularRule &qr) = default; TriangularRule(TriangularRule &&qr) = default; }; /// Compute weights and quadrature points. /** * References: * [1] D.A. Dunavant, High degree efficient symmetrical Gaussian quadrature * rules for the triangle, 1985. */ TriangularRule make_triangular_rule(int_t deg); constexpr int_t MAX_TRIANGULAR_RULE_DEGREE = 5; const TriangularRule &cached_triangular_quadrature_rule(int_t deg); } // namespace zisa #endif
24.891892
77
0.765472
1uc
7a1b72a1d7abe3ee6cc8f43a81b4fe5ecfe0ae00
156
cpp
C++
Lectures/Lecture14/counting.cpp
galursa/BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
2
2020-11-07T06:03:45.000Z
2020-12-02T08:22:42.000Z
Lectures/Lecture14/counting.cpp
galursa/WSTI_BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
null
null
null
Lectures/Lecture14/counting.cpp
galursa/WSTI_BasicsOfProgramming
ff3ce4f918048d25cbc724df5a96c09e48476792
[ "MIT" ]
1
2020-12-07T06:01:40.000Z
2020-12-07T06:01:40.000Z
#include <iostream> #include "calculator.h" using namespace std; int main(int argc, char** argv) { cout <<"Result" << multiply(3,5) << "\n"; return 0; }
17.333333
42
0.641026
galursa
7a23e4fe7de4de65f4078636619805e76b093486
14,170
cpp
C++
data/usma_optitrack/src/QuadScripts.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/usma_optitrack/src/QuadScripts.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
data/usma_optitrack/src/QuadScripts.cpp
khairulislam/phys
fc702520fcd3b23022b9253e7d94f878978b4500
[ "MIT" ]
null
null
null
#include "mocap_optitrack/Quad.h" #include "mocap_optitrack/QuadScripts.h" // Base class - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Publisher initialized in specific script class QuadScript::QuadScript() : data(NULL), needsWandCheck(false) {} void QuadScript::give_data(QuadData* data_in) { assert(data_in != NULL); data = data_in; init(); } bool QuadScript::standardWandCheckPasses() const { bool rot_check = std::abs(data->wand_pose.pose.orientation.y) < 0.1; bool z_check = data->wand_pose.pose.position.z > 0.8; return rot_check && z_check; } void QuadScript::set_needsWandCheck(bool input) { needsWandCheck = input; } // TAKEOFF - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Takeoff::Takeoff(double height_in) : tkoff_height(height_in), locked(false) {} void Takeoff::init() { ROS_INFO("Takeoff initialized"); pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); } bool Takeoff::completed() const { return data->local_pose.pose.position.z > tkoff_height; } void Takeoff::publish_topic() { ROS_INFO_ONCE("Starting Takeoff..."); if (!locked) { dest_pose = data->local_pose; locked = data->state.armed && data->state.mode == "OFFBOARD"; if (locked) { ROS_INFO("takeoff position locked!"); } } else { dest_pose.pose.position.z += (0.15) / FRAMES_PER_SEC; } pub.publish(dest_pose); } // SETPOSE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SetPose::SetPose(double px, double py, double pz, double ox, double oy, double oz, double ow) { dest_pose.pose.position.x = px; dest_pose.pose.position.y = py; dest_pose.pose.position.z = pz; dest_pose.pose.orientation.x = ox; dest_pose.pose.orientation.y = oy; dest_pose.pose.orientation.z = oz; dest_pose.pose.orientation.w = ow; } void SetPose::init() { dest_pose.header = data->local_pose.header; pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); ROS_INFO("SetPose initialized"); } bool SetPose::completed() const { double dist = 0.4; double rot = 0.1; bool wand_check = needsWandCheck ? standardWandCheckPasses() : 1; return wand_check && pose_dist_check(dest_pose.pose, data->local_pose.pose, dist, rot); } void SetPose::publish_topic() { ROS_INFO_ONCE("Starting SetPose"); dest_pose.header.stamp = ros::Time::now(); pub.publish(dest_pose); } // FOLLOWOFFSET - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FollowOffset::FollowOffset(double x, double y, double z, int quad_num) : mode(0), quad_to_follow(quad_num) { offset.x = x; offset.y = y; offset.z = z; } FollowOffset::FollowOffset(int mode_in, int quad_num) : mode(mode_in), quad_to_follow(quad_num) {} void FollowOffset::init() { dest_pose.header = data->local_pose.header; pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); ROS_INFO("FollowOffset initialized"); } bool FollowOffset::completed() const { double dist = 0.2; double rot = 0.2; bool wand_check = needsWandCheck ? standardWandCheckPasses() : 1; bool dist_check = pose_dist_check(dest_pose.pose, data->local_pose.pose, dist, rot); return wand_check && dist_check; } void FollowOffset::publish_topic() { ROS_INFO_ONCE("Starting FollowOffset"); dest_pose = data->other_quads.at(quad_to_follow)->get_local_pose(); dest_pose.header.stamp = ros::Time::now(); if (mode == 0) { dest_pose.pose.position.x += offset.x; dest_pose.pose.position.y += offset.y; dest_pose.pose.position.z += offset.z; } else { tf::Quaternion q; tf::quaternionMsgToTF(data->wand_pose.pose.orientation, q); double roll, pitch, yaw; tf::Matrix3x3(q).getRPY(roll, pitch, yaw); if (mode == WAND_ROTATE_TOP) { dest_pose.pose.position.y -= sin(roll) * 0.5; dest_pose.pose.position.x += cos(roll) * 0.5; } else if (mode == WAND_ROTATE_BOTTOM) { dest_pose.pose.position.y += sin(roll) * 0.5; dest_pose.pose.position.x -= cos(roll) * 0.5; } } pub.publish(dest_pose); } // CatchBall - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TODO this is placeholder CatchBall::CatchBall() : catching(false), last_z(0), hitPeak(false), timer(0), dip_timer(0), dipping(false) {} void CatchBall::init() { // TODO This is placeholder dest_pose.header = data->local_pose.header; dest_pose.pose = data->local_pose.pose; dest_pose.pose.position.z = 0.5; pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); } bool CatchBall::completed() const { // TODO placeholder return false; } void CatchBall::publish_topic() { ROS_INFO_ONCE("CatchBall started"); double catch_z = 0.5; // Calculate remaining t in ball flight double x = data->ball_pose.pose.position.x; double y = data->ball_pose.pose.position.y; double z = data->ball_pose.pose.position.z; double a = -9.8; double vx = data->ball_vel.twist.linear.x; double vy = data->ball_vel.twist.linear.y; if (!catching) { vz = data->ball_vel.twist.linear.z; } else { // Much faster instantaneous vz calculation needed vz = (z - last_z) * FRAMES_PER_SEC; } // Calculate t until ball reaches catch_z double t_plus = (-vz + sqrt(vz*vz - 2*a*(z - catch_z))) / a; double t_minus = (-vz - sqrt(vz*vz - 2*a*(z - catch_z))) / a; double t = t_plus > t_minus ? t_plus : t_minus; // Project to predict ending coordinates // TODO figure out why the 4* is needed double x_proj = x + 4 * (vx * t); double y_proj = y + 4 * (vy * t); // See if ball has been thrown yet if (!catching) { dest_pose.header = data->local_pose.header; dest_pose.pose.position.x = -0; dest_pose.pose.position.y = 0; dest_pose.pose.position.z = 0.5; dest_pose.pose.orientation.w = -1; if (catching = vz > 0.3 && z > 1) { ROS_INFO("catching!"); } } // See if ball has reached peak of trajectory if (!hitPeak) { hitPeak = last_z > z; } last_z = z; // Start catch timer if (catching) { ++timer; } // Begin catching movement geometry_msgs::PoseStamped comp_pose = dest_pose; if (timer > FRAMES_PER_SEC / 8) { // Move to projected ball coordinates at catch height if (!dipping) { dest_pose.pose.position.x = x_proj; dest_pose.pose.position.y = y_proj; dest_pose.pose.position.z = catch_z; ROS_INFO("Predicted coords: %.2f, %.2f in %.2fs", x_proj, y_proj, t); // Overcompensate for more aggressive maneuvering double dx = dest_pose.pose.position.x - data->local_pose.pose.position.x; double dy = dest_pose.pose.position.y - data->local_pose.pose.position.y; comp_pose.pose.position.x += 6 * dx; comp_pose.pose.position.y += 6 * dy; // See if about to catch if (dipping = z < catch_z + 0.2) { ROS_INFO("timer ref: %d", timer); ROS_INFO("Actual coords: %.2f, %.2f", x, y); ROS_INFO("STARTING DIP"); } } // Dip to softly catch ball else { ++dip_timer; // Move along trajectory toward a predicted spot underground double dip_z = -1.0; double t_plus_dip = (-vz + sqrt(vz*vz - 2*a*(z - dip_z))) / a; double t_minus_dip = (-vz - sqrt(vz*vz - 2*a*(z - dip_z))) / a; double t_dip = t_plus_dip > t_minus_dip ? t_plus_dip : t_minus_dip; comp_pose.pose.position.x = x + 4 * (vx * t_dip); comp_pose.pose.position.y = y + 4 * (vy * t_dip); comp_pose.pose.position.z = dip_z; ROS_INFO("Dip coords: %.2f, %.2f, -1.0", comp_pose.pose.position.x, comp_pose.pose.position.y); // Reset everything when dip is completed if (dip_timer >= FRAMES_PER_SEC / 4) { ROS_INFO("timer ref: %d", timer); ROS_INFO("ended dip"); ROS_INFO("RESETTING..."); dipping = hitPeak = catching = false; dip_timer = timer = 0; } } } pub.publish(comp_pose); } // Place ATTEMPT 2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Drift::Drift() : locked(false), init_locked(false) {} void Drift::init() { // dest_pose.pose.position.x = -1.0; dest_pose.header = data->local_pose.header; dest_pose.pose.position.z = 0.5; dest_pose.pose.orientation.w = -1; pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); } bool Drift::completed() const { // TODO this is placeholder return false; } void Drift::publish_topic() { ROS_INFO_ONCE("Drift started"); // Get some params double z_vel_offset = 0.01; double vx = data->local_vel.twist.linear.x; double vy = data->local_vel.twist.linear.y; double vz = data->local_vel.twist.linear.z - z_vel_offset; if (!locked) { locked_pose.pose = data->local_pose.pose; // Determine if should lock if (locked = (std::abs(vx) < 0.04 && std::abs(vy) < 0.04 && std::abs(vz) < 0.04) || !init_locked) { ROS_INFO("Locking new position at %.2f, %.2f, %.2f \n", locked_pose.pose.position.x, locked_pose.pose.position.y, locked_pose.pose.position.z); if (!init_locked) { ROS_INFO("making initial position lock"); init_locked = true; } } else { // Otherwise set drift conditions locked_pose.pose.position.x += vx; locked_pose.pose.position.y += vy; locked_pose.pose.position.z += vz - (1.0 / FRAMES_PER_SEC); } } // Unlock if pulled far enough if (locked && !pose_dist_check(locked_pose.pose, data->local_pose.pose, 0.17, 1)) { ROS_INFO("UNLOCKED"); locked = false; } locked_pose.header.stamp = ros::Time::now(); pub.publish(locked_pose); } // MOVINGLAND - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MovingLand::MovingLand() : set_z_above(0.5), disarmed(false) {} void MovingLand::init() { dest_pose = data->plat_pose; pub = data->node.advertise<geometry_msgs::PoseStamped> ("mavros/setpoint_position/local", FRAMES_PER_SEC); } bool MovingLand::completed() const { return !data->state.armed; } void MovingLand::publish_topic() { ROS_INFO_ONCE("Starting MovingLand"); // Aim for pose above platform dest_pose = data->plat_pose; dest_pose.pose.position.z = data->plat_pose.pose.position.z + set_z_above; // Align orientation of quad and platform (depends on arbitrary defn) dest_pose.pose.orientation.z = -data->plat_pose.pose.orientation.w; dest_pose.pose.orientation.w = -data->plat_pose.pose.orientation.z; // Set to move at same vel as plat double vx = data->plat_vel.twist.linear.x; double vy = data->plat_vel.twist.linear.y; dest_pose.pose.position.x += 2.2 * vx; dest_pose.pose.position.y += 2.2 * vy; // Overcompensate to catch up to plat // if (std::sqrt(vx*vx + vy*vy) > 0.10) { if (true) { ROS_INFO_ONCE("Overcompensating"); double dx = data->plat_pose.pose.position.x - data->local_pose.pose.position.x; double dy = data->plat_pose.pose.position.y - data->local_pose.pose.position.y; dest_pose.pose.position.x += 1.3 * dx; dest_pose.pose.position.y += 1.3 * dy; } if (abovePlatform()) { // Disarm if close enough double dz = data->local_pose.pose.position.z - data->plat_pose.pose.position.z; if (!disarmed && dz < 0.12) { data->this_quad->disarm(); ROS_INFO("Quad disarmed."); disarmed = true; } // Descend if above platform double fall_dist = -0.10; if ((dest_pose.pose.position.z - data->plat_pose.pose.position.z) > fall_dist) { // TODO THIS CHECK FOR DEMO ONLY // Only descend if platform moving if (std::sqrt(vx*vx + vy*vy) > 0.10) { set_z_above -= (0.5) / FRAMES_PER_SEC; } } else { set_z_above = data->plat_pose.pose.position.z + fall_dist; } } // Publish dest_pose.header.stamp = ros::Time::now(); pub.publish(dest_pose); } bool MovingLand::abovePlatform() const { return pose_xy_check(data->plat_pose.pose, data->local_pose.pose, 0.12); } // HELPER FUNCTIONS - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool pose_dist_check(geometry_msgs::Pose pose1, geometry_msgs::Pose pose2, double max_dist, double max_rot) { double dx = pose1.position.x - pose2.position.x; double dy = pose1.position.y - pose2.position.y; double dz = pose1.position.z - pose2.position.z; // ROS_INFO("dist: %.2f", std::sqrt(dx*dx + dy*dy + dz*dz)); bool dist_check = std::sqrt(dx*dx + dy*dy + dz*dz) < max_dist; double dox = pose1.orientation.x - pose2.orientation.x; double doy = pose1.orientation.y - pose2.orientation.y; double doz = pose1.orientation.z - pose2.orientation.z; double dow = pose1.orientation.w - pose2.orientation.w; bool rot_check = std::sqrt(dox*dox + doy*doy + doz*doz + dow*dow) < max_rot; return dist_check; } bool pose_xy_check(geometry_msgs::Pose pose1, geometry_msgs::Pose pose2, double max_dist) { double dx = pose1.position.x - pose2.position.x; double dy = pose1.position.y - pose2.position.y; return std::sqrt(dx*dx + dy*dy) < max_dist; }
31.55902
101
0.59379
khairulislam
7a2739c116f4f730377e2f9ed25c37e9efe11126
3,807
cpp
C++
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
Rendering/Light.cpp
nicolas92g/noisyEngine
306f4a031f70c548047cf6697cd1237dca650301
[ "Apache-2.0" ]
null
null
null
#include "Light.h" uint32_t ns::DirectionalLight::number_(0); uint32_t ns::PointLight::number_(0); uint32_t ns::SpotLight::number_(0); ns::LightBase_::LightBase_(const glm::vec3& color) { color_ = color; } void ns::LightBase_::setColor(const glm::vec3& color) { if (color.x < .0f || color.y < .0f || color.z < .0f) return; color_ = color; } const glm::vec3& ns::LightBase_::color() const { return color_; } ns::attenuatedLightBase_::attenuatedLightBase_(const glm::vec3& color, float attenuation) : LightBase_(color) { setAttenuation(attenuation); } void ns::attenuatedLightBase_::setAttenuation(float attenuationValue) { attenuation_ = std::max(attenuationValue, .0f); } float ns::attenuatedLightBase_::attenuationValue() { return attenuation_; } //-------------------------------- // directional light //-------------------------------- ns::DirectionalLight ns::DirectionalLight::nullDirectionalLightObject(glm::vec3(0, 1, 0), NS_BLACK); ns::DirectionalLight::DirectionalLight(const glm::vec3& direction, const glm::vec3& color) : LightBase_(color), DirectionalObject3d(glm::vec3(0), direction) { setDirection(direction); } void ns::DirectionalLight::send(const Shader& shader) { char name[18], buffer[40]; sprintf_s(name, "dirLights[%d]", number_); sprintf_s(buffer, "%s.direction", name); shader.set(buffer, glm::normalize(-direction())); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); number_++; } uint32_t ns::DirectionalLight::number() { return number_; } void ns::DirectionalLight::clear() { number_ = 0; } ns::DirectionalLight& ns::DirectionalLight::nullLight() { return nullDirectionalLightObject; } //-------------------------------- // point light //-------------------------------- ns::PointLight::PointLight(const glm::vec3& position, float attenuation, const glm::vec3& color) : attenuatedLightBase_(color, attenuation), Object3d(position) {} void ns::PointLight::send(const Shader& shader) { char name[20], buffer[42]; sprintf_s(name, "pointLights[%d]", number_); sprintf_s(buffer, "%s.position", name); shader.set(buffer, WorldPosition()); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); sprintf_s(buffer, "%s.attenuation", name); shader.set(buffer, attenuation_); number_++; } uint32_t ns::PointLight::number() { return number_; } void ns::PointLight::clear() { number_ = 0; } //-------------------------------- // spot light //-------------------------------- ns::SpotLight::SpotLight(const glm::vec3& position, float attenuation, const glm::vec3& color, const glm::vec3& direction, float innerAngle, float outerAngle) : attenuatedLightBase_(color, attenuation), DirectionalObject3d(position, direction) { setAngle(innerAngle, outerAngle); setDirection(direction); } void ns::SpotLight::setAngle(float innerAngle, float outerAngle) { innerCutOff_ = glm::cos(glm::radians(innerAngle)); outerCutOff_ = glm::cos(glm::radians(outerAngle)); } void ns::SpotLight::send(const Shader& shader) { char name[20], buffer[42]; sprintf_s(name, "spotLights[%d]", number_); sprintf_s(buffer, "%s.position", name); shader.set(buffer, WorldPosition()); sprintf_s(buffer, "%s.color", name); shader.set(buffer, color_); sprintf_s(buffer, "%s.attenuation", name); shader.set(buffer, attenuation_); sprintf_s(buffer, "%s.direction", name); shader.set(buffer, glm::normalize(-direction())); sprintf_s(buffer, "%s.innerCutOff", name); shader.set(buffer, innerCutOff_); sprintf_s(buffer, "%s.outerCutOff", name); shader.set(buffer, outerCutOff_); number_++; } uint32_t ns::SpotLight::number() { return number_; } void ns::SpotLight::clear() { number_ = 0; } void ns::clearLights() { PointLight::clear(); DirectionalLight::clear(); SpotLight::clear(); }
20.917582
158
0.67481
nicolas92g
7a28ef1353726be2c5934ea8363add2c2c9dd997
304
cpp
C++
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
src/fireFist.cpp
snow482/grawing_way_oop_2.0
f7e5deb6d4357dcbe40b4c4be5411efd286608c2
[ "MIT" ]
null
null
null
#include "fireFist.hpp" #include "Character.hpp" FireFist::FireFist(int fireDamage) : Skill("Fire fist"), m_fireDamage(fireDamage) {} void FireFist::Use(std::shared_ptr<Character> self, std::shared_ptr<Character> enemy) { noused(self); enemy->getDamage(m_fireDamage); }
21.714286
54
0.674342
snow482
7a299f471b1e2e2625c2c334cd4b9c5a65881633
803
hpp
C++
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
3
2021-10-09T03:24:57.000Z
2022-01-12T04:19:42.000Z
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
100
2019-10-01T05:29:03.000Z
2022-03-31T17:28:52.000Z
bulb/components/membrane/include/Membrane/RuntimeSubSystem.hpp
AGarlicMonkey/Clove
495e118024a30a39bd194f54c728d77ff0fa8d4a
[ "MIT" ]
1
2021-11-29T20:46:15.000Z
2021-11-29T20:46:15.000Z
#pragma once #include "Membrane/Scene.hpp" #include <Clove/SubSystem.hpp> namespace clove { class EntityManager; } namespace membrane { /** * @brief The sub system that is active while the game is running. * Deliberately does not handle editor events to simulate the game running. */ class RuntimeSubSystem : public clove::SubSystem { //VARIABLES private: Scene currentScene; //FUNCTIONS public: RuntimeSubSystem(); Group getGroup() const override; void onAttach() override; clove::InputResponse onInputEvent(clove::InputEvent const &inputEvent) override { return clove::InputResponse::Ignored; } void onUpdate(clove::DeltaTime const deltaTime) override; void onDetach() override; }; }
25.09375
129
0.666252
AGarlicMonkey
7a2b2fc2758fecf65469a16f91ac83aa209d439a
1,112
cpp
C++
projects/cmd_bio/src/utils/dir.cpp
Aaryan-kapur/core
5ebf096d18a3ddbe0259f83ca82a39607ba1f892
[ "Apache-2.0" ]
1
2020-03-13T17:43:34.000Z
2020-03-13T17:43:34.000Z
projects/cmd_bio/src/utils/dir.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
5
2020-12-23T00:19:32.000Z
2020-12-29T20:53:58.000Z
projects/cmd_bio/src/utils/dir.cpp
BhumikaSaini/core
baecdd736961d301fe2723858de94cef285296b0
[ "Apache-2.0" ]
3
2020-02-23T06:20:08.000Z
2021-12-02T04:18:29.000Z
#include "dir.h" #include <dirent.h> #include <regex> #include <biogears/filesystem/path.h> #include <biogears/string/manipulation.h> #include <exception> #include <iostream> namespace biogears { namespace filesystem { std::vector<std::string> dirlist(std::string path, std::string filter) { std::vector<std::string> result; DIR* dir = nullptr; dirent* ent = nullptr; if ((dir = opendir(path.c_str())) != NULL) { /* print all the files and directories within directory */ try { std::regex re{ filter }; std::smatch m; while ((ent = readdir(dir)) != NULL) { std::string file = ent->d_name; if (std::regex_match(file, m, re)) { result.push_back( (biogears::filesystem::path(path) / std::string(ent->d_name)).string()); } } } catch (...) { throw std::runtime_error("Unable to compile given regex " + filter); } closedir(dir); } else { throw std::runtime_error(biogears::asprintf("Unable to list directory containing %s", path.c_str())); } return result; } } }
27.8
107
0.59982
Aaryan-kapur
7a2b93a436713b7ee3b72fb1487b459dbc6940bb
1,022
cpp
C++
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
65
2017-04-04T20:33:44.000Z
2019-12-02T23:06:58.000Z
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
46
2017-04-21T12:26:38.000Z
2019-12-15T05:31:47.000Z
PolyEngine/Core/Src/Math/Plane.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
51
2017-04-12T10:53:32.000Z
2019-11-20T13:05:54.000Z
#include <CorePCH.hpp> #include <Math/Plane.hpp> using namespace Poly; Plane::eObjectLocation Plane::GetAABoxLocation(const AABox& box) const { auto vertices = box.GetVertices(); eObjectLocation guessedLocation = GetPointLocation(vertices[0]); for (Vector vert : vertices) { eObjectLocation loc = GetPointLocation(vert); if (loc == eObjectLocation::INTERSECTS || loc != guessedLocation) return eObjectLocation::INTERSECTS; } // guess was ok return guessedLocation; } Plane::eObjectLocation Plane::GetPointLocation(const Vector& point) const { const float dot = (point - Point).Dot(Normal); if (dot > 0) return eObjectLocation::FRONT; else if (dot < 0) return eObjectLocation::BEHIND; else return eObjectLocation::INTERSECTS; } //------------------------------------------------------------------------------ namespace Poly { std::ostream & operator<<(std::ostream& stream, const Plane& rect) { return stream << "Plane[Point: " << rect.Point << " Normal: " << rect.Normal << " ]"; } }
23.767442
87
0.654599
PiotrMoscicki
7a2f0492e5876988fc4083970591d4415676ee05
3,078
cpp
C++
plugins/community/repos/ML_modules/src/OctaTimes.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
233
2018-07-02T16:49:36.000Z
2022-02-27T21:45:39.000Z
plugins/community/repos/ML_modules/src/OctaTimes.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-09T11:32:15.000Z
2022-01-07T01:45:43.000Z
plugins/community/repos/ML_modules/src/OctaTimes.cpp
guillaume-plantevin/VeeSeeVSTRack
76fafc8e721613669d6f5ae82a0f58ce923a91e1
[ "Zlib", "BSD-3-Clause" ]
24
2018-07-14T21:55:30.000Z
2021-05-04T04:20:34.000Z
#include "ML_modules.hpp" #include "dsp/digital.hpp" namespace rack_plugin_ML_modules { struct OctaTimes : Module { enum ParamIds { MULT_PARAM, NUM_PARAMS }; enum InputIds { IN1_INPUT, IN2_INPUT, IN3_INPUT, IN4_INPUT, IN5_INPUT, IN6_INPUT, IN7_INPUT, IN8_INPUT, IN_B_1_INPUT, IN_B_2_INPUT, IN_B_3_INPUT, IN_B_4_INPUT, IN_B_5_INPUT, IN_B_6_INPUT, IN_B_7_INPUT, IN_B_8_INPUT, NUM_INPUTS }; enum OutputIds { OUT1_OUTPUT, OUT2_OUTPUT, OUT3_OUTPUT, OUT4_OUTPUT, OUT5_OUTPUT, OUT6_OUTPUT, OUT7_OUTPUT, OUT8_OUTPUT, SUM_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; SchmittTrigger trigger[8]; float out[8]; OctaTimes() : Module( NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS ) { reset(); }; void step() override; void reset() override { for(int i=0; i<8; i++) out[i] = 0.0; }; }; void OctaTimes::step() { float in_A[8], in_B[8]; float normal = params[MULT_PARAM].value==1?1.0f:10.f; float multiplier = params[MULT_PARAM].value==1?1.f:0.1f; in_A[0] = inputs[IN1_INPUT].normalize(0.f); // for(int i=1; i<8; i++) in_A[i] = inputs[IN1_INPUT+i].normalize(in_A[i-1]); for(int i=1; i<8; i++) in_A[i] = inputs[IN1_INPUT+i].normalize(0.f); in_B[0] = inputs[IN_B_1_INPUT].normalize(normal); for(int i=1; i<8; i++) in_B[i] = inputs[IN_B_1_INPUT+i].normalize(in_B[i-1]); float sum = 0.0f; for(int i=0; i<8; i++) sum += outputs[OUT1_OUTPUT+i].value = clamp(in_A[i] * in_B[i] * multiplier , -12.f, 12.f); outputs[SUM_OUTPUT].value = clamp(sum,-12.f,12.f); }; struct OctaTimesWidget : ModuleWidget { OctaTimesWidget(OctaTimes *module); }; OctaTimesWidget::OctaTimesWidget(OctaTimes *module) : ModuleWidget(module) { box.size = Vec(15*8, 380); { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(plugin,"res/OctaTimes.svg"))); addChild(panel); } addChild(Widget::create<MLScrew>(Vec(15, 0))); addChild(Widget::create<MLScrew>(Vec(box.size.x-30, 0))); addChild(Widget::create<MLScrew>(Vec(15, 365))); addChild(Widget::create<MLScrew>(Vec(box.size.x-30, 365))); const float offset_y = 60, delta_y = 32, row1=15, row2 = 48, row3 = 80; for( int i=0; i<8; i++) { addInput(Port::create<MLPort>(Vec(row1, offset_y + i*delta_y ), Port::INPUT, module, OctaTimes::IN1_INPUT+i)); addInput(Port::create<MLPort>(Vec(row2, offset_y + i*delta_y ), Port::INPUT, module, OctaTimes::IN_B_1_INPUT+i)); addOutput(Port::create<MLPort>(Vec(row3, offset_y + i*delta_y ), Port::OUTPUT, module, OctaTimes::OUT1_OUTPUT+i)); }; addOutput(Port::create<MLPort>(Vec(row3, 330 ), Port::OUTPUT, module, OctaTimes::SUM_OUTPUT)); addParam(ParamWidget::create<CKSS>( Vec(row1 + 5, 330 ), module, OctaTimes::MULT_PARAM , 0.0, 1.0, 0.0)); } } // namespace rack_plugin_ML_modules using namespace rack_plugin_ML_modules; RACK_PLUGIN_MODEL_INIT(ML_modules, OctaTimes) { Model *modelOctaTimes = Model::create<OctaTimes, OctaTimesWidget>("ML modules", "OctaTimes", "OctaTimes", UTILITY_TAG); return modelOctaTimes; }
23.142857
122
0.68681
guillaume-plantevin
7a39bf7245d2b1d2b4d008920dd168fea1f7a132
663
hpp
C++
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
src/link/rtti.hpp
martinnnnnn/link
6a407279fb28d7a9238ea5e18b85916bc15b3fbe
[ "MIT" ]
null
null
null
#pragma once #include <string> namespace link { class Rtti { public: Rtti(const std::string name, const Rtti* base); ~Rtti(); const std::string get_name() const; bool is_exactly(const Rtti& type) const; bool is_derived(const Rtti& base_type) const; private: std::string name; const Rtti* base; }; } #define LINK_DECLARE_RTTI \ public: \ static const link::Rtti TYPE; \ virtual const link::Rtti& get_type () const { return TYPE; } #define LINK_IMPLEMENT_RTTI(nsname,classname,baseclassname) \ const link::Rtti classname::TYPE(#nsname"."#classname,&baseclassname::TYPE)
21.387097
79
0.641026
martinnnnnn
7a3b510d0854f26140d3a9cb16581bca1a4a9441
383
cc
C++
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
src/core/utils/console.cc
5aitama/Bismuth
00fbd13a08ac08b77413d4a6797b1daa84a892cf
[ "MIT" ]
null
null
null
#include "console.h" using namespace std; void Console::Log(const char* str, const size_t& maxWidth) { char* x = new char[maxWidth]; for (size_t i = 0; i < maxWidth; i++) { if (*str != '\0') { x[i] = *str; str++; } else { x[i] = '.'; } } x[maxWidth - 1] = '\0'; cout << x; delete[] x; }
17.409091
60
0.420366
5aitama
7a3c4665b43702de0eb94923c656d96c0050dfb4
2,591
cpp
C++
tests/src/netlib/tests_port_layer.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2021-07-16T14:19:50.000Z
2021-07-16T14:19:50.000Z
tests/src/netlib/tests_port_layer.cpp
Mike-Bal/mart-common
0b52654c6f756e8e86689e56d24849c97079229c
[ "MIT" ]
1
2018-06-05T11:03:30.000Z
2018-06-05T11:03:30.000Z
tests/src/netlib/tests_port_layer.cpp
tum-ei-rcs/mart-common
6f8f18ac23401eb294d96db490fbdf78bf9b316c
[ "MIT" ]
null
null
null
#include <mart-netlib/port_layer.hpp> #include <catch2/catch.hpp> #include <iostream> namespace pl = mart::nw::socks::port_layer; namespace socks = mart::nw::socks; // call ech function at least once to ensure the implementation is there TEST_CASE( "net_port-layer_check_function_implementation_exists" ) { CHECK( pl::startup() ); [[maybe_unused]] auto nh = pl::to_native( pl::handle_t::Invalid ); [[maybe_unused]] int d = pl::to_native( socks::Domain::Inet ); [[maybe_unused]] int t = pl::to_native( socks::TransportType::Datagram ); [[maybe_unused]] int p = pl::to_native( socks::Protocol::Tcp ); socks::ReturnValue<pl::handle_t> ts = pl::socket( socks::Domain::Inet, socks::TransportType::Datagram, socks::Protocol::Default ); CHECK( ts.success() ); CHECK( ts.value_or( pl::handle_t::Invalid ) != pl::handle_t::Invalid ); pl::close_socket( ts.value_or( pl::handle_t::Invalid ) ); pl::handle_t s2 = pl::socket( socks::Domain::Inet, socks::TransportType::Datagram ).value_or( pl::handle_t::Invalid ); CHECK( s2 != pl::handle_t::Invalid ); pl::SockaddrIn addr{}; CHECK( set_blocking( s2, false ) ); CHECK( !accept( s2 ) ); CHECK( !accept( s2, addr ) ); // CHECK( connect( s2,addr ) ); // TODO: connect to empty works on some platforms but not on all connect( s2, addr ); // CHECK( !bind( s2, addr ) ); bind( s2, addr ); // CHECK( !listen( s2, 10 ) ); listen( s2, 10 ); } TEST_CASE( "net_port-layer_getaddrinfo" ) { CHECK( pl::startup() ); socks::AddrInfoHints hints{}; hints.flags = 0; hints.family = socks::Domain::Unspec; hints.socktype = socks::TransportType::Stream; auto info1 = pl::getaddrinfo( "www.google.de", "https", hints ); if( !info1.success() ) { std::cout << "Error in getaddrinfo:" << info1.error_code().raw_value() << std::endl; } CHECK( info1.success() ); auto& sockaddr_list = info1.value(); for( const auto& e : sockaddr_list ) { socks::ReturnValue<pl::handle_t> res = pl::socket( e.family, e.socktype, e.protocol ); CHECK( res.success() ); auto handle = res.value(); std::cout << "Connecting to (to_string) : " << pl::to_string( e.addr->to_Sockaddr() ) << std::endl; char buffer[30]{}; pl::inet_net_to_pres( e.addr->to_Sockaddr().to_native_ptr(), buffer, sizeof( buffer ) ); std::cout << "Connecting to (inet_net_to_pres): " << &( buffer[0] ) << std::endl; auto con_res = pl::connect( handle, e.addr->to_Sockaddr() ); if( !con_res.success() ) { std::cout << "Failed with error code: " << con_res.raw_value() << std::endl; } CHECK( pl::close_socket( handle ).success() ); } }
34.092105
112
0.656503
Mike-Bal
7a3e6daf930cb810e1ecc67e66519e2021ec0e55
1,509
cpp
C++
common/doc/examples/ca.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
1
2018-03-09T20:21:47.000Z
2018-03-09T20:21:47.000Z
common/doc/examples/ca.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
null
null
null
common/doc/examples/ca.cpp
ane-community/botan-crypto-ane
71056f5f0d5fd706e6d42e2f7ec0f7f55d86fb74
[ "MIT" ]
null
null
null
#include <botan/botan.h> #include <botan/x509_ca.h> #include <botan/time.h> using namespace Botan; #include <iostream> #include <memory> int main(int argc, char* argv[]) { if(argc != 5) { std::cout << "Usage: " << argv[0] << " <passphrase> " << "<ca cert> <ca key> <pkcs10>" << std::endl; return 1; } Botan::LibraryInitializer init; try { const std::string arg_passphrase = argv[1]; const std::string arg_ca_cert = argv[2]; const std::string arg_ca_key = argv[3]; const std::string arg_req_file = argv[4]; AutoSeeded_RNG rng; X509_Certificate ca_cert(arg_ca_cert); std::auto_ptr<PKCS8_PrivateKey> privkey( PKCS8::load_key(arg_ca_key, rng, arg_passphrase) ); X509_CA ca(ca_cert, *privkey, "SHA-256"); // got a request PKCS10_Request req(arg_req_file); // you would insert checks here, and perhaps modify the request // (this example should be extended to show how) // now sign the request X509_Time start_time(system_time()); X509_Time end_time(system_time() + 365 * 60 * 60 * 24); X509_Certificate new_cert = ca.sign_request(req, rng, start_time, end_time); // send the new cert back to the requestor std::cout << new_cert.PEM_encode(); } catch(std::exception& e) { std::cout << e.what() << std::endl; return 1; } return 0; }
25.15
72
0.580517
ane-community
7a417b06060b6257e39b42dbd818964050b3a122
5,645
cxx
C++
main/connectivity/source/drivers/ado/AColumns.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/connectivity/source/drivers/ado/AColumns.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/connectivity/source/drivers/ado/AColumns.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "ado/AColumns.hxx" #include "ado/AColumn.hxx" #include "ado/AConnection.hxx" #include "ado/Awrapado.hxx" #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <com/sun/star/sdbc/DataType.hpp> #include <com/sun/star/sdbc/ColumnValue.hpp> #include <comphelper/property.hxx> #include <comphelper/types.hxx> #include <connectivity/dbexception.hxx> #include <algorithm> #include "resource/ado_res.hrc" using namespace connectivity::ado; using namespace connectivity; using namespace comphelper; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::container; sdbcx::ObjectType OColumns::createObject(const ::rtl::OUString& _rName) { return new OAdoColumn(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName)); } // ------------------------------------------------------------------------- void OColumns::impl_refresh() throw(RuntimeException) { m_aCollection.Refresh(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OColumns::createDescriptor() { return new OAdoColumn(isCaseSensitive(),m_pConnection); } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OColumns::appendObject( const ::rtl::OUString&, const Reference< XPropertySet >& descriptor ) { OAdoColumn* pColumn = NULL; Reference< XPropertySet > xColumn; if ( !getImplementation( pColumn, descriptor ) || pColumn == NULL ) { // m_pConnection->throwGenericSQLException( STR_INVALID_COLUMN_DESCRIPTOR_ERROR,static_cast<XTypeProvider*>(this) ); pColumn = new OAdoColumn(isCaseSensitive(),m_pConnection); xColumn = pColumn; ::comphelper::copyProperties(descriptor,xColumn); } WpADOColumn aColumn = pColumn->getColumnImpl(); #if OSL_DEBUG_LEVEL > 0 sal_Int32 nPrecision; sal_Int32 nScale; sal_Int32 nType; nPrecision = aColumn.get_Precision(); nScale = aColumn.get_NumericScale(); nType = ADOS::MapADOType2Jdbc(aColumn.get_Type()); #endif ::rtl::OUString sTypeName; pColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPENAME)) >>= sTypeName; const OTypeInfoMap* pTypeInfoMap = m_pConnection->getTypeInfo(); ::comphelper::TStringMixEqualFunctor aCase(sal_False); // search for typeinfo where the typename is equal sTypeName OTypeInfoMap::const_iterator aFind = ::std::find_if(pTypeInfoMap->begin(), pTypeInfoMap->end(), ::std::compose1( ::std::bind2nd(aCase, sTypeName), ::std::compose1( ::std::mem_fun(&OExtendedTypeInfo::getDBName), ::std::select2nd<OTypeInfoMap::value_type>()) ) ); if ( aFind != pTypeInfoMap->end() ) // change column type if necessary aColumn.put_Type(aFind->first); if ( SUCCEEDED(((ADOColumns*)m_aCollection)->Append(OLEVariant(aColumn.get_Name()),aColumn.get_Type(),aColumn.get_DefinedSize())) ) { WpADOColumn aAddedColumn = m_aCollection.GetItem(OLEVariant(aColumn.get_Name())); if ( aAddedColumn.IsValid() ) { sal_Bool bAutoIncrement = sal_False; pColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISAUTOINCREMENT)) >>= bAutoIncrement; if ( bAutoIncrement ) OTools::putValue( aAddedColumn.get_Properties(), ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Autoincrement")), bAutoIncrement ); if ( aFind != pTypeInfoMap->end() && aColumn.get_Type() != aAddedColumn.get_Type() ) // change column type if necessary aColumn.put_Type(aFind->first); aAddedColumn.put_Precision(aColumn.get_Precision()); aAddedColumn.put_NumericScale(aColumn.get_NumericScale()); aAddedColumn.put_Attributes(aColumn.get_Attributes()); aAddedColumn.put_SortOrder(aColumn.get_SortOrder()); aAddedColumn.put_RelatedColumn(aColumn.get_RelatedColumn()); } } ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this)); return new OAdoColumn(isCaseSensitive(),m_pConnection,pColumn->getColumnImpl()); } // ------------------------------------------------------------------------- // XDrop void OColumns::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName) { if(!m_aCollection.Delete(_sElementName)) ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this)); } // -----------------------------------------------------------------------------
39.475524
133
0.670151
Grosskopf
7a41ee456370b9225fbfc9cdc293ff95944e7a1a
371
cpp
C++
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
treeDAG/util/nChooseKIterator.cpp
thomasfannes/treeDAG
c29eec45f0f08fec2d41bc163b26d8aaf9a68f6c
[ "MIT" ]
null
null
null
#include "nChooseKIterator.hpp" #include <algorithm> namespace treeDAG { namespace util { bool NChooseKProcessor::atEnd(const std::vector<bool> & mask) const { return mask.back(); } void NChooseKProcessor::increment(std::vector<bool> & mask) { mask.back() = !std::next_permutation(mask.begin(), mask.end() - 1); } } // util namespace } // treeDAG namespace
17.666667
71
0.695418
thomasfannes
7a42c138a6c0fb3e718883f2169bb9b2fc59a01a
275
cpp
C++
Demo/StatSet.cpp
mirzazulfan/Xenro-Engine
0e9383b113ec09a24daf5e92f9a5b84febaffb1b
[ "MIT" ]
null
null
null
Demo/StatSet.cpp
mirzazulfan/Xenro-Engine
0e9383b113ec09a24daf5e92f9a5b84febaffb1b
[ "MIT" ]
18
2018-02-28T21:34:30.000Z
2018-12-01T19:07:43.000Z
Demo/StatSet.cpp
mirzazulfan/Xenro-Engine
0e9383b113ec09a24daf5e92f9a5b84febaffb1b
[ "MIT" ]
1
2018-12-01T08:00:46.000Z
2018-12-01T08:00:46.000Z
#include "Statset.h" Statset::Statset(int HP, int MoveNum, int Dext, int Strength, int Wisdom, int Intelligence, int Level, int EXP) :hp(HP), moveNum(MoveNum), dext(Dext), strength(Strength), wisdom(Wisdom), intelligence(Intelligence), level(Level), exp(EXP) { //Empty }
34.375
112
0.723636
mirzazulfan
7a439686fd6777a0a1e1ee0cd233eca26e0a0c8e
1,231
cpp
C++
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
OOP/ErrorHandling/main.cpp
Rossoner40/NBU-Classwork-and-Homework
823e5eab2da616ae6d965da9c0a22fa0212d7887
[ "MIT" ]
null
null
null
#include <iostream> #include <RepeatedIn.h> #include <IndexError.h> #include <DblArr.h> #include <stdlib.h> #include <typeinfo> using namespace std; void tst(int n)throw(IndexError){ RepeatedIn ccin; DblArr x(n); int N; for(int i=0;i<n;i++) { x[i]=5.*rand()/RAND_MAX; } cout<<x<<endl; for(int i=0;i<5;i++){ try{ cout<<"index:";ccin>>N; cout<<"x["<<N<<"]="<<x[N]<<endl; } catch ( IndexError &e ){ throw e; }catch(...){ cerr<<"exception in tst() at line "<<__LINE__<<endl; throw; } } } int main( ) { int b; unsigned u; bool res = false; RepeatedIn ccin; do{ try { cout<<"Enter unsigned:"; ccin>>u; cout<<"Accepted: "<<u<<endl; b=__LINE__; tst(u); } catch ( IndexError &e ){ e.rep(cerr); cerr<<"Exception in main() at line "<<b<< " invoking tst("<<u<<")." <<endl; cerr << e.what( ) << " by "<< typeid( e ).name( ) << endl; res=true; } cout<<endl; if(res){res=!res;cout<<"Resumption:\n";} }while(1); return 0; }
20.180328
68
0.450853
Rossoner40
7a4616e9eac44cc3892e15d925e9ee5b4238b84e
955
hpp
C++
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
103
2016-02-08T21:04:11.000Z
2021-08-05T21:50:03.000Z
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
12
2015-12-29T23:53:52.000Z
2018-01-01T16:12:28.000Z
nytl/fwd/rect.hpp
nyorain/nyutil
26ad3247f909cc82f30608126659b1d6632f5a52
[ "BSL-1.0" ]
13
2016-02-24T12:25:31.000Z
2020-08-24T19:47:29.000Z
// Copyright (c) 2017-2019 nyorain // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #pragma once #ifndef NYTL_INCLUDE_FWD_RECT #define NYTL_INCLUDE_FWD_RECT #include <cstdlib> // std::size_t #include <cstdint> // std::uint8_t namespace nytl { template<std::size_t D, typename T> class Rect; template<typename T> using Rect2 = Rect<2, T>; template<typename T> using Rect3 = Rect<3, T>; template<typename T> using Rect4 = Rect<4, T>; using Rect2i = Rect<2, int>; using Rect2ui = Rect<2, unsigned int>; using Rect2f = Rect<2, float>; using Rect2d = Rect<2, double>; using Rect3i = Rect<3, int>; using Rect3ui = Rect<3, unsigned int>; using Rect3d = Rect<3, double>; using Rect3f = Rect<3, float>; using Rect4i = Rect<4, int>; using Rect4ui = Rect<4, unsigned int>; using Rect4d = Rect<4, double>; using Rect4f = Rect<4, float>; } #endif // header guard
24.487179
80
0.713089
nyorain
7a46d7a42f61926e7e19240bc46cdaee53253e0b
1,089
hpp
C++
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/util/range.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young 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. */ #pragma once /** * \brief Return a vector containing integers in the range [\p stt, \p stp) */ inline auto Range(int stt, int stp) { std::vector<int> range; range.reserve(std::abs(stp - stt) + 1); int stride = (stp - stt) >= 0 ? 1 : -1; for (int i = stt; i < stp; i += stride) { range.push_back(i); } return range; } /** * \brief Return a vector containing the integers in the interval [0, \p stp) */ inline auto Range(int stp) { return Range(0, stp); }
26.560976
77
0.673095
tp-ntouran
7a484eb8403730b712a19d67c78b3e9ee0f22cea
587
cpp
C++
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
76
2018-02-20T11:30:52.000Z
2022-03-31T12:45:06.000Z
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
27
2018-11-20T14:32:49.000Z
2021-11-24T15:26:45.000Z
unit_tests/dynamics/multibody/src/unit_retro.cpp
ricortiz/OpenTissue
f8c8ebc5137325b77ba90bed897f6be2795bd6fb
[ "Zlib" ]
24
2018-02-21T01:45:26.000Z
2022-03-07T07:06:49.000Z
// // OpenTissue, A toolbox for physical based simulation and animation. // Copyright (C) 2007 Department of Computer Science, University of Copenhagen // #include <OpenTissue/configuration.h> #define BOOST_AUTO_TEST_MAIN #include <OpenTissue/utility/utility_push_boost_filter.h> #include <boost/test/auto_unit_test.hpp> #include <boost/test/unit_test_suite.hpp> #include <boost/test/test_tools.hpp> #include <OpenTissue/utility/utility_pop_boost_filter.h> BOOST_AUTO_TEST_SUITE(opentissue_dynamics_multibody_mbd); BOOST_AUTO_TEST_CASE(no_test_yet) { } BOOST_AUTO_TEST_SUITE_END();
26.681818
78
0.819421
ricortiz
7a48b685d332754b6c4bee9c99aefabd14b5a794
2,466
cpp
C++
producer/api/cpp/unittests/test_producer_request.cpp
SergeyYakubov/asapo
25fddf9af6b215a6fc0da6108bc6b91dff813362
[ "MIT", "Apache-2.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
producer/api/cpp/unittests/test_producer_request.cpp
SergeyYakubov/asapo
25fddf9af6b215a6fc0da6108bc6b91dff813362
[ "MIT", "Apache-2.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
producer/api/cpp/unittests/test_producer_request.cpp
SergeyYakubov/asapo
25fddf9af6b215a6fc0da6108bc6b91dff813362
[ "MIT", "Apache-2.0", "MIT-0", "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "asapo/unittests/MockIO.h" #include "asapo/unittests/MockLogger.h" #include "asapo/common/error.h" #include "asapo/io/io.h" #include "asapo/producer/common.h" #include "asapo/producer/producer_error.h" #include "../src/request_handler_tcp.h" #include <asapo/common/networking.h> #include "asapo/io/io_factory.h" #include "mocking.h" namespace { using ::testing::Return; using ::testing::_; using ::testing::DoAll; using ::testing::SetArgReferee; using ::testing::Gt; using ::testing::Eq; using ::testing::Ne; using ::testing::Mock; using ::testing::AllOf; using testing::NiceMock; using ::testing::InSequence; using ::testing::HasSubstr; using ::testing::Sequence; TEST(ProducerRequest, Constructor) { char expected_file_name[asapo::kMaxMessageSize] = "test_name"; char expected_source_credentials[asapo::kMaxMessageSize] = "test_beamtime_id%test_streamid%test_token"; uint64_t expected_file_id = 42; uint64_t expected_file_size = 1337; uint64_t expected_meta_size = 137; std::string expected_meta = "meta"; std::string expected_api_version = "v0.4"; asapo::Opcode expected_op_code = asapo::kOpcodeTransferData; asapo::GenericRequestHeader header{expected_op_code, expected_file_id, expected_file_size, expected_meta_size, expected_file_name}; asapo::ProducerRequest request{expected_source_credentials, std::move(header), nullptr, expected_meta, "", nullptr, true, 0}; ASSERT_THAT(request.source_credentials, Eq(expected_source_credentials)); ASSERT_THAT(request.metadata, Eq(expected_meta)); ASSERT_THAT(request.header.message, testing::StrEq(expected_file_name)); ASSERT_THAT(request.header.data_size, Eq(expected_file_size)); ASSERT_THAT(request.header.data_id, Eq(expected_file_id)); ASSERT_THAT(request.header.op_code, Eq(expected_op_code)); ASSERT_THAT(request.header.meta_size, Eq(expected_meta_size)); ASSERT_THAT(request.header.api_version, testing::StrEq(expected_api_version)); } TEST(ProducerRequest, Destructor) { // fails with data corruption if done wrong char data_[100]; asapo::MessageData data{(uint8_t*)data_}; asapo::GenericRequestHeader header{asapo::kOpcodeTransferData, 1, 1, 1, ""}; asapo::ProducerRequest* request = new asapo::ProducerRequest{"", std::move(header), std::move(data), "", "", nullptr, false, 0}; delete request; } }
33.324324
132
0.738848
SergeyYakubov
7a4a78300d55ccaea3f07104f1870a684a56764c
6,936
cpp
C++
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
11
2015-02-12T04:34:43.000Z
2021-10-10T06:24:55.000Z
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
null
null
null
demo2/Classes/testLayer.cpp
wantnon2/3DToolKit-2-for-cocos2dx
518aa856f06788929e50897b43969e5cfa50c3cf
[ "MIT" ]
8
2015-06-30T11:51:30.000Z
2021-10-10T06:24:56.000Z
// // testLayer.cpp // HelloCpp // // Created by Yang Chao (wantnon) on 13-11-6. // // #include "testLayer.h" bool CtestLayer::init(){ CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); CCSize winSize=CCDirector::sharedDirector()->getWinSize(); float ZEye=CCDirector::sharedDirector()->getZEye(); //enable touch setTouchEnabled( true ); //enable update scheduleUpdate(); //update eye pos updateEyePos(); //----------------------------- //root3d m_root3d=new Cc3dRoot(); m_root3d->autorelease(); m_root3d->init(); m_root3d->setNodeName("root3d"); this->addChild(m_root3d); //camera Cc3dCamera*camera=m_root3d->getCamera3D(); m_r=(winSize.height/2)/tanf(camera->getFovy()/2*M_PI/180); camera->setEyePos(cc3dv4(0, 0, m_r, 1)); camera->setCenter(cc3dv4(0, 0, 0, 1)); camera->setUp(cc3dv4(0, 1, 0, 0)); camera->setProjectionMode(ec3dPerspectiveMode); //lightSource Cc3dLightSource*lightSource=new Cc3dLightSource(); lightSource->autorelease(); lightSource->init(); m_root3d->addChild(lightSource); lightSource->setAmbient(cc3dv4(0.8, 0.8, 0.8, 1)); lightSource->setPosition3D(cc3dv4(600, 900, 1200, 1)); //program Cc3dProgram*program=c3dGetProgram_c3dClassicLighting(); //actor3D m_actor3D=c3dSimpleLoadActor("toolKitRes/model/apple_cfc"); m_actor3D->setLightSource(lightSource); m_actor3D->setCamera3D(camera); m_actor3D->setPassUnifoCallback(passUnifoCallback_classicLighting); m_actor3D->setProgram(program); m_actor3D->setNodeName("actor3D"); m_root3d->addChild(m_actor3D,0); m_actor3D->scale3D(4, 4, 4); m_actor3D->setPosition3D(Cc3dVector4(0,-130,0,1)); //submit m_actor3D->submit(GL_STATIC_DRAW); //controlButton_swithProjMode { CCScale9Sprite* btnUp=CCScale9Sprite::create("button.png"); CCScale9Sprite* btnDn=CCScale9Sprite::create("button_dn.png"); CCLabelTTF*title=CCLabelTTF::create("proj mode", "Helvetica", 30); CCControlButton* controlButton=CCControlButton::create(title, btnUp); controlButton->setBackgroundSpriteForState(btnDn,CCControlStateHighlighted); controlButton->setPreferredSize(CCSize(180,80)); controlButton->setPosition(ccp(400,100)); controlButton->addTargetWithActionForControlEvents(this, (SEL_CCControlHandler)(&CtestLayer::switchProjModeCallBack), CCControlEventTouchDown); this->addChild(controlButton); m_controlButton_swithProjMode=controlButton; } //controlButton_transform { CCScale9Sprite* btnUp=CCScale9Sprite::create("button.png"); CCScale9Sprite* btnDn=CCScale9Sprite::create("button_dn.png"); CCLabelTTF*title=CCLabelTTF::create("transform", "Helvetica", 30); CCControlButton* controlButton=CCControlButton::create(title, btnUp); controlButton->setBackgroundSpriteForState(btnDn,CCControlStateHighlighted); controlButton->setPreferredSize(CCSize(180,80)); controlButton->setPosition(ccp(700,100)); controlButton->addTargetWithActionForControlEvents(this, (SEL_CCControlHandler)(&CtestLayer::transformCallBack), CCControlEventTouchDown); this->addChild(controlButton); m_controlButton_transform=controlButton; } //projection mode label m_pLabel=CCLabelTTF::create("proj mode: Perspective", "Arial", 35); m_pLabel->setPosition(ccp(origin.x + visibleSize.width*(3.0/4), origin.y + visibleSize.height - m_pLabel->getContentSize().height-100)); this->addChild(m_pLabel, 1); return true; } void CtestLayer::updateEyePos(){ float cosA=cosf(m_A*M_PI/180); float sinA=sinf(m_A*M_PI/180); float cosB=cosf(m_B*M_PI/180); float sinB=sinf(m_B*M_PI/180); m_eyePos.setx(m_r*cosB*sinA); m_eyePos.sety(m_r*sinB); m_eyePos.setz(m_r*cosB*cosA); m_eyePos.setw(1); } void CtestLayer::switchProjModeCallBack(CCObject *senderz, cocos2d::extension::CCControlEvent controlEvent){ Cc3dCamera*camera=m_root3d->getCamera3D(); switch(camera->getProjectionMode()) { case ec3dPerspectiveMode:{ camera->setProjectionMode(ec3dOrthographicMode); m_pLabel->setString("proj mode: Orthographic"); }break; case ec3dOrthographicMode:{ camera->setProjectionMode(ec3dPerspectiveMode); m_pLabel->setString("proj mode: Perspective"); }break; } } void CtestLayer::transformCallBack(CCObject *senderz, CCControlEvent controlEvent){ if(m_isDoUpdate){ //restore inital matrix m_actor3D->setTransform3D(m_initialMat); //stop update m_isDoUpdate=false; }else{ //store inital matrix m_initialMat=m_actor3D->getTransform3D(); //start update m_isDoUpdate=true; } } void CtestLayer::update(float dt){ if(m_isDoUpdate==false)return; m_actor3D->rotate3D(cc3dv4(0, 1, 0, 0), 120*dt); } void CtestLayer::ccTouchesEnded(CCSet* touches, CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; } } void CtestLayer::ccTouchesMoved(cocos2d::CCSet* touches , cocos2d::CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; //----update eyePos m_A+=-(m_mosPos.x-m_mosPosf.x)*0.4; m_B+=(m_mosPos.y-m_mosPosf.y)*0.4; if(m_B>89.9)m_B=89.9; if(m_B<-89.9)m_B=-89.9; updateEyePos(); m_root3d->getCamera3D()->setEyePos(m_eyePos); } } void CtestLayer::ccTouchesBegan(CCSet* touches, CCEvent* event) { CCSetIterator it; CCTouch* touch; for( it = touches->begin(); it != touches->end(); it++) { touch = (CCTouch*)(*it); if(!touch) break; CCPoint pointInWinSpace = touch->getLocationInView(); //note: for 3d mode, CCDirector::convertToGL() not works as we expected // CCPoint pointInWinSpace = CCDirector::sharedDirector()->convertToGL(pointInWinSpace); //----update mos m_mosPosf=m_mosPos; m_mosPos=pointInWinSpace; } }
31.384615
151
0.643454
wantnon2
7a4ee912ad4a5bbf719c9f1f407f170a2eb47069
26,355
cc
C++
src/algorithms/tests/BMR.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/algorithms/tests/BMR.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/algorithms/tests/BMR.cc
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
/* -*- Mode: C++; -*- */ // copyright (c) 2012 by Nikolaos Tziortziotis <ntziorzi@gmail.com> /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef MAKE_MAIN #include "Grid.h" #include "BasisSet.h" #include "Matrix.h" #include "MersenneTwister.h" #include "Random.h" #include "Vector.h" // -- Discrete environments -- // #include "DiscreteChain.h" #include "DoubleLoop.h" #include "Gridworld.h" #include "InventoryManagement.h" #include "OneDMaze.h" #include "OptimisticTask.h" #include "RandomMDP.h" #include "RiverSwim.h" // -- Continuous environments -- // #include "DiscretisedEnvironment.h" #include "LinearDynamicQuadratic.h" #include "MountainCar.h" #include "Pendulum.h" #include "PuddleWorld.h" // -- Randomness -- // #include "MersenneTwister.h" #include "RandomNumberFile.h" // -- Algorithms and models --// #include "BasisSet.h" #include "BayesianMultivariate.h" #include "BayesianMultivariateRegression.h" #include "FittedValueIteration.h" #include "Grid.h" #include "LinearModel.h" #include "OnlineAlgorithm.h" #include "RepresentativeStateModel.h" // -- Usual includes -- // #include <getopt.h> #include <cstring> struct EpisodeStatistics { real total_reward; real discounted_reward; int steps; real mse; int n_runs; EpisodeStatistics() : total_reward(0.0), discounted_reward(0.0), steps(0), mse(0), n_runs(0) {} }; struct Statistics { std::vector<EpisodeStatistics> ep_stats; std::vector<real> reward; std::vector<int> n_runs; }; void TrainingAlgorithm1( real gamma, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment, RepresentativeStateModel<LinearModel<Vector, int>, Vector, int>* R); void TrainingAlgorithm2(real gamma, int N, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment); Statistics EvaluateAlgorithm(int episode_steps, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment, real gamma); static const char* const help_text = "BMR - Linear Bayesian reinforcement learning using Bayesian Multivariate Regression\n\ Usage: BMR [options] algorithm environment\n\ \nOptions:\n\ --environment: {PuddleWorld, MountainCar, Pendulum, Linear}\n\ --n_states: number of states (usually there is no need to specify it)\n\ --n_actions: number of actions (usually there is no need to specify it)\n\ --gamma: reward discounting in [0,1] (* 0.99)\n\ --randomness: environment randomness (* 0.0)\n\ --n_runs: maximum number of runs (* 1)\n\ --n_train_episodes: maximum number of train episodes (ignored if < 0)\n\ --n_test_episodes: maximum number of test episodes (ignored if < 0)\n\ --episode_steps: maximum number of steps in each episode (ignored if <0)\n\ --n_steps: maximum number of total steps\n\ --rbf: use of basis functions or not (* 0 or 1)\n\ --grids: number of grid intervals for discretised environments (*3)\n\ --epsilon: use epsilon-greedy with randomness in [0,1] (* 0.01)\n\ --a: first linear model parameter (*0.1) \n\ --N0: second linear model parameter (*0.1) \n\ --n_samples: number of collected samples (* 1000) \n\ \n\ * denotes default parameter\n\ \n"; int main(int argc, char* argv[]) { int n_actions = 2; int n_states = 5; real gamma = 0.999; real randomness = 0.0; real epsilon = 0; real N0 = 0.001; real a = 0.001; uint n_runs = 100; int n_train_episodes = 1000; int n_test_episodes = 1000; uint episode_steps = 1000; uint n_steps = 10000000; uint rbf = 0; uint grids = 4; int n_samples = 40; int sampling = 1; // Value iteration threshold real threshold = 0.001; const char* environment_name = "MountainCar"; { // options int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"n_states", required_argument, 0, 0}, // 0 {"n_actions", required_argument, 0, 0}, // 1 {"gamma", required_argument, 0, 0}, // 2 {"n_runs", required_argument, 0, 0}, // 3 {"n_train_episodes", required_argument, 0, 0}, // 4 {"n_test_episodes", required_argument, 0, 0}, // 5 {"n_steps", required_argument, 0, 0}, // 6 {"epsilon", required_argument, 0, 0}, // 7 {"N0", required_argument, 0, 0}, // 8 {"a", required_argument, 0, 0}, // 9 {"environment_name", required_argument, 0, 0}, // 10 {"rbf", required_argument, 0, 0}, // 11 {"grids", required_argument, 0, 0}, // 12 {"randomness", required_argument, 0, 0}, // 13 {"episode_steps", required_argument, 0, 0}, // 14 {"n_samples", required_argument, 0, 0}, // 15 {"sampling", required_argument, 0, 0}, // 16 {"threshold", required_argument, 0, 0}, // 17 {0, 0, 0, 0}}; c = getopt_long(argc, argv, "", long_options, &option_index); if (c == -1) break; switch (c) { case 0: #if 1 printf("option %s (%d)", long_options[option_index].name, option_index); if (optarg) printf(" with arg %s", optarg); printf("\n"); #endif switch (option_index) { case 0: n_states = atoi(optarg); break; case 1: n_actions = atoi(optarg); break; case 2: gamma = atof(optarg); break; case 3: n_runs = atoi(optarg); break; case 4: n_train_episodes = atoi(optarg); break; case 5: n_test_episodes = atoi(optarg); break; case 6: n_steps = atoi(optarg); break; case 7: epsilon = atof(optarg); break; case 8: N0 = atof(optarg); break; case 9: a = atof(optarg); break; case 10: environment_name = optarg; break; case 11: rbf = atoi(optarg); break; case 12: grids = atoi(optarg); break; case 13: randomness = atof(optarg); break; case 14: episode_steps = atoi(optarg); break; case 15: n_samples = atoi(optarg); break; case 16: sampling = atoi(optarg); break; case 17: threshold = atof(optarg); break; default: fprintf(stderr, "%s", help_text); exit(0); break; } break; case '0': case '1': case '2': if (digit_optind != 0 && digit_optind != this_option_optind) printf("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf("option %c\n", c); break; default: std::cout << help_text; exit(-1); } } if (optind < argc) { printf("non-option ARGV-elements: "); while (optind < argc) { printf("%s ", argv[optind++]); } printf("\n"); } } assert(n_states > 0); assert(n_actions > 0); assert(gamma >= 0 && gamma <= 1); assert(randomness >= 0 && randomness <= 1); assert(n_runs > 0); assert(n_train_episodes > 0); assert(n_test_episodes > 0); assert(n_steps > 0); assert(rbfs == 0 || rbfs == 1); assert(grid_size > 0); n_steps = n_test_episodes * episode_steps; RandomNumberGenerator* rng; RandomNumberGenerator* environment_rng; MersenneTwisterRNG mersenne_twister_env; environment_rng = (RandomNumberGenerator*)&mersenne_twister_env; MersenneTwisterRNG mersenne_twister; rng = (RandomNumberGenerator*)&mersenne_twister; srand48(34987235); srand(34987235); setRandomSeed(34987235); environment_rng->manualSeed(228240153); rng->manualSeed(1361690241); std::cout << "Starting test program" << std::endl; std::cout << "Starting evaluation" << std::endl; // remember to use n_runs Statistics statistics; statistics.ep_stats.resize(n_test_episodes); statistics.reward.resize(n_steps, 0.0); statistics.n_runs.resize(n_steps, 0); // for (uint i=0; i<n_steps; ++i) { // statistics.reward[i] = 0; // statistics.n_runs[i] = 0; // } std::cout << " - Creating environment.." << std::endl; ContinuousStateEnvironment* environment = NULL; if (!strcmp(environment_name, "MountainCar")) { environment = new MountainCar(); environment->setRandomness(randomness); } else if (!strcmp(environment_name, "Pendulum")) { environment = new Pendulum(); environment->setRandomness(randomness); } else if (!strcmp(environment_name, "PuddleWorld")) { environment = new PuddleWorld(); } else if (!strcmp(environment_name, "Linear")) { environment = new LinearDynamicQuadratic(); } else { fprintf(stderr, "Unknown environment %s \n", environment_name); } std::cout << environment_name << " environment creation completed" << std::endl; // making sure the number of states & actions is correct n_states = environment->getNStates(); n_actions = environment->getNActions(); std::cout << "Creating environment: " << environment_name << " with " << n_states << " states and , " << n_actions << " actions.\n"; int m = n_states + 1; // Input dimensions (input state dimension plus a dummy state) int d_r = 1; // Reward dimensions int d_s = n_states; // Output states dimensions RBFBasisSet* RBFs = NULL; if (rbf == 1) { Vector S_L = environment->StateLowerBound(); S_L.print(stdout); Vector S_U = environment->StateUpperBound(); S_U.print(stdout); // Lower and upper environment bounds std::cout << "Creating Radial basis functions..." << std::endl; EvenGrid Discretisation(S_L, S_U, grids); RBFs = new RBFBasisSet(Discretisation, 1.0); m = RBFs->size() + 1; // redefinition of the input dimensions (size of the // created basis functions plus a dummy state) std::cout << "# Number of basis functions: " << m << std::endl; } std::cout << "# Creating " << n_actions << " bayesian multivariate models..." << std::endl; // bayesian multivariate regression model for the system transition model // one for each action std::vector<BayesianMultivariateRegression*> regression_t; regression_t.resize(n_actions); Matrix S0 = N0 * Matrix::Unity(d_s, d_s); for (int i = 0; i < n_actions; ++i) { regression_t[i] = new BayesianMultivariateRegression(m, d_s, S0, N0, a); } // bayesian multivariate regression model for the system reward model std::vector<BayesianMultivariateRegression*> regression_r; regression_r.resize(n_actions); S0 = N0 * Matrix::Unity(d_r, d_r); for (int i = 0; i < n_actions; ++i) { regression_r[i] = new BayesianMultivariateRegression(m, d_r, S0, N0, a); } std::cout << "Creation of the bayesian multivariate models completed..." << std::endl; // std::cout << "Linear model initialization..." << std::endl; // LinearModel<Vector,int>* lm = new LinearModel<Vector,int>( m, d_s, RBFs, // environment,regression_t); LinearModel<Vector, int>* lm = NULL; std::cout << "Fitted value iteration initialization..." << std::endl; FittedValueIteration<Vector, int>* FVI = new FittedValueIteration<Vector, int>(gamma, 3000, 1, grids, environment, regression_t, RBFs); std::cout << "Representative model creation..." << std::endl; // RepresentativeStateModel<LinearModel<Vector,int>, Vector, int> *RSM = // new RepresentativeStateModel<LinearModel<Vector,int>,Vector,int>(gamma, // threshold, *lm, n_samples, n_actions,FVI); RepresentativeStateModel<LinearModel<Vector, int>, Vector, int>* RSM = NULL; std::cout << "Creating online algorithm" << std::endl; BayesianMultivariate* algorithm = NULL; algorithm = new BayesianMultivariate(n_actions, m, d_s, gamma, epsilon, RBFs, regression_t, regression_r, lm, RSM, FVI); Matrix Stats(n_runs, n_test_episodes); Matrix Statr(n_runs, n_test_episodes); printf("Number of rollouts = %d\n", n_train_episodes); for (uint run = 0; run < n_runs; ++run) { std::cout << "# Run: " << run << std::endl; // algorithm->setGeometricSchedule(0.01,0.1); // TrainingAlgorithm1(gamma, n_train_episodes, algorithm, //environment, // RSM); TrainingAlgorithm2(gamma, n_samples, n_train_episodes, algorithm, environment); epsilon = 0.0; Statistics run_statistics = EvaluateAlgorithm( episode_steps, n_test_episodes, algorithm, environment, gamma); real train_steps = 0.0; for (uint i = 0; i < run_statistics.ep_stats.size(); ++i) { Stats(run, i) = run_statistics.ep_stats[i].steps; Statr(run, i) = run_statistics.ep_stats[i].total_reward; train_steps += run_statistics.ep_stats[i].steps; } printf("Mean number of steps = %f\n", train_steps / n_test_episodes); // for (uint i=0; i<run_statistics.ep_stats.size(); ++i) { // // statistics.ep_stats[i].total_reward += // run_statistics.ep_stats[i].total_reward; // statistics.ep_stats[i].discounted_reward += // run_statistics.ep_stats[i].discounted_reward; // statistics.ep_stats[i].steps += // run_statistics.ep_stats[i].steps; // statistics.ep_stats[i].mse += // run_statistics.ep_stats[i].mse; // statistics.ep_stats[i].n_runs++; // } // // for (uint i=0; i<run_statistics.reward.size(); ++i) { // statistics.reward[i] += run_statistics.reward[i]; // statistics.n_runs[i]++; // } algorithm->Reset(); } char buffer[100]; sprintf(buffer, "BRL_RESULTS_STEPS_%s->(Rollouts = %d)", environment_name, n_train_episodes); FILE* output = fopen(buffer, "w"); if (output != NULL) { Stats.print(output); } fclose(output); sprintf(buffer, "BRL_RESULTS_REWARDS_%s->(Rollouts = %d)", environment_name, n_train_episodes); output = fopen(buffer, "w"); if (output != NULL) { Statr.print(output); } fclose(output); // Pointer clearness delete environment; delete RBFs; for (int i = 0; i < n_actions; ++i) { delete regression_t[i]; delete regression_r[i]; } delete lm; delete algorithm; // for (uint i=0; i<statistics.ep_stats.size(); ++i) { // statistics.ep_stats[i].total_reward /= (float) n_runs; // statistics.ep_stats[i].discounted_reward /= (float) n_runs; // statistics.ep_stats[i].steps /= n_runs; // statistics.ep_stats[i].mse /= n_runs; // std::cout << statistics.ep_stats[i].n_runs << " " // << statistics.ep_stats[i].total_reward << " " // << statistics.ep_stats[i].discounted_reward << " //# // EPISODE_RETURN" // << std::endl; // std::cout << statistics.ep_stats[i].steps << " " // << statistics.ep_stats[i].mse << " # // INST_PAYOFF" // << std::endl; // } // // std::cout << "Done" << std::endl; return 0; } ///*** Policy exploration // n_steps: maximum number of total steps inside a trajectory. // */ void TrainingAlgorithm1( real gamma, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment, RepresentativeStateModel<LinearModel<Vector, int>, Vector, int>* R) { std::cout << "#Training ...." << environment->Name() << std::endl; Vector state; Vector next_state; environment->Reset(); real reward; float epsilon_add = 0; int nsamples; bool action_ok = true; bool flag; int step = 0; int current_time; for (int episode = 1; episode < n_episodes; ++episode) { nsamples = R->getNSamples(); printf("Number of representative states = %d\n", nsamples); for (int r_sample = 0; r_sample < nsamples; ++r_sample) { for (int action_rr = 0; action_rr < (int)environment->getNActions(); ++action_rr) { environment->Reset(); current_time = 0; state = R->getSample(r_sample); environment->setState(state); action_ok = true; step = 0; flag = false; if (urandom() < epsilon_add) { flag = true; } int action = action_rr; while (action_ok && urandom() > (1 - gamma) && current_time < 1) { step++; action_ok = environment->Act(action); if (current_time == 0) { R->UpdateStatistics(r_sample, action, action_ok); } reward = environment->getReward(); next_state = environment->getState(); algorithm->Observe(state, action, reward, next_state); state = next_state; action = algorithm->Act(state); if (flag == true && urandom() < 0.1) { flag = false; // printf("ADD //REPRESENTATIVE // STATE\n"); R->AddState(next_state); } current_time++; } } // if(urandom() < epsilon_add) { // flag = true; // // printf("ADD REPRESENTATIVE STATE\n"); //// R->AddState(next_state); // } // printf("Terminate at time step = %d\n",step); // algorithm->Update(); } epsilon_add = epsilon_add * 0.0; algorithm->Update(); printf("# episode %d complete\n", episode); } FILE* input = fopen("Input_samples.txt", "w"); if (input != NULL) { for (int i = 0; i < R->getNSamples(); ++i) { state = R->getSample(i); state.print(input); } } fclose(input); char buffer[100]; int n; for (int a = 0; a < (int)environment->getNActions(); ++a) { n = sprintf(buffer, "Output_samples_action_%d", a); FILE* output = fopen(buffer, "w"); n = sprintf(buffer, "Reward_samples_action_%d", a); FILE* rew = fopen(buffer, "w"); if (output != NULL) { for (int i = 0; i < R->getNSamples(); ++i) { environment->Reset(); state = R->getSample(i); environment->setState(state); action_ok = environment->Act(a); reward = environment->getReward(); Vector r(reward); r.print(rew); next_state = environment->getState(); next_state.print(output); } } fclose(output); fclose(rew); } algorithm->Predict(); algorithm->Update(); } /*** Policy exploration n_steps: maximum number of total steps inside a trajectory. */ void TrainingAlgorithm2(real gamma, int N, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment) { std::cout << "#Training ...." << environment->Name() << std::endl; Vector state; Vector next_state; environment->Reset(); real reward; float epsilon_add = 0; // int nsamples; bool action_ok = true; bool flag; int step = 0; int current_time; int action; Vector S_L = environment->StateLowerBound(); Vector S_U = environment->StateUpperBound(); std::vector<Vector> states; for (int i = 0; i < N; ++i) { state = urandom(S_L, S_U); states.push_back(state); } for (int episode = 0; episode < n_episodes; ++episode) { // nsamples = states.size(); // printf("Number of representative states = %d\n",nsamples); // for( int r_sample = 0; r_sample < nsamples; ++r_sample ) { // for( int action_rr = 0; action_rr < //(int)environment->getNActions(); //++action_rr) { environment->Reset(); state = environment->getState(); // int action_rr = (int) floor(urandom(0.0, (real) // environment->getNActions())); action = (int)floor(urandom(0.0, (real)environment->getNActions())); current_time = 0; // state = states[r_sample]; // environment->setState(state); action_ok = true; step = 0; flag = false; if (urandom() < epsilon_add) { flag = true; } // int action = action_rr; while (action_ok && current_time < N) { step++; action_ok = environment->Act(action); reward = environment->getReward(); next_state = environment->getState(); algorithm->Observe(state, action, reward, next_state); state = next_state; // action = algorithm->Act(state); action = (int)floor(urandom(0.0, (real)environment->getNActions())); current_time++; } // } // } // algorithm->Update(); // printf ("# episode %d complete -> Steps = %d \n", // episode,current_time); } FILE* input = fopen("Input_samples.txt", "w"); if (input != NULL) { for (uint i = 0; i < states.size(); ++i) { state = states[i]; state.print(input); } } fclose(input); char buffer[100]; int n; for (int a = 0; a < (int)environment->getNActions(); ++a) { n = sprintf(buffer, "Output_samples_action_%d", a); FILE* output = fopen(buffer, "w"); n = sprintf(buffer, "Reward_samples_action_%d", a); FILE* rew = fopen(buffer, "w"); if (output != NULL) { for (uint i = 0; i < states.size(); ++i) { environment->Reset(); state = states[i]; environment->setState(state); action_ok = environment->Act(a); reward = environment->getReward(); Vector r(reward); r.print(rew); next_state = environment->getState(); next_state.print(output); } } fclose(output); fclose(rew); } printf("Model training end\n"); // for(int i = 0; i<n_actions; ++i) { // regression_t[i]->Select(); // } algorithm->Predict(states); algorithm->Update(); // algorithm->Update(); } /*** Evaluate an algorithm episode_steps: maximum number of steps per episode. If negative, then ignore n_steps: maximun number of total steps. If negative, then ignore. n_episodes: maximum number of episodes. Cannot be negative. */ Statistics EvaluateAlgorithm(int episode_steps, int n_episodes, BayesianMultivariate* algorithm, ContinuousStateEnvironment* environment, real gamma) { std::cout << "# evaluating..." << environment->Name() << std::endl; int n_steps = episode_steps * n_episodes; Statistics statistics; statistics.ep_stats.reserve(n_episodes); statistics.reward.reserve(n_steps); uint step = 0; real discount = gamma; int current_time = 0; environment->Reset(); // environment->getState().print(stdout); std::cout << "(running)" << std::endl; int episode = -1; bool action_ok = false; real total_reward = 0.0; real discounted_reward = 0.0; while (1) { step++; if (episode_steps > 0 && current_time >= episode_steps) { action_ok = false; environment->Reset(); } if (!action_ok) { Vector state = environment->getState(); real reward = environment->getReward(); // action = algorithm->Act(state); statistics.reward.resize(step + 1); statistics.reward[step] = reward; // if (episode >= 0) { // statistics.ep_stats[episode].steps++; // statistics.ep_stats[episode].total_reward += reward; // statistics.ep_stats[episode].discounted_reward //+= discount * reward; // } total_reward += reward; discounted_reward += discount * reward; discount *= gamma; episode++; statistics.ep_stats.resize(episode + 1); statistics.ep_stats[episode].total_reward = 0.0; statistics.ep_stats[episode].discounted_reward = 0.0; statistics.ep_stats[episode].steps = 0; discount = 1.0; // printf ("# episode %d complete Step = %d\n", // episode,current_time); environment->Reset(); environment->getState(); //.print(stdout); action_ok = true; current_time = 0; if (n_episodes >= 0 && episode >= n_episodes) { // logmsg (" Breaking after %d episodes, %d steps\n", // episode, step); break; } // printf("New episode\n"); step++; } Vector state = environment->getState(); // state.print(stdout); int action; action = algorithm->Act(state); real reward = environment->getReward(); statistics.reward.resize(step + 1); statistics.reward[step] = reward; statistics.ep_stats[episode].steps++; statistics.ep_stats[episode].total_reward += reward; statistics.ep_stats[episode].discounted_reward += discount * reward; total_reward += reward; discounted_reward += discount * reward; discount *= gamma; // printf("action = %d\n",action); action_ok = environment->Act(action); current_time++; } // printf(" %f %f # RUN_REWARD\n", total_reward, discounted_reward); if ((int)statistics.ep_stats.size() != n_episodes) { statistics.ep_stats.resize(statistics.ep_stats.size() - 1); } // printf ("# Exiting after %d episodes, %d steps (%d %d)\n", // episode, n_steps, // (int) statistics.ep_stats.size(), // (int) statistics.reward.size()); // return statistics; } #endif
31.791315
91
0.586227
litlpoet
7a5844762dcaf766018b7c7ceef18282378acb4e
1,351
hpp
C++
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/math/fractional_part.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_MATH_FRACTIONAL_PART_HPP #define SPROUT_MATH_FRACTIONAL_PART_HPP #include <limits> #include <type_traits> #include <sprout/config.hpp> #include <sprout/math/detail/config.hpp> #include <sprout/math/integer_part.hpp> #include <sprout/type_traits/enabler_if.hpp> namespace sprout { namespace math { namespace detail { template< typename FloatType, typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR FloatType fractional_part(FloatType x) { return x == std::numeric_limits<FloatType>::infinity() || x == -std::numeric_limits<FloatType>::infinity() ? FloatType(0) : x == std::numeric_limits<FloatType>::quiet_NaN() ? std::numeric_limits<FloatType>::quiet_NaN() : x - sprout::math::integer_part(x) ; } template< typename IntType, typename sprout::enabler_if<std::is_integral<IntType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR double fractional_part(IntType x) { return sprout::math::detail::fractional_part(static_cast<double>(x)); } } // namespace detail using sprout::math::detail::fractional_part; } // namespace math using sprout::math::fractional_part; } // namespace sprout #endif // #ifndef SPROUT_MATH_FRACTIONAL_PART_HPP
31.418605
126
0.706884
osyo-manga
7a58da0624821c6e4c15b30faaf1535da7ef94da
17,586
cpp
C++
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
2
2022-01-01T22:26:57.000Z
2022-02-14T04:03:32.000Z
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
null
null
null
test/ProcessMoveTests.cpp
eunmann/chess-engine
42bfa6cbf108d2746505faa3b6ee5d31e0a87b7d
[ "MIT" ]
null
null
null
#include "TestFW.hpp" #include "Definitions.hpp" #include "BitBoardUtils.hpp" #include <cassert> #include "GameState.hpp" #include <vector> #include "MoveGeneration.hpp" namespace Tests { auto add_process_move_tests(TestFW::UnitTest &unit_tests) -> void { TestFW::TestCase process_move_test_case("Process Move"); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Kasparov vs. Topalov, Wijk aan Zee 1999", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "d7d6", "d2d4", "g8f6", "b1c3", "g7g6", "c1e3", "f8g7", "d1d2", "c7c6", "f2f3", "b7b5", "g1e2", "b8d7", "e3h6", "g7h6", "d2h6", "c8b7", "a2a3", "e7e5", "e1c1", "d8e7", "c1b1", "a7a6", "e2c1", "e8c8", "c1b3", "e5d4", "d1d4", "c6c5", "d4d1", "d7b6", "g2g3", "c8b8", "b3a5", "b7a8", "f1h3", "d6d5", "h6f4", "b8a7", "h1e1", "d5d4", "c3d5", "b6d5", "e4d5", "e7d6", "d1d4", "c5d4", "e1e7", "a7b6", "f4d4", "b6a5", "b2b4", "a5a4", "d4c3", "d6d5", "e7a7", "a8b7", "a7b7", "d5c4", "c3f6", "a4a3", "f6a6", "a3b4", "c2c3", "b4c3", "a6a1", "c3d2", "a1b2", "d2d1", "h3f1", "d8d2", "b7d7", "d2d7", "f1c4", "b5c4", "b2h8", "d7d3", "h8a8", "c4c3", "a8a4", "d1e1", "f3f4", "f7f5", "b1c1", "d3d2", "a4a7"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Morphy vs. Allies, Paris Opera 1858", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "e7e5", "g1f3", "d7d6", "d2d4", "c8g4", "d4e5", "g4f3", "d1f3", "d6e5", "f1c4", "g8f6", "f3b3", "d8e7", "b1c3", "c7c6", "c1g5", "b7b5", "c3b5", "c6b5", "c4b5", "b8d7", "e1c1", "a8d8", "d1d7", "d8d7", "h1d1", "e7e6", "b5d7", "f6d7", "b3b8", "d7b8", "d1d8"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Aronian vs. Anand, Wijk aan Zee 2013", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "d7d5", "c2c4", "c7c6", "g1f3", "g8f6", "b1c3", "e7e6", "e2e3", "b8d7", "f1d3", "d5c4", "d3c4", "b7b5", "c4d3", "f8d6", "e1g1", "e8g8", "d1c2", "c8b7", "a2a3", "a8c8", "f3g5", "c6c5", "g5h7", "f6g4", "f2f4", "c5d4", "e3d4", "d6c5", "d3e2", "d7e5", "e2g4", "c5d4", "g1h1", "e5g4", "h7f8", "f7f5", "f8g6", "d8f6", "h2h3", "f6g6", "c2e2", "g6h5", "e2d3", "d4e3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Karpov vs. Kasparov, World Championship 1985, game 16", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "c7c5", "g1f3", "e7e6", "d2d4", "c5d4", "f3d4", "b8c6", "d4b5", "d7d6", "c2c4", "g8f6", "b1c3", "a7a6", "b5a3", "d6d5", "c4d5", "e6d5", "e4d5", "c6b4", "f1e2", "f8c5", "e1g1", "e8g8", "e2f3", "c8f5", "c1g5", "f8e8", "d1d2", "b7b5", "a1d1", "b4d3", "a3b1", "h7h6", "g5h4", "b5b4", "c3a4", "c5d6", "h4g3", "a8c8", "b2b3", "g7g5", "g3d6", "d8d6", "g2g3", "f6d7", "f3g2", "d6f6", "a2a3", "a6a5", "a3b4", "a5b4", "d2a2", "f5g6", "d5d6", "g5g4", "a2d2", "g8g7", "f2f3", "f6d6", "f3g4", "d6d4", "g1h1", "d7f6", "f1f4", "f6e4", "d2d3", "e4f2", "f4f2", "g6d3", "f2d2", "d4e3", "d2d3", "c8c1", "a4b2", "e3f2", "b1d2", "c1d1", "b2d1", "e8e1",}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Byrne vs. Fischer, New York 1956", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"g1f3", "g8f6", "c2c4", "g7g6", "b1c3", "f8g7", "d2d4", "e8g8", "c1f4", "d7d5", "d1b3", "d5c4", "b3c4", "c7c6", "e2e4", "b8d7", "a1d1", "d7b6", "c4c5", "c8g4", "f4g5", "b6a4", "c5a3", "a4c3", "b2c3", "f6e4", "g5e7", "d8b6", "f1c4", "e4c3", "e7c5", "f8e8", "e1f1", "g4e6", "c5b6", "e6c4", "f1g1", "c3e2", "g1f1", "e2d4", "f1g1", "d4e2", "g1f1", "e2c3", "f1g1", "a7b6", "a3b4", "a8a4", "b4b6", "c3d1", "h2h3", "a4a2", "g1h2", "d1f2", "h1e1", "e8e1", "b6d8", "g7f8", "f3e1", "c4d5", "e1f3", "f2e4", "d8b8", "b7b5", "h3h4", "h7h5", "f3e5", "g8g7", "h2g1", "f8c5", "g1f1", "e4g3", "f1e1", "c5b4", "e1d1", "d5b3", "d1c1", "g3e2", "c1b1", "e2c3", "b1c1", "a2c2"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Ivanchuk vs. Yusupov, Brussels 1991", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"c2c4", "e7e5", "g2g3", "d7d6", "f1g2", "g7g6", "d2d4", "b8d7", "b1c3", "f8g7", "g1f3", "g8f6", "e1g1", "e8g8", "d1c2", "f8e8", "f1d1", "c7c6", "b2b3", "d8e7", "c1a3", "e5e4", "f3g5", "e4e3", "f2f4", "d7f8", "b3b4", "c8f5", "c2b3", "h7h6", "g5f3", "f6g4", "b4b5", "g6g5", "b5c6", "b7c6", "f3e5", "g5f4", "e5c6", "e7g5", "a3d6", "f8g6", "c3d5", "g5h5", "h2h4", "g6h4", "g3h4", "h5h4", "d5e7", "g8h8", "e7f5", "h4h2", "g1f1", "e8e6", "b3b7", "e6g6", "b7a8", "h8h7", "a8g8", "h7g8", "c6e7", "g8h7", "e7g6", "f7g6", "f5g7", "g4f2", "d6f4", "h2f4", "g7e6", "f4h2", "d1b1", "f2h3", "b1b7", "h7h8", "b7b8", "h2b8", "g2h3", "b8g3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Short vs. Timman, Tilburg 1991", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "g8f6", "e4e5", "f6d5", "d2d4", "d7d6", "g1f3", "g7g6", "f1c4", "d5b6", "c4b3", "f8g7", "d1e2", "b8c6", "e1g1", "e8g8", "h2h3", "a7a5", "a2a4", "d6e5", "d4e5", "c6d4", "f3d4", "d8d4", "f1e1", "e7e6", "b1d2", "b6d5", "d2f3", "d4c5", "e2e4", "c5b4", "b3c4", "d5b6", "b2b3", "b6c4", "b3c4", "f8e8", "e1d1", "b4c5", "e4h4", "b7b6", "c1e3", "c5c6", "e3h6", "g7h8", "d1d8", "c8b7", "a1d1", "h8g7", "d8d7", "e8f8", "h6g7", "g8g7", "d1d4", "a8e8", "h4f6", "g7g8", "h3h4", "h7h5", "g1h2", "e8c8", "h2g3", "c8e8", "g3f4", "b7c8", "f4g5"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Bai Jinshi vs. Ding Liren, Chinese League 2017", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "g8f6", "c2c4", "e7e6", "b1c3", "f8b4", "g1f3", "e8g8", "c1g5", "c7c5", "e2e3", "c5d4", "d1d4", "b8c6", "d4d3", "h7h6", "g5h4", "d7d5", "a1d1", "g7g5", "h4g3", "f6e4", "f3d2", "e4c5", "d3c2", "d5d4", "d2f3", "e6e5", "f3e5", "d4c3", "d1d8", "c3b2", "e1e2", "f8d8", "c2b2", "c5a4", "b2c2", "a4c3", "e2f3", "d8d4", "h2h3", "h6h5", "g3h2", "g5g4", "f3g3", "d4d2", "c2b3", "c3e4", "g3h4", "b4e7", "h4h5", "g8g7", "h2f4", "c8f5", "f4h6", "g7h7", "b3b7", "d2f2", "h6g5", "a8h8", "e5f7", "f5g6", "h5g4", "c6e5"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Rotlewi vs. Rubinstein, Lodz 1907", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "d7d5", "g1f3", "e7e6", "e2e3", "c7c5", "c2c4", "b8c6", "b1c3", "g8f6", "d4c5", "f8c5", "a2a3", "a7a6", "b2b4", "c5d6", "c1b2", "e8g8", "d1d2", "d8e7", "f1d3", "d5c4", "d3c4", "b7b5", "c4d3", "f8d8", "d2e2", "c8b7", "e1g1", "c6e5", "f3e5", "d6e5", "f2f4", "e5c7", "e3e4", "a8c8", "e4e5", "c7b6", "g1h1", "f6g4", "d3e4", "e7h4", "g2g3", "c8c3", "g3h4", "d8d2", "e2d2", "b7e4", "d2g2", "c3h3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back( TestFW::Test("GameUtils::process_user_move - Geller vs. Euwe, Zurich 1953", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"d2d4", "g8f6", "c2c4", "e7e6", "b1c3", "f8b4", "e2e3", "c7c5", "a2a3", "b4c3", "b2c3", "b7b6", "f1d3", "c8b7", "f2f3", "b8c6", "g1e2", "e8g8", "e1g1", "c6a5", "e3e4", "f6e8", "e2g3", "c5d4", "c3d4", "a8c8", "f3f4", "a5c4", "f4f5", "f7f6", "f1f4", "b6b5", "f4h4", "d8b6", "e4e5", "c4e5", "f5e6", "e5d3", "d1d3", "b6e6", "d3h7", "g8f7", "c1h6", "f8h8", "h7h8", "c8c2", "a1c1", "c2g2", "g1f1", "e6b3", "f1e1", "b3f3"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 1", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "b8a6", "d1h5", "a6b4", "f1c4", "b4c2", "e1d1", "c2e3", "d2e3", "d7d5", "c4d5", "c8e6", "c1d2", "d8d7", "d5e6", "e8d8", "e6d7"}; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 2", []() { GameState game_state; std::vector<std::string> moves{"e2e4", "g8h6", "d2d4", "h6f5", "e4f5"}; for (std::size_t i = 0; i < moves.size(); i += 2) { game_state.init(); for (std::size_t j = 0; j <= i; j++) { auto move = moves[j]; TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); } } })); process_move_test_case.tests.emplace_back(TestFW::Test("GameUtils::process_user_move - Test Game 3", []() { GameState game_state; game_state.init(); std::vector<std::string> moves{"e2e4", "b8c6", "d2d4", "d7d5", "e4d5", "d8d5", "g1f3", "d5e4", "d1e2", "e4e2", "f1e2", "c8g4", "b1c3", "a8d8", "c1e3", "d8d6", "e1c1", "g4h3", "g2h3"}; bool rook_moved = false; for (auto &move: moves) { TFW_ASSERT_EQ(true, GameUtils::process_user_move(game_state, move)); TFW_ASSERT_EQ(true, game_state.is_legal()); if (!rook_moved && game_state.has_rook_A_moved<Colors::BLACK>()) { rook_moved = true; } else if (rook_moved) { TFW_ASSERT_EQ(true, game_state.has_rook_A_moved<Colors::BLACK>()); } } TFW_ASSERT_EQ(true, game_state.has_rook_A_moved<Colors::BLACK>()); std::string illegal_black_queen_side_castle = "e8c8"; TFW_ASSERT_EQ(false, GameUtils::process_user_move(game_state, illegal_black_queen_side_castle)); })); unit_tests.test_cases.push_back(process_move_test_case); } }
66.362264
119
0.387808
eunmann
7a5a717b88036f76c2144b9d9dfbc4b3d47c7ece
7,250
cc
C++
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
null
null
null
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
1
2021-03-02T17:12:23.000Z
2021-03-02T17:12:23.000Z
src/svm_ila.cc
igreene2/SVMA
5bdfd380cb4a9bd46a67d55db1dc9a1e6cede4fc
[ "MIT" ]
null
null
null
/// \file the ila example of svma accelerator: /// support vector machine accelerator for biomedical purposes, // receives MMIO instruction /// Isabel Greene (igreene@princeton.edu) /// #include <ilang/ilang++.h> #include <svma_ila.h> #include <ilang/util/log.h> namespace ilang { namespace svma { Ila GetSVMAIla(const std::string& model_name) { // construct the model auto m = ilang::Ila("SVMA"); std::cout << "made svma\n"; // inputs m.NewBvInput("mode", 1); m.NewBvInput("addr_in", 32); m.NewBvInput("data_in", 32); // internal arch state m.NewBvState("base_addr_sv", 32); m.NewBvState("base_addr_tv", 32); m.NewBvState("tau", 32); m.NewBvState("c", 32); m.NewBvState("b", 32); m.NewBvState("fv_dim", 32); m.NewBvState("num_sv", 32); m.NewBvState("th", 32); m.NewBvState("shift1", 8); m.NewBvState("shift2", 8); m.NewBvState("shift3", 8); m.NewBvState("cmd_bits", 16); // the memory m.NewMemState("mem", 32, 32); // the output m.NewBvState("score", 32); m.NewBvState("output_proc", 32); // internal state m.NewBvState("run_svma", 1); m.NewBvState("interrupt_enable", 1); m.NewBvState("reformulation", 1); m.NewBvState("kernel", 2); m.NewBvState("order_poly", 1); m.NewBvState("output", 1); m.NewBvState("done", 1); m.NewBvState("child_state", 2); m.AddInit(m.state("child_state") == 0); std::cout << "declared all the state\n"; m.SetValid(m.input("addr_in") >= 0x0000 & m.input("addr_in") < 0x25C2); std::cout << "did the valid\n"; { // SVM_SV_BASEADDR_L std::cout << "inside SVM_SV_BASEADDR\n"; auto instr = m.NewInstr("SVM_SV_BASEADDR"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A4)); instr.SetUpdate(m.state("base_addr_sv"), m.input("data_in")); } { // SVM_TV_BASEADDR_L std::cout << "inside SVM_TV_BASEADDR\n"; auto instr = m.NewInstr("SVM_TV_BASEADDR"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A8)); instr.SetUpdate(m.state("base_addr_tv"), m.input("data_in")); } { // SVM_GAMMA (tau) std::cout << "inside SVM_GAMMA \n"; auto instr = m.NewInstr("SVM_GAMMA"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AA)); instr.SetUpdate(m.state("tau"), m.input("data_in")); } { // SVM_C std::cout << "inside SVM_C\n"; auto instr = m.NewInstr("SVM_C"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AC)); instr.SetUpdate(m.state("c"), m.input("data_in")); } { // SVM_B std::cout << "inside SVM_B\n"; auto instr = m.NewInstr("SVM_B"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25AE)); instr.SetUpdate(m.state("b"), m.input("data_in")); } { // SVM_FV_DIM std::cout << "inside SVM_FV_DIM\n"; auto instr = m.NewInstr("SVM_FV_DIM"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B0)); // instr.SetUpdate(m.state("fv_dim"), m.input("data_in")); } { // SVM_NUMSV std::cout << "inside SVM_NUMSV\n"; auto instr = m.NewInstr("SVM_NUMSV"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B2)); instr.SetUpdate(m.state("num_sv"), m.input("data_in")); } { // SVM_SHIFT12 std::cout << "inside SVM_SHIFT12\n"; auto instr = m.NewInstr("SVM_SHIFT12"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B4)); instr.SetUpdate(m.state("shift1"), Extract(m.input("data_in"), 7, 0)); instr.SetUpdate(m.state("shift2"), Extract(m.input("data_in"), 15, 8)); } { // SVM_SHIFT3 std::cout << "inside SVM_SHIFT3\n"; auto instr = m.NewInstr("SVM_SHIFT3"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B6)); instr.SetUpdate(m.state("shift3"), Extract(m.input("data_in"), 7, 0)); } { // SVM_TH std::cout << "inside SVM_TH\n"; auto instr = m.NewInstr("SVM_TH"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25B8)); instr.SetUpdate(m.state("th"), m.input("data_in")); } { // SVM_CMD_STATUS std::cout << "inside SVM_CMD_STATUS\n"; auto instr = m.NewInstr("SVM_CMD_STATUS"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") == 0x25A0)); // child valid bit instr.SetUpdate(m.state("run_svma"), SelectBit(m.input("data_in"), 7)); // child decode bits instr.SetUpdate(m.state("interrupt_enable"), SelectBit(m.input("data_in"), 6)); instr.SetUpdate(m.state("reformulation"), SelectBit(m.input("data_in"), 5)); instr.SetUpdate(m.state("kernel"), Extract(m.input("data_in"), 4, 3)); instr.SetUpdate(m.state("order_poly"), SelectBit(m.input("data_in"), 2)); DefineLinearChild(m); DefineLinearReformChild(m); DefineTwoPolyChild(m); DefineTwoPolyReformChild(m); DefineFourPolyChild(m); DefineRBFChild(m); } { // SVM_STORE_DATA std::cout << "inside STORE_DATA\n"; auto instr = m.NewInstr("STORE_DATA"); instr.SetDecode((m.input("mode") == 1) & (m.input("addr_in") < 0x25A2)); auto update_memory_at_addrin = Store(m.state("mem"), m.input("addr_in"), m.input("data_in")); instr.SetUpdate(m.state("mem"), update_memory_at_addrin); std::cout << "outside STORE_DATA\n"; } { // SVM_CMD_STATUS std::cout << "inside SVM_CMD_STATUS_OUT\n"; auto instr = m.NewInstr("SVM_CMD_STATUS_OUT"); instr.SetDecode((m.input("mode") == 0) & (m.input("addr_in") == 0x25A0)); auto combined = Concat(m.state("done"), m.state("output")); instr.SetUpdate(m.state("output_proc"), Concat(BvConst(0, 30), combined)); } { // SVM_SCORE std::cout << "inside SVM_SCORE\n"; auto instr = m.NewInstr("SVM_SCORE"); instr.SetDecode((m.input("mode") == 0) & (m.input("addr_in") == 0x25BA)); instr.SetUpdate(m.state("output_proc"), m.state("score")); } return m; } }; };
30.590717
105
0.50331
igreene2
7a61c19f1895879ada93ff5139c44c67c1dc87a3
1,803
cpp
C++
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
src/textures.cpp
sword-and-sorcery/glfw-textures
cb663fc39b9060057f4a726ffc93004e48229009
[ "MIT" ]
null
null
null
#include "tileset_glfw/textures.h" #include <iostream> #include <GLFW/glfw3.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> namespace opengl { namespace { std::map<std::string, const assets::tileset*> tilesets; // TODO: !!! std::map<std::pair<std::string, std::string>, std::tuple<int, int, void*>> images; } void add(const std::string& id, const assets::tileset& tileset) { tilesets.emplace(std::make_pair(id, &tileset)); } void* get_texture(const std::string& tileset, const std::string& id, int& width, int& height) { auto it_images = images.find(std::make_pair(tileset, id)); if (it_images != images.end()) { width = std::get<0>(it_images->second); height = std::get<1>(it_images->second); return std::get<2>(it_images->second); } auto it = tilesets.find(tileset); if (it != tilesets.end()) { auto tile = it->second->get(id); unsigned char* image_data = stbi_load(tile.filename.c_str(), &width, &height, NULL, 4); GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); void* ret = (void*)(intptr_t)my_opengl_texture; images[std::make_pair(tileset, id)] = std::make_tuple(width, height, ret); return ret; } throw std::runtime_error("Tileset (or tile) not found"); } }
37.5625
109
0.622296
sword-and-sorcery
7a6304ac12b7dee27b8d0f011b9049276014f31b
2,789
cpp
C++
unranged/468.cpp
Taowyoo/LeetCodeLog
cb05798538dd10675bf81011a419d0e33d85e4e0
[ "MIT" ]
null
null
null
unranged/468.cpp
Taowyoo/LeetCodeLog
cb05798538dd10675bf81011a419d0e33d85e4e0
[ "MIT" ]
null
null
null
unranged/468.cpp
Taowyoo/LeetCodeLog
cb05798538dd10675bf81011a419d0e33d85e4e0
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/validate-ip-address/ // Approach 1: use regex class Solution { public: /** * @brief Use std::regex to check whether given string is IPV4 or IPV6 * * @param IP Given IP address string * @return string Result */ string validIPAddress(string IP) { // create regex object for regulare expression regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"); regex ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"); if(regex_match(IP, ipv4)) // match regex expression with given IP string for IPv4 return "IPv4"; else if(regex_match(IP, ipv6)) // match regex expression with given IP string for IPv6 return "IPv6"; return "Neither"; // Otherwise return "Neither" } }; // Approach 2: normal check class Solution { public: /** * @brief Use stringsteam to check whether given string is IPV4 or IPV6 * * @param IP Given IP address string * @return string Result */ string validIPAddress(string IP) { istringstream is(IP); string t = ""; int cnt = 0; if (IP.find(':') == string::npos) { // Check IPv4 // use getline with customized delimiter to give each part of IPv4 address while (getline(is, t, '.')) { ++cnt; // count the number of subpart of address // only have 4 parts, no abbreviation, no leading zero if (cnt > 4 || t.empty() || (t.size() > 1 && t[0] == '0') || t.size() > 3) return "Neither"; for (char c : t) { // there are only numbers if (c < '0' || c > '9') return "Neither"; } int val = stoi(t); // number should be in [0,255] if (val < 0 || val > 255) return "Neither"; } return (cnt == 4 && IP.back() != '.') ? "IPv4" : "Neither"; } else { // Check IPv6 // use getline with customized delimiter to give each part of IPv6 address while (getline(is, t, ':')) { ++cnt; // count the number of subpart of address // only have 8 parts, no abbreviation, each part at most haas 4 hex numbers if (cnt > 8 || t.empty() || t.size() > 4) return "Neither"; for (char c : t) { // there are only hex numbers if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return "Neither"; } } // only have 8 parts return (cnt == 8 && IP.back() != ':') ? "IPv6" : "Neither"; } } };
41.014706
131
0.487271
Taowyoo
7a64f46225b59710178fb26e1fc9e32b985119ee
663
cpp
C++
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/gui/nodes/GUINode_Flow.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
#include <tdme/gui/nodes/GUINode_Flow.h> #include <string> #include <tdme/utils/Enum.h> using std::string; using tdme::gui::nodes::GUINode_Flow; using tdme::utils::Enum; GUINode_Flow::GUINode_Flow(const string& name, int ordinal) : Enum(name, ordinal) { } GUINode_Flow* tdme::gui::nodes::GUINode_Flow::INTEGRATED = new GUINode_Flow("INTEGRATED", 0); GUINode_Flow* tdme::gui::nodes::GUINode_Flow::FLOATING = new GUINode_Flow("FLOATING", 1); GUINode_Flow* GUINode_Flow::valueOf(const string& a0) { if (FLOATING->getName() == a0) return FLOATING; if (INTEGRATED->getName() == a0) return INTEGRATED; // TODO: throw exception here maybe return nullptr; }
23.678571
93
0.731523
mahula
7a652c8223f0c75e9e6c20c5e068ccb00d437004
793
cc
C++
DataFormats/ParticleFlowCandidate/src/IsolatedPFCandidate.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DataFormats/ParticleFlowCandidate/src/IsolatedPFCandidate.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DataFormats/ParticleFlowCandidate/src/IsolatedPFCandidate.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DataFormats/ParticleFlowCandidate/interface/IsolatedPFCandidate.h" #include <iostream> using namespace reco; using namespace std; IsolatedPFCandidate::IsolatedPFCandidate() : PFCandidate(), isolation_(-1) {} IsolatedPFCandidate::IsolatedPFCandidate( const PFCandidatePtr & candidatePtr, double isolation ) : PFCandidate(candidatePtr), isolation_(isolation) { } IsolatedPFCandidate * IsolatedPFCandidate::clone() const { return new IsolatedPFCandidate( * this ); } IsolatedPFCandidate::~IsolatedPFCandidate() {} std::ostream& reco::operator<<( std::ostream& out, const IsolatedPFCandidate& c ) { if(!out) return out; const PFCandidate& mother = c; out<<"IsolatedPFCandidate, isolation = " <<c.isolation()<<" " <<mother; return out; }
22.657143
79
0.725095
nistefan
7a654faac16def890e44cd51be734a7e23df592b
8,208
cc
C++
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
winch_control/brew_session.cc
garratt/brewhouse
eb0b07d19733aa975d8d6322b4e82fd3b2711ced
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 Garratt Gallagher. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpio.h" #include "grainfather2.h" #include "brew_session.h" #include <utility> #include <deque> #include <mutex> #include <list> #include <functional> #include <iostream> using std::placeholders::_1; using std::placeholders::_2; int BrewSession::InitSession(const char *spreadsheet_id) { printf("Initializing session\n"); // ------------------------------------------------------------------ // Initialize the logger, which reads from the google sheet int logger_status = brew_logger_.SetSession(spreadsheet_id); if (logger_status < 0) { printf("Failed to set session\n"); return -1; } if (logger_status > 0) { printf("Restarting sessions currently not supported\n"); return -1; } brew_recipe_ = brew_logger_.ReadRecipe(); // Start Scale Loop if(scale_.InitLoop(std::bind(&BrewSession::OnScaleError, this)) < 0) { printf("Scale did not initialize correctly\n"); return -1; } // Log the weight every 10 seconds scale_.SetPeriodicWeightCallback(10*1000*1000, std::bind(&BrewLogger::LogWeight, &brew_logger_, _1, _2)); // Set the function that the winch controller uses to see if it should abort movement winch_controller_.SetAbortCheck(std::bind(&ScaleFilter::HasKettleLifted, &scale_)); // ------------------------------------------------------------------ // Initialize the Grainfather serial interface // Make sure things are working if (grainfather_serial_.Init(std::bind(&BrewLogger::LogBrewState, &brew_logger_, _1)) < 0) { printf("Grainfather connection did not initialize correctly\n"); return -1; } if(grainfather_serial_.TestCommands() < 0) { printf("Grainfather serial interface did not pass tests.\n"); return -1; } // Load Recipe from spreadsheet // Connect to Grainfather // Load Session if(grainfather_serial_.LoadSession(brew_recipe_.GetSessionCommand().c_str())) { std::cout<<"Failed to Load Brewing Session into Grainfather. Exiting" <<std::endl; return -1; } drain_duration_s_ = brew_logger_.GetDrainTime() * 60; // Okay, initializations complete! printf("Initialization complete.\n"); return 0; } int BrewSession::PrepareSetup() { user_interface_.PleaseFillWithWater(brew_recipe_.initial_volume_liters); printf("Initializing session\n"); brew_logger_.LogWeightEvent(WeightEvent::InitWater, scale_.GetWeightStartingNow()); if (grainfather_serial_.HeatForMash()) return -1; user_interface_.PleaseAddHops(brew_recipe_.hops_grams, brew_recipe_.hops_type); user_interface_.PleasePositionWinches(); // Get weight with water and winch brew_logger_.LogWeightEvent(WeightEvent::InitRig, scale_.GetWeightStartingNow()); std::cout << "Waiting for temp. " << std::endl; while (!grainfather_serial_.IsMashTemp()) { // wait for temperature usleep(1000000); // sleep a second } // The OnMashTemp should just turn the buzzer off. user_interface_.PleaseAddGrain(); // Take weight with grain brew_logger_.LogWeightEvent(WeightEvent::InitGrain, scale_.GetWeightStartingNow()); if(user_interface_.PleaseFinalizeForMash()) return -1; // Okay, we are now ready for Automation! return 0; } int BrewSession::Mash() { if (grainfather_serial_.StartMash()) return -1; // Sleep while the pump starts SleepSeconds(5); //Watch for draining scale_.EnableDrainingAlarm(std::bind(&BrewSession::OnDrainAlarm, this)); while (!grainfather_serial_.IsMashDone()) { // wait for mash to complete SleepSeconds(1); // TODO: debug prints // std::cout << "Waiting for temp. Target: " << full_state_.state.target_temp; // std::cout << " Current: " << full_state_.state.current_temp << std::endl; } return 0; } void BrewSession::Fail(const char *segment) { std::cout << "Encountered Failure during " << segment; std::cout << " stage." << std::endl; GlobalPause(); } void BrewSession::GlobalPause() { // TODO: figure out how to pause timer, how to interrupt other waits // if (full_state_.state.timer_on) { // grainfather_serial_.PauseTimer(); // } TurnPumpOff(); grainfather_serial_.TurnHeatOff(); // tweet out a warning! } // Shut everything down because of error. void BrewSession::QuitSession() { GlobalPause(); grainfather_serial_.QuitSession(); } int BrewSession::Drain() { // std::cout << "Triggered: Mash is completed" << std::endl; // TODO: debug print if (grainfather_serial_.StartSparge()) return -1; // Might as well turn off valves: if (TurnPumpOff()) return -1; brew_logger_.LogWeightEvent(WeightEvent::AfterMash, scale_.GetWeightStartingNow()); // Now we wait for a minute or so to for fluid to drain from hoses SleepMinutes(1); // Raise a little bit to check that we are not caught if (winch_controller_.RaiseToDrain_1() < 0) return -1; SleepSeconds(3); if (scale_.HasKettleLifted()) { std::cout << "We lifted the kettle!" << std::endl; return -1; } // TODO: wait any more? // Raise the rest of the way std::cout << "RaiseStep2" << std::endl; if (winch_controller_.RaiseToDrain_2()) return -1; SleepMinutes(1); // After weight has settled from lifting the mash out brew_logger_.LogWeightEvent(WeightEvent::AfterLift, scale_.GetWeightStartingNow()); // Drain for 45 minutes // TODO: detect drain stopping SleepMinutes(drain_duration_s_); std::cout << "Draining is complete" << std::endl; brew_logger_.LogWeightEvent(WeightEvent::AfterDrain, scale_.GetWeightStartingNow()); if (winch_controller_.MoveToSink()) return -1; return 0; } // When Mash complete // Pump Off, valves closed // measure after_mash_weight, tweet loss // wait for minute, raise // wait 45 minutes // move to sink // advance to boil int BrewSession::Boil() { if (grainfather_serial_.HeatToBoil()) return -1; while (!grainfather_serial_.IsBoilTemp()) { // wait for Boil temp usleep(1000000); // sleep a second } std::cout << "Boiling Temp reached" << std::endl; if (winch_controller_.LowerHops()) return -1; //Watch for draining, because we are opening the valves if(PumpToKettle()) return -1; if (grainfather_serial_.StartBoil()) return -1; while (!grainfather_serial_.IsBoilDone()) { // wait for Boil temp usleep(1000000); // sleep a second } if(TurnPumpOff()) return -1; if (grainfather_serial_.QuitSession()) return -1; // Wait one minute before raising hops for lines to drain SleepMinutes(1); if (winch_controller_.RaiseHops()) return -1; SleepMinutes(1); // sleep for 1 minute to drain brew_logger_.LogWeightEvent(WeightEvent::AfterBoil, scale_.GetWeightStartingNow()); return 0; } int BrewSession::Decant() { std::cout << "Decanting" << std::endl; if (PumpToCarboy()) return -1; ActivateChillerPump(); while (!scale_.CheckEmpty()) { // wait kettle to empty usleep(500000); // sleep .5 second } DeactivateChillerPump(); if (TurnPumpOff()) return -1; return 0; } // TODO: make a function that handles the pump serial, valve status // and scale callbacks int BrewSession::TurnPumpOff() { SetFlow(NO_PATH); if (grainfather_serial_.TurnPumpOff()) return -1; // with the valves shut, can safely stop worrying about draining for the moment scale_.DisableDrainingAlarm(); return 0; } int BrewSession::PumpToKettle() { SetFlow(KETTLE); if (grainfather_serial_.TurnPumpOn()) return -1; scale_.EnableDrainingAlarm(std::bind(&BrewSession::OnDrainAlarm, this)); return 0; } int BrewSession::PumpToCarboy() { scale_.DisableDrainingAlarm(); SetFlow(CHILLER); if (grainfather_serial_.TurnPumpOn()) return -1; return 0; } int BrewSession::Run(const char *spreadsheet_id) { if (InitSession(spreadsheet_id)) { Fail("Init"); return -1; } if (PrepareSetup()) { Fail("Prepare"); return -1; } if (Mash()) { Fail("Mash"); return -1; } if (Drain()) { Fail("Drain"); return -1; } if (Boil()) { Fail("Boil"); return -1; } if (Decant()) { Fail("Decant"); return -1; } std::cout << "Brew finished with no problems!" << std::endl; return 0; }
32.442688
94
0.691399
garratt
7a66925f148b9c18dd2659af0b13cc577c79237c
2,739
cpp
C++
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-07-21T07:04:08.000Z
2021-07-21T07:04:08.000Z
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-08-07T12:46:32.000Z
2021-08-15T13:19:33.000Z
Page_Replacement_Algorithms/Class_Definition.cpp
Siddhartha-Dhar/Operating_System_Programs
5bbfa8f82e270bef1e0511e82b3678de6b42d713
[ "MIT" ]
1
2021-08-07T13:05:33.000Z
2021-08-07T13:05:33.000Z
#include<iostream> //.........................................................................Class Definition For Row class Block{ private: // Private Access Specifier Scope int Page_Number; int Status; public: // Public Access Specifier Scope void Set_PN(int); void Set_ST(int); int Get_PN(); int Get_ST(); }; //.......................................................................Class Definition for Frame class Frame{ private: // Private Access Specifier Scope int N, i; Block *frm; public: //.......................Function Decleration Frame(int); void Flush(); bool Full_Frame(); // 'true' when Frame is Full else returns 'false' void Add_Page(int, int); // Add Block at the end of the Queue void Disp_Frame(); // Display the Frame Components /*Returns 1 when target page is not found else 0*/ int Page_Replace(int, int, int); // Page_Replace Fucntion void FIFO(int [], int); // FIFO Page Replacement Algorithm void Incr_Stat(); // Increment the Statuses by 1 bool Search_Page(int, int &); void Set_ST_Index(int, int); int Find_Max_Stat(); // Return the target Page Number having maximum status void operator =(Frame); void Set_ST_Optimal(int[], int, int); // Set Status Optimal Function Sets the Status of the Frames acording to the Optimal Strategy }; //.......................................................................Result Class class Result{ private : // Private Scope int N; int fs; bool *H_M; // Hit_Miss_Array if 'true' then Hit else Miss Frame **Val_Frm; public: // Public Scope Result(int, int); void Ins_Res(int, bool, Frame); void Hit_Miss(int); void print_frm(int); }; //........................................................................Replace Class class Rplc{ private: //............Private Scope int Frame_Size; int *A=NULL; int N; float AT_FIFO, AT_LRU, AT_Optimal; // Access Time for every Algorithms Frame *f=NULL; Result *Res=NULL; public: //............Public Scope Rplc(int); void Insert_Page(int); void Print_Result(int); int FIFO(); // Returns the total Number of Page Faults (FIFO) int LRU(); // Returns the total Number of Page Faults (LRU) int Optimal(); // Returns the total Number of Page Faults (Optimal Page Replacement Algorithm) void Find_Access_Time(float, float); void Print_AT(); };
33.814815
140
0.514421
Siddhartha-Dhar
7a675430737d89d7246a9bdddf02cfadbae35e5e
3,928
hpp
C++
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
ee21/common/inc/ee/function.hpp
ygor-rezende/Expression-Evaluator
52868ff11ce72a4ae6fa9a4052005c02f8485b3c
[ "FTL" ]
null
null
null
#pragma once /*! \file function.hpp \brief Function classes declarations. \author Garth Santor \date 2021-10-29 \copyright Garth Santor, Trinh Han ============================================================= Declarations of the Function classes derived from Operation. Includes the subclasses: OneArgFunction Abs Arccos Arcsin Arctan Ceil Cos Exp Floor Lb Ln Log Result Sin Sqrt Tan TwoArgFunction Arctan2 Max Min Pow ThreeArgFunction ============================================================= Revision History ------------------------------------------------------------- Version 2021.10.02 C++ 20 validated Version 2019.11.05 C++ 17 cleanup Version 2016.11.02 Added 'override' keyword where appropriate. Version 2014.10.30 Removed binary function Version 2012.11.13 C++ 11 cleanup Version 2009.11.26 Alpha release. ============================================================= Copyright Garth Santor/Trinh Han The copyright to the computer program(s) herein is the property of Garth Santor/Trinh Han, Canada. The program(s) may be used and/or copied only with the written permission of Garth Santor/Trinh Han or in accordance with the terms and conditions stipulated in the agreement/contract under which the program(s) have been supplied. =============================================================*/ #include <ee/operation.hpp> #include <ee/integer.hpp> #include <vector> /*! Function token base class. */ class Function : public Operation { }; /*! One argument function token base class. */ class OneArgFunction : public Function { public: [[nodiscard]] virtual unsigned number_of_args() const override { return 1; } }; /*! Absolute value function token. */ class Abs : public OneArgFunction { }; /*! arc cosine function token. */ class Arccos : public OneArgFunction { }; /*! arc sine function token. */ class Arcsin : public OneArgFunction { }; /*! arc tangent function token. Argument is the slope. */ class Arctan : public OneArgFunction { }; /*! ceil function token. */ class Ceil : public OneArgFunction { }; /*! cosine function token. */ class Cos : public OneArgFunction { }; /*! exponential function token. pow(e,x), where 'e' is the euler constant and 'x' is the exponent. */ class Exp : public OneArgFunction { }; /*! floor function token. */ class Floor : public OneArgFunction { }; /*! logarithm base 2 function token. */ class Lb : public OneArgFunction { }; /*! natural logarithm function token. */ class Ln : public OneArgFunction { }; /*! logarithm base 10 function token. */ class Log : public OneArgFunction { }; /*! previous result token. Argument is the 1-base index of the result. */ class Result : public OneArgFunction { }; /*! sine function token. */ class Sin : public OneArgFunction { }; /*! Square root token. */ class Sqrt : public OneArgFunction { }; /*! tangeant function. */ class Tan : public OneArgFunction { }; /*! Two argument function token base class. */ class TwoArgFunction : public Function { public: [[nodiscard]] virtual unsigned number_of_args() const override { return 2; } }; /*! 2 parameter arc tangent function token. First argument is the change in Y, second argument is the change in X. */ class Arctan2 : public TwoArgFunction { }; /*! Maximum of 2 elements function token. */ class Max : public TwoArgFunction { }; /*! Minimum of 2 elements function token. */ class Min : public TwoArgFunction { }; /*! Pow function token. First argument is the base, second the exponent. */ class Pow : public TwoArgFunction { }; /*! Three argument function token base class. */ class ThreeArgFunction : public Function { public: virtual unsigned number_of_args() const override { return 3; } };
25.341935
106
0.62831
ygor-rezende
7a679acd4b628f55b69492359d814b6ac257b7ed
747
cpp
C++
Codeforces/VasyaAndTheBus.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/VasyaAndTheBus.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/VasyaAndTheBus.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> using namespace std; int n, m; int main(void) { cin >> n >> m; if(n == 0) { if(m == 0) { cout << "0 0" << endl; } else { cout << "Impossible" << endl; } return 0; } int max = n + (m - 1); int min = 0; int pay[n]; for(int i = 0; i < n; i++) pay[i] = 0; int i = 0; while(m > 0) { if(i == n) i = 0; pay[i] += 1; m -= 1; i += 1; } for(int i = 0; i < n; i++) { if(pay[i] == 0) { min += 1; } min += pay[i]; } if(m == 0) { min = n; max = n; } cout << min << " " << max << endl; return 0; }
17.372093
43
0.305221
aajjbb
7a7123426f612acbd9ebf2b38b219c9236ebd603
3,718
cc
C++
chrome/chrome_cleaner/os/process.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/chrome_cleaner/os/process.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/chrome_cleaner/os/process.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/chrome_cleaner/os/process.h" #include <windows.h> #include <psapi.h> #include <vector> #include "base/logging.h" namespace chrome_cleaner { bool GetLoadedModuleFileNames(HANDLE process, std::set<std::wstring>* module_names) { std::vector<HMODULE> module_handles; size_t modules_count = 128; // Adjust array size for all modules to fit into it. do { // Allocate more space than needed in case more modules were loaded between // calls to EnumProcessModulesEx. modules_count *= 2; module_handles.resize(modules_count); DWORD bytes_needed; if (!::EnumProcessModulesEx(process, module_handles.data(), modules_count * sizeof(HMODULE), &bytes_needed, LIST_MODULES_ALL)) { PLOG(ERROR) << "Failed to enumerate modules"; return false; } DCHECK_EQ(bytes_needed % sizeof(HMODULE), 0U); modules_count = bytes_needed / sizeof(HMODULE); } while (modules_count > module_handles.size()); DCHECK(module_names); wchar_t module_name[MAX_PATH]; for (size_t i = 0; i < modules_count; ++i) { size_t module_name_length = ::GetModuleFileNameExW( process, module_handles[i], module_name, MAX_PATH); if (module_name_length == 0) { PLOG(ERROR) << "Failed to get module filename"; continue; } module_names->insert(std::wstring(module_name, module_name_length)); } return true; } bool GetProcessExecutablePath(HANDLE process, std::wstring* path) { DCHECK(path); std::vector<wchar_t> image_path(MAX_PATH); DWORD path_length = image_path.size(); BOOL success = ::QueryFullProcessImageName(process, 0, image_path.data(), &path_length); if (!success && ::GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Process name is potentially greater than MAX_PATH, try larger max size. image_path.resize(SHRT_MAX); path_length = image_path.size(); success = ::QueryFullProcessImageName(process, 0, image_path.data(), &path_length); } if (!success) { PLOG_IF(ERROR, ::GetLastError() != ERROR_GEN_FAILURE) << "Failed to get process image path"; return false; } path->assign(image_path.data(), path_length); return true; } bool GetSystemResourceUsage(HANDLE process, SystemResourceUsage* stats) { DCHECK(stats); FILETIME creation_time; FILETIME exit_time; FILETIME kernel_time; FILETIME user_time; // The returned user and kernel times are to be interpreted as time // durations and not as time points. |base::Time| can convert from FILETIME // to |base::Time| and by subtracting from time zero, we get the duration as // a |base::TimeDelta|. if (!::GetProcessTimes(process, &creation_time, &exit_time, &kernel_time, &user_time)) { PLOG(ERROR) << "Could not get process times"; return false; } stats->kernel_time = base::Time::FromFileTime(kernel_time) - base::Time(); stats->user_time = base::Time::FromFileTime(user_time) - base::Time(); std::unique_ptr<base::ProcessMetrics> metrics( base::ProcessMetrics::CreateProcessMetrics(process)); if (!metrics || !metrics->GetIOCounters(&stats->io_counters)) { LOG(ERROR) << "Failed to get IO process counters"; return false; } PROCESS_MEMORY_COUNTERS pmc; if (::GetProcessMemoryInfo(::GetCurrentProcess(), &pmc, sizeof(pmc))) { stats->peak_working_set_size = pmc.PeakWorkingSetSize; } return true; } } // namespace chrome_cleaner
33.8
79
0.67886
zealoussnow
7a74070c20510abfe143167aca5f0e563cf903d8
746
cpp
C++
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
call.cpp
rgeorgiev583/RadoPlusPlusinterpreter
edf410403bb9b69cad1946a9250ac2fdd66f86a1
[ "MIT" ]
null
null
null
/* * call.cpp * * Created on: Jan 17, 2015 * Author: radoslav */ #include "call.h" #include "constructor-call.h" #include "function-call.h" #include "strtok.h" void Call::parse(const char*& code) { name = Identifier(code); if (!gotoToken(code, " \t\n\r") || *code != '(') { type = CALL_INVALID; return; } code++; while (gotoToken(code, ", \t\n\r") && *code != ')') arguments.push_back(ExpressionTree::createExpressionTree(code)); if (*code != ')') type = CALL_INVALID; else code++; } Call* Call::create(const char*& code) { return peekToken(code, " \t\n\r") != "new" ? (Call*) new ConstructorCall(code) : (Call*) new FunctionCall(code); } Call::Call(const char*& code): Value(VALUE_CALL) { parse(code); }
16.577778
113
0.612601
rgeorgiev583
7a764c97dd2e828e58570985f7357348f8f93012
587
hpp
C++
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
openssl-examples/include/cli/arguments.hpp
falk-werner/playground
501b425d4c8161bdd89ad92b78a4741d81af9acb
[ "MIT" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #ifndef CLI_ARGUMENTS_HPP #define CLI_ARGUMENTS_HPP #include <string> #include <unordered_map> namespace cli { class Arguments { public: Arguments(); ~ Arguments(); bool contains(char id) const; std::string const & get(char id) const; void set(char id, std::string const & value); private: std::unordered_map<char, std::string> values; }; } #endif
20.964286
70
0.689949
falk-werner
7a796768d7400ffddb6a87734e1311cb9b188af4
29,241
hpp
C++
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/UI/ScrollRect.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:38 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.EventSystems.UIBehaviour #include "UnityEngine/EventSystems/UIBehaviour.hpp" // Including type: UnityEngine.EventSystems.IInitializePotentialDragHandler #include "UnityEngine/EventSystems/IInitializePotentialDragHandler.hpp" // Including type: UnityEngine.EventSystems.IBeginDragHandler #include "UnityEngine/EventSystems/IBeginDragHandler.hpp" // Including type: UnityEngine.EventSystems.IEndDragHandler #include "UnityEngine/EventSystems/IEndDragHandler.hpp" // Including type: UnityEngine.EventSystems.IDragHandler #include "UnityEngine/EventSystems/IDragHandler.hpp" // Including type: UnityEngine.EventSystems.IScrollHandler #include "UnityEngine/EventSystems/IScrollHandler.hpp" // Including type: UnityEngine.UI.ICanvasElement #include "UnityEngine/UI/ICanvasElement.hpp" // Including type: UnityEngine.UI.ILayoutElement #include "UnityEngine/UI/ILayoutElement.hpp" // Including type: UnityEngine.UI.ILayoutGroup #include "UnityEngine/UI/ILayoutGroup.hpp" // Including type: UnityEngine.Vector2 #include "UnityEngine/Vector2.hpp" // Including type: UnityEngine.Bounds #include "UnityEngine/Bounds.hpp" // Including type: UnityEngine.DrivenRectTransformTracker #include "UnityEngine/DrivenRectTransformTracker.hpp" // Including type: System.Enum #include "System/Enum.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Scrollbar class Scrollbar; // Skipping declaration: MovementType because it is already included! // Skipping declaration: ScrollbarVisibility because it is already included! // Forward declaring type: CanvasUpdate struct CanvasUpdate; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Skipping declaration: Vector3 because it is already included! // Forward declaring type: RectTransform class RectTransform; // Forward declaring type: Matrix4x4 struct Matrix4x4; // Forward declaring type: Transform class Transform; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Autogenerated type: UnityEngine.UI.ScrollRect class ScrollRect : public UnityEngine::EventSystems::UIBehaviour, public UnityEngine::EventSystems::IInitializePotentialDragHandler, public UnityEngine::EventSystems::IEventSystemHandler, public UnityEngine::EventSystems::IBeginDragHandler, public UnityEngine::EventSystems::IEndDragHandler, public UnityEngine::EventSystems::IDragHandler, public UnityEngine::EventSystems::IScrollHandler, public UnityEngine::UI::ICanvasElement, public UnityEngine::UI::ILayoutElement, public UnityEngine::UI::ILayoutGroup, public UnityEngine::UI::ILayoutController { public: // Nested type: UnityEngine::UI::ScrollRect::MovementType struct MovementType; // Nested type: UnityEngine::UI::ScrollRect::ScrollbarVisibility struct ScrollbarVisibility; // Nested type: UnityEngine::UI::ScrollRect::ScrollRectEvent class ScrollRectEvent; // Autogenerated type: UnityEngine.UI.ScrollRect/MovementType struct MovementType : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static constexpr const int Unrestricted = 0; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static UnityEngine::UI::ScrollRect::MovementType _get_Unrestricted(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Unrestricted static void _set_Unrestricted(UnityEngine::UI::ScrollRect::MovementType value); // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Elastic static constexpr const int Elastic = 1; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Elastic static UnityEngine::UI::ScrollRect::MovementType _get_Elastic(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Elastic static void _set_Elastic(UnityEngine::UI::ScrollRect::MovementType value); // static field const value: static public UnityEngine.UI.ScrollRect/MovementType Clamped static constexpr const int Clamped = 2; // Get static field: static public UnityEngine.UI.ScrollRect/MovementType Clamped static UnityEngine::UI::ScrollRect::MovementType _get_Clamped(); // Set static field: static public UnityEngine.UI.ScrollRect/MovementType Clamped static void _set_Clamped(UnityEngine::UI::ScrollRect::MovementType value); // Creating value type constructor for type: MovementType MovementType(int value_ = {}) : value{value_} {} }; // UnityEngine.UI.ScrollRect/MovementType // Autogenerated type: UnityEngine.UI.ScrollRect/ScrollbarVisibility struct ScrollbarVisibility : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static constexpr const int Permanent = 0; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_Permanent(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility Permanent static void _set_Permanent(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static constexpr const int AutoHide = 1; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_AutoHide(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHide static void _set_AutoHide(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // static field const value: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static constexpr const int AutoHideAndExpandViewport = 2; // Get static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static UnityEngine::UI::ScrollRect::ScrollbarVisibility _get_AutoHideAndExpandViewport(); // Set static field: static public UnityEngine.UI.ScrollRect/ScrollbarVisibility AutoHideAndExpandViewport static void _set_AutoHideAndExpandViewport(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // Creating value type constructor for type: ScrollbarVisibility ScrollbarVisibility(int value_ = {}) : value{value_} {} }; // UnityEngine.UI.ScrollRect/ScrollbarVisibility // private UnityEngine.RectTransform m_Content // Offset: 0x18 UnityEngine::RectTransform* m_Content; // private System.Boolean m_Horizontal // Offset: 0x20 bool m_Horizontal; // private System.Boolean m_Vertical // Offset: 0x21 bool m_Vertical; // private UnityEngine.UI.ScrollRect/MovementType m_MovementType // Offset: 0x24 UnityEngine::UI::ScrollRect::MovementType m_MovementType; // private System.Single m_Elasticity // Offset: 0x28 float m_Elasticity; // private System.Boolean m_Inertia // Offset: 0x2C bool m_Inertia; // private System.Single m_DecelerationRate // Offset: 0x30 float m_DecelerationRate; // private System.Single m_ScrollSensitivity // Offset: 0x34 float m_ScrollSensitivity; // private UnityEngine.RectTransform m_Viewport // Offset: 0x38 UnityEngine::RectTransform* m_Viewport; // private UnityEngine.UI.Scrollbar m_HorizontalScrollbar // Offset: 0x40 UnityEngine::UI::Scrollbar* m_HorizontalScrollbar; // private UnityEngine.UI.Scrollbar m_VerticalScrollbar // Offset: 0x48 UnityEngine::UI::Scrollbar* m_VerticalScrollbar; // private UnityEngine.UI.ScrollRect/ScrollbarVisibility m_HorizontalScrollbarVisibility // Offset: 0x50 UnityEngine::UI::ScrollRect::ScrollbarVisibility m_HorizontalScrollbarVisibility; // private UnityEngine.UI.ScrollRect/ScrollbarVisibility m_VerticalScrollbarVisibility // Offset: 0x54 UnityEngine::UI::ScrollRect::ScrollbarVisibility m_VerticalScrollbarVisibility; // private System.Single m_HorizontalScrollbarSpacing // Offset: 0x58 float m_HorizontalScrollbarSpacing; // private System.Single m_VerticalScrollbarSpacing // Offset: 0x5C float m_VerticalScrollbarSpacing; // private UnityEngine.UI.ScrollRect/ScrollRectEvent m_OnValueChanged // Offset: 0x60 UnityEngine::UI::ScrollRect::ScrollRectEvent* m_OnValueChanged; // private UnityEngine.Vector2 m_PointerStartLocalCursor // Offset: 0x68 UnityEngine::Vector2 m_PointerStartLocalCursor; // protected UnityEngine.Vector2 m_ContentStartPosition // Offset: 0x70 UnityEngine::Vector2 m_ContentStartPosition; // private UnityEngine.RectTransform m_ViewRect // Offset: 0x78 UnityEngine::RectTransform* m_ViewRect; // protected UnityEngine.Bounds m_ContentBounds // Offset: 0x80 UnityEngine::Bounds m_ContentBounds; // private UnityEngine.Bounds m_ViewBounds // Offset: 0x98 UnityEngine::Bounds m_ViewBounds; // private UnityEngine.Vector2 m_Velocity // Offset: 0xB0 UnityEngine::Vector2 m_Velocity; // private System.Boolean m_Dragging // Offset: 0xB8 bool m_Dragging; // private System.Boolean m_Scrolling // Offset: 0xB9 bool m_Scrolling; // private UnityEngine.Vector2 m_PrevPosition // Offset: 0xBC UnityEngine::Vector2 m_PrevPosition; // private UnityEngine.Bounds m_PrevContentBounds // Offset: 0xC4 UnityEngine::Bounds m_PrevContentBounds; // private UnityEngine.Bounds m_PrevViewBounds // Offset: 0xDC UnityEngine::Bounds m_PrevViewBounds; // private System.Boolean m_HasRebuiltLayout // Offset: 0xF4 bool m_HasRebuiltLayout; // private System.Boolean m_HSliderExpand // Offset: 0xF5 bool m_HSliderExpand; // private System.Boolean m_VSliderExpand // Offset: 0xF6 bool m_VSliderExpand; // private System.Single m_HSliderHeight // Offset: 0xF8 float m_HSliderHeight; // private System.Single m_VSliderWidth // Offset: 0xFC float m_VSliderWidth; // private UnityEngine.RectTransform m_Rect // Offset: 0x100 UnityEngine::RectTransform* m_Rect; // private UnityEngine.RectTransform m_HorizontalScrollbarRect // Offset: 0x108 UnityEngine::RectTransform* m_HorizontalScrollbarRect; // private UnityEngine.RectTransform m_VerticalScrollbarRect // Offset: 0x110 UnityEngine::RectTransform* m_VerticalScrollbarRect; // private UnityEngine.DrivenRectTransformTracker m_Tracker // Offset: 0x118 UnityEngine::DrivenRectTransformTracker m_Tracker; // private readonly UnityEngine.Vector3[] m_Corners // Offset: 0x120 ::Array<UnityEngine::Vector3>* m_Corners; // public UnityEngine.RectTransform get_content() // Offset: 0x11F3370 UnityEngine::RectTransform* get_content(); // public System.Void set_content(UnityEngine.RectTransform value) // Offset: 0x11F3378 void set_content(UnityEngine::RectTransform* value); // public System.Boolean get_horizontal() // Offset: 0x11F3380 bool get_horizontal(); // public System.Void set_horizontal(System.Boolean value) // Offset: 0x11F3388 void set_horizontal(bool value); // public System.Boolean get_vertical() // Offset: 0x11F3394 bool get_vertical(); // public System.Void set_vertical(System.Boolean value) // Offset: 0x11F339C void set_vertical(bool value); // public UnityEngine.UI.ScrollRect/MovementType get_movementType() // Offset: 0x11F33A8 UnityEngine::UI::ScrollRect::MovementType get_movementType(); // public System.Void set_movementType(UnityEngine.UI.ScrollRect/MovementType value) // Offset: 0x11F33B0 void set_movementType(UnityEngine::UI::ScrollRect::MovementType value); // public System.Single get_elasticity() // Offset: 0x11F33B8 float get_elasticity(); // public System.Void set_elasticity(System.Single value) // Offset: 0x11F33C0 void set_elasticity(float value); // public System.Boolean get_inertia() // Offset: 0x11F33C8 bool get_inertia(); // public System.Void set_inertia(System.Boolean value) // Offset: 0x11F33D0 void set_inertia(bool value); // public System.Single get_decelerationRate() // Offset: 0x11F33DC float get_decelerationRate(); // public System.Void set_decelerationRate(System.Single value) // Offset: 0x11F33E4 void set_decelerationRate(float value); // public System.Single get_scrollSensitivity() // Offset: 0x11F33EC float get_scrollSensitivity(); // public System.Void set_scrollSensitivity(System.Single value) // Offset: 0x11F33F4 void set_scrollSensitivity(float value); // public UnityEngine.RectTransform get_viewport() // Offset: 0x11F33FC UnityEngine::RectTransform* get_viewport(); // public System.Void set_viewport(UnityEngine.RectTransform value) // Offset: 0x11F3404 void set_viewport(UnityEngine::RectTransform* value); // public UnityEngine.UI.Scrollbar get_horizontalScrollbar() // Offset: 0x11F34FC UnityEngine::UI::Scrollbar* get_horizontalScrollbar(); // public System.Void set_horizontalScrollbar(UnityEngine.UI.Scrollbar value) // Offset: 0x11F3504 void set_horizontalScrollbar(UnityEngine::UI::Scrollbar* value); // public UnityEngine.UI.Scrollbar get_verticalScrollbar() // Offset: 0x11F368C UnityEngine::UI::Scrollbar* get_verticalScrollbar(); // public System.Void set_verticalScrollbar(UnityEngine.UI.Scrollbar value) // Offset: 0x11F3694 void set_verticalScrollbar(UnityEngine::UI::Scrollbar* value); // public UnityEngine.UI.ScrollRect/ScrollbarVisibility get_horizontalScrollbarVisibility() // Offset: 0x11F381C UnityEngine::UI::ScrollRect::ScrollbarVisibility get_horizontalScrollbarVisibility(); // public System.Void set_horizontalScrollbarVisibility(UnityEngine.UI.ScrollRect/ScrollbarVisibility value) // Offset: 0x11F3824 void set_horizontalScrollbarVisibility(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // public UnityEngine.UI.ScrollRect/ScrollbarVisibility get_verticalScrollbarVisibility() // Offset: 0x11F382C UnityEngine::UI::ScrollRect::ScrollbarVisibility get_verticalScrollbarVisibility(); // public System.Void set_verticalScrollbarVisibility(UnityEngine.UI.ScrollRect/ScrollbarVisibility value) // Offset: 0x11F3834 void set_verticalScrollbarVisibility(UnityEngine::UI::ScrollRect::ScrollbarVisibility value); // public System.Single get_horizontalScrollbarSpacing() // Offset: 0x11F383C float get_horizontalScrollbarSpacing(); // public System.Void set_horizontalScrollbarSpacing(System.Single value) // Offset: 0x11F3844 void set_horizontalScrollbarSpacing(float value); // public System.Single get_verticalScrollbarSpacing() // Offset: 0x11F38E0 float get_verticalScrollbarSpacing(); // public System.Void set_verticalScrollbarSpacing(System.Single value) // Offset: 0x11F38E8 void set_verticalScrollbarSpacing(float value); // public UnityEngine.UI.ScrollRect/ScrollRectEvent get_onValueChanged() // Offset: 0x11F38F0 UnityEngine::UI::ScrollRect::ScrollRectEvent* get_onValueChanged(); // public System.Void set_onValueChanged(UnityEngine.UI.ScrollRect/ScrollRectEvent value) // Offset: 0x11F38F8 void set_onValueChanged(UnityEngine::UI::ScrollRect::ScrollRectEvent* value); // protected UnityEngine.RectTransform get_viewRect() // Offset: 0x11F3900 UnityEngine::RectTransform* get_viewRect(); // public UnityEngine.Vector2 get_velocity() // Offset: 0x11F3A0C UnityEngine::Vector2 get_velocity(); // public System.Void set_velocity(UnityEngine.Vector2 value) // Offset: 0x11F3A14 void set_velocity(UnityEngine::Vector2 value); // private UnityEngine.RectTransform get_rectTransform() // Offset: 0x11F3A1C UnityEngine::RectTransform* get_rectTransform(); // private System.Void UpdateCachedData() // Offset: 0x11F3CD0 void UpdateCachedData(); // private System.Void EnsureLayoutHasRebuilt() // Offset: 0x11F4D54 void EnsureLayoutHasRebuilt(); // public System.Void StopMovement() // Offset: 0x11F4DD8 void StopMovement(); // protected System.Void SetContentAnchoredPosition(UnityEngine.Vector2 position) // Offset: 0x11F55F8 void SetContentAnchoredPosition(UnityEngine::Vector2 position); // protected System.Void LateUpdate() // Offset: 0x11F5710 void LateUpdate(); // protected System.Void UpdatePrevData() // Offset: 0x11F4830 void UpdatePrevData(); // private System.Void UpdateScrollbars(UnityEngine.Vector2 offset) // Offset: 0x11F4618 void UpdateScrollbars(UnityEngine::Vector2 offset); // public UnityEngine.Vector2 get_normalizedPosition() // Offset: 0x11F5DA4 UnityEngine::Vector2 get_normalizedPosition(); // public System.Void set_normalizedPosition(UnityEngine.Vector2 value) // Offset: 0x11F6198 void set_normalizedPosition(UnityEngine::Vector2 value); // public System.Single get_horizontalNormalizedPosition() // Offset: 0x11F5EF0 float get_horizontalNormalizedPosition(); // public System.Void set_horizontalNormalizedPosition(System.Single value) // Offset: 0x11F61EC void set_horizontalNormalizedPosition(float value); // public System.Single get_verticalNormalizedPosition() // Offset: 0x11F6048 float get_verticalNormalizedPosition(); // public System.Void set_verticalNormalizedPosition(System.Single value) // Offset: 0x11F6200 void set_verticalNormalizedPosition(float value); // private System.Void SetHorizontalNormalizedPosition(System.Single value) // Offset: 0x11F6214 void SetHorizontalNormalizedPosition(float value); // private System.Void SetVerticalNormalizedPosition(System.Single value) // Offset: 0x11F6228 void SetVerticalNormalizedPosition(float value); // protected System.Void SetNormalizedPosition(System.Single value, System.Int32 axis) // Offset: 0x11F623C void SetNormalizedPosition(float value, int axis); // static private System.Single RubberDelta(System.Single overStretching, System.Single viewSize) // Offset: 0x11F554C static float RubberDelta(float overStretching, float viewSize); // private System.Boolean get_hScrollingNeeded() // Offset: 0x11F6458 bool get_hScrollingNeeded(); // private System.Boolean get_vScrollingNeeded() // Offset: 0x11F64C0 bool get_vScrollingNeeded(); // private System.Void UpdateScrollbarVisibility() // Offset: 0x11F5DFC void UpdateScrollbarVisibility(); // static private System.Void UpdateOneScrollbarVisibility(System.Boolean xScrollingNeeded, System.Boolean xAxisEnabled, UnityEngine.UI.ScrollRect/ScrollbarVisibility scrollbarVisibility, UnityEngine.UI.Scrollbar scrollbar) // Offset: 0x11F70B0 static void UpdateOneScrollbarVisibility(bool xScrollingNeeded, bool xAxisEnabled, UnityEngine::UI::ScrollRect::ScrollbarVisibility scrollbarVisibility, UnityEngine::UI::Scrollbar* scrollbar); // private System.Void UpdateScrollbarLayout() // Offset: 0x11F6D88 void UpdateScrollbarLayout(); // protected System.Void UpdateBounds() // Offset: 0x11F40BC void UpdateBounds(); // static System.Void AdjustBounds(UnityEngine.Bounds viewBounds, UnityEngine.Vector2 contentPivot, UnityEngine.Vector3 contentSize, UnityEngine.Vector3 contentPos) // Offset: 0x11F71B4 static void AdjustBounds(UnityEngine::Bounds& viewBounds, UnityEngine::Vector2& contentPivot, UnityEngine::Vector3& contentSize, UnityEngine::Vector3& contentPos); // private UnityEngine.Bounds GetBounds() // Offset: 0x11F6B38 UnityEngine::Bounds GetBounds(); // static UnityEngine.Bounds InternalGetBounds(UnityEngine.Vector3[] corners, UnityEngine.Matrix4x4 viewWorldToLocalMatrix) // Offset: 0x11F72F4 static UnityEngine::Bounds InternalGetBounds(::Array<UnityEngine::Vector3>* corners, UnityEngine::Matrix4x4& viewWorldToLocalMatrix); // private UnityEngine.Vector2 CalculateOffset(UnityEngine.Vector2 delta) // Offset: 0x11F50F0 UnityEngine::Vector2 CalculateOffset(UnityEngine::Vector2 delta); // static UnityEngine.Vector2 InternalCalculateOffset(UnityEngine.Bounds viewBounds, UnityEngine.Bounds contentBounds, System.Boolean horizontal, System.Boolean vertical, UnityEngine.UI.ScrollRect/MovementType movementType, UnityEngine.Vector2 delta) // Offset: 0x11F74F8 static UnityEngine::Vector2 InternalCalculateOffset(UnityEngine::Bounds& viewBounds, UnityEngine::Bounds& contentBounds, bool horizontal, bool vertical, UnityEngine::UI::ScrollRect::MovementType movementType, UnityEngine::Vector2& delta); // protected System.Void SetDirty() // Offset: 0x11F384C void SetDirty(); // protected System.Void SetDirtyCaching() // Offset: 0x11F342C void SetDirtyCaching(); // protected System.Void .ctor() // Offset: 0x11F3AC8 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static ScrollRect* New_ctor(); // public System.Void Rebuild(UnityEngine.UI.CanvasUpdate executing) // Offset: 0x11F3C1C // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::Rebuild(UnityEngine.UI.CanvasUpdate executing) void Rebuild(UnityEngine::UI::CanvasUpdate executing); // public System.Void LayoutComplete() // Offset: 0x11F490C // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::LayoutComplete() void LayoutComplete(); // public System.Void GraphicUpdateComplete() // Offset: 0x11F4910 // Implemented from: UnityEngine.UI.ICanvasElement // Base method: System.Void ICanvasElement::GraphicUpdateComplete() void GraphicUpdateComplete(); // protected override System.Void OnEnable() // Offset: 0x11F4914 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x11F4AB4 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDisable() void OnDisable(); // public override System.Boolean IsActive() // Offset: 0x11F4CC4 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Boolean UIBehaviour::IsActive() bool IsActive(); // public System.Void OnScroll(UnityEngine.EventSystems.PointerEventData data) // Offset: 0x11F4E44 // Implemented from: UnityEngine.EventSystems.IScrollHandler // Base method: System.Void IScrollHandler::OnScroll(UnityEngine.EventSystems.PointerEventData data) void OnScroll(UnityEngine::EventSystems::PointerEventData* data); // public System.Void OnInitializePotentialDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F512C // Implemented from: UnityEngine.EventSystems.IInitializePotentialDragHandler // Base method: System.Void IInitializePotentialDragHandler::OnInitializePotentialDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnInitializePotentialDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnBeginDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F51B4 // Implemented from: UnityEngine.EventSystems.IBeginDragHandler // Base method: System.Void IBeginDragHandler::OnBeginDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnBeginDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnEndDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F52E4 // Implemented from: UnityEngine.EventSystems.IEndDragHandler // Base method: System.Void IEndDragHandler::OnEndDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnEndDrag(UnityEngine::EventSystems::PointerEventData* eventData); // public System.Void OnDrag(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x11F5308 // Implemented from: UnityEngine.EventSystems.IDragHandler // Base method: System.Void IDragHandler::OnDrag(UnityEngine.EventSystems.PointerEventData eventData) void OnDrag(UnityEngine::EventSystems::PointerEventData* eventData); // protected override System.Void OnRectTransformDimensionsChange() // Offset: 0x11F6454 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnRectTransformDimensionsChange() void OnRectTransformDimensionsChange(); // public System.Void CalculateLayoutInputHorizontal() // Offset: 0x11F6528 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Void ILayoutElement::CalculateLayoutInputHorizontal() void CalculateLayoutInputHorizontal(); // public System.Void CalculateLayoutInputVertical() // Offset: 0x11F652C // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Void ILayoutElement::CalculateLayoutInputVertical() void CalculateLayoutInputVertical(); // public System.Single get_minWidth() // Offset: 0x11F6530 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_minWidth() float get_minWidth(); // public System.Single get_preferredWidth() // Offset: 0x11F6538 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_preferredWidth() float get_preferredWidth(); // public System.Single get_flexibleWidth() // Offset: 0x11F6540 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_flexibleWidth() float get_flexibleWidth(); // public System.Single get_minHeight() // Offset: 0x11F6548 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_minHeight() float get_minHeight(); // public System.Single get_preferredHeight() // Offset: 0x11F6550 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_preferredHeight() float get_preferredHeight(); // public System.Single get_flexibleHeight() // Offset: 0x11F6558 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Single ILayoutElement::get_flexibleHeight() float get_flexibleHeight(); // public System.Int32 get_layoutPriority() // Offset: 0x11F6560 // Implemented from: UnityEngine.UI.ILayoutElement // Base method: System.Int32 ILayoutElement::get_layoutPriority() int get_layoutPriority(); // public System.Void SetLayoutHorizontal() // Offset: 0x11F6568 // Implemented from: UnityEngine.UI.ILayoutController // Base method: System.Void ILayoutController::SetLayoutHorizontal() void SetLayoutHorizontal(); // public System.Void SetLayoutVertical() // Offset: 0x11F6C2C // Implemented from: UnityEngine.UI.ILayoutController // Base method: System.Void ILayoutController::SetLayoutVertical() void SetLayoutVertical(); // private UnityEngine.Transform UnityEngine.UI.ICanvasElement.get_transform() // Offset: 0x11F76EC // Implemented from: UnityEngine.UI.ICanvasElement // Base method: UnityEngine.Transform ICanvasElement::get_transform() UnityEngine::Transform* UnityEngine_UI_ICanvasElement_get_transform(); }; // UnityEngine.UI.ScrollRect } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect*, "UnityEngine.UI", "ScrollRect"); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect::MovementType, "UnityEngine.UI", "ScrollRect/MovementType"); DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::ScrollRect::ScrollbarVisibility, "UnityEngine.UI", "ScrollRect/ScrollbarVisibility"); #pragma pack(pop)
51.120629
553
0.757943
Futuremappermydud
7a7c5c97f5aa712eebe55dc8d0ac8f0efc2cf4ac
8,616
cc
C++
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
9
2015-12-23T21:18:28.000Z
2018-11-25T10:10:12.000Z
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
1
2016-01-08T20:56:21.000Z
2016-01-08T20:56:21.000Z
nacl/net/udp_listener.cc
maxsong11/nacld
c4802cc7d9bda03487bde566a3003e8bc0f574d3
[ "BSD-3-Clause" ]
6
2015-12-04T18:23:49.000Z
2018-11-06T03:52:58.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Copyright 2015 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include <string.h> #include <sstream> #include "base/logger.h" #include "base/ptr_utils.h" #include "net/udp_listener.h" #ifdef WIN32 #undef PostMessage // Allow 'this' in initializer list #pragma warning(disable : 4355) #endif static uint16_t Htons(uint16_t hostshort) { uint8_t result_bytes[2]; result_bytes[0] = (uint8_t)((hostshort >> 8) & 0xFF); result_bytes[1] = (uint8_t)(hostshort & 0xFF); uint16_t result; memcpy(&result, result_bytes, 2); return result; } UDPListener::UDPListener(pp::Instance* instance, UDPDelegateInterface* delegate, const std::string& host, uint16_t port) : instance_(instance), delegate_(delegate), callback_factory_(this), network_monitor_(instance_), stop_listening_(false) { Start(host, port); } UDPListener::~UDPListener() {} bool UDPListener::IsConnected() { if (!udp_socket_.is_null()) return true; return false; } void UDPListener::Start(const std::string& host, uint16_t port) { if (IsConnected()) { WRN() << "Already connected."; return; } udp_socket_ = pp::UDPSocket(instance_); if (udp_socket_.is_null()) { ERR() << "Could not create UDPSocket."; return; } if (!pp::HostResolver::IsAvailable()) { ERR() << "HostResolver not available."; return; } resolver_ = pp::HostResolver(instance_); if (resolver_.is_null()) { ERR() << "Could not create HostResolver."; return; } PP_NetAddress_IPv4 ipv4_addr = {Htons(port), {0, 0, 0, 0}}; local_host_ = pp::NetAddress(instance_, ipv4_addr); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnResolveCompletion); PP_HostResolver_Hint hint = {PP_NETADDRESS_FAMILY_UNSPECIFIED, 0}; resolver_.Resolve(host.c_str(), port, hint, callback); DINF() << "Resolving..."; } void UDPListener::OnNetworkListCompletion(int32_t result, pp::NetworkList network_list) { if (result != PP_OK) { ERR() << "Update Network List failed: " << result; return; } int count = network_list.GetCount(); DINF() << "Number of networks found: " << count; for (int i = 0; i < network_list.GetCount(); i++) { DINF() << "network: " << i << ", name: " << network_list.GetName(i).c_str(); } /* pp::CompletionCallback callback = */ /* callback_factory_.NewCallback(&UDPListener::OnSetOptionCompletion); */ DINF() << "Binding..."; /* udp_socket_.SetOption(PP_UDPSOCKET_OPTION_MULTICAST_IF, pp::Var(0), * callback); */ pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnConnectCompletion); udp_socket_.Bind(local_host_, callback); } void UDPListener::OnJoinedCompletion(int32_t result) { DINF() << "OnJoined result: " << result; pp::NetAddress addr = udp_socket_.GetBoundAddress(); INF() << "Bound to: " << addr.DescribeAsString(true).AsString(); Receive(); } void UDPListener::OnSetOptionCompletion(int32_t result) { if (result != PP_OK) { ERR() << "SetOption failed: " << result; return; } pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnConnectCompletion); udp_socket_.Bind(local_host_, callback); } void UDPListener::OnResolveCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Resolve failed: " << result; return; } pp::CompletionCallbackWithOutput<pp::NetworkList> netlist_callback = callback_factory_.NewCallbackWithOutput( &UDPListener::OnNetworkListCompletion); network_monitor_.UpdateNetworkList(netlist_callback); pp::NetAddress addr = resolver_.GetNetAddress(0); INF() << "Resolved: " << addr.DescribeAsString(true).AsString(); group_addr_ = addr; } void UDPListener::Stop() { if (!IsConnected()) { WRN() << "Not connected."; return; } udp_socket_.Close(); udp_socket_ = pp::UDPSocket(); INF() << "Closed connection."; } void UDPListener::Send(const std::string& message) { if (!IsConnected()) { WRN() << "Cant send, not connected."; return; } if (send_outstanding_) { WRN() << "Already sending."; return; } if (!remote_host_) { ERR() << "Can't send packet: remote host not set yet."; return; } uint32_t size = message.size(); const char* data = message.c_str(); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnSendCompletion); int32_t result; result = udp_socket_.SendTo(data, size, *remote_host_, callback); if (result < 0) { if (result == PP_OK_COMPLETIONPENDING) { DINF() << "Sending bytes."; send_outstanding_ = true; } else { WRN() << "Send return error: " << result; } } else { DINF() << "Sent bytes synchronously: " << result; } } void UDPListener::SendPacket(PacketRef packet) { if (!IsConnected()) { ERR() << "Can't send packet: not connected."; return; } packets_.push(packet); SendPacketsInternal(); } void UDPListener::SendPacketsInternal() { if (!remote_host_) { ERR() << "Can't send packet: remote host not set yet."; return; } if (send_outstanding_ || packets_.empty()) return; while (!send_outstanding_ && !packets_.empty()) { PacketRef packet = packets_.front(); uint32_t size = packet->size(); const char* data = reinterpret_cast<char*>(packet->data()); pp::CompletionCallback callback = callback_factory_.NewCallback(&UDPListener::OnSendPacketCompletion); int32_t result; result = udp_socket_.SendTo(data, size, *remote_host_, callback); if (result < 0) { if (result == PP_OK_COMPLETIONPENDING) { // will send, just wait completion now send_outstanding_ = true; } else { ERR() << "Error sending packet: " << result; } } else { // packet sent synchronously packets_.pop(); } } } void UDPListener::Receive() { memset(receive_buffer_, 0, kBufferSize); pp::CompletionCallbackWithOutput<pp::NetAddress> callback = callback_factory_.NewCallbackWithOutput( &UDPListener::OnReceiveFromCompletion); udp_socket_.RecvFrom(receive_buffer_, kBufferSize, callback); } void UDPListener::OnConnectCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Connection failed: " << result; return; } pp::CompletionCallback joinCallback = callback_factory_.NewCallback(&UDPListener::OnJoinedCompletion); udp_socket_.JoinGroup(group_addr_, joinCallback); } void UDPListener::OnReceiveFromCompletion(int32_t result, pp::NetAddress source) { if (!remote_host_) { INF() << "Setting remote host to: " << source.DescribeAsString(true).AsString(); remote_host_ = make_unique<pp::NetAddress>(source); } OnReceiveCompletion(result); } void UDPListener::OnReceiveCompletion(int32_t result) { if (result < 0) { ERR() << "Receive failed with error: " << result; return; } delegate_->OnReceived(receive_buffer_, result); /* PostMessage(std::string("Received: ") + std::string(receive_buffer_, * result)); */ if (!stop_listening_) Receive(); } void UDPListener::OnSendCompletion(int32_t result) { if (result < 0) { ERR() << "Send failed with error: " << result; } else { DINF() << "Sent " << result << " bytes."; } send_outstanding_ = false; } void UDPListener::OnSendPacketCompletion(int32_t result) { if (result < 0) { ERR() << "SendPacket failed with error: " << result; } packets_.pop(); send_outstanding_ = false; SendPacketsInternal(); } void UDPListener::OnLeaveCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Could not rejoin multicast group: " << result; return; } auto rejoinCallback = callback_factory_.NewCallback(&UDPListener::OnRejoinCompletion); udp_socket_.JoinGroup(group_addr_, rejoinCallback); } void UDPListener::OnRejoinCompletion(int32_t result) { if (result != PP_OK) { ERR() << "Could not leave multicast group: " << result; return; } } void UDPListener::OnNetworkTimeout() { auto leaveCallback = callback_factory_.NewCallback(&UDPListener::OnLeaveCompletion); udp_socket_.LeaveGroup(group_addr_, leaveCallback); } void UDPListener::StopListening() { stop_listening_ = true; } void UDPListener::StartListening() { stop_listening_ = false; Receive(); }
26.925
80
0.666086
maxsong11
7a81f0e4fbe6c12e6731da0d2ca35dd96c70c5eb
4,413
cpp
C++
src/graphics/renderers/cloud_renderer.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/renderers/cloud_renderer.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
null
null
null
src/graphics/renderers/cloud_renderer.cpp
alexkafer/planets
ad118c7ba9d479afc29ba9d5b65222c8c7f2cde2
[ "Unlicense", "MIT" ]
1
2021-03-02T16:54:40.000Z
2021-03-02T16:54:40.000Z
#include "cloud_renderer.hpp" // Local Headers #include "graphics/vert_buffer.hpp" #include "utils/math_utils.h" #include "utils/math/interpolation.h" #include "scene.hpp" const int nrOfSpawnpoints = 30, particlesPerOffset = 6; CloudRenderer::CloudRenderer(): quad(new Mesh("cloud_quad", 4, 6, Mesh::getQuad()->attributes)) { ResourceManager::LoadShader("clouds.vert", "clouds.frag", "clouds"); noiseTex = ResourceManager::LoadTexture("textures/noise.dds", "noise"); quad->vertices = Mesh::getQuad()->vertices; quad->indices = Mesh::getQuad()->indices; VertBuffer::uploadSingleMesh(quad); VertAttributes verts; unsigned int spawnpoint_offset = verts.add({"SPAWNPOINT", 3}); const Universe & universe = Globals::scene->getUniverse(); const std::vector<Planet * > & planets = universe.getPlanets(); VertData spawnpoints(verts, std::vector<u_char>(nrOfSpawnpoints * 4 * 3 * planets.size())); // for (int p = 0; p < planets.size(); p++) { int p = 0; for (int i = 0; i < nrOfSpawnpoints; i++) { glm::vec3 spawn = glm::vec3(mu::random() - .5, (mu::random() - .5) * .3, mu::random() - .5) * vec3(1 + i * .2) * vec3(110.); // spawn += planets[p]->get_position(); spawnpoints.set(spawn, p * nrOfSpawnpoints + i, spawnpoint_offset); } // } quad->vertBuffer->uploadPerInstanceData(spawnpoints, particlesPerOffset); } void CloudRenderer::render(double realtimeDT) { const Universe & universe = Globals::scene->getUniverse(); const std::vector<Planet * > & planets = universe.getPlanets(); for (Planet * planet : universe.getPlanets()) { // The dt above is real time. The universe dt is the simulations. render(planet, universe.getTime(), universe.getDeltaTime()); } } void CloudRenderer::render(Planet * planet, double time, float deltaTime) { float planetRadius = 150; while (clouds.size() < 40) clouds.push_back({ mu::random(360), // lon mu::random(mu::random() > .5 ? 40. : 0., mu::random() > .5 ? 120. : 180.), // lat mu::random(.7, 1.3), // speed 0, mu::random(30, 60), // time to live mu::randomInt(3, 30) // nr of particles }); Shader shader = ResourceManager::GetShader("clouds"); shader.enable(); glUniform1f(shader.uniform("time"), time); noiseTex->bind(0); glUniform1i(shader.uniform("noiseTex"), 0); glDepthMask(false); for (int i = clouds.size() - 1; i >= 0; i--) { auto &cloud = clouds[i]; cloud.timeSinceSpawn += deltaTime; cloud.timeToDespawn -= deltaTime; if (cloud.timeToDespawn <= 0) clouds.erase(clouds.begin() + i); cloud.lon += .7 * deltaTime * cloud.speed; cloud.lat += .4 * deltaTime * cloud.speed; glm::mat4 transformFromCenter = rotate(glm::mat4(1.f), glm::radians(cloud.lon), mu::Y); transformFromCenter = rotate(transformFromCenter, glm::radians(cloud.lat), mu::X); transformFromCenter = translate(transformFromCenter, vec3(0, planet->config.radius + planet->config.cloudHeight, 0)); glm::mat4 transformFromCenterInverse = glm::inverse(transformFromCenter); CameraState state = camera->getState(); glm::vec3 up = transformFromCenterInverse * vec4(state.up, 0); glm::vec3 right = transformFromCenterInverse * vec4(state.right, 0); glm::mat4 transform = camera->combined * planet->get_last_model() * transformFromCenter; float light = 0; light += max(0.f, 1 - Interpolation::circleIn(min(1., cloud.lat / 30.))); light += max(0.f, 1 - Interpolation::circleIn(min(1., (180 - cloud.lat) / 30.))); light += min(1.f, max(0.0f, dot(rotate(vec3(0, 0, 1), cloud.lon * mu::DEGREES_TO_RAD, mu::Y), camera->sunDir) + .8f)); glUniformMatrix4fv(shader.uniform("mvp"), 1, GL_FALSE, glm::value_ptr(transform)); glUniform3f(shader.uniform("up"), up.x, up.y, up.z); glUniform3f(shader.uniform("right"), right.x, right.y, right.z); glUniform1f(shader.uniform("cloudOpacity"), Interpolation::circleIn(max(0.f, min(cloud.timeToDespawn, cloud.timeSinceSpawn)) / 20.)); glUniform1f(shader.uniform("light"), light); quad->renderInstances(cloud.spawnPoints * particlesPerOffset); } glDepthMask(true); }
38.710526
141
0.624972
alexkafer
18528f1718cf409c430581856e0e283feec890e6
27
cpp
C++
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
1
2019-07-10T07:35:58.000Z
2019-07-10T07:35:58.000Z
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
null
null
null
src/http_method.cpp
pozitiffcat/rester
e930a833910ea93180bacbedf1b1be23f45ee4da
[ "MIT" ]
null
null
null
#include "http_method.hpp"
13.5
26
0.777778
pozitiffcat
1856afa93da83c4b693e43da18982be2e90199cf
484
cpp
C++
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
pat/pat1031.cpp
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<string.h> #include<algorithm> using namespace std; int main() { string s; cin>>s; int len = s.length(); int n1 = len/3,n3 = len/3, n2 = len-n1-n3; //不能n1=n2=n3 if(len%3 == 0) { n1--;n3--;n2 +=2;} for(int i=0; i<n1; i++){ cout<<s[i]; for(int j=1; j<=n2-2; j++) cout<<" "; cout<<s[len-i-1]<<endl; } for(int i=n1; i<len-n1; i++) cout<<s[i]; cout<<endl; return 0; }
21.043478
59
0.491736
zofvbeaf
185707fd55ea6faf75bbdb73bbf5aa8529f77874
3,158
cpp
C++
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
16
2019-05-23T08:10:39.000Z
2021-12-21T11:20:37.000Z
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
null
null
null
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/ECMapMover.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
2
2019-05-23T18:37:43.000Z
2021-08-24T21:29:40.000Z
#include "ECMapMover.h" #include "Map.h" #include "Game.h" #include "MapGrid.h" #include "Node.h" using namespace qge; ECMapMover::ECMapMover(Entity *entity): EntityController(entity), borderThreshold_(10) { assert(entity != nullptr); // listen to when entity moves connect(entity,&Entity::moved,this,&ECMapMover::onEntityMoved); } /// Sets the border threshold. Whenever the controlled entity gets within /// this distance to any of the borders of its map, it will be transported /// to the next map in that direction. void ECMapMover::setBorderThreshold(double threshold) { borderThreshold_ = threshold; } /// Returns the border threshold. /// See setBorderThreshold() for more info. double ECMapMover::borderThreshold() { return borderThreshold_; } /// Executed when the controlled entity moves. /// Will see if it should move to new border map. void ECMapMover::onEntityMoved(Entity *controlledEntity, QPointF fromPos, QPointF toPos) { // do nothing if controlled entity is not in a map Entity* entity = entityControlled(); Map* entitysMap = entity->map(); if (entitysMap == nullptr) return; // do nothing if entitys map is not in a map grid Game* entitysGame = entitysMap->game(); if (entitysGame == nullptr) return; MapGrid* mapGrid = entitysGame->mapGrid(); if (mapGrid == nullptr) return; if (!mapGrid->contains(entitysMap)) return; // other wise, move entity to next maps // set up variables Node mapPos = mapGrid->positionOf(entitysMap); QPointF entityPos = entity->pos(); // if entity moved high up enough, move to top map if (entityPos.y() < borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x(),mapPos.y()-1); if (m){ double fracAlong = entity->x() / entitysMap->width(); m->addEntity(entity); entity->setPos(QPointF(fracAlong * m->width(),m->height() - borderThreshold_*2)); } } // if entity moved low enough, move to bot map if (entityPos.y() > entitysMap->height() - borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x(),mapPos.y()+1); if (m){ double fracAlong = entity->x() / entitysMap->width(); m->addEntity(entity); entity->setPos(QPointF(fracAlong * m->width(),borderThreshold_*2)); } } // if entity moved left enough, move to left map if (entityPos.x() < borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x()-1,mapPos.y()); if (m){ double fracAlong = entity->y() / entitysMap->height(); m->addEntity(entity); entity->setPos(QPointF(m->width() - borderThreshold_*2,fracAlong * m->height())); } } // if entity moved right enough, move to right map if (entityPos.x() > entitysMap->width() - borderThreshold_){ Map* m = mapGrid->mapAt(mapPos.x()+1,mapPos.y()); if (m){ double fracAlong = entity->y() / entitysMap->height(); m->addEntity(entity); entity->setPos(QPointF(borderThreshold_*2,fracAlong * m->height())); } } }
30.960784
93
0.624763
JamesMBallard
185894efec17052bd63aa3fe982827369c8edc6d
775
hh
C++
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
src/file.hh
deurzen/bulkrename
8de602ae3a34716e874ce334d0609a80536c9dbb
[ "BSD-3-Clause" ]
null
null
null
#ifndef __BULKRENAME_FILE_GUARD__ #define __BULKRENAME_FILE_GUARD__ #include "node.hh" #include <fstream> #include <string.h> #include <iostream> #include <string> #include <cstdio> class filehandler_t { public: filehandler_t() { char* tmpname = strdup("/tmp/tmpfileXXXXXXXXXX"); mkstemp(tmpname); tmpfile = tmpname; free(tmpname); out = ::std::ofstream(tmpfile); } ~filehandler_t() { out.close(); in.close(); } void write_out(const nodetree_t&); void read_in(const nodetree_t&); void edit() const; void propagate_rename(const nodetree_t&) const; private: ::std::string tmpfile; ::std::ifstream in; ::std::ofstream out; }; #endif//__BULKRENAME_FILE_GUARD__
17.222222
57
0.636129
deurzen
185a633de3a64811253334a39e0ac7f71e4e31c6
7,366
cpp
C++
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
76
2015-03-31T01:36:17.000Z
2021-12-29T08:16:25.000Z
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
68
2016-11-28T18:58:26.000Z
2018-08-10T13:33:35.000Z
test/unit/tcframe/driver/TestCaseDriverTests.cpp
tcgen/tcgen
d3b79585b40995ea8fc8091ecc6b6b19c2cb46ad
[ "MIT" ]
17
2015-04-24T03:52:32.000Z
2022-03-11T23:28:02.000Z
#include "gmock/gmock.h" #include "../mock.hpp" #include <sstream> #include <streambuf> #include <utility> #include "MockRawIOManipulator.hpp" #include "../spec/io/MockIOManipulator.hpp" #include "../spec/verifier/MockVerifier.hpp" #include "tcframe/driver/TestCaseDriver.hpp" using ::testing::_; using ::testing::Eq; using ::testing::InSequence; using ::testing::Return; using ::testing::StrEq; using ::testing::Test; using ::testing::Truly; using std::istreambuf_iterator; using std::istringstream; using std::move; using std::ostringstream; namespace tcframe { class TestCaseDriverTests : public Test { public: static int T; static int N; protected: MOCK(RawIOManipulator) rawIOManipulator; MOCK(IOManipulator) ioManipulator; MOCK(Verifier) verifier; TestCase sampleTestCase = TestCaseBuilder() .setName("foo_sample_1") .setSubtaskIds({1, 2}) .setData(new SampleTestCaseData("42\n", "yes\n")) .build(); TestCase officialTestCase = TestCaseBuilder() .setName("foo_1") .setDescription("N = 42") .setSubtaskIds({1, 2}) .setData(new OfficialTestCaseData([&]{N = 42;})) .build(); MultipleTestCasesConfig multipleTestCasesConfig = MultipleTestCasesConfigBuilder() .Counter(T) .build(); MultipleTestCasesConfig multipleTestCasesConfigWithOutputPrefix = MultipleTestCasesConfigBuilder() .Counter(T) .OutputPrefix("Case #%d: ") .build(); ostream* out = new ostringstream(); TestCaseDriver driver = createDriver(MultipleTestCasesConfig()); TestCaseDriver driverWithMultipleTestCases = createDriver(multipleTestCasesConfig); TestCaseDriver driverWithMultipleTestCasesWithOutputPrefix = createDriver(multipleTestCasesConfigWithOutputPrefix); TestCaseDriver createDriver(MultipleTestCasesConfig multipleTestCasesConfig) { return {&rawIOManipulator, &ioManipulator, &verifier, multipleTestCasesConfig}; } void SetUp() { ON_CALL(verifier, verifyConstraints(_)) .WillByDefault(Return(ConstraintsVerificationResult())); ON_CALL(verifier, verifyMultipleTestCasesConstraints()) .WillByDefault(Return(MultipleTestCasesConstraintsVerificationResult())); } struct InputStreamContentIs { string content_; explicit InputStreamContentIs(string content) : content_(move(content)) {} bool operator()(istream* in) const { return content_ == string(istreambuf_iterator<char>(*in), istreambuf_iterator<char>()); } }; }; int TestCaseDriverTests::T; int TestCaseDriverTests::N; TEST_F(TestCaseDriverTests, GenerateInput_Sample) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseInput(Truly(InputStreamContentIs("42\n")))); EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, print(out, "42\n")); } driver.generateInput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, GenerateInput_Official) { { InSequence sequence; EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(ioManipulator, printInput(out)); } N = 0; driver.generateInput(officialTestCase, out); EXPECT_THAT(N, Eq(42)); } TEST_F(TestCaseDriverTests, GenerateInput_Failed_Verification) { ConstraintsVerificationResult failedResult({}, {1}); ON_CALL(verifier, verifyConstraints(_)) .WillByDefault(Return(failedResult)); try { driver.generateInput(officialTestCase, out); FAIL(); } catch (FormattedError& e) { EXPECT_THAT(e, Eq(failedResult.asFormattedError())); } } TEST_F(TestCaseDriverTests, GenerateSampleOutput) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driver.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput) { istringstream in; EXPECT_CALL(ioManipulator, parseOutput(&in)); driver.validateOutput(&in); } TEST_F(TestCaseDriverTests, GenerateInput_MultipleTestCases_Sample) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseInput(Truly(InputStreamContentIs("42\n")))); EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, printLine(out, "1")); EXPECT_CALL(rawIOManipulator, print(out, "42\n")); } driverWithMultipleTestCases.generateInput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, GenerateInput_MultipleTestCases_Official) { { InSequence sequence; EXPECT_CALL(verifier, verifyConstraints(set<int>{1, 2})); EXPECT_CALL(rawIOManipulator, printLine(out, "1")); EXPECT_CALL(ioManipulator, printInput(out)); } N = 0; driverWithMultipleTestCases.generateInput(officialTestCase, out); EXPECT_THAT(N, Eq(42)); } TEST_F(TestCaseDriverTests, GenerateSampleOutput_MultipleTestCases) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driverWithMultipleTestCases.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases) { istringstream in("yes\n"); EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); driver.validateOutput(&in); } TEST_F(TestCaseDriverTests, GenerateSampleOutput_MultipleTestCases_WithOutputPrefix) { { InSequence sequence; EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); EXPECT_CALL(rawIOManipulator, print(out, "Case #1: ")); EXPECT_CALL(rawIOManipulator, print(out, "yes\n")); } driverWithMultipleTestCasesWithOutputPrefix.generateSampleOutput(sampleTestCase, out); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases_WithOutputPrefix) { istringstream in("Case #1: yes\n"); EXPECT_CALL(ioManipulator, parseOutput(Truly(InputStreamContentIs("yes\n")))); driverWithMultipleTestCasesWithOutputPrefix.validateOutput(&in); } TEST_F(TestCaseDriverTests, ValidateOutput_MultipleTestCases_WithOutputPrefix_Failed) { istringstream in("yes\n"); try { driverWithMultipleTestCasesWithOutputPrefix.validateOutput(&in); FAIL(); } catch (runtime_error& e) { EXPECT_THAT(e.what(), StrEq("Output must start with \"Case #1: \"")); } } TEST_F(TestCaseDriverTests, ValidateMultipleTestCasesInput) { EXPECT_CALL(verifier, verifyMultipleTestCasesConstraints()); driverWithMultipleTestCases.validateMultipleTestCasesInput(3); EXPECT_THAT(T, Eq(3)); } TEST_F(TestCaseDriverTests, ValidateMultipleTestCasesInput_Failed) { MultipleTestCasesConstraintsVerificationResult failedResult({"desc"}); ON_CALL(verifier, verifyMultipleTestCasesConstraints()) .WillByDefault(Return(failedResult)); try { driverWithMultipleTestCases.validateMultipleTestCasesInput(3); FAIL(); } catch (FormattedError& e) { EXPECT_THAT(e, Eq(failedResult.asFormattedError())); } } }
33.481818
119
0.706489
tcgen
185ad667e2140f0aeddd86cc3cb6970d9175e079
333
hpp
C++
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
Micasa/image_scaler.hpp
terrakuh/micasa
38aefce30c2a508557468a11d770f3e3d482d1da
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <QtWidgets\QWidget> #include <QtCore\QTimeLine> #include "image_item.hpp" class image_scaler { public: image_scaler(QWidget * _widget, image_item ** _image); void add_steps(int _steps); private: int _destination_level; QTimeLine _scaler; static double scaling_function(double _x); };
15.857143
55
0.762763
terrakuh
18610cffdd5cccbc3b0d94bfc335ee41f1d485f2
854
cxx
C++
track_oracle/core/element_descriptor.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
1
2017-07-31T07:07:32.000Z
2017-07-31T07:07:32.000Z
track_oracle/core/element_descriptor.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
4
2021-03-19T00:52:41.000Z
2022-03-11T23:48:06.000Z
track_oracle/core/element_descriptor.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +5 * Copyright 2012-2016 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "element_descriptor.h" using std::string; namespace kwiver { namespace track_oracle { string element_descriptor ::role2str( element_role e ) { switch (e) { case INVALID: return "invalid"; case SYSTEM: return "system"; case WELLKNOWN: return "well-known"; case ADHOC: return "ad-hoc"; default: return "unknown?"; } } element_descriptor::element_role element_descriptor ::str2role( const string& s ) { if (s == "system") return SYSTEM; else if (s == "well-known") return WELLKNOWN; else if (s == "ad-hoc") return ADHOC; else return INVALID; } } // ...track_oracle } // ...kwiver
20.333333
77
0.693208
neal-siekierski
18660c726f1c064723b6456e956839c4cc4155df
1,459
cc
C++
src/tcg/tcg_device_opal_2.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/tcg/tcg_device_opal_2.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
src/tcg/tcg_device_opal_2.cc
jc-lab/jcu-dparm
140efc844e339ca22d79a9958bdcbc7195701835
[ "Apache-2.0" ]
null
null
null
/** * @file tcg_device_opal_2.cc * @author Joseph Lee <development@jc-lab.net> * @date 2020/07/27 * @copyright Copyright (C) 2020 jc-lab.\n * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ #include <assert.h> #include "tcg_device_opal_2.h" #include "../drive_handle_base.h" #include "../intl_utils.h" namespace jcu { namespace dparm { namespace tcg { TcgDeviceOpal2::TcgDeviceOpal2(DriveHandleBase *drive_handle) : TcgDeviceOpalBase(drive_handle) { } TcgDeviceType TcgDeviceOpal2::getDeviceType() const { return kOpalV2Device; } uint16_t TcgDeviceOpal2::getBaseComId() const { const DriveInfo& drive_info = drive_handle_->getDriveInfo(); auto feat_it = drive_info.tcg_raw_features.find(kFcOpalSscV200); assert(feat_it != drive_info.tcg_raw_features.cend()); const auto *feature = (const tcg::discovery0_opal_ssc_feature_v200_t *)feat_it->second.data(); return SWAP16(feature->base_com_id); } uint16_t TcgDeviceOpal2::getNumComIds() const { const DriveInfo& drive_info = drive_handle_->getDriveInfo(); auto feat_it = drive_info.tcg_raw_features.find(kFcOpalSscV200); assert(feat_it != drive_info.tcg_raw_features.cend()); const auto *feature = (const tcg::discovery0_opal_ssc_feature_v200_t *)feat_it->second.data(); return SWAP16(feature->num_com_ids); } } // namespace tcg } // namespace dparm } // namespace jcu
30.395833
96
0.74366
jc-lab
18663000d41284c595c75793284e23e783255fc9
3,609
cpp
C++
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
5
2019-12-02T12:28:57.000Z
2021-04-07T21:21:13.000Z
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
null
null
null
integrate/property_server/source/sr_main.cpp
BoneCrasher/ShirabeEngine
39b3aa2c5173084d59b96b7f60c15207bff0ad04
[ "MIT" ]
1
2020-01-09T14:25:42.000Z
2020-01-09T14:25:42.000Z
/*! * @file sr_main.cpp * @author Marc-Anton Boehm-von Thenen * @date 27/06/2018 * @copyright SmartRay GmbH (www.smartray.com) */ #include "sr_pch.h" #include <functional> #include <iostream> #include "application/sr_state.h" #include "application/sr_handler_factory.h" #include <tcp_server_client/sr_server.h> //<--------------------------------------------- int main( int aArgC, char* aArgV[] ) { if (aArgC != 2) { std::cerr << "Usage: ./property_server <port> \n"; return 1; } std::string const port = aArgV[1]; asio::io_context asioIOContext; CStdSharedPtr_t<CTCPServer> tcpServer = nullptr; try { CStdSharedPtr_t<CTCPSession> session = nullptr; std::atomic<bool> connected(false); auto connectionSuccessHandler = [&] (CStdSharedPtr_t<CTCPSession> aSession) { connected.store(true); session = aSession; }; auto const tcpThreadFn = [&](std::string const &aPort) -> int32_t { tcp::endpoint endPoint(tcp::v4(), std::atoi(aPort.c_str())); tcpServer = makeStdSharedPtr<CTCPServer>(asioIOContext, endPoint, connectionSuccessHandler); tcpServer->start(); asioIOContext.run(); return 0; }; std::future<int32_t> tcpThreadResult = std::async(std::launch::async, tcpThreadFn, port); while(!connected.load()) { std::cout << "Waiting for connection...\n"; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } CStdSharedPtr_t<CHandlerFactory> handlerFactory = makeStdSharedPtr<CHandlerFactory>(session); CStdSharedPtr_t<CState> state = makeStdSharedPtr<CState>(handlerFactory); std::string serializedState = std::string(); bool const &stateInitialized = state->initialize(); bool const serialized = stateInitialized && state->getSerializedState(serializedState); CTCPMessage const outputMessage = CTCPMessage::create(serializedState); tcpServer->getSession()->writeMessage(outputMessage); std::string command = std::string(); while(1) { std::cin >> command; if(!command.compare("exit")) { break; } if(!command.compare("write_property")) { std::string path{}; (std::cin >> path); std::string index{}; (std::cin >> index); std::string value{}; (std::cin >> value); std::string outputCommand = CString::formatString("writeProperty/%s/%s/%s", path.c_str(), index.c_str(), value.c_str()); CTCPMessage outputMessage = CTCPMessage::create(outputCommand); tcpServer->getSession()->writeMessage(outputMessage); } } asioIOContext.stop(); std::future_status status = std::future_status::ready; do { std::cout << "Waiting for TCP thread to return...\n"; status = tcpThreadResult.wait_for(std::chrono::milliseconds(500)); } while(std::future_status::ready != status); int32_t const tcpThreadReturned = tcpThreadResult.get(); std::cout << "TCP thread returned status code: " << tcpThreadReturned << "\n"; return tcpThreadReturned; } catch(std::exception const &e) { std::cerr << "Exception: " << e.what() << "\n"; return -1; } }
28.872
136
0.563591
BoneCrasher
1870b9c705fcaa7116e0c66235bee0ccd2701359
1,783
cpp
C++
src/Entity.cpp
PeaTea/Wolfenstein3D-Cpp-Clone-WIP
c82cd6fe2de43e6dba0d974b93edd910fbe44798
[ "MIT" ]
null
null
null
src/Entity.cpp
PeaTea/Wolfenstein3D-Cpp-Clone-WIP
c82cd6fe2de43e6dba0d974b93edd910fbe44798
[ "MIT" ]
1
2017-10-08T09:25:01.000Z
2018-05-14T21:46:37.000Z
src/Entity.cpp
PeaTea/Wolfenstein3D-Cpp-Clone-WIP
c82cd6fe2de43e6dba0d974b93edd910fbe44798
[ "MIT" ]
null
null
null
#include "Entity.h" Entity::Entity(unsigned int tex_id, const glm::vec3& pos, const Vec2<float>& size, GLfloat rotation, const glm::vec3& rotation_vec, const glm::vec4& color) : m_texture_id {tex_id} , m_position {pos} , m_size {size} , m_rotation {rotation} , m_rotation_vec {rotation_vec} , m_color {color} , m_is_rotated {false} , m_cam_pos {} { } Entity::Entity(unsigned int tex_id, const glm::vec3& pos, const glm::vec3& cam_pos, const Vec2<float>& size, const glm::vec4& color) : m_texture_id {tex_id} , m_position {pos} , m_cam_pos {cam_pos} , m_size {size} , m_color {color} , m_is_rotated {true} , m_rotation {} , m_rotation_vec {} { } void Entity::set_cam_pos(const glm::vec3& cam_pos) { if(m_is_rotated) { m_cam_pos = cam_pos; } } void Entity::render(std::unordered_map<std::string, GLProgram>& programs, const int& cf_height) { BasicRenderer::set_program(m_is_rotated ? programs["point"] : programs["normal"]); (m_is_rotated) ? BasicRenderer::draw_sprite_facing_cam(m_texture_id, {m_position.x, m_position.y - cf_height, m_position.z}, m_cam_pos, m_size, m_color) : BasicRenderer::draw_sprite(m_texture_id, {m_position.x, m_position.y - cf_height, m_position.z}, m_size, m_rotation, m_rotation_vec, m_color); } glm::vec3 Entity::get_position() const { return m_position; } glm::vec4 Entity::get_color() const { return m_color; }
29.716667
129
0.557487
PeaTea
18766da2fb8b4a197e862b8f6772a05660f0cc66
1,194
cpp
C++
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
orm-cpp/orm/test_mock/store_mock/orm/store_mark/store.cpp
ironbit/showcase-app
3bb5fad9f616c04bdbec67b682713fbb671fce4a
[ "MIT" ]
null
null
null
#include "orm/store_mark/store.h" namespace orm::store_mark { test::mock::Store& Store::mock() { return mMock; } std::shared_ptr<orm::core::Property> Store::query(std::int64_t identity) { return mMock.query(identity); } bool Store::commit() { return mMock.commit(); } std::shared_ptr<orm::core::Property> Store::fetch() { return mMock.fetch(); } bool Store::insert(std::int64_t identity, std::shared_ptr<orm::core::Property>&& record) { return mMock.insert(identity, std::forward<std::shared_ptr<orm::core::Property>>(record)); } bool Store::insert(std::int64_t identity, const std::shared_ptr<orm::core::Property>& record) { return mMock.insert(identity, record); } bool Store::update(std::int64_t identity, std::shared_ptr<orm::core::Property>&& record) { return mMock.update(identity, std::forward<std::shared_ptr<orm::core::Property>>(record)); } bool Store::update(std::int64_t identity, const std::shared_ptr<orm::core::Property>& record) { return mMock.update(identity, record); } bool Store::remove(std::int64_t identity) { return mMock.remove(identity); } std::unique_ptr<orm::store::Store> Store::clone() { return mMock.clone(); } } // orm::store_mark namespace
25.956522
95
0.717755
ironbit
187727753cbf4ffc33b237b442477bf1452f9cf8
347
hpp
C++
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
src/mainView/mainView.hpp
Tau5/mkrandom
f6586690d6d696c564a83e28e39679eeb0d8d5e9
[ "MIT" ]
null
null
null
#ifndef __MAINVIEW_H__ #define __MAINVIEW_H__ #include "../scenario.hpp" #include "../context.hpp" #include "../scenarioContext.hpp" #include "../view.hpp" class MainView: public View { private: int subview; public: MainView(Context context); void init(); void loop(SceCtrlData pad, SceCtrlData pad_prev); }; #endif // __MAINVIEW_H__
18.263158
51
0.720461
Tau5
18779c3b9615171d49bdd7503a8e2d6be74892ea
1,334
cpp
C++
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
1
2021-01-18T14:51:20.000Z
2021-01-18T14:51:20.000Z
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
Dynamic Programming/2zeroOneKnapsack.cpp
Coderangshu/450DSA
fff6cee65f75e5a0bb61d5fd8d000317a7736ca3
[ "MIT" ]
null
null
null
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to return max value that can be put in knapsack of capacity W. int knapSack(int W, int wt[], int val[], int n) { // Your code here vector<vector<int>> dp(W+1,vector<int>(n+1)); for(int i=0;i<W+1;i++){ for(int j=0;j<n+1;j++){ if(i==0 or j==0) dp[i][j] = 0; else if(wt[j-1]>i) dp[i][j] = dp[i][j-1]; else dp[i][j] = max(dp[i-wt[j-1]][j-1]+val[j-1],dp[i][j-1]); } } // for(auto e:dp){ // for(auto f:e) cout<<f<<" "; // cout<<endl; // } return dp[W][n]; } }; // { Driver Code Starts. int main() { //taking total testcases int t; cin>>t; while(t--) { //reading number of elements and weight int n, w; cin>>n>>w; int val[n]; int wt[n]; //inserting the values for(int i=0;i<n;i++) cin>>val[i]; //inserting the weights for(int i=0;i<n;i++) cin>>wt[i]; Solution ob; //calling method knapSack() cout<<ob.knapSack(w, wt, val, n)<<endl; } return 0; } // } Driver Code Ends
21.516129
77
0.450525
Coderangshu
187917397e0bfb8c27c277b2d18fcaf25674360f
1,022
cpp
C++
Gems/Atom/RPI/Code/Source/RPI.Reflect/FeatureProcessorDescriptor.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/Atom/RPI/Code/Source/RPI.Reflect/FeatureProcessorDescriptor.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/Atom/RPI/Code/Source/RPI.Reflect/FeatureProcessorDescriptor.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Serialization/SerializeContext.h> #include <Atom/RPI.Reflect/FeatureProcessorDescriptor.h> namespace AZ { namespace RPI { /** * @brief Reflects the FeatureProcessorDescriptor struct to the Serialization system * @param[in] context The reflection context */ void FeatureProcessorDescriptor::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<FeatureProcessorDescriptor>() ->Version(0) ->Field("MaxRenderGraphLatency", &FeatureProcessorDescriptor::m_maxRenderGraphLatency) ; } } } // namespace RPI } // namespace AZ
30.969697
106
0.637965
cypherdotXd
187b40aa525a495705a119ea25f4c43c37dabfd7
161
hpp
C++
strategy/FlyBehavior.hpp
jinbooooom/design-patterns
1399500c9ac8bd8cd0c90926482c2a841471a784
[ "MIT" ]
null
null
null
strategy/FlyBehavior.hpp
jinbooooom/design-patterns
1399500c9ac8bd8cd0c90926482c2a841471a784
[ "MIT" ]
null
null
null
strategy/FlyBehavior.hpp
jinbooooom/design-patterns
1399500c9ac8bd8cd0c90926482c2a841471a784
[ "MIT" ]
null
null
null
#ifndef FLYBEHAVIOR_HPP #define FLYBEHAVIOR_HPP // 接口类 class FlyBehavior { public: virtual void fly() = 0; virtual ~FlyBehavior() = default; }; #endif
12.384615
37
0.695652
jinbooooom
187bcf9d3a46194b1e9ad708a033401e9f6f5cf6
283
hpp
C++
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
11
2018-01-10T12:35:04.000Z
2018-08-29T01:47:48.000Z
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
null
null
null
test/strategy.hpp
fyquah95/robot_cpp
f0898957fb0b1258419e4ace9d7464143caaa5e4
[ "MIT" ]
2
2018-01-10T13:04:08.000Z
2018-01-10T13:24:12.000Z
#ifndef STRATEGY_HPP #define STRATEGY_HPP #include "game.hpp" game_state_t strategy_init(const game_state_t & state); game_state_t strategy_step(const game_state_t & state, bool *moved); game_state_t strategy_term(game_state_t state); void strategy_print_internal_state(); #endif
23.583333
68
0.823322
fyquah95
187f1e267bf275dd1c60a0dfafa60bf3658cf60d
168
hpp
C++
src/include/streamer/manipulation.hpp
philip1337/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
2
2017-07-23T23:27:03.000Z
2017-07-24T06:18:13.000Z
src/include/streamer/manipulation.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
src/include/streamer/manipulation.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
#ifndef MANIPULATION_HPP #define MANIPULATION_HPP #pragma once #include "config.hpp" STREAMER_BEGIN_NS int Streamer_GetUpperBound(int type); STREAMER_END_NS #endif
12.923077
37
0.827381
philip1337
18869220aaac503fc651d518f224e5118ec6d1b1
210
cpp
C++
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
1
2020-08-21T01:26:47.000Z
2020-08-21T01:26:47.000Z
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
null
null
null
source/ballstatus.cpp
BonexGoo/ballt
33e4022161cf4b0017da7460d19847d0d5d2d51d
[ "MIT" ]
1
2020-08-21T01:26:55.000Z
2020-08-21T01:26:55.000Z
#include <boss.hpp> #include "ballstatus.hpp" BallStatus& BallStatus::operator=(const BallStatus& rhs) { Memory::Copy(&mRailCode, &rhs.mRailCode, sizeof(BallStatus) - sizeof(uint32)); return *this; }
23.333333
82
0.709524
BonexGoo
188873b0a94b3ede34ed0801b4d62205dfdb13f2
1,618
cpp
C++
hw/Assignment3-vs2008/KarelGoesHome.cpp
Liquidibrium/PAbstractions
e3cf51b5d713a181abdda87ed5205d998289f878
[ "MIT" ]
null
null
null
hw/Assignment3-vs2008/KarelGoesHome.cpp
Liquidibrium/PAbstractions
e3cf51b5d713a181abdda87ed5205d998289f878
[ "MIT" ]
null
null
null
hw/Assignment3-vs2008/KarelGoesHome.cpp
Liquidibrium/PAbstractions
e3cf51b5d713a181abdda87ed5205d998289f878
[ "MIT" ]
null
null
null
/* File: KarelGoesHome.cpp * * A solution to the Karel Goes Home warmup problem for Assignment 3. */ #include <iostream> #include "simpio.h" using namespace std; /* Function to compute the number of paths back home. */ int numPathsHome(int street, int avenue); int main() { int street = getInteger("Enter the street number: "); int avenue = getInteger("Enter the avenue number: "); cout << "Number of paths back: " << numPathsHome(street, avenue) << endl; } /* Solves the Karel Goes Home problem. The recursive structure is as follows: * * Base Case 1: If Karel is at an invalid index, then there are no paths * back home. * * Base Case 2: If Karel is at (1, 1), then there is exactly one path back: * just stay where you are! * * Recursive Step: Every journey begins with a single step, as they say (it's * not quite clear who "they" are, though). Every path Karel can * take either starts with a step left or a step down. If we count * how many paths there are having taken those first steps, we will * have found the total number of paths back. */ int numPathsHome(int street, int avenue) { /* Base case 1: If we're not on the map, there's no way back. */ if (street < 1 || avenue < 1) { return 0; } /* Base case 2: If we're home, there's exactly one path back. */ else if (street == 1 && avenue == 1) { return 1; } /* Recursive step: Take a step in each direction and sum up the * number of paths. */ else { return numPathsHome(street - 1, avenue) + numPathsHome(street, avenue - 1); } }
32.36
80
0.647095
Liquidibrium
188cefdcb77849ba038b1a21d023b1ce4eb97481
1,270
cpp
C++
C++/Cpp-Concurrency-in-Action/listing_8.7.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
1
2021-02-20T00:14:35.000Z
2021-02-20T00:14:35.000Z
C++/Cpp-Concurrency-in-Action/listing_8.7.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
C++/Cpp-Concurrency-in-Action/listing_8.7.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
template <typename Iterator, typename Func> void parallel_for_each(Iterator first, Iterator last, Func f) { unsigned long const length = std::distance(first, last); if (!length) return; unsigned long const min_per_thread = 25; unsigned long const max_threads = (length + min_per_thread - 1) / min_per_thread; unsigned long const hardware_threads = std::thread::hardware_concurrency(); unsigned long const num_threads = std::min(hardware_threads != 0 ? hardware_threads : 2, max_threads); unsigned long const block_size = length / num_threads; std::vector<std::future<void> > futures(num_threads - 1); std::vector<std::thread> threads(num_threads - 1); join_threads joiner(threads); Iterator block_start = first; for (unsigned long i = 0; i < (num_threads - 1); ++i) { Iterator block_end = block_start; std::advance(block_end, block_size); std::packaged_task<void(void)> task( [=]() { std::for_each(block_start, block_end, f); }); futures[i] = task.get_future(); threads[i] = std::thread(std::move(task)); block_start = block_end; } std::for_each(block_start, last, f); for (unsigned long i = 0; i < (num_threads - 1); ++i) { futures[i].get(); } }
34.324324
78
0.66063
haohaibo
188d5a14490cc58d8bf29d451376f39297ddea5e
35,755
cc
C++
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
31
2020-06-23T13:53:47.000Z
2022-03-28T08:09:00.000Z
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2020-11-01T21:35:47.000Z
2021-08-29T11:40:50.000Z
omnetpy/bindings/bind_ccomponent.cc
ranarashadmahmood/OMNETPY
13ab49106a3ac700aa633a8eb37acdad5e3157ab
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2021-03-22T15:32:22.000Z
2022-02-02T14:57:56.000Z
#include <pybind11/pybind11.h> #include <omnetpp.h> #include <omnetpp/ccomponent.h> /* * make public all the protected members of cComponent * we want to expose to python */ class cComponentPublicist : public omnetpp::cComponent { public: using omnetpp::cComponent::initialize; using omnetpp::cComponent::numInitStages; using omnetpp::cComponent::finish; using omnetpp::cComponent::handleParameterChange; using omnetpp::cComponent::refreshDisplay; }; void bind_cComponent(pybind11::module &m) { pybind11::class_<omnetpp::cComponent> py_cComponent( m, "_cComponent", R"docstring( `cComponent` provides parameters, properties, display string, RNG mapping, initialization and finalization support, simulation signals support, and several other services to its subclasses. Initialize and finish functions may be provided by the user, to perform special tasks at the beginning and the end of the simulation. The functions are made protected because they are supposed to be called only via `callInitialize()` and `callFinish()`. The initialization process was designed to support multi-stage initialization of compound modules (i.e. initialization in several 'waves'). (Calling the `initialize()` function of a simple module is hence a special case). The initialization process is performed on a module like this. First, the number of necessary initialization stages is determined by calling `numInitStages()`, then `initialize(stage)` is called with `0,1,...numstages-1` as argument. The default implementation of `numInitStages()` and `initialize(stage)` provided here defaults to single-stage initialization, that is, `numInitStages()` returns 1 and initialize(stage) simply calls initialize() if stage is 0. )docstring" ); pybind11::enum_<omnetpp::cComponent::ComponentKind>(py_cComponent, "ComponentKind") .value("KIND_MODULE", omnetpp::cComponent::ComponentKind::KIND_MODULE) .value("KIND_CHANNEL", omnetpp::cComponent::ComponentKind::KIND_CHANNEL) .value("KIND_OTHER", omnetpp::cComponent::ComponentKind::KIND_OTHER) .export_values(); /* * cComponent is abstract and we don't need to instantiate it from python * so do not add init method. * py_cComponent.def( pybind11::init<const char*>(), R"docstring( Constructor. Note that module and channel objects should not be created directly, via their `cComponentType` objects. `cComponentType.create()` will do all housekeeping associated with creating the module (assigning an ID to the module, inserting it into the `simulation` object, etc.). )docstring", pybind11::arg("name") = nullptr ); */ py_cComponent.def( "initialize", pybind11::overload_cast<>(&cComponentPublicist::initialize), R"docstring( Single-stage initialization hook. This default implementation does nothing. )docstring" ); py_cComponent.def( "initialize", pybind11::overload_cast<int>(&cComponentPublicist::initialize), R"docstring( Multi-stage initialization hook. This default implementation does single-stage init, that is, calls initialize() if stage is 0. )docstring", pybind11::arg("stage") ); py_cComponent.def( "numInitStages", &cComponentPublicist::numInitStages, R"docstring( Multi-stage initialization hook, should be redefined to return the number of initialization stages required. This default implementation does single-stage init, that is, returns 1. )docstring" ); py_cComponent.def( "finish", &cComponentPublicist::finish, R"docstring( Finish hook. `finish()` is called after end of simulation if it terminated without error. This default implementation does nothing. )docstring" ); py_cComponent.def( "handleParameterChange", &cComponentPublicist::handleParameterChange, R"docstring( This method is called by the simulation kernel to notify the module or channel that the value of an existing parameter has changed. Redefining this method allows simple modules and channels to be react on parameter changes, for example by re-reading the value. This default implementation does nothing. The parameter name is `None` if more than one parameter has changed. To make it easier to write predictable components, the function is NOT called on uninitialized components (i.e. when `initialized()` returns `False`). For each component, the function is called (with `None` as a parname) after the last stage of the initialization, so that the module gets a chance to update its cached parameters. Also, one must be extremely careful when changing parameters from inside handleParameterChange(), to avoid creating an infinite notification loop. )docstring", pybind11::arg("parname") ); py_cComponent.def( "refreshDisplay", &cComponentPublicist::refreshDisplay, R"docstring( This method is called on all components of the simulation by graphical user interfaces (Qtenv, Tkenv) whenever GUI contents need to be refreshed after processing some simulation events. Components that contain visualization-related code are expected to override `refreshDisplay()`, and move visualization code display string manipulation, canvas figures maintenance, OSG scene graph update, etc.) into it. As it is unpredictable when and whether this method is invoked, the simulation logic should not depend on it. It is advisable that code in `refreshDisplay()` does not alter the state of the model at all. This behavior is gently encouraged by having this method declared as const. (Data members that do need to be updated inside refreshDisplay(), i.e. those related to visualization, may be declared mutable to allow that). Tkenv and Qtenv invoke `refreshDisplay()` with similar strategies: in Step and Run mode, after each event; in Fast Run and Express Run mode, every time the screen is refereshed, which is typically on the order of once per second. Cmdenv does not invoke `refreshDisplay()` at all. Note that overriding `refreshDisplay()` is generally preferable to doing display updates as part of event handling: it results in essentially zero per-event runtime overhead, and potentially more consistent information being displayed (as all components refresh their visualization, not only the one which has just processed an event.) )docstring" ); py_cComponent.def( "getId", &omnetpp::cComponent::getId, R"docstring( Returns the component's ID in the simulation object (cSimulation). Component IDs are guaranteed to be unique during a simulation run (that is, IDs of deleted components are not reused for new components.) )docstring" ); py_cComponent.def( "getNedTypeName", &omnetpp::cComponent::getNedTypeName, R"docstring( Returns the fully qualified NED type name of the component (i.e. the simple name prefixed with the package name and any existing enclosing NED type names). This method is a shortcut to `self.getComponentType().getFullName()`. )docstring" ); py_cComponent.def( "isModule", &omnetpp::cComponent::isModule, R"docstring( Returns true for cModule and subclasses, otherwise false. )docstring" ); py_cComponent.def( "isChannel", &omnetpp::cComponent::isChannel, R"docstring( Returns true for channels, and false otherwise. )docstring" ); py_cComponent.def( "getSimulation", &omnetpp::cComponent::getSimulation, R"docstring( Returns the simulation the component is part of. Currently may only be invoked if the component's simulation is the active one (see cSimulation::getActiveSimulation()). )docstring", pybind11::return_value_policy::reference ); py_cComponent.def( "getSystemModule", &omnetpp::cComponent::getSystemModule, R"docstring( Returns the toplevel module in the current simulation. This is a shortcut to `self.getSimulation().getSystemModule()`. )docstring" ); py_cComponent.def( "getNumParams", &omnetpp::cComponent::getNumParams, R"docstring( Returns total number of the component's parameters. )docstring" ); py_cComponent.def( "par", pybind11::overload_cast<int>(&omnetpp::cComponent::par), R"docstring( Returns reference to the parameter identified with its index k. Throws an error if the parameter does not exist. )docstring", pybind11::arg("k"), pybind11::return_value_policy::reference ); py_cComponent.def( "par", pybind11::overload_cast<const char *>(&omnetpp::cComponent::par), R"docstring( Returns reference to the parameter specified with its name. Throws an error if the parameter does not exist. )docstring", pybind11::arg("parname"), pybind11::return_value_policy::reference ); py_cComponent.def( "findPar", &omnetpp::cComponent::findPar, R"docstring( Returns index of the parameter specified with its name. Returns -1 if the object doesn't exist. )docstring", pybind11::arg("parname") ); py_cComponent.def( "hasPar", &omnetpp::cComponent::hasPar, R"docstring( Check if a parameter exists. )docstring", pybind11::arg("parname") ); py_cComponent.def( "getRNG", &omnetpp::cComponent::getRNG, R"docstring( Returns the global RNG mapped to local RNG number k. For large indices (k >= map size) the global RNG k is returned, provided it exists. )docstring", pybind11::arg("k") ); py_cComponent.def( "intrand", &omnetpp::cComponent::intrand, R"docstring( Produces a random integer in the range [0,r) using the RNG given with its index. )docstring", pybind11::arg("r"), pybind11::arg("rng") = 0 ); py_cComponent.def( "dblrand", &omnetpp::cComponent::dblrand, R"docstring( Produces a random double in the range [0,1) using the RNG given with its index. )docstring", pybind11::arg("rng") = 0 ); py_cComponent.def( "uniform", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::uniform, pybind11::const_), R"docstring( Returns a random variate with uniform distribution in the range [a,b). :param a, b: the interval, a < b :param rng: index of the component RNG to use, see `getRNG(int)` )docstring", pybind11::arg("a"), pybind11::arg("a"), pybind11::arg("rng") = 0 ); py_cComponent.def( "uniform", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::uniform, pybind11::const_), R"docstring( SimTime version of uniform(double, double, int), for convenience. )docstring", pybind11::arg("a"), pybind11::arg("a"), pybind11::arg("rng") = 0 ); py_cComponent.def( "exponential", pybind11::overload_cast<double, int>(&omnetpp::cComponent::exponential, pybind11::const_), R"docstring( Returns a random variate from the exponential distribution with the given mean (that is, with parameter lambda=1/mean). :param mean: mean value :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "exponential", pybind11::overload_cast<omnetpp::SimTime, int>(&omnetpp::cComponent::exponential, pybind11::const_), R"docstring( SimTime version of exponential(double,int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "normal", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::normal, pybind11::const_), R"docstring( Returns a random variate from the normal distribution with the given mean and standard deviation. :param mean: mean of the normal distribution :param stddev: standard deviation of the normal distribution :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "normal", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::normal, pybind11::const_), R"docstring( SimTime version of normal(double, double, int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "truncnormal", pybind11::overload_cast<double, double, int>(&omnetpp::cComponent::truncnormal, pybind11::const_), R"docstring( Normal distribution truncated to nonnegative values. It is implemented with a loop that discards negative values until a nonnegative one comes. This means that the execution time is not bounded: a large negative mean with much smaller stddev is likely to result in a large number of iterations. The mean and stddev parameters serve as parameters to the normal distribution <i>before</i> truncation. The actual random variate returned will have a different mean and standard deviation. :param mean: mean of the normal distribution :param stddev: standard deviation of the normal distribution :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "truncnormal", pybind11::overload_cast<omnetpp::SimTime, omnetpp::SimTime, int>(&omnetpp::cComponent::truncnormal, pybind11::const_), R"docstring( SimTime version of truncnormal(double,double,int), for convenience. )docstring", pybind11::arg("mean"), pybind11::arg("stddev"), pybind11::arg("rng") = 0 ); py_cComponent.def( "gamma_d", &omnetpp::cComponent::gamma_d, R"docstring( Returns a random variate from the gamma distribution with parameters alpha>0, theta>0. Alpha is known as the "shape" parameter, and theta as the "scale" parameter. Some sources in the literature use the inverse scale parameter beta = 1 / theta, called the "rate" parameter. Various other notations can be found in the literature; our usage of (alpha,theta) is consistent with Wikipedia and Mathematica (Wolfram Research). Gamma is the generalization of the Erlang distribution for non-integer k values, which becomes the alpha parameter. The chi-square distribution is a special case of the gamma distribution. For alpha=1, Gamma becomes the exponential distribution with mean=theta. The mean of this distribution is alpha*theta, and variance is alpha*theta<sup>2</sup>. Generation: if alpha=1, it is generated as exponential(theta). For alpha>1, we make use of the acceptance-rejection method in "A Simple Method for Generating Gamma Variables", George Marsaglia and Wai Wan Tsang, ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000. The alpha < 1 case makes use of the alpha > 1 algorithm, as suggested by the above paper. .. note:: The name gamma_d is chosen to avoid ambiguity with a function of the same name :param alpha: >0 the "shape" parameter :param theta: >0 the "scale" parameter :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("alpha"), pybind11::arg("theta"), pybind11::arg("rng") = 0 ); py_cComponent.def( "beta", &omnetpp::cComponent::beta, R"docstring( Returns a random variate from the beta distribution with parameters alpha1, alpha2. Generation is using relationship to Gamma distribution: if Y1 has gamma distribution with alpha=alpha1 and beta=1 and Y2 has gamma distribution with alpha=alpha2 and beta=2, then Y = Y1/(Y1+Y2) has beta distribution with parameters alpha1 and alpha2. :param alpha1, alpha2: >0 :param rng :index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("alpha1"), pybind11::arg("alpha2"), pybind11::arg("rng") = 0 ); py_cComponent.def( "erlang_k", &omnetpp::cComponent::erlang_k, R"docstring( Returns a random variate from the Erlang distribution with k phases and mean mean. This is the sum of k mutually independent random variables, each with exponential distribution. Thus, the kth arrival time in the Poisson process follows the Erlang distribution. Erlang with parameters m and k is gamma-distributed with alpha=k and beta=m/k. Generation makes use of the fact that exponential distributions sum up to Erlang. :param k: number of phases, k>0 :param mean: >0 :@param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("k"), pybind11::arg("mean"), pybind11::arg("rng") = 0 ); py_cComponent.def( "chi_square", &omnetpp::cComponent::chi_square, R"docstring( Returns a random variate from the chi-square distribution with k degrees of freedom. The chi-square distribution arises in statistics. If Yi are k independent random variates from the normal distribution with unit variance, then the sum-of-squares (sum(Yi^2)) has a chi-square distribution with k degrees of freedom. The expected value of this distribution is k. Chi_square with parameter k is gamma-distributed with alpha=k/2, beta=2. Generation is using relationship to gamma distribution. :param k: degrees of freedom, k>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("k"), pybind11::arg("rng") = 0 ); py_cComponent.def( "student_t", &omnetpp::cComponent::student_t, R"docstring( Returns a random variate from the student-t distribution with i degrees of freedom. If Y1 has a normal distribution and Y2 has a chi-square distribution with k degrees of freedom then X = Y1 / sqrt(Y2/k) has a student-t distribution with k degrees of freedom. Generation is using relationship to gamma and chi-square. :param i: degrees of freedom, i>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("i"), pybind11::arg("rng") = 0 ); py_cComponent.def( "cauchy", &omnetpp::cComponent::cauchy, R"docstring( Returns a random variate from the Cauchy distribution (also called Lorentzian distribution) with parameters a,b where b>0. This is a continuous distribution describing resonance behavior. It also describes the distribution of horizontal distances at which a line segment tilted at a random angle cuts the x-axis. Generation uses inverse transform. :param a: :param b: b>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "triang", &omnetpp::cComponent::triang, R"docstring( Returns a random variate from the triangular distribution with parameters a <= b <= c. Generation uses inverse transform. :param a, b, c: a <= b <= c :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("c"), pybind11::arg("rng") = 0 ); py_cComponent.def( "lognormal", &omnetpp::cComponent::lognormal, R"docstring( Returns a random variate from the lognormal distribution with "scale" parameter m and "shape" parameter w. m and w correspond to the parameters of the underlying normal distribution (m: mean, w: standard deviation.) Generation is using relationship to normal distribution. :param m: "scale" parameter, m>0 :param w: "shape" parameter, w>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("m"), pybind11::arg("w"), pybind11::arg("rng") = 0 ); py_cComponent.def( "weibull", &omnetpp::cComponent::weibull, R"docstring( Returns a random variate from the Weibull distribution with parameters a, b > 0, where a is the "scale" parameter and b is the "shape" parameter. Sometimes Weibull is given with alpha and beta parameters, then alpha=b and beta=a. The Weibull distribution gives the distribution of lifetimes of objects. It was originally proposed to quantify fatigue data, but it is also used in reliability analysis of systems involving a "weakest link," e.g. in calculating a device's mean time to failure. When b=1, Weibull(a,b) is exponential with mean a. Generation uses inverse transform. :param a: the "scale" parameter, a>0 :param b: the "shape" parameter, b>0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "pareto_shifted", &omnetpp::cComponent::pareto_shifted, R"docstring( Returns a random variate from the shifted generalized Pareto distribution. Generation uses inverse transform. :param a, b: the usual parameters for generalized Pareto :param c: shift parameter for left-shift :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("c"), pybind11::arg("rng") = 0 ); py_cComponent.def( "intuniform", &omnetpp::cComponent::intuniform, R"docstring( Returns a random integer with uniform distribution in the range [a,b], inclusive. (Note that the function can also return b.) :param a, b: the interval, a<b :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "intuniformexcl", &omnetpp::cComponent::intuniformexcl, R"docstring( Returns a random integer with uniform distribution over [a,b), that is, from [a,b-1]. :param a, b: the interval, a<b :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("a"), pybind11::arg("b"), pybind11::arg("rng") = 0 ); py_cComponent.def( "bernoulli", &omnetpp::cComponent::bernoulli, R"docstring( Returns the result of a Bernoulli trial with probability p, that is, 1 with probability p and 0 with probability (1-p). Generation is using elementary look-up. :param p: 0=<p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "binomial", &omnetpp::cComponent::binomial, R"docstring( Returns a random integer from the binomial distribution with parameters n and p, that is, the number of successes in n independent trials with probability p. Generation is using the relationship to Bernoulli distribution (runtime is proportional to n). :param n: n>=0 :param p: 0<=p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("n"), pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "geometric", &omnetpp::cComponent::geometric, R"docstring( Returns a random integer from the geometric distribution with parameter p, that is, the number of independent trials with probability p until the first success. This is the n=1 special case of the negative binomial distribution. Generation uses inverse transform. :param p: 0<p<=1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "negbinomial", &omnetpp::cComponent::negbinomial, R"docstring( Returns a random integer from the negative binomial distribution with parameters n and p, that is, the number of failures occurring before n successes in independent trials with probability p of success. Generation is using the relationship to geometric distribution (runtime is proportional to n). :param n: n>=0 :param p: 0<p<1 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("n"), pybind11::arg("p"), pybind11::arg("rng") = 0 ); py_cComponent.def( "poisson", &omnetpp::cComponent::poisson, R"docstring( Returns a random integer from the Poisson distribution with parameter lambda, that is, the number of arrivals over unit time where the time between successive arrivals follow exponential distribution with parameter lambda. Lambda is also the mean (and variance) of the distribution. Generation method depends on value of lambda: - 0<lambda<=30: count number of events - lambda>30: Acceptance-Rejection due to Atkinson (see Banks, page 166) :param lambda: > 0 :param rng: index of the component RNG to use, see getRNG(int) )docstring", pybind11::arg("lambda"), pybind11::arg("rng") = 0 ); py_cComponent.def_static( "registerSignal", &omnetpp::cComponent::registerSignal, R"docstring( Returns the signal ID (handle) for the given signal name. Signal names and IDs are global. The signal ID for a particular name gets assigned at the first registerSignal() call; further registerSignal() calls for the same name will return the same ID. )docstring", pybind11::arg("name") ); py_cComponent.def_static( "getSignalName", &omnetpp::cComponent::getSignalName, R"docstring( The inverse of `registerSignal()`: returns the name of the given signal, or `None` for invalid signal handles. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, long, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the long value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("l"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, double, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the double value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("d"), pybind11::arg("details") = nullptr); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const omnetpp::SimTime&, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the simtime_t value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("t"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const char*, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the given string as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("s"), pybind11::arg("details") = nullptr); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, const omnetpp::cObject*, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the given object as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("obj"), pybind11::arg("details") = nullptr ); py_cComponent.def( "emit", pybind11::overload_cast<omnetpp::simsignal_t, bool, omnetpp::cObject *>(&omnetpp::cComponent::emit), R"docstring( Emits the boolean value as a signal. If the given signal has listeners in this component or in ancestor components, their appropriate receiveSignal() methods are called. If there are no listeners, the runtime cost is usually minimal. )docstring", pybind11::arg("signalID"), pybind11::arg("b"), pybind11::arg("details") = nullptr ); py_cComponent.def( "mayHaveListeners", &omnetpp::cComponent::mayHaveListeners, R"docstring( If producing a value for a signal has a significant runtime cost, this method can be used to check beforehand whether the given signal possibly has any listeners at all. if not, emitting the signal can be skipped. This method has a constant cost but may return false positive. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "hasListeners", &omnetpp::cComponent::hasListeners, R"docstring( Returns true if the given signal has any listeners. In the current implementation, this involves checking listener lists in ancestor modules until the first listener is found, or up to the root. This method may be useful if producing the data for an emit() call would be expensive compared to a hasListeners() call. )docstring", pybind11::arg("signalID") ); py_cComponent.def( "recordScalar", pybind11::overload_cast<const char *, double, const char *>(&omnetpp::cComponent::recordScalar), R"docstring( Records a double into the scalar result file. )docstring", pybind11::arg("name"), pybind11::arg("value"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "recordScalar", pybind11::overload_cast<const char *, omnetpp::simtime_t, const char *>(&omnetpp::cComponent::recordScalar), R"docstring( Convenience method, delegates to recordScalar(const char *, double, const char*). )docstring", pybind11::arg("name"), pybind11::arg("value"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "hasGUI", &omnetpp::cComponent::hasGUI, R"docstring( Returns true if the current environment is a graphical user interface. (For example, it returns true if the simulation is running over Tkenv/Qtenv, and false if it's running over Cmdenv.) Modules can examine this flag to decide whether or not they need to bother with visualization, e.g. dynamically update display strings or draw on canvases. This method delegates to cEnvir::isGUI(). )docstring" ); py_cComponent.def( "getDisplayString", &omnetpp::cComponent::getDisplayString, R"docstring( Returns the display string which defines presentation when the module is displayed as a submodule in a compound module graphics. )docstring", pybind11::return_value_policy::reference ); py_cComponent.def( "setDisplayString", &omnetpp::cComponent::setDisplayString, R"docstring( Shortcut to `getDisplayString().set(dispstr)` )docstring", pybind11::arg("dispstr") ); py_cComponent.def( "bubble", &omnetpp::cComponent::bubble, R"docstring( When the models is running under Tkenv or Qtenv, it displays the given text in the network graphics, as a bubble above the module's icon. )docstring", pybind11::arg("text") ); py_cComponent.def( "recordStatistic", pybind11::overload_cast<omnetpp::cStatistic *, const char *>(&omnetpp::cComponent::recordStatistic), R"docstring( Records the given statistics into the scalar result file. Delegates to cStatistic::recordAs(). Note that if the statistics object is a histogram, this operation may invoke its transform() method. )docstring", pybind11::arg("stats"), pybind11::arg("unit") = nullptr ); py_cComponent.def( "recordStatistic", pybind11::overload_cast<const char *, omnetpp::cStatistic *, const char *>(&omnetpp::cComponent::recordStatistic), R"docstring( Records the given statistics into the scalar result file. Delegates to cStatistic::recordAs(). Note that if the statistics object is a histogram, this operation may invoke its transform() method. )docstring", pybind11::arg("name"), pybind11::arg("stats"), pybind11::arg("unit") = nullptr ); }
38.695887
127
0.646315
ranarashadmahmood
188deba36441ae6ebeafde6fc6f303409baa2ba8
451
cpp
C++
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
9
2018-07-21T00:30:35.000Z
2021-09-04T02:54:11.000Z
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
null
null
null
Engine/Source/Built-in/Script/S_LookAt.cpp
Aredhele/OOM-Engine
e52f706d17f1867f575a85ba5b87b4cc34a7fa97
[ "MIT" ]
1
2021-12-03T14:12:41.000Z
2021-12-03T14:12:41.000Z
/// \file S_LookAt.cpp /// \date 06/08/2018 /// \project OOM-Engine /// \package Composite /// \author Vincent STEHLY--CALISTO #include "SDK/SDK.hpp" /*virtual */ void S_LookAt::Start() { GetTransform()->LookAt(mp_target->GetTransform()); } /*virtual */ void S_LookAt::Update() { GetTransform()->LookAt(mp_target->GetTransform()); } void S_LookAt::SetTarget(Oom::CGameObject* p_game_object) { mp_target = p_game_object; }
19.608696
57
0.660754
Aredhele
18971363691c792d79e615d8045be24b56a25d4c
391
hpp
C++
src/perfmon/collect.hpp
zadcha/rethinkdb
bb4f5cc28242dc1e29e9a46a8a931ec54420070c
[ "Apache-2.0" ]
21,684
2015-01-01T03:42:20.000Z
2022-03-30T13:32:44.000Z
src/perfmon/collect.hpp
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
4,067
2015-01-01T00:04:51.000Z
2022-03-30T13:42:56.000Z
src/perfmon/collect.hpp
RethonkDB/rethonkdb
8c9c1ddc71b1b891fdb8aad7ca5891fc036b80ee
[ "Apache-2.0" ]
1,901
2015-01-01T21:05:59.000Z
2022-03-21T08:14:25.000Z
// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef PERFMON_COLLECT_HPP_ #define PERFMON_COLLECT_HPP_ #include "perfmon/core.hpp" /* `perfmon_get_stats()` collects all the stats about the server and puts them * into the `ql::datum_t` object. It must be run in a coroutine and it * blocks until it is done. */ ql::datum_t perfmon_get_stats(); #endif // PERFMON_COLLECT_HPP_
27.928571
78
0.759591
zadcha
1897978d06090c03b05b161c0623079c38bab094
1,416
hpp
C++
android-31/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/os/health/HealthStats.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" namespace android::os::health { class TimerStat; } class JString; namespace android::os::health { class HealthStats : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit HealthStats(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} HealthStats(QJniObject obj); // Constructors // Methods JString getDataType() const; jlong getMeasurement(jint arg0) const; jint getMeasurementKeyAt(jint arg0) const; jint getMeasurementKeyCount() const; JObject getMeasurements(jint arg0) const; jint getMeasurementsKeyAt(jint arg0) const; jint getMeasurementsKeyCount() const; JObject getStats(jint arg0) const; jint getStatsKeyAt(jint arg0) const; jint getStatsKeyCount() const; android::os::health::TimerStat getTimer(jint arg0) const; jint getTimerCount(jint arg0) const; jint getTimerKeyAt(jint arg0) const; jint getTimerKeyCount() const; jlong getTimerTime(jint arg0) const; JObject getTimers(jint arg0) const; jint getTimersKeyAt(jint arg0) const; jint getTimersKeyCount() const; jboolean hasMeasurement(jint arg0) const; jboolean hasMeasurements(jint arg0) const; jboolean hasStats(jint arg0) const; jboolean hasTimer(jint arg0) const; jboolean hasTimers(jint arg0) const; }; } // namespace android::os::health
27.764706
152
0.738701
YJBeetle
1899978de2f05a70559f83b02de8f3c37ae30dd9
8,215
cpp
C++
mozilla/gfx/2d/NativeFontResourceDWrite.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
5
2016-12-20T15:48:05.000Z
2020-05-01T20:12:09.000Z
mozilla/gfx/2d/NativeFontResourceDWrite.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
null
null
null
mozilla/gfx/2d/NativeFontResourceDWrite.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
2
2016-12-20T15:48:13.000Z
2019-12-10T15:15:05.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "NativeFontResourceDWrite.h" #include <unordered_map> #include "DrawTargetD2D.h" #include "Logging.h" #include "mozilla/RefPtr.h" namespace mozilla { namespace gfx { static Atomic<uint64_t> sNextFontFileKey; static std::unordered_map<uint64_t, IDWriteFontFileStream*> sFontFileStreams; class DWriteFontFileLoader : public IDWriteFontFileLoader { public: DWriteFontFileLoader() { } // IUnknown interface IFACEMETHOD(QueryInterface)(IID const& iid, OUT void** ppObject) { if (iid == __uuidof(IDWriteFontFileLoader)) { *ppObject = static_cast<IDWriteFontFileLoader*>(this); return S_OK; } else if (iid == __uuidof(IUnknown)) { *ppObject = static_cast<IUnknown*>(this); return S_OK; } else { return E_NOINTERFACE; } } IFACEMETHOD_(ULONG, AddRef)() { return 1; } IFACEMETHOD_(ULONG, Release)() { return 1; } // IDWriteFontFileLoader methods /** * Important! Note the key here has to be a uint64_t that will have been * generated by incrementing sNextFontFileKey. */ virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey(void const* fontFileReferenceKey, UINT32 fontFileReferenceKeySize, OUT IDWriteFontFileStream** fontFileStream); /** * Gets the singleton loader instance. Note that when using this font * loader, the key must be a uint64_t that has been generated by incrementing * sNextFontFileKey. * Also note that this is _not_ threadsafe. */ static IDWriteFontFileLoader* Instance() { if (!mInstance) { mInstance = new DWriteFontFileLoader(); DrawTargetD2D::GetDWriteFactory()-> RegisterFontFileLoader(mInstance); } return mInstance; } private: static IDWriteFontFileLoader* mInstance; }; class DWriteFontFileStream : public IDWriteFontFileStream { public: /** * Used by the FontFileLoader to create a new font stream, * this font stream is created from data in memory. The memory * passed may be released after object creation, it will be * copied internally. * * @param aData Font data */ DWriteFontFileStream(uint8_t *aData, uint32_t aSize, uint64_t aFontFileKey); ~DWriteFontFileStream(); // IUnknown interface IFACEMETHOD(QueryInterface)(IID const& iid, OUT void** ppObject) { if (iid == __uuidof(IDWriteFontFileStream)) { *ppObject = static_cast<IDWriteFontFileStream*>(this); return S_OK; } else if (iid == __uuidof(IUnknown)) { *ppObject = static_cast<IUnknown*>(this); return S_OK; } else { return E_NOINTERFACE; } } IFACEMETHOD_(ULONG, AddRef)() { ++mRefCnt; return mRefCnt; } IFACEMETHOD_(ULONG, Release)() { --mRefCnt; if (mRefCnt == 0) { delete this; return 0; } return mRefCnt; } // IDWriteFontFileStream methods virtual HRESULT STDMETHODCALLTYPE ReadFileFragment(void const** fragmentStart, UINT64 fileOffset, UINT64 fragmentSize, OUT void** fragmentContext); virtual void STDMETHODCALLTYPE ReleaseFileFragment(void* fragmentContext); virtual HRESULT STDMETHODCALLTYPE GetFileSize(OUT UINT64* fileSize); virtual HRESULT STDMETHODCALLTYPE GetLastWriteTime(OUT UINT64* lastWriteTime); private: std::vector<uint8_t> mData; uint32_t mRefCnt; uint64_t mFontFileKey; }; IDWriteFontFileLoader* DWriteFontFileLoader::mInstance = nullptr; HRESULT STDMETHODCALLTYPE DWriteFontFileLoader::CreateStreamFromKey(const void *fontFileReferenceKey, UINT32 fontFileReferenceKeySize, IDWriteFontFileStream **fontFileStream) { if (!fontFileReferenceKey || !fontFileStream) { return E_POINTER; } uint64_t fontFileKey = *static_cast<const uint64_t*>(fontFileReferenceKey); auto found = sFontFileStreams.find(fontFileKey); if (found == sFontFileStreams.end()) { *fontFileStream = nullptr; return E_FAIL; } found->second->AddRef(); *fontFileStream = found->second; return S_OK; } DWriteFontFileStream::DWriteFontFileStream(uint8_t *aData, uint32_t aSize, uint64_t aFontFileKey) : mRefCnt(0) , mFontFileKey(aFontFileKey) { mData.resize(aSize); memcpy(&mData.front(), aData, aSize); } DWriteFontFileStream::~DWriteFontFileStream() { sFontFileStreams.erase(mFontFileKey); } HRESULT STDMETHODCALLTYPE DWriteFontFileStream::GetFileSize(UINT64 *fileSize) { *fileSize = mData.size(); return S_OK; } HRESULT STDMETHODCALLTYPE DWriteFontFileStream::GetLastWriteTime(UINT64 *lastWriteTime) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE DWriteFontFileStream::ReadFileFragment(const void **fragmentStart, UINT64 fileOffset, UINT64 fragmentSize, void **fragmentContext) { // We are required to do bounds checking. if (fileOffset + fragmentSize > mData.size()) { return E_FAIL; } // truncate the 64 bit fileOffset to size_t sized index into mData size_t index = static_cast<size_t>(fileOffset); // We should be alive for the duration of this. *fragmentStart = &mData[index]; *fragmentContext = nullptr; return S_OK; } void STDMETHODCALLTYPE DWriteFontFileStream::ReleaseFileFragment(void *fragmentContext) { } /* static */ already_AddRefed<NativeFontResourceDWrite> NativeFontResourceDWrite::Create(uint8_t *aFontData, uint32_t aDataLength, bool aNeedsCairo) { IDWriteFactory *factory = DrawTargetD2D::GetDWriteFactory(); if (!factory) { gfxWarning() << "Failed to get DWrite Factory."; return nullptr; } uint64_t fontFileKey = sNextFontFileKey++; RefPtr<IDWriteFontFileStream> ffsRef = new DWriteFontFileStream(aFontData, aDataLength, fontFileKey); sFontFileStreams[fontFileKey] = ffsRef; RefPtr<IDWriteFontFile> fontFile; HRESULT hr = factory->CreateCustomFontFileReference(&fontFileKey, sizeof(fontFileKey), DWriteFontFileLoader::Instance(), getter_AddRefs(fontFile)); if (FAILED(hr)) { gfxWarning() << "Failed to load font file from data!"; return nullptr; } BOOL isSupported; DWRITE_FONT_FILE_TYPE fileType; DWRITE_FONT_FACE_TYPE faceType; UINT32 numberOfFaces; hr = fontFile->Analyze(&isSupported, &fileType, &faceType, &numberOfFaces); if (FAILED(hr) || !isSupported) { gfxWarning() << "Font file is not supported."; return nullptr; } RefPtr<NativeFontResourceDWrite> fontResource = new NativeFontResourceDWrite(factory, fontFile.forget(), faceType, numberOfFaces, aNeedsCairo); return fontResource.forget(); } already_AddRefed<ScaledFont> NativeFontResourceDWrite::CreateScaledFont(uint32_t aIndex, uint32_t aGlyphSize) { if (aIndex >= mNumberOfFaces) { gfxWarning() << "Font face index is too high for font resource."; return nullptr; } IDWriteFontFile *fontFile = mFontFile; RefPtr<IDWriteFontFace> fontFace; if (FAILED(mFactory->CreateFontFace(mFaceType, 1, &fontFile, aIndex, DWRITE_FONT_SIMULATIONS_NONE, getter_AddRefs(fontFace)))) { gfxWarning() << "Failed to create font face from font file data."; return nullptr; } RefPtr<ScaledFontBase> scaledFont = new ScaledFontDWrite(fontFace, aGlyphSize); #ifdef USE_CAIRO_SCALED_FONT if (mNeedsCairo && !scaledFont->PopulateCairoScaledFont()) { gfxWarning() << "Unable to create cairo scaled font DWrite font."; return nullptr; } #endif return scaledFont.forget(); } } // gfx } // mozilla
28.425606
81
0.672794
naver
189f03d25cf4592fb21bed78f0db9eed2738ead9
696
cpp
C++
test/std/numerics/numarray/template.valarray/valarray.members/sum.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
test/std/numerics/numarray/template.valarray/valarray.members/sum.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
test/std/numerics/numarray/template.valarray/valarray.members/sum.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <valarray> // template<class T> class valarray; // value_type sum() const; #include <valarray> #include <cassert> int main() { { typedef double T; T a1[] = {1.5, 2.5, 3, 4, 5.5}; const unsigned N1 = sizeof(a1)/sizeof(a1[0]); std::valarray<T> v1(a1, N1); assert(v1.sum() == 16.5); } }
24
80
0.441092
AOSiP
18a1a13ed16965bcbc7647a731537a22cba44e44
5,197
cpp
C++
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
Arduboy_audio.cpp
Lswbanban/RickArdurous
fc716b6b201c5535f8a7660309d9524f2dca2d25
[ "DOC" ]
null
null
null
#include "CustomArduboy.h" #include "Arduboy_audio.h" const byte PROGMEM tune_pin_to_timer_PGM[] = { 3, 1 }; volatile byte *_tunes_timer1_pin_port; volatile byte _tunes_timer1_pin_mask; volatile byte *_tunes_timer3_pin_port; volatile byte _tunes_timer3_pin_mask; byte _tune_pins[AVAILABLE_TIMERS]; #define LOWEST_NOTE 52 #define FIRST_NOTE_IN_INT_ARRAY 52 #define HIGHEST_NOTE 82 // Table of midi note frequencies * 2 // They are times 2 for greater accuracy, yet still fits in a word. // Generated from Excel by =ROUND(2*440/32*(2^((x-9)/12)),0) for 0<x<128 // The lowest notes might not work, depending on the Arduino clock frequency // Ref: http://www.phy.mtu.edu/~suits/notefreqs.html //const uint8_t PROGMEM _midi_byte_note_frequencies[] = { //16,17,18,19,21,22,23,24,26,28, // note 0 to 9 //29,31,33,35,37,39,41,44,46,49, // note 10 to 19 //52,55,58,62,65,69,73,78,82,87, // note 20 to 29 //92,98,104,110,117,123,131,139,147,156, // note 30 to 39 //165,175,185,196,208,220,233,247 // note 40 to 47 //}; const unsigned int PROGMEM _midi_word_note_frequencies[] = { //262,277,294, //note 48 to 50 /*311,*/330,349,370,392,415,440,466,494,523, //note 51 to 60 554,587,622,659,698,740,784,831,880,932, //note 61 to 70 988,1047,1109,1175,1245,1319,1397,1480,1568,1661, //note 71 to 80 1760,1865//,1976,2093,2217,2349,2489,2637,2794,2960, //note 81 to 90 //3136,3322,3520,3729,3951,4186,4435,4699,4978,5274, //note 91 to 100 //5588,5920,6272,6645,7040,7459,7902,8372,8870,9397, //note 101 to 110 //9956,10548,11175,11840,12544,13290,14080,14917,15804,16744, //note 111 to 120 //17740,18795,19912,21096,22351,23680,25088 //note 121 to 127 }; unsigned int NoteToFrequency(byte note) { return pgm_read_word(_midi_word_note_frequencies + note - FIRST_NOTE_IN_INT_ARRAY); } /* AUDIO */ void ArduboyAudio::on() { power_timer1_enable(); power_timer3_enable(); } void ArduboyAudio::off() { power_timer1_disable(); power_timer3_disable(); } void ArduboyAudio::begin() { on(); } /* TUNES */ void ArduboyTunes::initChannel(byte pin, byte chan) { byte timer_num; // we are all out of timers if (chan >= AVAILABLE_TIMERS) return; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); _tune_pins[chan] = pin; pinMode(pin, OUTPUT); switch (timer_num) { case 1: // 16 bit timer TCCR1A = 0; TCCR1B = 0; bitWrite(TCCR1B, WGM12, 1); bitWrite(TCCR1B, CS10, 1); _tunes_timer1_pin_port = portOutputRegister(digitalPinToPort(pin)); _tunes_timer1_pin_mask = digitalPinToBitMask(pin); break; case 3: // 16 bit timer TCCR3A = 0; TCCR3B = 0; bitWrite(TCCR3B, WGM32, 1); bitWrite(TCCR3B, CS30, 1); _tunes_timer3_pin_port = portOutputRegister(digitalPinToPort(pin)); _tunes_timer3_pin_mask = digitalPinToBitMask(pin); playNote(0, 60); /* start and stop channel 0 (timer 3) on middle C so wait/delay works */ stopNote(0); break; } } void ArduboyTunes::playNote(byte chan, byte note) { byte timer_num; byte prescalar_bits; unsigned int frequency2; /* frequency times 2 */ unsigned long ocr; // we can't plan on a channel that does not exist if (chan >= AVAILABLE_TIMERS) return; // we only have frequencies for a certain range of notes if ((note < LOWEST_NOTE) || (note > HIGHEST_NOTE)) return; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); //if (note < 48) // frequency2 = pgm_read_byte(_midi_byte_note_frequencies + note - LOWEST_NOTE); //else frequency2 = pgm_read_word(_midi_word_note_frequencies + note - FIRST_NOTE_IN_INT_ARRAY); //****** 16-bit timer ********* // two choices for the 16 bit timers: ck/1 or ck/64 ocr = F_CPU / frequency2 - 1; prescalar_bits = 0b001; if (ocr > 0xffff) { ocr = F_CPU / frequency2 / 64 - 1; prescalar_bits = 0b011; } // Set the OCR for the given timer, then turn on the interrupts switch (timer_num) { case 1: TCCR1B = (TCCR1B & 0b11111000) | prescalar_bits; OCR1A = ocr; bitWrite(TIMSK1, OCIE1A, 1); break; case 3: TCCR3B = (TCCR3B & 0b11111000) | prescalar_bits; OCR3A = ocr; bitWrite(TIMSK3, OCIE3A, 1); break; } } void ArduboyTunes::stopNote(byte chan) { byte timer_num; timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); switch (timer_num) { case 1: TIMSK1 &= ~(1 << OCIE1A); // disable the interrupt *_tunes_timer1_pin_port &= ~(_tunes_timer1_pin_mask); // keep pin low after stop break; case 3: *_tunes_timer3_pin_port &= ~(_tunes_timer3_pin_mask); // keep pin low after stop break; } } void ArduboyTunes::closeChannels(void) { byte timer_num; for (uint8_t chan=0; chan < AVAILABLE_TIMERS; chan++) { timer_num = pgm_read_byte(tune_pin_to_timer_PGM + chan); switch (timer_num) { case 1: TIMSK1 &= ~(1 << OCIE1A); break; case 3: TIMSK3 &= ~(1 << OCIE3A); break; } digitalWrite(_tune_pins[chan], 0); } } // TIMER 1 ISR(TIMER1_COMPA_vect) { *_tunes_timer1_pin_port ^= _tunes_timer1_pin_mask; // toggle the pin } // TIMER 3 ISR(TIMER3_COMPA_vect) { }
28.091892
96
0.675005
Lswbanban
18a4b1a7b26df9f23cf9cc71422069083e0da9c8
2,646
cpp
C++
component/oai-amf/src/ngap/ngapIEs/GlobalgNBId.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/ngap/ngapIEs/GlobalgNBId.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/ngap/ngapIEs/GlobalgNBId.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file \brief \author Keliang DU, BUPT \date 2020 \email: contact@openairinterface.org */ #include "GlobalgNBId.hpp" #include <iostream> using namespace std; namespace ngap { //------------------------------------------------------------------------------ GlobalgNBId::GlobalgNBId() { plmnId = NULL; gNB_ID = NULL; } //------------------------------------------------------------------------------ GlobalgNBId::~GlobalgNBId() {} //------------------------------------------------------------------------------ void GlobalgNBId::setGlobalgNBId(PlmnId* plmn, GNB_ID* gnbid) { plmnId = plmn; gNB_ID = gnbid; } //------------------------------------------------------------------------------ bool GlobalgNBId::encode2GlobalgNBId(Ngap_GlobalGNB_ID_t* globalgnbid) { if (!plmnId->encode2octetstring(globalgnbid->pLMNIdentity)) return false; if (!gNB_ID->encode2bitstring(globalgnbid->gNB_ID)) return false; return true; } //------------------------------------------------------------------------------ bool GlobalgNBId::decodefromGlobalgNBId(Ngap_GlobalGNB_ID_t* globalgnbid) { if (plmnId == nullptr) plmnId = new PlmnId(); if (gNB_ID == nullptr) gNB_ID = new GNB_ID(); if (!plmnId->decodefromoctetstring(globalgnbid->pLMNIdentity)) return false; if (!gNB_ID->decodefrombitstring(globalgnbid->gNB_ID)) return false; return true; } //------------------------------------------------------------------------------ void GlobalgNBId::getGlobalgNBId(PlmnId*& plmn, GNB_ID*& gnbid) { if (plmnId) plmn = plmnId; if (gNB_ID) gnbid = gNB_ID; } } // namespace ngap
35.28
81
0.583522
kukkalli
18a67c1af6a1acb3f30fa8032f9d7e1c055c7db6
1,675
cpp
C++
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
src/Homography/Triangulation.cpp
diegomazala/Homography
545e7456284656f45aa77121baf9f54a8ae8557c
[ "MIT" ]
null
null
null
#include "Triangulation.h" #include <iostream> Triangulation::Triangulation( const Eigen::MatrixXd& P0, const Eigen::MatrixXd& P1, const Eigen::VectorXd& x0, const Eigen::VectorXd& x1): P(P0, P1), x(x0, x1) { } Triangulation::Triangulation(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& _P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& _x): P(_P), x(_x) { } Eigen::VectorXd Triangulation::solve() const { return Triangulation::solve(P, x); } Eigen::VectorXd Triangulation::solve(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& x) { Eigen::MatrixXd A = buildMatrixA(P, x); //std::cout << "A:\n" << A << std::endl << std::endl; Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinV); Eigen::VectorXd X = svd.matrixV().rightCols(1); X /= X(3); return X; } Eigen::MatrixXd Triangulation::buildMatrixA(const std::pair<Eigen::MatrixXd, Eigen::MatrixXd>& P, const std::pair<Eigen::VectorXd, Eigen::VectorXd>& x) { Eigen::MatrixXd A(4, 4); #if 0 A.row(0) = x.first.x() * P.first.row(2) - P.first.row(0); A.row(1) = x.first.y() * P.first.row(2) - P.first.row(1); A.row(2) = x.second.x() * P.second.row(2) - P.second.row(0); A.row(3) = x.second.y() * P.second.row(2) - P.second.row(1); #else A.row(0) = (x.first.x() * P.first.row(2) - P.first.row(0)).normalized(); A.row(1) = (x.first.y() * P.first.row(2) - P.first.row(1)).normalized(); A.row(2) = (x.second.x() * P.second.row(2) - P.second.row(0)).normalized(); A.row(3) = (x.second.y() * P.second.row(2) - P.second.row(1)).normalized(); #endif return A; }
24.275362
97
0.619701
diegomazala
18aabab0761eaa85dc96d77a702af78561d28097
8,874
cpp
C++
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
3
2020-11-23T23:53:30.000Z
2021-12-26T16:14:23.000Z
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
4
2020-12-05T17:58:31.000Z
2020-12-13T00:54:28.000Z
WeatherModel/WeatherModel.cpp
patrickn/QPhotoFrame
18b5cccc1e56d6561b64505e1395faa20261056e
[ "MIT" ]
1
2021-09-24T21:04:12.000Z
2021-09-24T21:04:12.000Z
//----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QNetworkConfigurationManager> #include <QNetworkReply> #include <QProcessEnvironment> #include <QUrlQuery> #include "Common/Logging.h" #include "WeatherModel.h" //----------------------------------------------------------------------------- static const double ZERO_KELVIN = 273.15; WeatherModel::WeatherModel(QObject* parent) : QObject(parent), _src(nullptr), _nam(nullptr), _ns(nullptr), _nErrors(0), _minMsBeforeNewRequest(baseMsBeforeNewRequest), m_weatherDataAppId(QProcessEnvironment::systemEnvironment().value("QPF_WEATHERDATA_APPID")) { if (m_weatherDataAppId.isEmpty()) { qCCritical(weatherModelLog()) << "Critical error: QPF_WEATHERDATA_APPID not set. Unable to retrieve weather data."; } _delayedCityRequestTimer.setSingleShot(true); _delayedCityRequestTimer.setInterval(1000); // 1 s _requestNewWeatherTimer.setSingleShot(false); _requestNewWeatherTimer.setInterval(20 * 60 * 1000); // 20 mins _throttle.invalidate(); connect(&_delayedCityRequestTimer, SIGNAL(timeout()), this, SLOT(queryCity())); connect(&_requestNewWeatherTimer, SIGNAL(timeout()), this, SLOT(refreshWeather())); _requestNewWeatherTimer.start(); _nam = new QNetworkAccessManager; QNetworkConfigurationManager ncm; _ns = new QNetworkSession(ncm.defaultConfiguration(), this); connect(_ns, SIGNAL(opened()), this, SLOT(networkSessionOpened())); if (_ns->isOpen()) { this->networkSessionOpened(); } _ns->open(); } WeatherModel::~WeatherModel() { _ns->close(); if (_src) { _src->stopUpdates(); } } bool WeatherModel::ready() const { return _ready; } bool WeatherModel::hasSource() const { return (_src != nullptr); } void WeatherModel::hadError(bool tryAgain) { qCDebug(weatherModelLog) << "hadError, will " << (tryAgain ? "" : "not ") << "rety"; _throttle.start(); if (_nErrors < 10) { ++_nErrors; } _minMsBeforeNewRequest = (_nErrors + 1) * baseMsBeforeNewRequest; if (tryAgain) { _delayedCityRequestTimer.start(); } } void WeatherModel::refreshWeather() { if (_city.isEmpty()) { qCDebug(weatherModelLog) << "Cannot refresh weather, no city"; return; } qCDebug(weatherModelLog) << "refreshing weather"; QUrl url("http://api.openweathermap.org/data/2.5/weather"); QUrlQuery query; query.addQueryItem("q", _city); query.addQueryItem("mode", "json"); query.addQueryItem("APPID", m_weatherDataAppId); url.setQuery(query); QNetworkReply* rep = _nam->get(QNetworkRequest(url)); connect(rep, &QNetworkReply::finished, this, [this, rep]() { handleWeatherNetworkData(rep); }); } bool WeatherModel::hasValidCity() const { return (!(_city.isEmpty()) && _city.size() > 1 && _city != ""); } bool WeatherModel::hasValidWeather() const { return hasValidCity() && (!(_now.weatherIcon().isEmpty()) && (_now.weatherIcon().size() > 1) && _now.weatherIcon() != ""); } QString WeatherModel::city() const { return _city; } void WeatherModel::setCity(const QString& value) { _city = value; emit cityChanged(); refreshWeather(); } WeatherData* WeatherModel::weather() const { return const_cast<WeatherData*>(&(_now)); } void WeatherModel::queryCity() { // Don't update more than once a minute to keep server load low if (_throttle.isValid() && _throttle.elapsed() < _minMsBeforeNewRequest) { qCDebug(weatherModelLog) << "delaying query of city"; if (_delayedCityRequestTimer.isActive()) { _delayedCityRequestTimer.start(); } } qCDebug(weatherModelLog) << "requested city"; _throttle.start(); _minMsBeforeNewRequest = (_nErrors + 1) * baseMsBeforeNewRequest; QString latitude, longitude; longitude.setNum(_coord.longitude()); latitude.setNum(_coord.latitude()); QUrl url("http://api.openweathermap.org/data/2.5/weather"); QUrlQuery query; query.addQueryItem("lat", latitude); query.addQueryItem("lon", longitude); query.addQueryItem("mode", "json"); query.addQueryItem("APPID", m_weatherDataAppId); url.setQuery(query); qCDebug(weatherModelLog) << "submitting API request"; QNetworkReply* rep = _nam->get(QNetworkRequest(url)); // connect up the signal right away connect(rep, &QNetworkReply::finished, this, [this, rep]() { handleGeoNetworkData(rep); }); } void WeatherModel::networkSessionOpened() { _src = QGeoPositionInfoSource::createDefaultSource(this); if (_src) { connect(_src, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); connect(_src, SIGNAL(error(QGeoPositionInfoSource::Error)), this, SLOT(positionError(QGeoPositionInfoSource::Error))); _src->startUpdates(); } else { qCDebug(weatherModelLog) << "Could not create default source."; } } void WeatherModel::positionUpdated(QGeoPositionInfo gpsPos) { qCDebug(weatherModelLog) << "WeatherModel::positionUpdated(...)"; _coord = gpsPos.coordinate(); queryCity(); } void WeatherModel::positionError(QGeoPositionInfoSource::Error e) { qCDebug(weatherModelLog) << "WeatherModel::positionError(...): " << e; } void WeatherModel::handleGeoNetworkData(QNetworkReply* networkReply) { qCDebug(weatherModelLog) << "WeatherModel::handleGeoNetworkData(...)"; if (!networkReply) { hadError(false); // should retry? return; } if (!networkReply->error()) { _nErrors = 0; if (!_throttle.isValid()) { _throttle.start(); } _minMsBeforeNewRequest = baseMsBeforeNewRequest; //convert coordinates to city name QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); QJsonObject jo = document.object(); QJsonValue jv = jo.value(QStringLiteral("name")); const QString city = jv.toString(); qCDebug(weatherModelLog) << "got city: " << city; if (city != _city) { _city = city; emit cityChanged(); refreshWeather(); } } else { hadError(true); } networkReply->deleteLater(); } static QString niceTemperatureString(double t) { return QString::number((t - ZERO_KELVIN), 'f', 1)/* + QChar(0xB0)*/; } void WeatherModel::handleWeatherNetworkData(QNetworkReply* networkReply) { qCDebug(weatherModelLog) << "WeatherModel::handleWeatherNetworkData(...)"; if (!networkReply) { return; } if (!networkReply->error()) { foreach (WeatherData* inf, _forecast) { delete inf; } _forecast.clear(); QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll()); if (document.isObject()) { QJsonObject obj = document.object(); QJsonObject tempObject; QJsonValue val; if (obj.contains(QStringLiteral("weather"))) { val = obj.value(QStringLiteral("weather")); QJsonArray weatherArray = val.toArray(); val = weatherArray.at(0); tempObject = val.toObject(); _now.setWeatherDescription(tempObject.value(QStringLiteral("description")).toString()); _now.setWeatherIcon(tempObject.value("icon").toString()); } if (obj.contains(QStringLiteral("main"))) { val = obj.value(QStringLiteral("main")); tempObject = val.toObject(); val = tempObject.value(QStringLiteral("temp")); _now.setTemperature(niceTemperatureString(val.toDouble())); } } } networkReply->deleteLater(); //retrieve the forecast // QUrl url("http://api.openweathermap.org/data/2.5/forecast/daily"); // QUrlQuery query; // query.addQueryItem("q", d->city); // query.addQueryItem("mode", "json"); // query.addQueryItem("cnt", "5"); // query.addQueryItem("APPID", d->app_ident); // url.setQuery(query); // QNetworkReply *rep = d->nam->get(QNetworkRequest(url)); // // connect up the signal right away // connect(rep, &QNetworkReply::finished, this, [this, rep]() { // handleForecastNetworkData(rep); // }); // Move this to handleForecastNetworkData emit weatherChanged(); } void WeatherModel::handleForecastNetworkData(QNetworkReply* networkReply) { Q_UNUSED(networkReply) qCDebug(weatherModelLog) << "WeatherModel::handleForecastNetworkData(...)"; }
29.878788
126
0.630156
patrickn
18ad9c5af589eab8c064ad9cb769055557a78b39
1,614
cpp
C++
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
05_WalkTester/Source/main.cpp
bugsbycarlin/SecretSalsa
b4b15e7ba14cdc2be9aad4d111e710ed0ec507ee
[ "MIT" ]
null
null
null
/* Secret Salsa Matthew Carlin Copyright 2019 */ #include "honey.h" #include <string> #include <array> using namespace Honey; using namespace std; position player_position; int step_width; float frame_delay; int current_frame; bool quit = false; void initialize() { player_position = { hot_config.getInt("walk", "starting_x"), hot_config.getInt("walk", "starting_y") }; step_width = hot_config.getInt("walk", "step_width"); frame_delay = hot_config.getFloat("walk", "frame_delay"); graphics.addImages("Art/", { "Walk1", "Walk2", "Walk3", "Walk4", }); current_frame = 4; } void logic() { if (input.keyPressed("quit") > 0) { quit = true; } if (input.threeQuickKey("escape")) { quit = true; } if (!timing.check("animate") || timing.since("animate") > frame_delay) { current_frame += 1; if (current_frame > 4) current_frame = 1; if (current_frame == 2 || current_frame == 4) { player_position.x += 85; } else { player_position.x += 5; } timing.mark("animate"); } if (player_position.x > hot_config.getInt("layout", "screen_width")) { player_position.x = -250; } } void render() { graphics.clearScreen("#EEEEEE"); graphics.setColor("#FFFFFF", 1.0); graphics.drawImage( "Walk" + to_string(current_frame), player_position.x, player_position.y ); } int main(int argc, char* args[]) { StartHoney("Secret Salsa WorldBuilder"); graphics.draw2D(); initialize(); while (!quit) { input.processInput(); logic(); render(); graphics.updateDisplay(); } }
16.989474
74
0.627633
bugsbycarlin
18ae5a2da6dfcf3eff7523efdd669f7314a3dc93
8,356
cpp
C++
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
6
2022-03-24T15:40:03.000Z
2022-03-30T09:40:20.000Z
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
7
2022-03-24T18:53:52.000Z
2022-03-30T10:15:50.000Z
framework/imp/sys/common/ByteBuffer.cpp
dterletskiy/carpc
c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5
[ "MIT" ]
1
2022-03-20T21:22:09.000Z
2022-03-20T21:22:09.000Z
#include "api/sys/common/ByteBuffer.hpp" #include "api/sys/trace/Trace.hpp" #define CLASS_ABBR "B_BUFFER" using namespace carpc; ByteBuffer::ByteBuffer( const size_t capacity ) { if( true == allocate( capacity ) ) fill( ); } ByteBuffer::ByteBuffer( const void* p_buffer, const size_t size ) { if( false == allocate( size ) ) { SYS_ERR( "unable to allocate %zu bytes", size ); return; } if( false == push( p_buffer, size ) ) { SYS_ERR( "unable to fullfil buffer" ); return; } // SYS_INF( "created: " ); // dump( ); } ByteBuffer::ByteBuffer( const ByteBuffer& buffer ) { if( false == allocate( buffer.m_size ) ) { SYS_ERR( "unable to allocate %zu bytes", buffer.m_size ); return; } if( false == push( buffer ) ) { SYS_ERR( "unable to fullfil buffer" ); return; } // SYS_INF( "created: " ); // dump( ); } ByteBuffer::~ByteBuffer( ) { reset( ); } void ByteBuffer::dump( ) const { // leads to core dump // std::stringstream ss; // for( size_t i = 0; i < m_size; ++i ) // ss << std::setfill('0') << std::setw(2) << std::showbase << std::hex << static_cast< size_t >( mp_buffer[i] ) << " "; // SYS_INF( "%s", ss.str( ).c_str( ) ); for( size_t i = 0; i < m_size; ++i ) printf( "%#x ", static_cast< uint8_t* >( mp_buffer )[i] ); printf( "\n" ); } void ByteBuffer::info( ) const { SYS_INF( "address: %p / capacity: %zu / size: %zu", mp_buffer, m_capacity, m_size ); } void ByteBuffer::fill( const char symbol ) { memset( mp_buffer, symbol, m_capacity ); } bool ByteBuffer::allocate( const size_t capacity ) { // Nothing to allocate if( 0 == capacity ) return false; // Buffer already allocated if( nullptr != mp_buffer ) return false; mp_buffer = malloc( capacity ); // Allocate error if( nullptr == mp_buffer ) return false; m_capacity = capacity; return true; } bool ByteBuffer::reallocate( const size_t capacity, const bool is_store ) { // Nothing to allocate if( 0 == capacity ) return false; // What is the sense of reallocation? if( capacity == m_capacity ) return false; // Allocating buffer because is was not allocated before if( nullptr == mp_buffer ) return allocate( capacity ); // Storing previous data during reallocation is requested but // current data size is more then requested capacity if( true == is_store && m_size > capacity ) return false; void* p_buffer = malloc( capacity ); // Allocate error if( nullptr == p_buffer ) return false; // Copying current data to new buffer => size will be the same if( true == is_store ) memcpy( p_buffer, mp_buffer, m_size ); // Storing data was not requested => size should be 0 else m_size = 0; free( mp_buffer ); mp_buffer = p_buffer; m_capacity = capacity; return true; } bool ByteBuffer::trancate( ) { if( m_size == m_capacity ) return true; return reallocate( m_size, true ); } void ByteBuffer::reset( ) { if( nullptr != mp_buffer ) free( mp_buffer ); // Reset data mp_buffer = nullptr; m_size = m_capacity = 0; } /***************************************** * * Read / Write buffer methods * ****************************************/ bool ByteBuffer::write( const void* p_buffer, const size_t size, const bool is_reallocate ) { // Nothing to push if( 0 == size ) return false; // Buffer is not allocated if( nullptr == p_buffer ) return false; // Buffer is not allocated if( nullptr == mp_buffer ) return false; // Reallocating buffer is requested with saving prevous content if( ( m_capacity - m_size ) < size ) { if( true == is_reallocate ) { if( false == reallocate( m_size + size, true ) ) return false; } else return false; } memcpy( static_cast< uint8_t* >( mp_buffer ) + m_size, p_buffer, size ); return true; } bool ByteBuffer::read( const void* p_buffer, const size_t size ) { // Not enough data to pop if( size > m_size ) return false; // Nothing to pop if( 0 == size ) return false; // Buffer is not allocated if( nullptr == p_buffer ) return false; // Buffer is not allocated if( nullptr == mp_buffer ) return false; memcpy( const_cast< void* >( p_buffer ), static_cast< uint8_t* >( mp_buffer ) + m_size - size, size ); return true; } /***************************************** * * Push buffer methods * ****************************************/ bool ByteBuffer::push( void* p_buffer, const size_t size, const bool is_reallocate ) { return push( const_cast< const void* >( p_buffer ), size, is_reallocate ); } bool ByteBuffer::push( const void* p_buffer, const size_t size, const bool is_reallocate ) { if( false == write( p_buffer, size, is_reallocate ) ) return false; m_size += size; return true; } bool ByteBuffer::push( const void* const p_buffer, const bool is_reallocate ) { if( false == write( &p_buffer, sizeof( void* ), is_reallocate ) ) return false; m_size += sizeof( void* ); return true; } bool ByteBuffer::push( const std::string& string, const bool is_reallocate ) { const void* p_buffer = static_cast< const void* >( string.c_str( ) ); const size_t size = string.size( ); return push_buffer_with_size( p_buffer, size, is_reallocate ); } bool ByteBuffer::push( const ByteBuffer& _buffer, const bool is_reallocate ) { const void* p_buffer = _buffer.mp_buffer; const size_t size = _buffer.m_size; return push_buffer_with_size( p_buffer, size, is_reallocate ); } bool ByteBuffer::push_buffer_with_size( const void* p_buffer, const size_t size, const bool is_reallocate ) { // Backup buffer state. size_t size_backup = m_size; // It should be possible to store next amount of bytes: content size + size of content. if( ( m_capacity - m_size ) < ( size + sizeof( size ) ) && false == is_reallocate ) return false; // Storing buffer content if( false == push( p_buffer, size, is_reallocate ) ) return false; // Storing size of buffer. In case of error prevoius buffer state will be restored. // In this case stored buffer content will be deleted. if( false == push( size, is_reallocate ) ) { m_size = size_backup; return false; } return true; } /***************************************** * * Pop buffer methods * ****************************************/ bool ByteBuffer::pop( void* p_buffer, const size_t size ) { return pop( const_cast< const void* >( p_buffer ), size ); } bool ByteBuffer::pop( const void* p_buffer, const size_t size ) { if( false == read( p_buffer, size ) ) return false; m_size -= size; return true; } bool ByteBuffer::pop( const void*& p_buffer ) { if( false == read( &p_buffer, sizeof( void* ) ) ) return false; m_size -= sizeof( void* ); return true; } bool ByteBuffer::pop( std::string& string ) { // Backup buffer state. size_t size_backup = m_size; size_t size = 0; // Reading size of string content if( false == pop( size ) ) return false; // Error in case of rest of data in buffer less then size to be read. // push previously poped data to restore previous buffer state. if( size > m_size ) { m_size = size_backup; return false; } char p_buffer[ size + 1 ]; // +1 for termitating '\0' if( false == pop( static_cast< void* >( p_buffer ), size ) ) return false; // Adding termitating '\0' p_buffer[ size + 1 - 1 ] = 0; string = p_buffer; return true; } bool ByteBuffer::pop( ByteBuffer& _buffer ) { // Backup buffer state. size_t size_backup = m_size; size_t size = 0; // Reading size of string content if( false == pop( size ) ) return false; // Error in case of rest of data in buffer less then size to be read. // push previously poped data to restore previous buffer state. if( size > m_size ) { m_size = size_backup; return false; } void* p_buffer = malloc( size ); if( false == pop( p_buffer, size ) ) { free( p_buffer ); return false; } if( false == _buffer.push( p_buffer, size ) ) { free( p_buffer ); return false; } free( p_buffer ); return true; }
23.275766
126
0.61034
dterletskiy
18b16a73f45a3fcb4f32c53f2652ad9362df7854
7,889
hpp
C++
src/serac/physics/utilities/functional/boundary_integral.hpp
LLNL/serac
7fe0c7fa82cff1a7eea65f58ae2cae2e52c01e1a
[ "BSD-3-Clause" ]
64
2020-02-24T21:57:43.000Z
2022-03-17T20:48:40.000Z
src/serac/physics/utilities/functional/boundary_integral.hpp
LLNL/serac
7fe0c7fa82cff1a7eea65f58ae2cae2e52c01e1a
[ "BSD-3-Clause" ]
615
2020-02-24T22:31:14.000Z
2022-03-31T23:50:10.000Z
src/serac/physics/utilities/functional/boundary_integral.hpp
LLNL/serac
7fe0c7fa82cff1a7eea65f58ae2cae2e52c01e1a
[ "BSD-3-Clause" ]
16
2020-04-01T04:55:18.000Z
2022-03-07T19:32:44.000Z
// Copyright (c) 2019-2021, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) /** * @file boundary_integral.hpp * * @brief This file defines a class, BoundaryIntegral, for integrating q-functions against finite element * basis functions on a mesh boundary region. */ #pragma once #include "mfem.hpp" #include "mfem/linalg/dtensor.hpp" #include "serac/physics/utilities/finite_element_state.hpp" #include "serac/physics/utilities/functional/tensor.hpp" #include "serac/physics/utilities/functional/quadrature.hpp" #include "serac/physics/utilities/functional/tuple_arithmetic.hpp" #include "serac/physics/utilities/functional/integral_utilities.hpp" #include "serac/physics/utilities/functional/boundary_integral_kernels.hpp" #if defined(__CUDACC__) #include "serac/physics/utilities/functional/boundary_integral_kernels.cuh" #endif namespace serac { /** * @brief Describes a single boundary integral term in a weak forumulation of a partial differential equation * @tparam spaces A @p std::function -like set of template parameters that describe the test and trial * function spaces, i.e., @p test(trial) * @tparam exec whether or not the calculation and memory will be on the CPU or GPU */ template <typename spaces, ExecutionSpace exec> class BoundaryIntegral { public: using test_space = test_space_t<spaces>; ///< the test function space using trial_space = trial_space_t<spaces>; ///< the trial function space /** * @brief Constructs an @p BoundaryIntegral from a user-provided quadrature function * @tparam dim The dimension of the element (2 for quad, 3 for hex, etc) * @tparam qpt_data_type The type of the data to store for each quadrature point * @param[in] num_elements The number of elements in the mesh * @param[in] J The Jacobians of the element transformations at all quadrature points * @param[in] X The actual (not reference) coordinates of all quadrature points * @param[in] normals The unit normals of all quadrature points * @see mfem::GeometricFactors * @param[in] qf The user-provided quadrature function * @note The @p Dimension parameters are used to assist in the deduction of the dim template parameter */ template <int dim, typename lambda_type, typename qpt_data_type = void> BoundaryIntegral(int num_elements, const mfem::Vector& J, const mfem::Vector& X, const mfem::Vector& normals, Dimension<dim>, lambda_type&& qf) : J_(J), X_(X), normals_(normals) { SLIC_ERROR_ROOT_IF(exec == ExecutionSpace::GPU, "BoundaryIntegral doesn't currently support GPU kernels yet"); constexpr auto geometry = supported_geometries[dim]; constexpr auto Q = std::max(test_space::order, trial_space::order) + 1; constexpr auto quadrature_points_per_element = detail::pow(Q, dim); uint32_t num_quadrature_points = quadrature_points_per_element * uint32_t(num_elements); // these lines of code figure out the argument types that will be passed // into the quadrature function in the finite element kernel. // // we use them to observe the output type and allocate memory to store // the derivative information at each quadrature point using x_t = tensor<double, dim + 1>; using u_du_t = typename detail::lambda_argument<trial_space, dim, dim + 1>::type; using derivative_type = decltype(get_gradient(qf(x_t{}, x_t{}, make_dual(u_du_t{})))); // allocate memory for the derivatives of the q-function at each quadrature point // // Note: ptr's lifetime is managed in an unusual way! It is captured by-value in one of the // lambda functions below to augment the reference count, and extend its lifetime to match // that of the BoundaryIntegral that allocated it. // TODO: change this allocation to use exec, rather than ExecutionSpace::CPU, once // we implement GPU boundary kernels auto ptr = accelerator::make_shared_array<derivative_type, ExecutionSpace::CPU>(num_quadrature_points); size_t n1 = static_cast<size_t>(num_elements); size_t n2 = static_cast<size_t>(quadrature_points_per_element); CPUView<derivative_type, 2> qf_derivatives{ptr.get(), n1, n2}; // this is where we actually specialize the finite element kernel templates with // our specific requirements (element type, test/trial spaces, quadrature rule, q-function, etc). // // std::function's type erasure lets us wrap those specific details inside a function with known signature // // this lambda function captures ptr by-value to extend its lifetime // vvv evaluation_ = [this, ptr, qf_derivatives, num_elements, qf](const mfem::Vector& U, mfem::Vector& R) { boundary_integral::evaluation_kernel<geometry, test_space, trial_space, Q>(U, R, qf_derivatives, J_, X_, normals_, num_elements, qf); }; action_of_gradient_ = [this, qf_derivatives, num_elements](const mfem::Vector& dU, mfem::Vector& dR) { boundary_integral::action_of_gradient_kernel<geometry, test_space, trial_space, Q>(dU, dR, qf_derivatives, J_, num_elements); }; element_gradient_ = [this, qf_derivatives, num_elements](ArrayView<double, 3, exec> K_b) { boundary_integral::element_gradient_kernel<geometry, test_space, trial_space, Q>(K_b, qf_derivatives, J_, num_elements); }; } /** * @brief Applies the integral, i.e., @a output_E = evaluate( @a input_E ) * @param[in] input_E The input to the evaluation; per-element DOF values * @param[out] output_E The output of the evalution; per-element DOF residuals * @see evaluation_kernel */ void Mult(const mfem::Vector& input_E, mfem::Vector& output_E) const { evaluation_(input_E, output_E); } /** * @brief Applies the integral, i.e., @a output_E = gradient( @a input_E ) * @param[in] input_E The input to the evaluation; per-element DOF values * @param[out] output_E The output of the evalution; per-element DOF residuals * @see action_of_gradient_kernel */ void GradientMult(const mfem::Vector& input_E, mfem::Vector& output_E) const { action_of_gradient_(input_E, output_E); } /** * @brief Computes the derivative of each element's residual with respect to the element values * @param[inout] K_b The reshaped vector as a mfem::DeviceTensor of size (test_dim * test_dof, trial_dim * trial_dof, * nelems) */ void ComputeElementGradients(ArrayView<double, 3, exec> K_b) const { element_gradient_(K_b); } private: /** * @brief Jacobians of the element transformations at all quadrature points */ const mfem::Vector J_; /** * @brief Mapped (physical) coordinates of all quadrature points */ const mfem::Vector X_; /** * @brief physical coordinates of surface unit normals at all quadrature points */ const mfem::Vector normals_; /** * @brief Type-erased handle to evaluation kernel * @see evaluation_kernel */ std::function<void(const mfem::Vector&, mfem::Vector&)> evaluation_; /** * @brief Type-erased handle to kernel that evaluates the action of the gradient * @see action_of_gradient_kernel */ std::function<void(const mfem::Vector&, mfem::Vector&)> action_of_gradient_; /** * @brief Type-erased handle to kernel that computes each element's gradients * @see gradient_matrix_kernel */ std::function<void(ArrayView<double, 3, exec>)> element_gradient_; }; } // namespace serac
44.570621
120
0.694131
LLNL
18b624c1e5950224ef77b44e0e041667b8d75fe3
5,707
cc
C++
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
11
2019-08-21T04:35:36.000Z
2021-07-13T02:11:21.000Z
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
null
null
null
KV_Store_Engine_TaurusDB_Race_stage2/src/kv_service/KeyFile.cc
chenshuaihao/KV_Store_Engine_TaurusDB_Race
b025879e5aa827800919354b56c474639ec34b62
[ "MIT" ]
1
2020-03-30T07:39:53.000Z
2020-03-30T07:39:53.000Z
#include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <sys/types.h> #include <set> #include <map> #include <unordered_map> #include <sparsepp/spp.h> #include <thread> #include <iostream> #include <sstream> #include <string> #include <exception> #include <chrono> #include "utils.h" #include "kv_string.h" #include "KeyFile.h" #include "params.h" std::shared_ptr<spp::sparse_hash_map<int64_t , int32_t>> KeyFile::keyOrderMaparray_[16]; int KeyFile::mapCnt_ = 0; std::mutex KeyFile::mutex_[16]; std::condition_variable KeyFile::Condition_; KeyFile::KeyFile(DataAgent* agent, int id, bool exist) :keyFilePosition_(0), keyOrderMap_(new spp::sparse_hash_map<int64_t , int32_t>()) { // 设置链接的接口 // 构建索引(在第一个findkey调用) // 设置目前索引含有key的量:keyFilePosition_ agent_ = agent; id_ = id; this->keyCacheBuffer_ = new char[4000000*8]; //四百万个8byte //int keyNum = ConstructKeyOrderMap(0); //keyFilePosition_ = keyNum; // 下面与预判有关 this->state_ = 0; keyOrderMaparray_[id_] = this->keyOrderMap_; } KeyFile::~KeyFile() { KV_LOG(INFO) << "~KeyFile id:" << id_; mapCnt_ = 0; if(keyCacheBuffer_ != nullptr) delete []keyCacheBuffer_; } // 构建 map<key, order> int KeyFile::ConstructKeyOrderMap(int begin) { //printf("\nstart KeyFile::ConstructKeyOrderMap\n"); int32_t pos = begin; int64_t k = 0; int len = 0; std::lock_guard<std::mutex> lock(mutex_[id_]); if( (len = agent_->GetKeys(KV_OP_META_GET, pos, this->keyCacheBuffer_, 0, pos)) > 0) { // 接收一次,获取 keyFile //printf("start build map:%d\n", id_); KV_LOG(INFO) << "start build map:" << id_; for (; pos < len; ++pos) { k = *(int64_t*)(this->keyCacheBuffer_ + pos * sizeof(int64_t)); try { this->keyOrderMap_->insert(pair<int64_t, int32_t>(k, pos)); } catch(const std::exception& e) { std::cerr << e.what() << "keyOrderMap_->insert\n"; delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return -1; } } } else { delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return -1; } this->keyFilePosition_ = len;//max(len, this->keyFilePosition_); //printf("id:%d,build Map success,len: %d, setting agent.valueFilePositon\n",id_, len); KV_LOG(INFO) << "id:" << id_ << ",build Map success,len:" << len << "setting agent.valueFilePositon"; this->agent_->SetValueFilePosition(this->keyFilePosition_); delete []keyCacheBuffer_; keyCacheBuffer_ = nullptr; return pos; } int64_t KeyFile::FindKey(int64_t key, int &fileId) { //printf("FindKey,id:%d\n", id_); if (unlikely(this->keyOrderMap_->empty())) { // 不存在, 构建 Map if(this->ConstructKeyOrderMap(0) == -1) return -1; std::this_thread::sleep_for(std::chrono::milliseconds(100));// 确保其他线程进入了map构建阶段 // 将构建好的map放到全局map数组 //keyOrderMaparray_[id_] = this->keyOrderMap_; // 先找本线程id的map,找到则说明是功能测试,单线程 spp::sparse_hash_map<int64_t, int32_t>::const_iterator iter = keyOrderMaparray_[id_]->find(key); if (iter != keyOrderMaparray_[id_]->end() ) { fileId = id_; return iter->second; } //printf("for find,id:%d\n", id_); spp::sparse_hash_map<int64_t, int32_t>::const_iterator isiter; // for循环查找每个map for(int i = 0; i < 16; ++i) { if(i == id_) continue; std::lock_guard<std::mutex> lock(mutex_[i]); isiter = keyOrderMaparray_[i]->find(key); if (isiter != keyOrderMaparray_[i]->end() ) { fileId = i; return isiter->second; } } } else if (unlikely(this->keyOrderMap_->size() < (this->keyFilePosition_))) { // Map 数量落后(kill 阶段重新写入数据), 继续构建 keyOrderMap_ this->ConstructKeyOrderMap(this->keyOrderMap_->size()); } // 将构建好的map放到全局map数组 //keyOrderMaparray_[id_] = this->keyOrderMap_; // 先找本线程id的map,找到则说明是功能测试,单线程 spp::sparse_hash_map<int64_t, int32_t>::const_iterator iter = keyOrderMaparray_[id_]->find(key); if (iter != keyOrderMaparray_[id_]->end() ) { fileId = id_; return iter->second; } //printf("for find,id:%d\n", id_); spp::sparse_hash_map<int64_t, int32_t>::const_iterator isiter; // for循环查找每个map for(int i = 0; i < 16; ++i) { if(i == id_) continue; isiter = keyOrderMaparray_[i]->find(key); if (isiter != keyOrderMaparray_[i]->end() ) { fileId = i; return isiter->second; } } return -1; } int64_t KeyFile::GetKeyPosition(KVString & key, int &fileId) { int64_t pos = this->FindKey(*(int64_t*)(key.Buf()), fileId); // KV_LOG(INFO) << "cfk:" << *((uint64_t*)key.Buf()) << " pos:" << pos; if (this->state_ == 0) { // 0 : 随机读,判断状态 JudgeStage(pos); } return pos; } int KeyFile::GetState() { return this->state_; } void KeyFile::SetKey(KVString & key) { ++this->keyFilePosition_; } void KeyFile::JudgeStage(int pos) { if(pos == 0) { this->state_ = 1; return; } int key_num = keyFilePosition_;//4000000;keyFilePosition_ int partition = pos / (PARTITION_SIZE * 1024 / 4); if (partition == ((key_num-1) / (PARTITION_SIZE * 1024 / 4))) { this->state_ = 2; return; } this->state_ = 0; } size_t KeyFile::GetKeyFilePosition(){ return this->keyFilePosition_; } void KeyFile::SetKeyFilePosition(int pos) { this->keyFilePosition_ = pos; }
31.882682
127
0.591204
chenshuaihao
18ba6a1e22a6c8cd3194e2c86243e21e1b8b2e42
4,981
cpp
C++
bootlinux.cpp
Risca/biffboot
63df31c91fcae7a00b5245e357acee89bb3be46b
[ "Unlicense" ]
null
null
null
bootlinux.cpp
Risca/biffboot
63df31c91fcae7a00b5245e357acee89bb3be46b
[ "Unlicense" ]
1
2021-11-22T22:57:18.000Z
2021-12-14T12:39:21.000Z
bootlinux.cpp
Risca/biffboot
63df31c91fcae7a00b5245e357acee89bb3be46b
[ "Unlicense" ]
1
2021-11-28T00:24:51.000Z
2021-11-28T00:24:51.000Z
#include <stdlib.h> #include <stdio.h> #include "iolib.h" #include "bootlinux.h" #include <string.h> //#include "LzmaDec.h" #include "flash.h" #include "flashmap.h" #include "config.h" #include "mmc.h" #include "assem.h" // Defines for the linux loader #define SETUP_SIZE_OFF 497 #define SECTSIZE 512 #define SETUP_VERSION 0x0201 #define SETUP_HIGH 0x01 #define BIG_SYSSEG 0x10000 #define DEF_BOOTLSEG 0x9020 struct bootsect_header { u8 pad0[0x1f1]; u8 setup_sects; u16 root_flags; // If set, the root is mounted readonly u16 syssize; // DO NOT USE - for bootsect.S use only u16 swap_dev; // DO NOT USE - obsolete u16 ram_size; // DO NOT USE - for bootsect.S use only u16 vid_mode; u16 root_dev; // Default root device number u16 boot_flag; // 0xAA55 magic number }; struct setup_header { u8 jump[2]; u8 magic[4]; // "HdrS" u16 version; // >= 0x0201 for initrd u8 realmode_swtch[4]; u16 start_sys_seg; u16 kernel_version; /* note: above part of header is compatible with loadlin-1.5 (header v1.5),*/ /* must not change it */ u8 type_of_loader; u8 loadflags; u16 setup_move_size; u32 code32_start; u32 ramdisk_image; u32 ramdisk_size; u32 bootsect_kludge; /* VERSION: 2.01+ */ u16 heap_end_ptr; u16 pad1; /* VERSION: 2.02+ */ u32 cmd_line_ptr; /* VERSION: 2.03+ */ u32 initrd_addr_max; }; #define PARAM 0x90000 #define PARAM_ORIG_X *(u8*) (PARAM+0x000) #define PARAM_ORIG_Y *(u8*) (PARAM+0x001) #define PARAM_EXT_MEM_K *(u16*)(PARAM+0x002) #define PARAM_ORIG_VIDEO_PAGE *(u16*)(PARAM+0x004) #define PARAM_ORIG_VIDEO_MODE *(u8*) (PARAM+0x006) #define PARAM_ORIG_VIDEO_COLS *(u8*) (PARAM+0x007) #define PARAM_ORIG_VIDEO_EGA_BX *(u16*)(PARAM+0x00a) #define PARAM_ORIG_VIDEO_LINES *(u8*) (PARAM+0x00E) #define PARAM_ORIG_VIDEO_ISVGA *(u8*) (PARAM+0x00F) #define PARAM_ORIG_VIDEO_POINTS *(u16*)(PARAM+0x010) #define PARAM_ALT_MEM_K *(u32*)(PARAM+0x1e0) #define PARAM_E820NR *(u8*) (PARAM+0x1e8) // hlin ==> #define PARAM_DF_ROOT *(u16*) (PARAM+0x1fc) #define PARAM_LOADER *(u8*) (PARAM+0x210) #define PARAM_INITRD_ADDR *(u32*)(PARAM+0x218) #define PARAM_INITRD_LEN *(u32*)(PARAM+0x21c) // hlin <== #define PARAM_VID_MODE *(u16*)(PARAM+0x1fa) #define PARAM_E820MAP (struct e820entry*)(PARAM+0x2d0); #define PARAM_CMDLINE (char *)(PARAM+0x3400) void bootlinux_go(u32 length) { u32 base_addr = config_loadaddress_get(); u32 mem_size = 0x2000000; /// 32 meg u32 int15_e801 = 0; struct bootsect_header *bs_header = 0; struct setup_header *s_header = 0; int setup_sects = 0; // Ensure we're operating with a standard gdt assem_linux_gdt(); // zero any low memory dma_free_all(); // Round length up to the next quad word length = (length + 3) & ~0x3; mem_size >>= 10; // convert from bytes to kilobytes. // Result of int15 ax=0xe801 int15_e801 = mem_size - 1024 ; // 1M+ only bs_header = (struct bootsect_header *)base_addr; s_header = (struct setup_header *)(base_addr + SECTSIZE); if (bs_header->boot_flag != 0xAA55) { printf("boot_flag not found\n"); return; } if (memcmp(s_header->magic,"HdrS",4) != 0) { printf("Linux kernel not found\n"); return; } if (s_header->version < SETUP_VERSION) { printf("Kernel too old\n"); return; } setup_sects = bs_header->setup_sects ? bs_header->setup_sects : 4; // + 1 for boot sector base_addr += (setup_sects + 1 ) * SECTSIZE; length -= (setup_sects + 1 ) * SECTSIZE; // Clear the data area memset ( (void*)PARAM, 0, 0x10000 ); strcpy( PARAM_CMDLINE, config_cmndline_get() ); printf("Booting Linux with: "); printf(config_cmndline_get()); printf("\n"); memcpy((void*)(PARAM+SECTSIZE), s_header, sizeof(struct setup_header)); s_header = (struct setup_header*)(PARAM+SECTSIZE); s_header->version = SETUP_VERSION; // Command Line s_header->cmd_line_ptr = (u32)PARAM_CMDLINE; // Loader type s_header->type_of_loader = 0xFF; // Fill in the interesting bits of data area... // ... Memory sizes PARAM_EXT_MEM_K = int15_e801; PARAM_ALT_MEM_K = (u32)int15_e801; // ... No e820 map! // PARAM_E820NR = (u8)0; // Length of map // PARAM_DF_ROOT = (u16)0x0000 ; // default root device PARAM_LOADER = (u8)0x20 ; // type of loader // PARAM_INITRD_ADDR = (u32)0 ; // ramdisk address // PARAM_INITRD_LEN = (u32)0 ; // ramdisk size // printf("Copy to: "); print_hex32(s_header->code32_start); // printf(" Copy from: "); print_hex32(base_addr); // printf(" bytes: "); print_hex32(length); // printf("\n"); memcpy((char*)s_header->code32_start, (char*)base_addr, length); assem_linux_boot(s_header->code32_start, PARAM); while (1); }
26.924324
81
0.64726
Risca
18bc87786c4905941d79352bf2755a679164a3e0
2,072
hpp
C++
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
7
2019-04-09T16:25:49.000Z
2021-12-07T10:29:52.000Z
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
null
null
null
lib/parser.hpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
4
2019-08-07T07:43:27.000Z
2021-05-21T07:54:14.000Z
#pragma once #include "boost/utility/string_ref.hpp" #include <base/magic.hpp> namespace minips { namespace lib { template<typename Sample> class Parser { public: /** * Parsing logic for one line in file * * @param line a line read from the input file */ static Sample parse_libsvm(boost::string_ref line) { // check the LibSVM format and complete the parsing // hints: you may use boost::tokenizer, std::strtok_r, std::stringstream or any method you like // so far we tried all the tree and found std::strtok_r is fastest :) SVMItem item; char* pos; std::unique_ptr<char> buffer(new char[line.size() + 1]); strncpy(buffer.get(), line.data(), line.size()); buffer.get()[line.size()] = '\0'; char* token = strtok_r(buffer.get(), " \t:", &pos); int i = -1; int index; double value; while (token != nullptr) { if (i == 0) { index = std::atoi(token) - 1; i = 1; } else if (i == 1) { value = std::atof(token); item.first.push_back(std::make_pair(index, value)); i = 0; } else { // the class label item.second = std::atof(token); i = 0; } token = strtok_r(nullptr, " \t:", &pos); } return item; } static Sample parse_mnist(boost::string_ref line) { // check the MNIST format and complete the parsing // TODO: may be done in the future } // You may implement other parsing logic }; // class Parser } // namespace lib } // namespace minips
34.533333
111
0.441602
RickAi
18bd8329ff859f91d153112c30c047d8e0b27648
32,359
cc
C++
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
1
2016-01-18T12:41:28.000Z
2016-01-18T12:41:28.000Z
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
src/LogCleaner.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
/* Copyright (c) 2010-2013 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <stdint.h> #include "Common.h" #include "Fence.h" #include "Log.h" #include "LogCleaner.h" #include "ShortMacros.h" #include "Segment.h" #include "SegmentIterator.h" #include "ServerConfig.h" #include "WallTime.h" namespace RAMCloud { /** * Construct a new LogCleaner object. The cleaner will not perform any garbage * collection until the start() method is invoked. * * \param context * Overall information about the RAMCloud server. * \param config * Server configuration from which the cleaner will extract any runtime * parameters that affect its operation. * \param segmentManager * The SegmentManager to query for newly cleanable segments, allocate * survivor segments from, and report cleaned segments to. * \param replicaManager * The ReplicaManager to use in backing up segments written out by the * cleaner. * \param entryHandlers * Class responsible for entries stored in the log. The cleaner will invoke * it when they are being relocated during cleaning, for example. */ LogCleaner::LogCleaner(Context* context, const ServerConfig* config, SegmentManager& segmentManager, ReplicaManager& replicaManager, LogEntryHandlers& entryHandlers) : context(context), segmentManager(segmentManager), replicaManager(replicaManager), entryHandlers(entryHandlers), writeCostThreshold(config->master.cleanerWriteCostThreshold), disableInMemoryCleaning(config->master.disableInMemoryCleaning), numThreads(config->master.cleanerThreadCount), candidates(), candidatesLock("LogCleaner::candidatesLock"), segletSize(config->segletSize), segmentSize(config->segmentSize), doWorkTicks(0), doWorkSleepTicks(0), inMemoryMetrics(), onDiskMetrics(), threadMetrics(numThreads), threadsShouldExit(false), threads() { if (!segmentManager.initializeSurvivorReserve(numThreads * SURVIVOR_SEGMENTS_TO_RESERVE)) throw FatalError(HERE, "Could not reserve survivor segments"); if (writeCostThreshold == 0) disableInMemoryCleaning = true; for (int i = 0; i < numThreads; i++) threads.push_back(NULL); } /** * Destroy the cleaner. Any running threads are stopped first. */ LogCleaner::~LogCleaner() { stop(); TEST_LOG("destroyed"); } /** * Start the log cleaner, if it isn't already running. This spins a thread that * continually cleans if there's work to do until stop() is called. * * The cleaner will not do any work until explicitly enabled via this method. * * This method may be called any number of times, but it is not thread-safe. * That is, do not call start() and stop() in parallel. */ void LogCleaner::start() { for (int i = 0; i < numThreads; i++) { if (threads[i] == NULL) threads[i] = new std::thread(cleanerThreadEntry, this, context); } } /** * Halt the cleaner thread (if it is running). Once halted, it will do no more * work until start() is called again. * * This method may be called any number of times, but it is not thread-safe. * That is, do not call start() and stop() in parallel. */ void LogCleaner::stop() { threadsShouldExit = true; Fence::sfence(); for (int i = 0; i < numThreads; i++) { if (threads[i] != NULL) { threads[i]->join(); delete threads[i]; threads[i] = NULL; } } threadsShouldExit = false; } /** * Fill in the provided protocol buffer with metrics, giving other modules and * servers insight into what's happening in the cleaner. */ void LogCleaner::getMetrics(ProtoBuf::LogMetrics_CleanerMetrics& m) { m.set_poll_usec(POLL_USEC); m.set_max_cleanable_memory_utilization(MAX_CLEANABLE_MEMORY_UTILIZATION); m.set_live_segments_per_disk_pass(MAX_LIVE_SEGMENTS_PER_DISK_PASS); m.set_survivor_segments_to_reserve(SURVIVOR_SEGMENTS_TO_RESERVE); m.set_min_memory_utilization(MIN_MEMORY_UTILIZATION); m.set_min_disk_utilization(MIN_DISK_UTILIZATION); m.set_do_work_ticks(doWorkTicks); m.set_do_work_sleep_ticks(doWorkSleepTicks); inMemoryMetrics.serialize(*m.mutable_in_memory_metrics()); onDiskMetrics.serialize(*m.mutable_on_disk_metrics()); threadMetrics.serialize(*m.mutable_thread_metrics()); } /****************************************************************************** * PRIVATE METHODS ******************************************************************************/ static volatile uint32_t threadCnt; /** * Static entry point for the cleaner thread. This is invoked via the * std::thread() constructor. This thread performs continuous cleaning on an * as-needed basis. */ void LogCleaner::cleanerThreadEntry(LogCleaner* logCleaner, Context* context) { LOG(NOTICE, "LogCleaner thread started"); CleanerThreadState state; state.threadNumber = __sync_fetch_and_add(&threadCnt, 1); try { while (1) { Fence::lfence(); if (logCleaner->threadsShouldExit) break; logCleaner->doWork(&state); } } catch (const Exception& e) { DIE("Fatal error in cleaner thread: %s", e.what()); } LOG(NOTICE, "LogCleaner thread stopping"); } /** * Main cleaning loop, constantly invoked via cleanerThreadEntry(). If there * is cleaning to be done, do it now return. If no work is to be done, sleep for * a bit before returning (and getting called again), rather than banging on the * CPU. */ void LogCleaner::doWork(CleanerThreadState* state) { MetricCycleCounter _(&doWorkTicks); threadMetrics.noteThreadStart(); // Update our list of candidates whether we need to clean or not (it's // better not to put off work until we really need to clean). candidatesLock.lock(); segmentManager.cleanableSegments(candidates); candidatesLock.unlock(); int memUtil = segmentManager.getAllocator().getMemoryUtilization(); bool lowOnMemory = (segmentManager.getAllocator().getMemoryUtilization() >= MIN_MEMORY_UTILIZATION); bool notKeepingUp = (segmentManager.getAllocator().getMemoryUtilization() >= MEMORY_DEPLETED_UTILIZATION); bool lowOnDiskSpace = (segmentManager.getSegmentUtilization() >= MIN_DISK_UTILIZATION); bool haveWorkToDo = (lowOnMemory || lowOnDiskSpace); if (haveWorkToDo) { if (state->threadNumber == 0) { if (lowOnDiskSpace || notKeepingUp) doDiskCleaning(lowOnDiskSpace); else doMemoryCleaning(); } else { int threshold = 90 + 2 * static_cast<int>(state->threadNumber); if (memUtil >= std::min(99, threshold)) doMemoryCleaning(); else haveWorkToDo = false; } } threadMetrics.noteThreadStop(); if (!haveWorkToDo) { MetricCycleCounter __(&doWorkSleepTicks); // Jitter the sleep delay a little bit (up to 10%). It's not a big deal // if we don't, but it can make some locks look artificially contended // when there's no cleaning to be done and threads manage to caravan // together. useconds_t r = downCast<useconds_t>(generateRandom() % POLL_USEC) / 10; usleep(POLL_USEC + r); } } /** * Perform an in-memory cleaning pass. This takes a segment and compacts it, * re-packing all live entries together sequentially, allowing us to reclaim * some of the dead space. */ uint64_t LogCleaner::doMemoryCleaning() { TEST_LOG("called"); MetricCycleCounter _(&inMemoryMetrics.totalTicks); if (disableInMemoryCleaning) return 0; uint32_t freeableSeglets; LogSegment* segment = getSegmentToCompact(freeableSeglets); if (segment == NULL) return 0; // Allocate a survivor segment to write into. This call may block if one // is not available right now. MetricCycleCounter waitTicks(&inMemoryMetrics.waitForFreeSurvivorTicks); LogSegment* survivor = segmentManager.allocSideSegment( SegmentManager::FOR_CLEANING | SegmentManager::MUST_NOT_FAIL, segment); assert(survivor != NULL); waitTicks.stop(); inMemoryMetrics.totalBytesInCompactedSegments += segment->getSegletsAllocated() * segletSize; uint64_t entriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveEntriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t scannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveScannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint32_t bytesAppended = 0; for (SegmentIterator it(*segment); !it.isDone(); it.next()) { LogEntryType type = it.getType(); Buffer buffer; it.appendToBuffer(buffer); Log::Reference reference = segment->getReference(it.getOffset()); RelocStatus s = relocateEntry(type, buffer, reference, survivor, inMemoryMetrics, &bytesAppended); if (expect_false(s == RELOCATION_FAILED)) throw FatalError(HERE, "Entry didn't fit into survivor!"); entriesScanned[type]++; scannedEntryLengths[type] += buffer.getTotalLength(); if (expect_true(s == RELOCATED)) { liveEntriesScanned[type]++; liveScannedEntryLengths[type] += buffer.getTotalLength(); } } // Be sure to update the usage statistics for the new segment. This // is done once here, rather than for each relocated entry because // it avoids the expense of atomically updating two separate fields. survivor->liveBytes += bytesAppended; for (size_t i = 0; i < TOTAL_LOG_ENTRY_TYPES; i++) { inMemoryMetrics.totalEntriesScanned[i] += entriesScanned[i]; inMemoryMetrics.totalLiveEntriesScanned[i] += liveEntriesScanned[i]; inMemoryMetrics.totalScannedEntryLengths[i] += scannedEntryLengths[i]; inMemoryMetrics.totalLiveScannedEntryLengths[i] += liveScannedEntryLengths[i]; } // The survivor segment has at least as many seglets allocated as the one // we've compacted (it was freshly allocated, so it has the maximum number // of seglets). We can therefore free the difference (which ensures a 0 net // gain) plus the number extra seglets that getSegmentToCompact() told us // we could free. That value was carefully calculated to ensure that future // disk cleaning will make forward progress (not use more seglets after // cleaning than before). uint32_t segletsToFree = survivor->getSegletsAllocated() - segment->getSegletsAllocated() + freeableSeglets; survivor->close(); bool r = survivor->freeUnusedSeglets(segletsToFree); assert(r); uint64_t bytesFreed = freeableSeglets * segletSize; inMemoryMetrics.totalBytesFreed += bytesFreed; inMemoryMetrics.totalBytesAppendedToSurvivors += survivor->getAppendedLength(); inMemoryMetrics.totalSegmentsCompacted++; MetricCycleCounter __(&inMemoryMetrics.compactionCompleteTicks); segmentManager.compactionComplete(segment, survivor); return static_cast<uint64_t>( static_cast<double>(bytesFreed) / Cycles::toSeconds(_.stop())); } /** * Perform a disk cleaning pass if possible. Doing so involves choosing segments * to clean, extracting entries from those segments, writing them out into new * "survivor" segments, and alerting the segment manager upon completion. */ uint64_t LogCleaner::doDiskCleaning(bool lowOnDiskSpace) { TEST_LOG("called"); MetricCycleCounter _(&onDiskMetrics.totalTicks); // Obtain the segments we'll clean in this pass. We're guaranteed to have // the resources to clean what's returned. LogSegmentVector segmentsToClean; getSegmentsToClean(segmentsToClean); if (segmentsToClean.size() == 0) return 0; // Extract the currently live entries of the segments we're cleaning and // sort them by age. EntryVector entries; getSortedEntries(segmentsToClean, entries); uint64_t maxLiveBytes = 0; uint32_t segletsBefore = 0; foreach (LogSegment* segment, segmentsToClean) { uint64_t liveBytes = segment->liveBytes; if (liveBytes == 0) onDiskMetrics.totalEmptySegmentsCleaned++; maxLiveBytes += liveBytes; segletsBefore += segment->getSegletsAllocated(); } // Relocate the live entries to survivor segments. LogSegmentVector survivors; uint64_t entryBytesAppended = relocateLiveEntries(entries, survivors); uint32_t segmentsAfter = downCast<uint32_t>(survivors.size()); uint32_t segletsAfter = 0; foreach (LogSegment* segment, survivors) segletsAfter += segment->getSegletsAllocated(); TEST_LOG("used %u seglets and %u segments", segletsAfter, segmentsAfter); // If this doesn't hold, then our statistics are wrong. Perhaps // MasterService is issuing a log->free(), but is leaving a reference in // the hash table. assert(entryBytesAppended <= maxLiveBytes); uint32_t segmentsBefore = downCast<uint32_t>(segmentsToClean.size()); assert(segletsBefore >= segletsAfter); assert(segmentsBefore >= segmentsAfter); uint64_t memoryBytesFreed = (segletsBefore - segletsAfter) * segletSize; uint64_t diskBytesFreed = (segmentsBefore - segmentsAfter) * segmentSize; onDiskMetrics.totalMemoryBytesFreed += memoryBytesFreed; onDiskMetrics.totalDiskBytesFreed += diskBytesFreed; onDiskMetrics.totalSegmentsCleaned += segmentsToClean.size(); onDiskMetrics.totalSurvivorsCreated += survivors.size(); onDiskMetrics.totalRuns++; if (lowOnDiskSpace) onDiskMetrics.totalLowDiskSpaceRuns++; MetricCycleCounter __(&onDiskMetrics.cleaningCompleteTicks); segmentManager.cleaningComplete(segmentsToClean, survivors); return static_cast<uint64_t>( static_cast<double>(memoryBytesFreed) / Cycles::toSeconds(_.stop())); } /** * Choose the best segment to clean in memory. We greedily choose the segment * with the most freeable seglets. Care is taken to ensure that we determine the * number of freeable seglets that will keep the segment under our maximum * cleanable utilization after compaction. This ensures that we will always be * able to use the compacted version of this segment during disk cleaning. * * \param[out] outFreeableSeglets * The maximum number of seglets the caller should free from this segment * is returned here. Freeing any more may make it impossible to clean the * resulting compacted segment on disk, which may deadlock the system if * it prevents freeing up tombstones in other segments. */ LogSegment* LogCleaner::getSegmentToCompact(uint32_t& outFreeableSeglets) { MetricCycleCounter _(&inMemoryMetrics.getSegmentToCompactTicks); Lock guard(candidatesLock); size_t bestIndex = -1; uint32_t bestDelta = 0; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; uint32_t liveBytes = candidate->liveBytes; uint32_t segletsNeeded = (100 * (liveBytes + segletSize - 1)) / segletSize / MAX_CLEANABLE_MEMORY_UTILIZATION; uint32_t segletsAllocated = candidate->getSegletsAllocated(); uint32_t delta = segletsAllocated - segletsNeeded; if (segletsNeeded < segletsAllocated && delta > bestDelta) { bestIndex = i; bestDelta = delta; } } // If we don't think any memory can be safely freed then either we're full // up with live objects (in which case nothing's wrong and we can't actually // do anything), or we have a lot of dead tombstones sitting around that is // causing us to assume that we're full when we really aren't. This can // happen because we don't (and can't easily) keep track of which tombstones // are dead, so all are presumed to be alive. When objects are large and // tombstones are relatively small, this accounting error is usually // harmless. However, when storing very small objects, tombstones are // relatively large and our percentage error can be significant. Also, one // can imagine what'd happen if the cleaner somehow groups tombstones // together into their own segments that always appear to have 100% live // entries. // // So, to address this we'll try compacting the candidate segment with the // most tombstones that has not been compacted in a while. Hopefully this // will choose the one with the most dead tombstones and shake us out of // any deadlock. // // It's entirely possible that we'd want to do this earlier (before we run // out of candidates above, rather than as a last ditch effort). It's not // clear to me, however, when we'd decide and what would give the best // overall performance. // // Did I ever mention how much I hate tombstones? if (bestIndex == static_cast<size_t>(-1)) { __uint128_t bestGoodness = 0; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; uint32_t tombstoneCount = candidate->getEntryCount(LOG_ENTRY_TYPE_OBJTOMB); uint64_t timeSinceLastCompaction = WallTime::secondsTimestamp() - candidate->lastCompactionTimestamp; __uint128_t goodness = (__uint128_t)tombstoneCount * timeSinceLastCompaction; if (goodness > bestGoodness) { bestIndex = i; bestGoodness = goodness; } } // Still no dice. Looks like we're just full of live data. if (bestIndex == static_cast<size_t>(-1)) return NULL; // It's not safe for the compactor to free any memory this time around // (it could be that no tombstones were dead, or we will free too few to // allow us to free seglets while still guaranteeing forward progress // of the disk cleaner). // // If we do free enough memory, we'll get it back in a subsequent pass. // The alternative would be to have a separate algorithm that just // counts dead tombstones and updates the liveness counters. That is // slightly more complicated. Perhaps if this becomes frequently enough // we can optimise that case. bestDelta = 0; } LogSegment* best = candidates[bestIndex]; candidates[bestIndex] = candidates.back(); candidates.pop_back(); outFreeableSeglets = bestDelta; return best; } void LogCleaner::sortSegmentsByCostBenefit(LogSegmentVector& segments) { MetricCycleCounter _(&onDiskMetrics.costBenefitSortTicks); // Sort segments so that the best candidates are at the front of the vector. // We could probably use a heap instead and go a little faster, but it's not // easy to say how many top candidates we'd want to track in the heap since // they could each have significantly different numbers of seglets. std::sort(segments.begin(), segments.end(), CostBenefitComparer()); } /** * Compute the best segments to clean on disk and return a set of them that we * are guaranteed to be able to clean while consuming no more space in memory * than they currently take up. * * \param[out] outSegmentsToClean * Vector in which segments chosen for cleaning are returned. * \return * Returns the total number of seglets allocated in the segments chosen for * cleaning. */ void LogCleaner::getSegmentsToClean(LogSegmentVector& outSegmentsToClean) { MetricCycleCounter _(&onDiskMetrics.getSegmentsToCleanTicks); Lock guard(candidatesLock); foreach (LogSegment* segment, candidates) { onDiskMetrics.allSegmentsDiskHistogram.storeSample( segment->getDiskUtilization()); } sortSegmentsByCostBenefit(candidates); uint32_t totalSeglets = 0; uint64_t totalLiveBytes = 0; uint64_t maximumLiveBytes = MAX_LIVE_SEGMENTS_PER_DISK_PASS * segmentSize; vector<size_t> chosenIndices; for (size_t i = 0; i < candidates.size(); i++) { LogSegment* candidate = candidates[i]; int utilization = candidate->getMemoryUtilization(); if (utilization > MAX_CLEANABLE_MEMORY_UTILIZATION) continue; uint64_t liveBytes = candidate->liveBytes; if ((totalLiveBytes + liveBytes) > maximumLiveBytes) break; totalLiveBytes += liveBytes; totalSeglets += candidate->getSegletsAllocated(); outSegmentsToClean.push_back(candidate); chosenIndices.push_back(i); } // Remove chosen segments from the list of candidates. At this point, we've // committed to cleaning what we chose and have guaranteed that we have the // necessary resources to complete the operation. reverse_foreach(size_t i, chosenIndices) { candidates[i] = candidates.back(); candidates.pop_back(); } TEST_LOG("%lu segments selected with %u allocated segments", chosenIndices.size(), totalSeglets); } /** * Sort the given segment entries by their timestamp. Used to sort the survivor * data that is written out to multiple segments during disk cleaning. This * helps to segregate data we expect to live longer from those likely to be * shorter lived, which in turn can reduce future cleaning costs. * * This happens to sort younger objects first, but the opposite should work just as * well. * * \param entries * Vector containing the entries to sort. */ void LogCleaner::sortEntriesByTimestamp(EntryVector& entries) { MetricCycleCounter _(&onDiskMetrics.timestampSortTicks); std::sort(entries.begin(), entries.end(), TimestampComparer()); } /** * Extract a complete list of entries from the given segments we're going to * clean and sort them by age. * * \param segmentsToClean * Vector containing the segments to extract entries from. * \param[out] outEntries * Vector containing sorted live entries in the segment. */ void LogCleaner::getSortedEntries(LogSegmentVector& segmentsToClean, EntryVector& outEntries) { MetricCycleCounter _(&onDiskMetrics.getSortedEntriesTicks); foreach (LogSegment* segment, segmentsToClean) { for (SegmentIterator it(*segment); !it.isDone(); it.next()) { LogEntryType type = it.getType(); Buffer buffer; it.appendToBuffer(buffer); uint32_t timestamp = entryHandlers.getTimestamp(type, buffer); outEntries.push_back( Entry(segment, it.getOffset(), timestamp)); } } sortEntriesByTimestamp(outEntries); // TODO(Steve): Push all of this crap into LogCleanerMetrics. It already // knows about the various parts of cleaning, so why not have simple calls // into it at interesting points of cleaning and let it extract the needed // metrics? foreach (LogSegment* segment, segmentsToClean) { onDiskMetrics.totalMemoryBytesInCleanedSegments += segment->getSegletsAllocated() * segletSize; onDiskMetrics.totalDiskBytesInCleanedSegments += segmentSize; onDiskMetrics.cleanedSegmentMemoryHistogram.storeSample( segment->getMemoryUtilization()); onDiskMetrics.cleanedSegmentDiskHistogram.storeSample( segment->getDiskUtilization()); } TEST_LOG("%lu entries extracted from %lu segments", outEntries.size(), segmentsToClean.size()); } /** * Given a vector of entries from segments being cleaned, write them out to * survivor segments in order and alert their owning module (MasterService, * usually), that they've been relocated. * * \param entries * Vector the entries from segments being cleaned that may need to be * relocated. * \param outSurvivors * The new survivor segments created to hold the relocated live data are * returned here. * \return * The number of live bytes appended to survivors is returned. This value * includes any segment metadata overhead. This makes it directly * comparable to the per-segment liveness statistics that also include * overhead. */ uint64_t LogCleaner::relocateLiveEntries(EntryVector& entries, LogSegmentVector& outSurvivors) { MetricCycleCounter _(&onDiskMetrics.relocateLiveEntriesTicks); LogSegment* survivor = NULL; uint64_t currentSurvivorBytesAppended = 0; uint64_t entryBytesAppended = 0; uint64_t entriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveEntriesScanned[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t scannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint64_t liveScannedEntryLengths[TOTAL_LOG_ENTRY_TYPES] = { 0 }; uint32_t bytesAppended = 0; foreach (Entry& entry, entries) { Buffer buffer; LogEntryType type = entry.segment->getEntry(entry.offset, buffer); Log::Reference reference = entry.segment->getReference(entry.offset); RelocStatus s = relocateEntry(type, buffer, reference, survivor, onDiskMetrics, &bytesAppended); if (s == RELOCATION_FAILED) { if (survivor != NULL) { survivor->liveBytes += bytesAppended; bytesAppended = 0; closeSurvivor(survivor); } // Allocate a survivor segment to write into. This call may block if // one is not available right now. MetricCycleCounter waitTicks( &onDiskMetrics.waitForFreeSurvivorsTicks); survivor = segmentManager.allocSideSegment( SegmentManager::FOR_CLEANING | SegmentManager::MUST_NOT_FAIL, NULL); assert(survivor != NULL); waitTicks.stop(); outSurvivors.push_back(survivor); currentSurvivorBytesAppended = survivor->getAppendedLength(); s = relocateEntry(type, buffer, reference, survivor, onDiskMetrics, &bytesAppended); if (s == RELOCATION_FAILED) throw FatalError(HERE, "Entry didn't fit into empty survivor!"); } entriesScanned[type]++; scannedEntryLengths[type] += buffer.getTotalLength(); if (s == RELOCATED) { liveEntriesScanned[type]++; liveScannedEntryLengths[type] += buffer.getTotalLength(); } if (survivor != NULL) { uint32_t newSurvivorBytesAppended = survivor->getAppendedLength(); entryBytesAppended += (newSurvivorBytesAppended - currentSurvivorBytesAppended); currentSurvivorBytesAppended = newSurvivorBytesAppended; } } if (survivor != NULL) { survivor->liveBytes += bytesAppended; closeSurvivor(survivor); } // Ensure that the survivors have been synced to backups before proceeding. foreach (survivor, outSurvivors) { MetricCycleCounter __(&onDiskMetrics.survivorSyncTicks); survivor->replicatedSegment->sync(survivor->getAppendedLength()); } for (size_t i = 0; i < TOTAL_LOG_ENTRY_TYPES; i++) { onDiskMetrics.totalEntriesScanned[i] += entriesScanned[i]; onDiskMetrics.totalLiveEntriesScanned[i] += liveEntriesScanned[i]; onDiskMetrics.totalScannedEntryLengths[i] += scannedEntryLengths[i]; onDiskMetrics.totalLiveScannedEntryLengths[i] += liveScannedEntryLengths[i]; } return entryBytesAppended; } /** * Close a survivor segment we've written data to as part of a disk cleaning * pass and tell the replicaManager to begin flushing it asynchronously to * backups. Any unused seglets in the survivor will will be freed for use in * new segments. * * \param survivor * The new disk segment we've written survivor data to. */ void LogCleaner::closeSurvivor(LogSegment* survivor) { MetricCycleCounter _(&onDiskMetrics.closeSurvivorTicks); onDiskMetrics.totalBytesAppendedToSurvivors += survivor->getAppendedLength(); survivor->close(); // Once the replicatedSegment is told that the segment is closed, it will // begin replicating the contents. By closing survivors as we go, we can // overlap backup writes with filling up new survivors. survivor->replicatedSegment->close(); // Immediately free any unused seglets. bool r = survivor->freeUnusedSeglets(survivor->getSegletsAllocated() - survivor->getSegletsInUse()); assert(r); } /****************************************************************************** * LogCleaner::CostBenefitComparer inner class ******************************************************************************/ /** * Construct a new comparison functor that compares segments by cost-benefit. * Used when selecting among candidate segments by first sorting them. */ LogCleaner::CostBenefitComparer::CostBenefitComparer() : now(WallTime::secondsTimestamp()), version(Cycles::rdtsc()) { } /** * Calculate the cost-benefit ratio (benefit/cost) for the given segment. */ uint64_t LogCleaner::CostBenefitComparer::costBenefit(LogSegment* s) { // If utilization is 0, cost-benefit is infinity. uint64_t costBenefit = -1UL; int utilization = s->getDiskUtilization(); if (utilization != 0) { uint64_t timestamp = s->getAge(); // This generally shouldn't happen, but is possible due to: // 1) Unsynchronized TSCs across cores (WallTime uses rdtsc). // 2) Unsynchronized clocks and "newer" recovered data in the log. if (timestamp > now) { LOG(WARNING, "timestamp > now"); timestamp = now; } uint64_t age = now - timestamp; costBenefit = ((100 - utilization) * age) / utilization; } return costBenefit; } /** * Compare two segment's cost-benefit ratios. Higher values (better cleaning * candidates) are better, so the less than comparison is inverted. */ bool LogCleaner::CostBenefitComparer::operator()(LogSegment* a, LogSegment* b) { // We must ensure that we maintain the weak strictly ordered constraint, // otherwise surprising things may happen in the stl algorithms when // segment statistics change and alter the computed cost-benefit of a // segment from one comparison to the next during the same sort operation. if (a->costBenefitVersion != version) { a->costBenefit = costBenefit(a); a->costBenefitVersion = version; } if (b->costBenefitVersion != version) { b->costBenefit = costBenefit(b); b->costBenefitVersion = version; } return a->costBenefit > b->costBenefit; } } // namespace
37.891101
83
0.665719
taschik
18c778b01f3f7a81a4a3286822b0eded2795264d
9,718
hpp
C++
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
1
2021-12-13T12:34:27.000Z
2021-12-13T12:34:27.000Z
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
62
2020-07-17T07:33:00.000Z
2021-05-22T15:30:20.000Z
include/malbolge/virtual_cpu.hpp
cmannett85/malbolge
a3216af7b029d1b942af1dd3678d43fbb5d3c017
[ "MIT" ]
1
2021-12-13T12:34:30.000Z
2021-12-13T12:34:30.000Z
/* Cam Mannett 2020 * * See LICENSE file */ #pragma once #include "malbolge/utility/signal.hpp" #include "malbolge/virtual_memory.hpp" namespace malbolge { /** Represents a virtual CPU. * * This class can not be copied, but can be moved. */ class virtual_cpu { public: /** Execution state. */ enum class execution_state { READY, ///< Ready to run RUNNING, ///< Program running PAUSED, ///< Program paused WAITING_FOR_INPUT, ///< Similar to paused, except the program will ///< resume when input data provided STOPPED, ///< Program stopped, cannot be resumed or ran again NUM_STATES ///< Number of execution states }; /** vCPU register identifiers. */ enum class vcpu_register { A, ///< Accumulator C, ///< Code pointer D, ///< Data pointer NUM_REGISTERS ///< Number of registers }; /** Signal type to indicate the program running state, and any exception in * case of error. * * In case of an error the execution state is always STOPPED. * @tparam execution_state Execution state * @tparam std::exception_ptr Exception pointer, null if no error */ using state_signal_type = utility::signal<execution_state, std::exception_ptr>; /** Signal type carrying program output data. * * @tparam char Character output from program */ using output_signal_type = utility::signal<char>; /** Signal type fired when a breakpoint is hit. * * @tparam math::ternary Address the breakpoint resides at */ using breakpoint_hit_signal_type = utility::signal<math::ternary>; /** Address value result callback type. * * @param address Address in virtual memory that was requested * @param value Value at @a address */ using address_value_callback_type = std::function<void (math::ternary address, math::ternary value)>; /** Register value result callback type. * * @param reg Requested register * @param address If @a reg is C or D then it contains an address * @param value The value of the register if @a address is empty, otherwise * the value at @a address */ using register_value_callback_type = std::function<void (vcpu_register reg, std::optional<math::ternary> address, math::ternary value)>; /** Constructor. * * Although it is not emitted in the state signal, the instance begins in * a execution_state::READY state. * @param vmem Virtual memory containing the initialised memory space * (including program data) */ explicit virtual_cpu(virtual_memory vmem); /** Move constructor. * * @param other Instance to move from */ virtual_cpu(virtual_cpu&& other) noexcept = default; /** Move assignment operator. * * @param other Instance to move from * @return A reference to this */ virtual_cpu& operator=(virtual_cpu&& other) noexcept = default; virtual_cpu(const virtual_cpu&) = delete; virtual_cpu& operator=(const virtual_cpu&) = delete; /** Destructor. */ ~virtual_cpu(); /** Runs or resumes program execution. * * If the program is already running or waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void run(); /** Pauses a running program. * * If the program is already paused or waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void pause(); /** Advances the program by a single execution. * * If the program is running, this will pause it and then advance by a * single execution. If the program is waiting-for-input, then this is a * no-op. * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move * @exception execution_exception Thrown if the vCPU ha already been * stopped */ void step(); /** Adds @a data to the input queue for the program. * * If the program is waiting for input, then calling this will resume * program execution. * @param data Input add to add * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void add_input(std::string data); /** Adds a breakpoint to the program. * * If another breakpoint is already at the given address, it is replaced. * Breakpoints can be added to the program whilst in any non-STOPPED state, * but results can be unpredicatable if the program is running. * * The breakpoint-hit signal is fired when a breakpoint is reached. The * signal is fired when then code pointer reaches the address i.e. * @em before the instruction is executed, so you need to step to see the * result of the instruction execution. * @param address Address to attach a breakpoint * @param ignore_count Number of times the breakpoint is hit before the * breakpoint_hit_signal_type signal is fired * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void add_breakpoint(math::ternary address, std::size_t ignore_count = 0); /** Removes a breakpoint at the given address. * * This is a no-op if there is no breakpoint at @a address. * @param address vmem address to remove a breakpoint from * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void remove_breakpoint(math::ternary address); /** Asynchronously returns the value at a given vmem address via @a cb. * * @param address vmem address * @param cb Called with the result * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void address_value(math::ternary address, address_value_callback_type cb) const; /** Asynchronously returns the address and/or value of a given register. * * @param reg Register to query * @param cb For C and D registers returns the address held in the register * and the value it points at, for the A register it only returns the value * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ void register_value(vcpu_register reg, register_value_callback_type cb) const; /** Register @a slot to be called when the state signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ state_signal_type::connection register_for_state_signal(state_signal_type::slot_type slot); /** Register @a slot to be called when the output signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ output_signal_type::connection register_for_output_signal(output_signal_type::slot_type slot); /** Register @a slot to be called when the breakpoint hit signal fires. * * You can disconnect from the signal using the returned connection * instance. * @note @a slot is called from the vCPU's local event loop thread, so you * may need to post into the event loop you intend on processing it with * @param slot Callable instance called when the signal fires * @return Connection data * @exception execution_exception Thrown if backend has been destroyed, * usually as a result of use-after-move */ breakpoint_hit_signal_type::connection register_for_breakpoint_hit_signal(breakpoint_hit_signal_type::slot_type slot); private: void impl_check() const; class impl_t; std::shared_ptr<impl_t> impl_; }; /** Textual streaming operator for virtual_cpu::vcpu_register. * * @param stream Output stream * @param register_id Instance to stream * @return @a stream */ std::ostream& operator<<(std::ostream& stream, virtual_cpu::vcpu_register register_id); /** Textual streaming operator for virtual_cpu::execution_state. * * @param stream Output stream * @param state Instance to stream * @return @a stream */ std::ostream& operator<<(std::ostream& stream, virtual_cpu::execution_state state); }
36.261194
87
0.666392
cmannett85
18c8052bf09362fa35b1e958280afa0aceb9f5b0
764
hh
C++
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
null
null
null
dev/g++/projects/embedded/security/include/sha_algorithms.hh
YannGarcia/repo
0f3de24c71d942c752ada03c10861e83853fdf71
[ "MIT" ]
1
2017-01-27T12:53:50.000Z
2017-01-27T12:53:50.000Z
/*! * \file sha_algorithms.hh * \brief Header file for the lightweight security library. * \author garciay.yann@gmail.com * \copyright Copyright (c) 2017 ygarcia. All rights reserved * \license This project is released under the MIT License * \version 0.1 */ #pragma once /*! \namespace security * \brief security namespace */ namespace security { /*! * \enum sha_algorithms_t * \brief List of supported sha algorithms */ enum sha_algorithms_t : uint8_t { // TODO Add 224,226,384,512 sha1 = 0x00, /*!< Secure Hash Algorithm SHA-1 */ sha256 = 0x01, /*!< Secure Hash Algorithm SHA-256 */ sha384 = 0x02 /*!< Secure Hash Algorithm SHA-384 */ }; // End of enum sha_algorithms_t } // End of namespace security
28.296296
63
0.663613
YannGarcia
18ca4de1028c085073e30a11718a7ca5dd3876d9
1,333
cpp
C++
WOJ/#/woj1072.cpp
lijiansong/ACM-Algorithms
f7014f2785390870627885bd3f0b3526115f5894
[ "MIT" ]
1
2021-01-03T09:56:34.000Z
2021-01-03T09:56:34.000Z
WOJ/#/woj1072.cpp
lijiansong/ACM-Algorithms
f7014f2785390870627885bd3f0b3526115f5894
[ "MIT" ]
null
null
null
WOJ/#/woj1072.cpp
lijiansong/ACM-Algorithms
f7014f2785390870627885bd3f0b3526115f5894
[ "MIT" ]
1
2017-12-30T06:14:51.000Z
2017-12-30T06:14:51.000Z
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <string> #include <vector> #include <stack> #include <queue> #include <set> #include <time.h> using namespace std; const int maxint = -1u>>1; #define MAX 10001 int N,p,k; int dp[MAX]; int T[MAX]; typedef struct nt { int start,end,length; bool operator < (const nt a)const { if(start == end) return a.end > end; else return start < a.start; } }TS; TS node[MAX]; int main() { while(scanf("%d", &N) != EOF) { for(int i = 0; i < N; i ++) { scanf("%d %d",&node[i].start, &node[i].end); node[i].length = node[i].end - node[i].start + 1; } stable_sort(node,node+N); memset(dp,0,sizeof(dp)); dp[0] = node[0].length; T[0] = node[0].length; for(int i = 1;i < N; i ++) { int s = i - 1; T[i] = node[i].length; int dT = 0; for(;s >=0;s --) { if(node[i].start > node[s].end) dT = max(dT ,T[s]); } T[i] += dT; dp[i] = max(dp[i-1],T[i]); } printf("%d\n",dp[N - 1]) ; } return 0; }
21.15873
61
0.446362
lijiansong
18cc84ea63bf272b7b3968240e62a15abf619c8a
1,131
cpp
C++
src/Interface/Handling/JSONAPI/JsonAPIErrorBuilder.cpp
edson-a-soares/poco_restful_resource_model
dc9794d619963c6ec990e1764df0de4c72e34aa0
[ "Apache-2.0" ]
59
2018-01-24T08:19:58.000Z
2022-02-10T09:20:46.000Z
src/Interface/Handling/JSONAPI/JsonAPIErrorBuilder.cpp
edson-a-soares/poco_restful_resource_model
dc9794d619963c6ec990e1764df0de4c72e34aa0
[ "Apache-2.0" ]
1
2021-11-11T10:46:18.000Z
2021-11-11T10:46:18.000Z
src/Interface/Handling/JSONAPI/JsonAPIErrorBuilder.cpp
edson-a-soares/poco_restful_resource_model
dc9794d619963c6ec990e1764df0de4c72e34aa0
[ "Apache-2.0" ]
29
2018-04-18T13:03:12.000Z
2022-03-23T12:55:00.000Z
#include "Poco/JSON/Object.h" #include "Interface/Handling/JSONAPI/JsonAPIErrorBuilder.h" namespace Interface { namespace Handling { JsonAPIErrorBuilder::JsonAPIErrorBuilder(const std::string & url) : host(url), commonError(), rootJsonStructure(), errorsCollection(), sourceErrorPointer() { } void JsonAPIErrorBuilder::withStatusCode(int code) { commonError.insert("status", code); } void JsonAPIErrorBuilder::withType(const std::string & type) { commonError.insert("type", type); } void JsonAPIErrorBuilder::withDetails(const std::string & text) { commonError.insert("details", text); } void JsonAPIErrorBuilder::sourceAt(const std::string & pointer) { sourceErrorPointer.insert("pointer", host + pointer); } Poco::DynamicStruct & JsonAPIErrorBuilder::build() { commonError.insert("source", sourceErrorPointer); errorsCollection.push_back(commonError); rootJsonStructure.insert("error", errorsCollection); return rootJsonStructure; } } }
23.5625
69
0.650752
edson-a-soares
18cc9dbab4d69abd7ef7072287689b4a1f3f1342
5,112
cpp
C++
smtbx/refinement/constraints/boost_python/same_group.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
155
2016-11-23T12:52:16.000Z
2022-03-31T15:35:44.000Z
smtbx/refinement/constraints/boost_python/same_group.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
590
2016-12-10T11:31:18.000Z
2022-03-30T23:10:09.000Z
smtbx/refinement/constraints/boost_python/same_group.cpp
rimmartin/cctbx_project
644090f9432d9afc22cfb542fc3ab78ca8e15e5d
[ "BSD-3-Clause-LBNL" ]
115
2016-11-15T08:17:28.000Z
2022-02-09T15:30:14.000Z
#include <boost/python/class.hpp> #include <boost/python/implicit.hpp> #include <scitbx/boost_python/container_conversions.h> #include <smtbx/refinement/constraints/same_group.h> #include <smtbx/refinement/constraints/proxy.h> namespace smtbx { namespace refinement { namespace constraints { namespace boost_python { struct same_group_xyz_wrapper { typedef same_group_xyz wt; static void wrap() { using namespace boost::python; class_<wt, bases<asu_parameter>, std::auto_ptr<wt> >("same_group_xyz", no_init) .def(init<af::shared<wt::scatterer_type *> const &, af::shared<site_parameter *> const &, scitbx::mat3<double> const &, independent_small_vector_parameter<6> *> ((arg("scatterers"), arg("sites"), arg("alignment_matrix"), arg("shifts_and_angles") ))) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; struct same_group_u_iso_wrapper { typedef same_group_u_iso wt; static void wrap() { using namespace boost::python; class_<wt, bases<asu_parameter>, std::auto_ptr<wt> >("same_group_u_iso", no_init) .def(init<af::shared<wt::scatterer_type *> const &, af::shared<scalar_parameter *> const &> ((arg("scatterers"), arg("u_isos") ))) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; struct same_group_u_star_wrapper { typedef same_group_u_star wt; static void wrap() { using namespace boost::python; class_<wt, bases<asu_parameter>, std::auto_ptr<wt> >("same_group_u_star", no_init) .def(init<af::shared<wt::scatterer_type *> const &, af::shared<u_star_parameter *> const &, scitbx::mat3<double> const &, independent_small_vector_parameter<6> *> ((arg("scatterers"), arg("u_stars"), arg("alignment_matrix"), arg("shifts_and_angles") ))) .def(init<af::shared<wt::scatterer_type *> const &, af::shared<u_star_parameter *> const &, scitbx::mat3<double> const &, independent_small_vector_parameter<3> *> ((arg("scatterers"), arg("u_stars"), arg("alignment_matrix"), arg("angles") ))) .add_property("alpha", &wt::alpha) .add_property("beta", &wt::beta) .add_property("gamma", &wt::gamma) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; struct same_group_site_proxy_wrapper { typedef site_proxy<same_group_xyz> wt; static void wrap() { using namespace boost::python; class_<wt, bases<site_parameter>, std::auto_ptr<wt> >("same_group_site_proxy", no_init) .def(init<same_group_xyz *, int> ((arg("parent"), arg("index")))) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; struct same_group_u_iso_proxy_wrapper { typedef u_iso_proxy<same_group_u_iso> wt; static void wrap() { using namespace boost::python; class_<wt, bases<scalar_parameter>, std::auto_ptr<wt> >("same_group_u_iso_proxy", no_init) .def(init<same_group_u_iso *, int> ((arg("parent"), arg("index")))) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; struct same_group_u_star_proxy_wrapper { typedef u_star_proxy<same_group_u_star> wt; static void wrap() { using namespace boost::python; class_<wt, bases<u_star_parameter>, std::auto_ptr<wt> >("same_group_u_star_proxy", no_init) .def(init<same_group_u_star *, int> ((arg("parent"), arg("index")))) ; implicitly_convertible<std::auto_ptr<wt>, std::auto_ptr<parameter> >(); } }; void wrap_same_group() { { using namespace scitbx::boost_python::container_conversions; tuple_mapping_variable_capacity< af::shared<u_star_parameter *> >(); tuple_mapping_variable_capacity< af::shared<scalar_parameter *> >(); } same_group_xyz_wrapper::wrap(); same_group_u_iso_wrapper::wrap(); same_group_u_star_wrapper::wrap(); same_group_site_proxy_wrapper::wrap(); same_group_u_iso_proxy_wrapper::wrap(); same_group_u_star_proxy_wrapper::wrap(); } }}}}
33.411765
79
0.544405
rimmartin
18cd127a29a1d3773239a5ffb2432d85d8bcb02b
8,028
cpp
C++
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
main/gui/LvDisplayDriver.cpp
enelson1001/M5StackDemo01
0ed654406b01e2575facaff522289fcaf555fa91
[ "MIT" ]
null
null
null
/**************************************************************************************** * LvDisplayDriver.h - A LittlevGL Display Driver for ILI9341 * Created on Dec. 03, 2019 * Copyright (c) 2019 Ed Nelson (https://github.com/enelson1001) * Licensed under MIT License (see LICENSE file) * * Derivative Works * Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF * Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) * Licensed under the Apache License, Version 2.0 (the "License"); * * LittlevGL - A powerful and easy-to-use embedded GUI * Copyright (c) 2016 Gábor Kiss-Vámosi (https://github.com/littlevgl/lvgl) * Licensed under MIT License ***************************************************************************************/ #include "gui/LvDisplayDriver.h" #include <esp_freertos_hooks.h> #include <smooth/core/logging/log.h> #include <smooth/core/io/spi/SpiDmaFixedBuffer.h> using namespace smooth::core::io::spi; using namespace smooth::application::display; using namespace smooth::core::logging; namespace redstone { // Class Constants static const char* TAG = "LvDisplayDriver"; static IRAM_ATTR LvDisplayDriver* ptrLvDisplayDriver; // Constructor LvDisplayDriver::LvDisplayDriver() : spi_host(VSPI_HOST), // Use VSPI as host spi_master( spi_host, // host VSPI DMA_1, // use DMA GPIO_NUM_23, // mosi gpio pin GPIO_NUM_19, // miso gpio pin (full duplex) GPIO_NUM_18, // clock gpio pin MAX_DMA_LEN) // max transfer size { } // Initialize the display driver bool LvDisplayDriver::initialize() { Log::info(TAG, "initializing ........"); ili9341_initialized = init_ILI9341(); if (ili9341_initialized) { // M5Stack requires a different setting for a portrait screen display->set_rotation(0x68); // set callback pointer to this object ptrLvDisplayDriver = this; // initialize LittlevGL graphics library lv_init(); // create two small buffers, used by LittlevGL to draw screen content static SpiDmaFixedBuffer<uint8_t, MAX_DMA_LEN> display_buf1; static SpiDmaFixedBuffer<uint8_t, MAX_DMA_LEN> display_buf2; if (display_buf1.is_buffer_allocated() && display_buf2.is_buffer_allocated()) { static lv_color1_t* buf1 = reinterpret_cast<lv_color1_t*>(display_buf1.data()); static lv_color1_t* buf2 = reinterpret_cast<lv_color1_t*>(display_buf2.data()); // initialize a descriptor for the buffer static lv_disp_buf_t disp_buf; lv_disp_buf_init(&disp_buf, buf1, buf2, MAX_DMA_LEN / COLOR_SIZE); //lv_disp_buf_init(&disp_buf, buf1, NULL, MAX_DMA_LEN/COLOR_SIZE); // initialize and register a display driver lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.buffer = &disp_buf; disp_drv.flush_cb = ili9341_flush_cb; lv_disp_drv_register(&disp_drv); // LittlevGL graphics library's tick - runs every 1ms esp_register_freertos_tick_hook(lv_tick_task); } else { ili9341_initialized = false; } } return ili9341_initialized; } // Initialize the ILI9341 bool LvDisplayDriver::init_ILI9341() { auto device = spi_master.create_device<ILI9341>( GPIO_NUM_14, // chip select gpio pin GPIO_NUM_27, // data command gpio pin GPIO_NUM_33, // reset gpio pin GPIO_NUM_32, // backlight gpio pin 0, // spi command_bits 0, // spi address_bits, 0, // bits_between_address_and_data_phase, 0, // spi_mode = 0, 128, // spi positive_duty_cycle, 0, // spi cs_ena_posttrans, SPI_MASTER_FREQ_16M, // spi-sck = 16MHz 0, // full duplex (4-wire) 7, // queue_size, true, // use pre-trans callback true); // use post-trans callback bool res = device->init(spi_host); if (res) { device->reset_display(); res &= device->send_init_cmds(); device->set_back_light(true); display = std::move(device); } else { Log::error(TAG, "Initializing of SPI Device: ILI9341 --- FAILED"); } return res; } // A class instance callback to flush the display buffer and thereby write colors to screen void LvDisplayDriver::display_drv_flush(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map) { uint32_t x1 = area->x1; uint32_t y1 = area->y1; uint32_t x2 = area->x2; uint32_t y2 = area->y2; uint32_t number_of_bytes_to_flush = (x2 - x1 + 1) * (y2 - y1 + 1) * COLOR_SIZE; uint32_t number_of_dma_blocks_with_complete_lines_to_send = number_of_bytes_to_flush / MAX_DMA_LEN; uint32_t number_of_bytes_in_not_complete_lines_to_send = number_of_bytes_to_flush % MAX_DMA_LEN; uint32_t start_row = y1; uint32_t end_row = y1 + LINES_TO_SEND - 1; // Drawing area that has a height of LINES_TO_SEND while (number_of_dma_blocks_with_complete_lines_to_send--) { display->send_lines(x1, start_row, x2, end_row, reinterpret_cast<uint8_t*>(color_map), MAX_DMA_LEN); display->wait_for_send_lines_to_finish(); // color_map is pointer to type lv_color_t were the data type is based on color size so the // color_map pointer may have a data type of uint8_t or uint16_t or uint32_t. MAX_DMA_LEN is // a number based on uint8_t so we need to divide MAX_DMA_LEN by the color size to increment // color_map pointer correctly color_map += MAX_DMA_LEN / COLOR_SIZE; // update start_row and end_row since we have sent a quantity of LINES_TO_SEND rows start_row = end_row + 1; end_row = start_row + LINES_TO_SEND - 1; } // Drawing area that has a height of less than LINE_TO_SEND if (number_of_bytes_in_not_complete_lines_to_send) { end_row = y2; display->send_lines(x1, start_row, x2, end_row, reinterpret_cast<uint8_t*>(color_map), number_of_bytes_in_not_complete_lines_to_send); display->wait_for_send_lines_to_finish(); } // Inform the lvgl graphics library that we are ready for flushing buffer lv_disp_t* disp = lv_refr_get_disp_refreshing(); lv_disp_flush_ready(&disp->driver); } // The "C" style callback required by LittlevGL void IRAM_ATTR LvDisplayDriver::ili9341_flush_cb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* color_map) { if (ptrLvDisplayDriver != nullptr) { ptrLvDisplayDriver->display_drv_flush(drv, area, color_map); } } // The lv_tick_task that is required by LittlevGL for internal timing void IRAM_ATTR LvDisplayDriver::lv_tick_task(void) { lv_tick_inc(portTICK_RATE_MS); // 1 ms tick_task } }
40.341709
118
0.565272
enelson1001
18d1fa45078e1f1e037d2d2b84088bd5c7ff7016
264
cpp
C++
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
8
2015-01-02T21:40:55.000Z
2016-05-12T10:48:09.000Z
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
compiler/AST/Operators/Standard/SubtractionOperatorNode.cpp
mattmassicotte/three
3986c656724d1317bdb46d4777f8f952103d7ce7
[ "MIT" ]
null
null
null
#include "SubtractionOperatorNode.h" namespace Three { std::string SubtractionOperatorNode::nodeName() const { return "Subtraction Operator"; } void SubtractionOperatorNode::accept(ASTVisitor& visitor) { visitor.visit(*this); } }
22
63
0.685606
mattmassicotte
18d479e04481497d84db0ebcade886391c34a155
2,801
cpp
C++
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/unit/boolean/scalar/seldec.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/boolean/include/functions/seldec.hpp> #include <boost/simd/sdk/simd/io.hpp> #include <boost/dispatch/meta/as_integer.hpp> #include <nt2/sdk/unit/tests/relation.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/type_expr.hpp> #include <boost/simd/include/constants/one.hpp> #include <boost/simd/include/constants/zero.hpp> #include <boost/simd/include/constants/mone.hpp> NT2_TEST_CASE_TPL ( seldec_signed_int__2_0, BOOST_SIMD_INTEGRAL_SIGNED_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Mone<T>()), boost::simd::Mtwo<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Mone<T>()); } NT2_TEST_CASE_TPL ( seldec_unsigned_int__2_0, BOOST_SIMD_UNSIGNED_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Two<T>()), boost::simd::One<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Valmax<T>()); } NT2_TEST_CASE_TPL( seldec_floating, BOOST_SIMD_REAL_TYPES) { using boost::simd::seldec; using boost::simd::tag::seldec_; typedef typename boost::dispatch::meta::call<seldec_(T, T)>::type r_t; typedef T wished_r_t; // return type conformity test NT2_TEST_TYPE_IS( r_t, wished_r_t ); // specific values tests NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::One<T>()), boost::simd::Zero<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Two<T>()), boost::simd::One<T>()); NT2_TEST_EQUAL(seldec(boost::simd::One<T>(), boost::simd::Zero<T>()), boost::simd::Mone<T>()); }
41.80597
98
0.650125
psiha
18d5fbbcb5bc408e579b72d5dc4e21c2f8a7a2e1
898
hpp
C++
pom/maths/operation/noise/gradient_2_value.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
pom/maths/operation/noise/gradient_2_value.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
pom/maths/operation/noise/gradient_2_value.hpp
e-Sharp/pom_gen_proc
cef7a57620d52631c1e94f71c71e0455f9e1b653
[ "MIT" ]
null
null
null
#pragma once #include "gradient_2.hpp" #include "pom/maths/operation/cubic_step.hpp" #include "pom/maths/operation/floor.hpp" #include "pom/maths/operation/fract.hpp" #include "pom/maths/operation/lerp.hpp" #include "pom/maths/vector/all.hpp" namespace pom::maths { template<typename N> constexpr auto value(const gradient_noise_2<N>& n, static_vector<float, 2> v) { auto i = floor(v); auto f = fract(v); auto x = cubic_step(0.f, 1.f, at(f, 0)); auto y = cubic_step(0.f, 1.f, at(f, 1)); constexpr auto v00 = vector_of(0.f, 0.f); constexpr auto v10 = vector_of(1.f, 0.f); constexpr auto v01 = vector_of(0.f, 1.f); constexpr auto v11 = vector_of(1.f, 1.f); return lerp( lerp(dot(n.hash(i + v00), f - v00), dot(n.hash(i + v10), f - v10), x), lerp(dot(n.hash(i + v01), f - v01), dot(n.hash(i + v11), f - v11), x), y); } }
26.411765
69
0.615813
e-Sharp
18de0b122c448eeb1dfa08698cefb228782d2d7f
1,281
cpp
C++
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
1090 - Trailing Zeroes (II).cpp
BRAINIAC2677/Lightoj-Solutions
e75f56b2cb4ef8f7e00de39fed447b1b37922427
[ "MIT" ]
null
null
null
/*BISMILLAH THE WHITE WOLF NO DREAM IS TOO BIG AND NO DREAMER IS TOO SMALL*/ #include<bits/stdc++.h> using namespace std; #define io ios_base::sync_with_stdio(false) #define ll long long #define ull unsigned long long #define vi vector<int> #define vll vector<long long> #define pb push_back #define mod 1000000007 #define pii pair<int, int> #define PI 2*acos(0.0) int wasp[500005]; void climax() { for(int i = 1; i <= 500000; i++) { int even = 2*i, x = 0; while(even%2 == 0) { even/= 2; x++; } wasp[i] = wasp[i-1] + x; } } int trailer(int x) { int aa=0; while(x>=5) { x = x/5; aa += x; } return aa; } int main() { io; climax(); int t; cin>>t; for(int i = 1; i<=t; i++) { int n, r, p, q; cin>>n>>r>>p>>q; int x = 0, ans, two = p, y = 0; while(p%5 == 0) { x++; p/=5; } while(two%2==0) { y++; two/=2; } x = trailer(n) - trailer(r) - trailer(n-r) + x*q; y = y*q + wasp[n/2] - wasp[r/2] - wasp[(n-r)/2]; ans = min(x, y); cout << "Case " << i <<": " <<ans <<"\n"; } return 0; }
17.547945
57
0.440281
BRAINIAC2677
18df442e5a42c7bc562ecfdb26050d84f9b570f6
9,441
cpp
C++
src/mame/drivers/miniframe.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/miniframe.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/miniframe.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:GPL-2.0+ // copyright-holders:Dirk Best, R. Belmont /*************************************************************************** Convergent Miniframe Preliminary driver by R. Belmont based on unixpc.cpp by Dirk Best & R. Belmont ***************************************************************************/ #include "emu.h" #include "cpu/m68000/m68000.h" #include "imagedev/floppy.h" #include "machine/ram.h" #include "machine/wd_fdc.h" #include "machine/bankdev.h" #include "machine/pit8253.h" #include "machine/pic8259.h" #include "screen.h" /*************************************************************************** DRIVER STATE ***************************************************************************/ class miniframe_state : public driver_device { public: miniframe_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_ram(*this, RAM_TAG) , m_wd2797(*this, "wd2797") , m_floppy(*this, "wd2797:0:525dd") , m_ramrombank(*this, "ramrombank") , m_mapram(*this, "mapram") { } void miniframe(machine_config &config); private: required_device<m68010_device> m_maincpu; required_device<ram_device> m_ram; required_device<wd2797_device> m_wd2797; required_device<floppy_image_device> m_floppy; required_device<address_map_bank_device> m_ramrombank; uint32_t screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); virtual void machine_start() override; virtual void machine_reset() override; uint16_t ram_mmu_r(offs_t offset); void ram_mmu_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); void general_ctrl_w(uint16_t data); DECLARE_WRITE_LINE_MEMBER( wd2797_intrq_w ); DECLARE_WRITE_LINE_MEMBER( wd2797_drq_w ); required_shared_ptr<uint16_t> m_mapram; void miniframe_mem(address_map &map); void ramrombank_map(address_map &map); uint16_t *m_ramptr; uint32_t m_ramsize; uint16_t m_diskdmasize; uint32_t m_diskdmaptr; bool m_fdc_intrq; }; /*************************************************************************** MEMORY ***************************************************************************/ static constexpr unsigned MMU_MAX_PAGES = 1024; static constexpr uint16_t MMU_WRITE_ENABLE = 0x8000; static constexpr uint16_t MMU_STATUS_MASK = 0x6000; static constexpr uint16_t MMU_STATUS_NOT_PRESENT = 0x0000; static constexpr uint16_t MMU_STATUS_PRESENT_NOT_ACCESSED = 0x2000; static constexpr uint16_t MMU_STATUS_ACCESSED_NOT_WRITTEN = 0x4000; static constexpr uint16_t MMU_STATUS_ACCESSED_WRITTEN = 0x6000; uint16_t miniframe_state::ram_mmu_r(offs_t offset) { uint8_t fc = m_maincpu->get_fc(); uint16_t mapentry = m_mapram[(offset >> 11) & 0x7ff]; if ((offset < ((512*1024)>>1)) && (fc != M68K_FC_SUPERVISOR_DATA) && (fc != M68K_FC_SUPERVISOR_PROGRAM)) { fatalerror("mmu: user mode access to lower 512K, need to generate a fault\n"); } if ((mapentry & MMU_STATUS_MASK) != MMU_STATUS_NOT_PRESENT) { uint32_t addr = (offset & 0x7ff) | ((mapentry & 0xfff) << 11); //printf("mmu_r: orig %x entry %04x xlate %x\n", offset, mapentry, addr); // indicate page has been read if ((mapentry & MMU_STATUS_MASK) == MMU_STATUS_PRESENT_NOT_ACCESSED) { m_mapram[(offset >> 11) & 0x7ff] &= ~MMU_STATUS_MASK; m_mapram[(offset >> 11) & 0x7ff] |= MMU_STATUS_ACCESSED_NOT_WRITTEN; } return m_ramptr[addr]; } else { fatalerror("miniframe: invalid MMU page accessed, need to throw a fault\n"); } } void miniframe_state::ram_mmu_w(offs_t offset, uint16_t data, uint16_t mem_mask) { uint8_t fc = m_maincpu->get_fc(); uint16_t mapentry = m_mapram[(offset >> 11) & 0x7ff]; if ((offset < ((512*1024)>>1)) && (fc != M68K_FC_SUPERVISOR_DATA) && (fc != M68K_FC_SUPERVISOR_PROGRAM)) { fatalerror("mmu: user mode access to lower 512K, need to generate a fault\n"); } if ((mapentry & MMU_STATUS_MASK) != MMU_STATUS_NOT_PRESENT) { uint32_t addr = (offset & 0x7ff) | ((mapentry & 0xfff) << 11); //printf("mmu_w: orig %x entry %04x xlate %x\n", offset, mapentry, addr); if (!(mapentry & MMU_WRITE_ENABLE) && (fc != M68K_FC_SUPERVISOR_PROGRAM) && (fc != M68K_FC_SUPERVISOR_DATA)) { fatalerror("mmu: write protection violation, need to throw a fault\n"); } // indicate page has been written // we know it's OK to just OR this m_mapram[(offset >> 11) & 0x7ff] |= MMU_STATUS_ACCESSED_WRITTEN; COMBINE_DATA(&m_ramptr[addr]); } else { fatalerror("miniframe: invalid MMU page accessed, need to throw a fault\n"); } } void miniframe_state::general_ctrl_w(uint16_t data) { if (data & 0x1000) // ROM mirror at 0 if set { m_ramrombank->set_bank(1); } else { m_ramrombank->set_bank(0); } logerror("%x to general_ctrl_w\n", data); } void miniframe_state::machine_start() { m_ramptr = (uint16_t *)m_ram->pointer(); m_ramsize = m_ram->size(); } void miniframe_state::machine_reset() { // force ROM into lower mem on reset m_ramrombank->set_bank(0); // invalidate all pages by clearing all entries memset(m_mapram, 0, MMU_MAX_PAGES * sizeof(uint16_t)); } /*************************************************************************** VIDEO ***************************************************************************/ uint32_t miniframe_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { return 0; } /*************************************************************************** ADDRESS MAPS ***************************************************************************/ void miniframe_state::miniframe_mem(address_map &map) { map(0x000000, 0x3fffff).m(m_ramrombank, FUNC(address_map_bank_device::amap16)); map(0x400000, 0x4007ff).ram().share("mapram"); map(0x450000, 0x450001).w(FUNC(miniframe_state::general_ctrl_w)); map(0x800000, 0x81ffff).rom().region("bootrom", 0); map(0xc00000, 0xc00007).rw("pit8253", FUNC(pit8253_device::read), FUNC(pit8253_device::write)).umask16(0x00ff); map(0xc40000, 0xc40007).rw("baudgen", FUNC(pit8253_device::read), FUNC(pit8253_device::write)).umask16(0x00ff); map(0xc90000, 0xc90003).rw("pic8259", FUNC(pic8259_device::read), FUNC(pic8259_device::write)).umask16(0x00ff); } void miniframe_state::ramrombank_map(address_map &map) { map(0x000000, 0x3fffff).rom().region("bootrom", 0); map(0x400000, 0x7fffff).rw(FUNC(miniframe_state::ram_mmu_r), FUNC(miniframe_state::ram_mmu_w)); } /*************************************************************************** INPUT PORTS ***************************************************************************/ static INPUT_PORTS_START( miniframe ) INPUT_PORTS_END /*************************************************************************** MACHINE DRIVERS ***************************************************************************/ static void miniframe_floppies(device_slot_interface &device) { device.option_add("525dd", FLOPPY_525_DD); } void miniframe_state::miniframe(machine_config &config) { // basic machine hardware M68010(config, m_maincpu, XTAL(10'000'000)); m_maincpu->set_addrmap(AS_PROGRAM, &miniframe_state::miniframe_mem); // internal ram RAM(config, RAM_TAG).set_default_size("1M").set_extra_options("2M"); // RAM/ROM bank ADDRESS_MAP_BANK(config, "ramrombank").set_map(&miniframe_state::ramrombank_map).set_options(ENDIANNESS_BIG, 16, 32, 0x400000); // floppy WD2797(config, m_wd2797, 1000000); // m_wd2797->intrq_wr_callback().set(FUNC(miniframe_state::wd2797_intrq_w)); // m_wd2797->drq_wr_callback().set(FUNC(miniframe_state::wd2797_drq_w)); FLOPPY_CONNECTOR(config, "wd2797:0", miniframe_floppies, "525dd", floppy_image_device::default_mfm_floppy_formats); // 8263s pit8253_device &pit8253(PIT8253(config, "pit8253", 0)); pit8253.set_clk<0>(76800); pit8253.set_clk<1>(76800); pit8253.out_handler<0>().set("pic8259", FUNC(pic8259_device::ir4_w)); // FIXME: fighting for IR4 - error, or needs input merger? // chain clock 1 output into clock 2 pit8253.out_handler<1>().set("pit8253", FUNC(pit8253_device::write_clk2)); // and ir4 on the PIC pit8253.out_handler<1>().append("pic8259", FUNC(pic8259_device::ir4_w)); pit8253_device &baudgen(PIT8253(config, "baudgen", 0)); baudgen.set_clk<0>(1228800); baudgen.set_clk<1>(1228800); baudgen.set_clk<2>(1228800); // PIC8259s pic8259_device &pic8259(PIC8259(config, "pic8259", 0)); pic8259.out_int_callback().set_inputline(m_maincpu, M68K_IRQ_4); pic8259.in_sp_callback().set_constant(1); } /*************************************************************************** ROM DEFINITIONS ***************************************************************************/ ROM_START( minifram ) ROM_REGION16_BE(0x400000, "bootrom", 0) ROM_LOAD16_BYTE("72-00357.bin", 0x000001, 0x002000, CRC(17c2749c) SHA1(972b5300b4d6ec65536910eab2b8550b9df9bb4d)) ROM_LOAD16_BYTE("72-00356.bin", 0x000000, 0x002000, CRC(28b6c23a) SHA1(479e739a8154b6754e2e9b1fcfeb99d6ceaf9dbe)) ROM_END /*************************************************************************** GAME DRIVERS ***************************************************************************/ // YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS COMP( 1985, minifram, 0, 0, miniframe, miniframe, miniframe_state, empty_init, "Convergent", "Miniframe", MACHINE_NOT_WORKING | MACHINE_NO_SOUND )
33.478723
156
0.6297
Robbbert
18e2ba5b4b8151f01eb041d30255f0c1163bf2a9
1,835
hxx
C++
opencascade/TopOpeBRep_WPointInter.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/TopOpeBRep_WPointInter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/TopOpeBRep_WPointInter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1993-11-10 // Created by: Jean Yves LEBEY // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRep_WPointInter_HeaderFile #define _TopOpeBRep_WPointInter_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopOpeBRep_PPntOn2S.hxx> #include <Standard_Real.hxx> class IntSurf_PntOn2S; class gp_Pnt2d; class gp_Pnt; class TopOpeBRep_WPointInter { public: DEFINE_STANDARD_ALLOC Standard_EXPORT TopOpeBRep_WPointInter(); Standard_EXPORT void Set (const IntSurf_PntOn2S& P); Standard_EXPORT void ParametersOnS1 (Standard_Real& U, Standard_Real& V) const; Standard_EXPORT void ParametersOnS2 (Standard_Real& U, Standard_Real& V) const; Standard_EXPORT void Parameters (Standard_Real& U1, Standard_Real& V1, Standard_Real& U2, Standard_Real& V2) const; Standard_EXPORT gp_Pnt2d ValueOnS1() const; Standard_EXPORT gp_Pnt2d ValueOnS2() const; Standard_EXPORT const gp_Pnt& Value() const; Standard_EXPORT TopOpeBRep_PPntOn2S PPntOn2SDummy() const; protected: private: TopOpeBRep_PPntOn2S myPP2S; }; #endif // _TopOpeBRep_WPointInter_HeaderFile
22.378049
117
0.775477
valgur
18e2d45e5d9bbd28f4cb0a08a12d5c82384b3fc8
7,154
hpp
C++
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
1
2021-07-14T19:59:59.000Z
2021-07-14T19:59:59.000Z
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
null
null
null
src/GvmClusterPairs.hpp
mdejong/GvmCpp
827130a145164ae610416d177bfc091246174a60
[ "Apache-2.0" ]
1
2017-11-10T17:05:58.000Z
2017-11-10T17:05:58.000Z
// // GvmClusterPairs.hpp // GvmCpp // // Created by Mo DeJong on 8/14/15. // // 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 // // Maintains a heap of cluster pairs. #import "GvmCommon.hpp" #import "GvmClusterPair.hpp" namespace Gvm { // S // // Cluster vector space. // V // // Cluster vector type. // K // // Type of key. // FP // // Floating point type. template<typename S, typename V, typename K, typename FP> class GvmClusterPairs { public: static inline int ushift_left(int n) { #if defined(DEBUG) assert(n >= 0); #endif // DEBUG uint32_t un = (uint32_t) n; un <<= 1; return un; } static inline int ushift_right(int n) { #if defined(DEBUG) assert(n >= 0); #endif // DEBUG uint32_t un = (uint32_t) n; un >>= 1; return un; } // Pairs is an array of pointers to GvmClusterPair objects. // This data structure makes it easy to move an item // allocated on the heap around in the array without having // to copy the object data which is critical for performance. GvmClusterPair<S,V,K,FP> **pairs; // Cluster pairs are allocated as a solid block of (N * N) instances // so that these pointers can be sorted and rearranged without use // of shared_ptr for each cluster pair object. GvmClusterPair<S,V,K,FP> *pairsArray; int size; // The size of the pairs allocation. This size is defined at object // construction time and cannot be changed during object lifetime // for performance reasons. int capacity; // The number of pairsArray values that have been used. int pairsUsed; GvmClusterPairs<S,V,K,FP>(int inCapacity) : size(0), capacity(inCapacity), pairsUsed(0) { // For N clusters, allocate solid block of (N * N) cluster pairs, // this allocation represents a significant amount of the memory // used by the library. assert(capacity > 0); pairsArray = new GvmClusterPair<S,V,K,FP>[capacity]; assert(pairsArray); if ((0)) { fprintf(stdout, "alloc pairsArray of size %d bytes : 0x%p\n", (int)(capacity * sizeof(GvmClusterPair<S,V,K,FP>)), pairsArray); } // pairs is an array of pointers into pairsArray // initialized to nullptr. pairs = new GvmClusterPair<S,V,K,FP>*[capacity](); assert(pairs); if ((0)) { fprintf(stdout, "alloc pairs of size %d bytes : 0x%p\n", (int)(capacity * sizeof(GvmClusterPair<S,V,K,FP>*)), pairs); } return; } ~GvmClusterPairs<S,V,K,FP>() { if ((0)) { fprintf(stdout, "dealloc pairs 0x%p\n", pairs); } delete [] pairs; if ((0)) { fprintf(stdout, "dealloc pairsArray 0x%p\n", pairsArray); } delete [] pairsArray; } // Copy constructor explicitly deleted GvmClusterPairs<S,V,K,FP>(GvmClusterPairs<S,V,K,FP> &that) = delete; GvmClusterPairs<S,V,K,FP>(const GvmClusterPairs<S,V,K,FP> &that) = delete; // Operator= explicitly deleted GvmClusterPairs<S,V,K,FP>& operator=(GvmClusterPairs<S,V,K,FP>& x) = delete; GvmClusterPairs<S,V,K,FP>& operator=(const GvmClusterPairs<S,V,K,FP>& x) = delete; // add() should be passed a pair pointer returned by newSharedPair. void add(GvmClusterPair<S,V,K,FP> *pair) { int i = size; // Note that grow() logic is not supported here since the object // uses a fixed max size for pairs so that this add() method // can execute a more optimal execution path. #if defined(DEBUG) if (i >= capacity) { assert(0); } #endif // DEBUG size = i + 1; if (i == 0) { pairs[0] = pair; pair->index = 0; } else { heapifyUp(i, pair); } return; } // add cluster pair and return ref to shared pair object that was just added GvmClusterPair<S,V,K,FP>* newSharedPair(GvmCluster<S,V,K,FP> &c1, GvmCluster<S,V,K,FP> &c2) { assert(pairsUsed <= (capacity-1)); GvmClusterPair<S,V,K,FP> *pairPtr = &pairsArray[pairsUsed]; pairsUsed++; pairPtr->set(&c1, &c2); return pairPtr; } GvmClusterPair<S,V,K,FP>* peek() { return size == 0 ? nullptr : pairs[0]; } bool remove(GvmClusterPair<S,V,K,FP> *pair) { int i = indexOf(pair); if (i == -1) return false; removeAt(i); return true; } void reprioritize(GvmClusterPair<S,V,K,FP> *pair) { int i = indexOf(pair); #if defined(DEBUG) if (i == -1) { assert(0); } #endif // DEBUG pair->update(); GvmClusterPair<S,V,K,FP> *parent = (i == 0) ? nullptr : pairs[ ushift_right(i - 1) ]; if (parent != nullptr && parent->value > pair->value) { heapifyUp(i, pair); } else { heapifyDown(i, pair); } } int getSize() { return size; } void clear() { for (int i = 0; i < size; i++) { GvmClusterPair<S,V,K,FP> *e = pairs[i]; e->index = -1; //pairs[i] = e; } size = 0; } int indexOf(GvmClusterPair<S,V,K,FP> *pair) { #if defined(DEBUG) assert(pair != nullptr); #endif // DEBUG return pair->index; } void removeAt(int i) { int s = --size; if (s == i) { // removing last element pairs[i]->index = -1; pairs[i] = nullptr; } else { // Move pair object from one array slot to another GvmClusterPair<S,V,K,FP> *moved = pairs[s]; pairs[s] = nullptr; moved->index = -1; heapifyDown(i, moved); if (pairs[i] == moved) { heapifyUp(i, moved); if (pairs[i] != moved) { return; } } } return; } void heapifyUp(int k, GvmClusterPair<S,V,K,FP> *pair) { auto pairValue = pair->value; while (k > 0) { int parent = ushift_right(k - 1); GvmClusterPair<S,V,K,FP> *e = pairs[parent]; if (pairValue >= e->value) break; pairs[k] = e; e->index = k; k = parent; } pairs[k] = pair; pair->index = k; } void heapifyDown(int k, GvmClusterPair<S,V,K,FP> *pair) { auto pairValue = pair->value; int half = ushift_right(size); while (k < half) { int child = ushift_left(k) + 1; GvmClusterPair<S,V,K,FP> *c = pairs[child]; int right = child + 1; if (right < size && c->value > pairs[right]->value) { child = right; c = pairs[child]; } if (pairValue <= c->value) break; pairs[k] = c; c->index = k; k = child; } pairs[k] = pair; pair->index = k; } }; // end class GvmClusterPairs }
25.368794
134
0.549623
mdejong