blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
sequencelengths
1
1
author
stringlengths
0
119
11b96deb8736709de660495f1f98f3916dc4f88b
0365db07f7469678afaf922542176a3b73357736
/host/analyze_mjpeg.cpp
5b939743ec30767e6dcceb0521876dabed9e436f
[ "MIT" ]
permissive
zk1132/stm32f429idiscovery-usb-screen
9b26f6578d99f96ffb350bf7d283ef394996fbae
777603e3e0d752bc0eea0764eeb72e21c3ba6e9a
refs/heads/master
2021-01-12T04:34:22.498160
2016-10-02T23:18:02
2016-10-02T23:18:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,819
cpp
#include "stdafx.h" #include "jpeg.h" #include "stm32f4_discovery_usb_screen.h" // astyle --pad-oper --indent=spaces=2 --pad-header analyze_mjpeg.cpp using namespace std; #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; using namespace boost::algorithm; using boost::asio::ip::tcp; using boost::lexical_cast; int run(int argc, char* argv[]); void reduce_and_convert(u16* dst, int dst_w, int dst_h, const u8* src, int src_w, int src_h); int main(int argc, char* argv[]) { if (argc != 4) { cout << "Usage: " << argv[0] << " <server> <port> <path>\n" << endl; return 1; } try { return run(argc, argv); } catch (std::exception& e) { cout << "Exception: " << e.what() << "\n"; return 1; } return 0; } int run(int argc, char* argv[]) { init_usb(); //uint16_t b[320*200*2]; //send_screen(b); boost::asio::io_service io_service; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { //cout << "trying..." << endl; socket.close(); socket.connect(*endpoint_iterator++, error); } if (error) { throw boost::system::system_error(error); } //cout << "connected" << endl; // Form the request. boost::asio::streambuf request; ostream request_stream(&request); request_stream << "GET " << argv[3] << " HTTP/1.1\r\n"; // Some buggy cams don't work without a user-agent. The header SHOULD be // included according to the HTTP spec. request_stream << "User-Agent: MJPEGviewer\r\n"; request_stream << "Host: " << argv[1] << ":" << argv[2] << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "\r\n"; // Send the request. boost::asio::write(socket, request); //cout << "sent" << endl; // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); //cout << "got response" << endl; // Check that response is OK. istream response_stream(&response); string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; string status_message; getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { cout << "Invalid response\n"; return 1; } if (status_code != 200) { cout << "Response returned with status code " << status_code << "\n"; return 1; } //cout << "response is ok" << endl; // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); //cout << "header read ok" << endl; // Get the MIME multipart boundary from the headers. regex rx_content_type("Content-Type:.*boundary=(.*)", regex::icase); regex rx_content_length("Content-length: (.*)", regex::icase); smatch match; string header; string boundary; while (getline(response_stream, header) && header != "\r") { //cout << "HTTP HEADER: " << header << endl; if (regex_search(header, match, rx_content_type)) { boundary = match[1]; //cout << "BOUNDARY SELECTED: " << boundary << endl; } } //cout << "got mime ok" << endl; //cout << "boundary: " << boundary << endl; // Abort if a boundary was not found. if (boundary == "") { cout << "Not a valid MJPEG stream" << endl; return false; } u32 buf_size(0); char* buf(0); u32 cycles = 0; while (1) { //cout << "-- START CYCLE --" << endl; //cout << "RESPONSE SIZE, BEFORE READ TO BOUNDARY: " << response.size() << endl; // Read until there is a boundary in the response. If there is already a // boundary in the buffer, this is a no-op. boost::asio::read_until(socket, response, boundary); //cout << "RESPONSE SIZE, AFTER READ TO BOUNDARY: " << response.size() << endl; // Remove everything up to and including the boundary that is now known to // be there. while (getline(response_stream, header)) { //cout << "BOUNDARY SEARCH: " << header << endl; if (header == boundary) { //cout << "BOUNDARY FOUND: " << header << endl; break; } } // Read the headers that follow the boundary. These always end with a blank // line. Content-Length must be one of the header lines, and the size of the // compressed jpeg is read from it. //cout << "RESPONSE SIZE, AFTER BOUNDARY SEARCH: " << response.size() << endl; u32 content_length; while (getline(response_stream, header) && header != "\r") { trim(header); //cout << "MM HEADER: " << header << endl; if (regex_search(header, match, rx_content_length)) { content_length = lexical_cast<int>(match[1]); //cout << "MM HEADER CONTENT-LENGTH FOUND: " << content_length << endl; } } // Read until the entire jpeg is in the response. if (response.size() < content_length) { boost::asio::read(socket, response, boost::asio::transfer_at_least( content_length - response.size())); } //cout << "RESPONSE SIZE, BEFORE SGETN: " << response.size() << endl; if (buf_size < content_length) { buf_size = content_length; if (buf) { free(buf); } buf = (char*)malloc(buf_size); } response.sgetn(buf, content_length); //cout << "RESPONSE SIZE, BEFORE JPEG CONSUME: " << response.size() << endl; //response.consume(content_length); //cout << "RESPONSE SIZE, AFTER JPEG CONSUME: " << response.size() << endl; // Dump JPG to file for debugging. //char buf2[10000] = {0}; //response.sgetn(buf2, 1000); //ofstream o("out.bin", ios::binary); //o.write(buf2, 1000); Image image = decompress_jpeg(buf, content_length); if (!image.error) { const u8* image_ptr(&image.image_data[0]); uint16_t screen_buf[320 * 240]; reduce_and_convert(screen_buf, 320, 240, image_ptr, image.w, image.h); send_screen(screen_buf); } ++cycles; //cout << "cycles: " << cycles << endl; } free(buf); deinit_usb(); return 0; } // - Convert from 24-bit RGB to 16-bit RGB. // - Reduce size from native web cam to 320x240 using pixel averages. If source // size does not divide evenly by destination size on an axis, part of the // source is unused in that axis. // - Rotate image 90 deg to compensate for portrait memory layout on Discovery // board. void reduce_and_convert(u16* dst, int dst_w, int dst_h, const u8* src, int src_w, int src_h) { int w_ratio = src_w / dst_w; int h_ratio = src_h / dst_h; int ratio = w_ratio * h_ratio; for (int dst_y = 0; dst_y < dst_h; ++dst_y) { for (int dst_x = 0; dst_x < dst_w; ++dst_x) { int r = 0; int g = 0; int b = 0; for (int src_y = 0; src_y < h_ratio; ++src_y) { int pos_y = (dst_y * h_ratio + src_y) * src_w * 3; for (int src_x = 0; src_x < w_ratio; ++src_x) { int pos_x = (dst_x * w_ratio + src_x) * 3; int offset = pos_x + pos_y; r += src[offset]; g += src[++offset]; b += src[++offset]; } } r /= ratio; g /= ratio; b /= ratio; dst[dst_y + dst_h * (dst_w - 1 - dst_x)] = (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3); } } }
be6e8b925373f4db10b5d2e8116c68e67e3366b8
ab7ec9eab24f5a1ceeb33220ecaca36595ae5646
/CS216PA3 with bonus/Project3/WordLadder.h
56299551d3a4c4866c1b1cadf9533c5f2141e30b
[]
no_license
hacker41601/special-happiness
ca0cb8cbe88fdec584197118faa90f89a2ff1ab2
9cc36e6b76aed1f0c1689a74f95d7a7975523f4f
refs/heads/master
2022-05-28T13:14:39.998549
2020-05-01T21:25:44
2020-05-01T21:25:44
260,560,514
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
h
/* * File: WordLadder.h * Course: CS216-003 * Project: Project 3 * Purpose: Declaration of WordLadder class */ #ifndef WORDLADDER_H #define WORDLADDER_H #include "Graph.h" #include <vector> #include <stack> #include <string> using namespace std; class WordLadder{ public: // default constructor WordLadder(); // alternative constructor WordLadder(const vector<string>& words); // to add a newword in the collection void insertWord(string newword); // return a graph from the group of words with the same lengths = length // there is an edge between two words // if two words are only different in a single letter Graph<string> WordsGraph(int length) const; // return a vector of words // which represents a word ladder from word1 to word2 // any two adjacent words along the ladder differ in only one character vector<string> getLadder(string word1, string word2) const; private: // Group all the words by the number of characters in each word: // the private data member represents a mapping from the length (key) // to a vector of words which contain length number of characters (value) map<int, vector<string> > wordsByLength; }; #endif
2c6839dd118adef3ffd678da6f0cba172666009e
d1b2b8edcc725770488068bfa47baede1da7058c
/5 dynamic_programming/1 0-1_knapsack/4 Minimum_sum_partition/Min_diff_partition_subset.cpp
90bf6050ea5bd4aa4b12951cdc15b007b9e64488
[]
no_license
shubhamg199630/coding_interview_course
dbe060a2f33e21f3c7cbaeeff7571c80358aa2ea
6f06438758e87ee0e6c9d70a5b5e2d2c2aa5c2e5
refs/heads/main
2023-06-08T08:51:59.173107
2021-06-19T19:56:46
2021-06-19T19:56:46
326,496,520
0
1
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include<bits/stdc++.h> using namespace std; bool dp[1001][1001]; bool subset_sum(int arr[], int n ,int sum) { for (int i=1;i<=n;i++) { for (int j=1;j<=sum;j++) { if(arr[i-1]<=j) dp[i][j]=dp[i-1][j]||dp[i-1][j-arr[i-1]]; else dp[i][j]=dp[i-1][j]; } } return dp[n][sum]; } void intialization_of_dp() { memset(dp,false,sizeof(dp)); for (int i=0;i<=1000;i++) { for (int j=0;j<=1000;j++) { if (j==0) dp[i][j]=true; else if (i==0) dp[i][j]=false; } } } void printdp(int n, int sum) { for (int i=0;i<=n;i++) { for (int j=0;j<=sum;j++) { cout<<dp[i][j]<<" "; } cout<<endl; } } int min_diff_partition_subset(int arr[], int n) { int range=0; for (int i=0;i<n;i++) range=range+arr[i]; subset_sum(arr,n, range); int mi=INT_MAX; for (int i=0;i<=range;i++) if(dp[n][i]==true) mi=min(mi,abs(range-2*i)); return mi; } int main() { int n; n=6; int arr[]={8, 4, 5, 7, 6, 2 };//sum=10; //Target Sum intialization_of_dp(); cout<<min_diff_partition_subset(arr,n)<<endl; //printdp(n,sum); }
1cd28019f65db30869125aa68f0040026fa638dd
54a0e4f3f7df67cda627b13f88243c6d94058b90
/lab2/lab2.cpp
5d78e6af18e9d101e8813f5eec57ed44ecc92260
[]
no_license
jacobhilty/Jacobhilty-csci20-fall2016
11060b349c70278440ea949c20563146ea74fb05
34b2f010f6caba2dfd5544885c495721d09a7f45
refs/heads/master
2020-11-30T13:53:49.381013
2016-09-06T09:54:20
2016-09-06T09:54:20
66,402,110
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
//Jacob hilty //8/25/16 //Creating an algorithm in comments, finished at home. //1. Computer chooses any number between 1 and 10 that the user cannot see //2. User picks number between 1 and 10 //3. if user's chosen number is the same as number chosen by the compputer, user is awarded 10 points. //4. if user's chosen number is not the same as number chosen by the computer, user may guess again, losing 1 possible point in the process of an incorrect guess. //4-2. example: computer picks 2, user picks 3, user loses 1 possible point out of 10. In the next guess, user picks 2, gets 9 points.
23ca988c0b8a51164b47758cd682c0c6d3dfc63d
b5ab8ab0eb0585ce4ed3650dfb0fdee2934ee0d8
/TMCDriver.h
6f2ffffd588756d6417ef4c7945561f26049702a
[]
no_license
wwkkww1983/Stretcher-Unit
6564359c21936a5336863231bf9e569f5f1b438c
365c1333d28b04bb35b67c320177e50d79473ff2
refs/heads/master
2022-06-12T03:28:08.183167
2020-05-04T05:49:54
2020-05-04T05:49:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,699
h
#ifndef TMCDRIVER_H_ #define TMCDRIVER_H_ class TMC2660 { public: void init(); //DRVCONF void slopeControlHigh(); void slopeControlLow(); void motorShortTimer(); //TS2G short to ground timer. (turns off power mosfets) void stepMode(); //RDSEL 0: step and dir interface, 1: SPI interface void rmsCurrent(); //VSENSE void readMode(); //RDSEL Microstep positon or stallguard or coolStep current level readback //SGCSCONF void filterMode(); //SFILT 0: standard mode, rapid stall detection 1: Filtered mode for precise load measurement. void stallGrdThresh(); //SGT the higher the value, the higher the torque required to indicate a stall, start with 0. void currentScale(); //CS //SMARTEN void minCoilCurrent(); //SEIMIN 0: 1/2 of CS 1: 1/4 of CS void coilDecrementSpd(); //SEDN number of times stallguard2 is above threshold is sampled before decrement. void coilUpperThreshold(); //SEMAX Threshold (high) is (SEMIN + SEMAX + 1)*32 decreases current scaling when above threshold. void coilLowerThreshold(); //SEMIN Threshold (low) is (SEMIN)*32 increases current scaling when below threshold. void coilIncrementSize(); //SEUP The magnitude of compensation when the coil current drops below the low threshold. //CHOPCONF void blankTime(); //TBL the number of cycles after a switch, in which the sense resistor ringing is ignored (ripples are bad). void chopperMode(); //CHM 1: constant off-time mode 0: spreadCycle mode //Spreadcycle mode (dynamic TOFF mode) void hystEnd(); //HEND sets minimum allowable offset value from target current. void hystStart(); //HSTRT sets maximum allowable offset value from target current. void hystDecrement(); //HDEC sets the rate at which the value decrements from HSTRT+HEND to HEND. //Constant TOFF mode void slowDecayTime(); //TOFF t = (1/fclk)*((TOFF * 32) + 12) //DRVCTRL_STEP/DIR_MODE void setMicroStep(uint8_t); //MRES void doubleStepping(); //DEDGE 0: Rising step pulse is active, falling is inactive 1: Both rising and falling edge active void stepInterpolation(); //INTPOL 0: Disable STEP pulse interpolation 1: Enable step pulse multiplication by 16. //TODO: DRVCTRL_SPI_MODE private: //Bitfield construction void constructBitField(uint32_t bits, uint32_t reg); uint32_t DRVCTRL_0; uint32_t DRVCTRL_1; uint32_t DRVCONF; uint32_t CHOPCONF; uint32_t SMARTEN; uint32_t SGCSCONF; }; #endif
07893178797b2a59515d7cfbaa18d008397c6581
e7ec698e7153e8580ad19136a44fd60acc147836
/src/page/b_plus_tree_page.cpp
db886bbde517b60d69967bfff19498c6fb2f2329
[ "MIT" ]
permissive
awfeequdng/DatabaseBackendEngine
f641532b14107eb217404a5d7f9b10401fb5aafd
9cb22617a8de14ea6e6136614e6d91842aa06984
refs/heads/master
2021-09-24T11:02:39.031715
2018-10-07T01:23:03
2018-10-07T01:23:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,666
cpp
/** * b_plus_tree_page.cpp */ #include "page/b_plus_tree_page.h" namespace cmudb { /* * Helper methods to get/set page type * Page type enum class is defined in b_plus_tree_page.h */ bool BPlusTreePage::IsLeafPage() const { return (page_type_ == IndexPageType::LEAF_PAGE); } bool BPlusTreePage::IsRootPage() const { return (page_type_ == IndexPageType::INTERNAL_PAGE && parent_page_id_ == INVALID_PAGE_ID); } void BPlusTreePage::SetPageType(IndexPageType page_type) { page_type_ = page_type; } /* * Helper methods to get/set size (number of key/value pairs stored in that * page) */ int BPlusTreePage::GetSize() const { return size_; } void BPlusTreePage::SetSize(int size) { size_ = size; } void BPlusTreePage::IncreaseSize(int amount) { size_+= amount; } /* * Helper methods to get/set max size (capacity) of the page */ int BPlusTreePage::GetMaxSize() const { return max_size_; } void BPlusTreePage::SetMaxSize(int size) { max_size_ = size; } /* * Helper method to get min page size * Generally, min page size == max page size / 2 */ int BPlusTreePage::GetMinSize() const { return max_size_/2; } /* * Helper methods to get/set parent page id */ page_id_t BPlusTreePage::GetParentPageId() const { return parent_page_id_; } void BPlusTreePage::SetParentPageId(page_id_t parent_page_id) { parent_page_id_ = parent_page_id; } /* * Helper methods to get/set self page id */ page_id_t BPlusTreePage::GetPageId() const { return page_id_; } void BPlusTreePage::SetPageId(page_id_t page_id) { page_id_ = page_id; } /* * Helper methods to set lsn */ void BPlusTreePage::SetLSN(lsn_t lsn) { lsn_ = lsn; } } // namespace cmudb
80aed4fa8131d6cb15b7bcb7166b61be6559a44b
f6d271233b8a91f63c30148cdcdb86341ba45c2f
/external/TriBITS/tribits/examples/TribitsExampleProject/packages/with_subpackages/b/tests/testlib/b_test_utils.hpp
c0436a413900f739a8cc26ca779849a9cafbdfd9
[ "BSD-2-Clause", "BSD-3-Clause", "GPL-1.0-or-later", "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
wawiesel/BootsOnTheGround
09e7884b9df9c1eb39a4a4f3d3f8f109960aeca0
bdb63ae6f906c34f66e995973bf09aa6f2999148
refs/heads/master
2021-01-11T20:13:10.304516
2019-10-09T16:44:33
2019-10-09T16:44:33
79,069,796
4
1
MIT
2019-10-09T16:44:34
2017-01-16T00:47:11
CMake
UTF-8
C++
false
false
207
hpp
#ifndef WITHSUBPACKAGES_B_TEST_UTILS_HPP #define WITHSUBPACKAGES_B_TEST_UTILS_HPP #include <string> namespace WithSubpackages { std::string b_test_utils(); } #endif // WITHSUBPACKAGES_B_TEST_UTILS_HPP
11854da4f9625a93e1706cd22c1817d31a832012
0df48df9ed35e5995af25812137dc0d9d42f96dc
/sketch/RealtekQuadcopter/mpuxxxx.cpp
f67b0be2e28e15275a37f9f13c8f56edb14cb137
[ "MIT" ]
permissive
ambiot/amb1_arduino
81539be6ba18a13cc2a33ec37021c5b27684e047
16720c2dcbcffa2acee0c9fe973a959cafc3ba8c
refs/heads/dev
2023-06-08T15:27:52.848876
2023-06-07T02:38:24
2023-06-07T02:38:24
232,280,578
9
7
null
2022-06-01T08:51:01
2020-01-07T08:37:52
C
UTF-8
C++
false
false
6,303
cpp
/* The mpuXXXX.cpp is placed under the MIT license Copyright (c) 2016 Wu Tung Cheng, Realtek Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Notes: 1. This quadcopter project is adapted from Raspberry Pilot (Github: https://github.com/jellyice1986/RaspberryPilot). 2. Some functions in this file are adapted from http://www.i2cdevlib.com/devices/mpu6050#source */ #if 1 #include "common_lib.h" #include "./MPU6050/MPU6050_9Axis_MotionApps41.h" #include "mpuxxxx.h" MPU6050 mpu; static float yaw; static float pitch; static float roll; static float yawGyro; static float pitchGyro; static float rollGyro; static float asaX; static float asaY; static float asaZ; static unsigned char *dmpPacketBuffer; static unsigned short dmpPacketSize; volatile bool mpuInterrupt = false; bool blinkState = false; bool dmpReady = false; uint8_t mpuIntStatus; uint8_t devStatus; uint16_t packetSize; uint16_t fifoCount; uint8_t fifoBuffer[64]; Quaternion q; VectorInt16 aa; VectorInt16 aaReal; VectorInt16 aaWorld; VectorFloat gravity; float euler[3]; float ypr[3]; int16_t rate[3]; void setYaw(float t_yaw) { yaw = t_yaw; } void setPitch(float t_pitch) { pitch = t_pitch; } void setRoll(float t_roll) { roll = t_roll; } float getYaw() { return yaw; } float getPitch() { return pitch; } float getRoll() { return roll; } void setYawGyro(float t_yaw_gyro) { yawGyro = t_yaw_gyro; } void setPitchGyro(float t_pitch_gyro) { pitchGyro = t_pitch_gyro; } void setRollGyro(float t_roll_gyro) { rollGyro = t_roll_gyro; } float getYawGyro() { return yawGyro; } float getPitchGyro() { return pitchGyro; } float getRollGyro() { return rollGyro; } void dmpDataReady() { mpuInterrupt = true; } bool mpu6050Init() { printf("Initializing I2C devices...\n"); mpu.initialize(); // load and configure the DMP printf("Initializing DMP...\n"); devStatus = mpu.dmpInitialize(); // supply your own gyro offsets here, scaled for min sensitivity mpu.setXGyroOffset(0); mpu.setYGyroOffset(0); mpu.setZGyroOffset(0); // make sure it worked (returns 0 if so) if (devStatus == 0) { // turn on the DMP, now that it's ready printf("Enabling DMP...\n"); mpu.setDMPEnabled(true); // enable Arduino interrupt detection printf("Enabling interrupt detection (Ameba D3 pin)...\n"); attachInterrupt(3, dmpDataReady, RISING); mpuIntStatus = mpu.getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it printf("DMP ready! Waiting for first interrupt...\n"); dmpReady = true; // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); /* We should avoid send/recv I2C data while there is an interrupt invoked. * Otherwise the MPU6050 would hang and need a power down/up reset. * So we set this vale big enough that we can finish task before next interrupt happend. */ mpu.setRate(3); // 1khz / (1 + 3) = 200 Hz // configure LED for output pinMode(LED_PIN, OUTPUT); return true; } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) printf("DMP Initialization failed (code %d)\n",devStatus); return false; } } unsigned char getYawPitchRollInfo(float *yprAttitude, float *yprRate, float *xyzAcc, float *xyzGravity, float *xyzMagnet) { if (!dmpReady) return -1; // wait for MPU interrupt or extra packet(s) available if (!mpuInterrupt && fifoCount < packetSize) { return -1; } // reset interrupt flag and get INT_STATUS byte mpuInterrupt = false; mpuIntStatus = mpu.getIntStatus(); // get current FIFO count fifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); printf("FIFO overflow!"); return 2; // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); while (fifoCount >= packetSize){ // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) fifoCount -= packetSize; } mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); mpu.dmpGetGyro(rate, fifoBuffer); yprRate[0] = (float) rate[0]; yprRate[1] = (float) rate[1]; yprRate[2] = (float) rate[2]; yprAttitude[0] = ypr[0] * RAD; yprAttitude[1] = ypr[1] *RAD; yprAttitude[2] = ypr[2] * RAD; //printf("yprAttitude[0]=%f,yprAttitude[1]=%f,yprAttitude[2]=%f\n",yprAttitude[0],yprAttitude[3],yprAttitude[2]); blinkState = !blinkState; digitalWrite(LED_PIN, blinkState); return 0; } } #endif
7b7cbd42e0739a3ede1386fdcb8a69db641126d7
3c378513afb8e6c2680715c91c31845b67e71885
/src/KScheme_4Bit_IU.cpp
83f6e2757c6451b54b037899acefdb27fbbfd6f9
[]
no_license
yingfeng/integer_encoding_library_sparklezzz
582f21140a0c6cccae692f8e92464b8a1f093674
8ba46561cde38920674f4789f4f413ceed45ef6b
refs/heads/master
2021-01-17T12:26:12.838738
2015-01-14T13:37:40
2015-01-14T13:37:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,082
cpp
/* * KScheme_4Bit_IU.cpp * * Created on: 2013-2-25 * Author: zxd */ #include "KScheme_4Bit_IU.hpp" using namespace paradise::index; int KScheme_4Bit_IU::encodeUint32(char* des, const uint32_t* src, uint32_t encodeNum) { return encode<uint32_t> (des, src, encodeNum); } int KScheme_4Bit_IU::decodeUint32(uint32_t* des, const char* src, uint32_t decodeNum) { return decode<uint32_t> (des, src, decodeNum); } int KScheme_4Bit_IU::encodeUint16(char* des, const uint16_t* src, uint32_t encodeNum) { return encode<uint16_t> (des, src, encodeNum); } int KScheme_4Bit_IU::decodeUint16(uint16_t* des, const char* src, uint32_t decodeNum) { return decode<uint16_t> (des, src, decodeNum); } int KScheme_4Bit_IU::encodeUint8(char* des, const uint8_t* src, uint32_t encodeNum) { return encode<uint8_t> (des, src, encodeNum); } int KScheme_4Bit_IU::decodeUint8(uint8_t* des, const char* src, uint32_t decodeNum) { return decode<uint8_t> (des, src, decodeNum); } Compressor* KScheme_4Bit_IU::clone() { Compressor* pNewComp = new KScheme_4Bit_IU(*this); return pNewComp; }
7b23b562c585d1d8d9d460994be9f3ba9adaa8cf
2b090d51eb8b0603a02a82f03c7f8bd1a3b90893
/CCO/DMOJ Mock CCO/ccoprep3p2.cpp
57cacd582dfe3c18d38ceb339b40cd5a5ac2b7d4
[]
no_license
AnishMahto/Competitive-Programming-Code-and-Solutions
eecffc3a2c72cf557c48a25fa133a3a2b645cd69
20a7bed2cdda0efdb48b915fc4a68d6edc446f69
refs/heads/master
2020-04-28T14:13:25.614349
2019-03-13T03:07:50
2019-03-13T03:07:50
175,331,066
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
#include <iostream> #include <cstdio> #include <deque> #include <string.h> using namespace std; long long n, L, dp[3*1000002]; deque <long long> pts; long long sum[3*1000002]; //(dp[x] + X^2, X) double slope (long long f, long long s) { return (double)((dp[f] + sum[f]*sum[f])-(dp[s] + sum[s]*sum[s]))/(double)(2*(sum[f]-sum[s])); } int main () { memset(dp, sizeof(dp), 0); memset(sum, sizeof(sum), 0); long long temp, X; scanf ("%lld %lld", &n, &L); for (int x = 1; x <= n; x++) { scanf ("%lld", &temp); sum[x] = temp + sum[x-1] + 1; } sum[0] = dp[0] = 0; L++; pts.push_back(0); for (int x = 1; x <= n; x++) { while (pts.size() >= 2 && (slope(pts.front(), pts[1]) < (sum[x]-L))) { pts.pop_front(); } X = (sum[x]-sum[pts.front()]); dp[x] = dp[pts.front()] + (X-L)*(X-L); while (pts.size() >= 2) { if (slope(x, pts.back()) < slope(pts.back(), pts[pts.size()-2])) { pts.pop_back(); } else { break; } } pts.push_back(x); } cout << dp[n] << endl; }
19ed2e659710138c2f4d825a7a8f594a2d4e7b3a
6618549c2c3d1088c95532f075a77c222e0605d4
/trunk/angry_bus/Node.h
7db1000c49c46ca25ba556892d5564a060455351
[]
no_license
cpzhang/bus
56ba89eb34bbcc1eb80c4db3691f08b7e2e05ad8
705ef7d6145f974b707c1fe843764a4c39207dd5
refs/heads/master
2016-09-11T07:52:05.859263
2012-02-22T00:37:52
2012-02-22T00:37:52
2,634,123
0
0
null
null
null
null
UTF-8
C++
false
false
8,460
h
#ifndef _Node_ #define _Node_ #include <vector> #include <string> #include "Vector3.h" #include "Entity.h" #include "ITouch.h" enum eNodeType { eNodeType_Normal, eNodeType_Transformation, eNodeType_Button, eNodeType_Size, }; template <class T> class Node: public ITouch { public: Node(const std::string& name) :_name(name), _visible(true), _data(0), _enable(true) { } virtual ~Node() { } virtual void addChild(Node* n) { _children.push_back(n); } virtual void removeChild(Node* n) { typename std::vector<Node*>::iterator it = _children.begin(); for (; it != _children.end(); ++it) { if (n == *it) { _children.erase(it); return; } } } virtual size_t getChildrenNumber() { return _children.size(); } virtual Node* getChild(size_t index) { return _children[index]; } virtual void setData(T* d) { _data = d; } virtual T* getData() { return _data; } typedef void (T::*do_void_void)(); virtual void breadth_first(do_void_void f) { if(_data) (_data->*f)(); for(size_t i = 0; i != getChildrenNumber(); ++i) { _children[i]->breadth_first(f); } } typedef bool (T::*do_bool_float_float)(float, float); virtual bool breadth_first(do_bool_float_float f, float x, float y) { if(_data && ((_data->*f)(x, y))) return true; for(size_t i = 0; i != getChildrenNumber(); ++i) { if(_children[i]->breadth_first(f, x, y)) return true; } return false; } typedef bool (T::*do_bool_float_float_float_float)(float, float, float, float); virtual bool breadth_first(do_bool_float_float_float_float f, float x, float y, float previousX, float previousY) { if(_data && ((_data->*f)(x, y, previousX, previousY))) return true; for(size_t i = 0; i != getChildrenNumber(); ++i) { if(_children[i]->breadth_first(f, x, y, previousX, previousY)) return true; } return false; } virtual void release() { for(size_t i = 0; i != getChildrenNumber(); ++i) { _children[i]->release(); } _children.clear(); delete this; } virtual void render(){}; virtual void setTransformation(float s=1.0, bool inherit = true){}; virtual bool touchBegin(float x, float y) { if (_visible && _enable) { if(touchBeginImp(x, y)) { return true; } else { // for(size_t i = 0; i != getChildrenNumber(); ++i) { if(_children[i]->touchBegin(x, y)) return true; } } } return false; } virtual bool touchMoved(float x, float y, float previousX, float previousY) { if (_visible && _enable) { if(touchMovedImp(x, y, previousX, previousY)) { return true; } else { // for(size_t i = 0; i != getChildrenNumber(); ++i) { if(_children[i]->touchMoved(x, y, previousX, previousY)) return true; } } } return false; } virtual bool touchEnd(float x, float y) { if (_visible && _enable) { if(touchEndImp(x, y)) { return true; } else { // for(size_t i = 0; i != getChildrenNumber(); ++i) { if(_children[i]->touchEnd(x, y)) return true; } } } return false; } virtual bool touchBeginImp(float x, float y){return false;} virtual bool touchMovedImp(float x, float y, float previousX, float previousY){return false;} virtual bool touchEndImp(float x, float y){return false;} void hide(){_visible = false;} void show(){_visible = true;} void setVisible(bool b){_visible = b;} bool isVisible(){return _visible;} inline void enable() { _enable = true; } inline void disable() { _enable = false; } inline bool isEnable() { return _enable; } Node* getNodeByName(const std::string& name) { if (_name == name) { return this; } // for(size_t i = 0; i != getChildrenNumber(); ++i) { Node* n = _children[i]->getNodeByName(name); if(n) return n; } return 0; } virtual void setCallBack(IButtonPushedCallBack* cb){}; virtual void setScale(float sx, float sy, float sz){}; virtual void setPosition(float x, float y, float z){}; virtual void setPosition(const Vector3& p){}; virtual void setRotation(float angle){}; // virtual void translate(float x, float y, float z){}; virtual void translate(const Vector3& p){}; virtual void rotateZ(float angle){}; virtual Vector3 getScale(){return Vector3::ZERO;}; virtual Vector3 getPosition(){return Vector3::ZERO;}; virtual float getRotation(){return 0.0;}; protected: std::vector<Node*> _children; Node* _parent; T* _data; std::string _name; bool _visible; bool _enable; }; //template<class T> class TransformationNode: public Node<Entity> { public: inline TransformationNode(const std::string& name) :_angle(0.0), Node<Entity>(name) { } ~TransformationNode(){}; void render() { if (_visible) { if(_data) { if (_enable) { _data->render(); } else { _data->render(Color(0.5, 0.5, 0.5, 1.0)); } } for(size_t i = 0; i != getChildrenNumber(); ++i) { _children[i]->render(); } } } virtual void setTransformation(float s=1.0, bool inherit = true) { if(_data) { _data->setPosition(_position); _data->setScale(_scale * s); _data->setRotation(_angle); } if (inherit) { for(size_t i = 0; i != getChildrenNumber(); ++i) { _children[i]->setTransformation(s); } } } virtual void setScale(float sx, float sy, float sz) { _scale.x = sx; _scale.y = sy; _scale.z = sz; } virtual void setPosition(float x, float y, float z) { _position.x = x; _position.y = y; _position.z = z; } virtual void setPosition(const Vector3& p) { _position = p; setTransformation(); }; virtual void setRotation(float angle) { _angle = angle; } virtual Vector3 getScale(){return _scale;}; virtual Vector3 getPosition(){return _position;}; virtual float getRotation(){return _angle;}; // virtual void translate(float x, float y, float z) { _position.x += x; _position.y += y; _position.z += z; } virtual void translate(const Vector3& p) { _position += p; } virtual void rotateZ(float angle) { _angle += angle; } protected: Vector3 _position; Vector3 _scale; float _angle; }; class ButtonNode: public TransformationNode { public: ButtonNode(const std::string& name); ~ButtonNode(); virtual bool touchBeginImp(float x, float y); virtual bool touchMovedImp(float x, float y, float previousX, float previousY); virtual bool touchEndImp(float x, float y); virtual void setCallBack(IButtonPushedCallBack* cb); private: bool isInside(float x, float y); void onHover(); void onHoverEnd(); void onPushed(); private: eButtonState _state; IButtonPushedCallBack* _callback; }; #endif
b27fdb7cae46d64dae857cc4f5cf6c0be0b634ab
56ace8049811f81bb3422c9ef8dffabd9b880ebd
/semester1/hw02/hw02_task02/hw.02_task.02.cpp
3452cf0dd559af1528f6190570c0613cd2e788b6
[]
no_license
ramntry/homeworks
eebb83b1d96a043e0024f9f9a9a5c488b9f48baf
09a211b0008d95aa877b0c1d83120190ea1cb0fc
refs/heads/master
2016-09-10T02:14:49.395055
2013-05-26T20:19:13
2013-05-26T20:19:13
2,675,593
1
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
// author: Roman Tereshin // email: [email protected] // hw 02, task 02 // Реализовать подсчет возведение в целую степень // (с логарифмической сложностью алгоритма) // [time start] 21:19 21.09.11 // [time estimate] 00:15 00 #include <iostream> using namespace std; template <class T> T pow(T base, int n) { T result = 1; while (n != 0) { if (n & 1) result *= base; base *= base; n >>= 1; } return result; } int main() { clog << "This program calculates base^n\nEnter\t base n: "; double base = 0.0; int n = 0; cin >> base >> n; cout << base << '^' << n << " = " << pow<double>(base, n) << endl; return 0; } // [time done] 21:29 21.09.11 // [time real] 00:10 00
cfd4f195c055c29162163abc6e6bb92bcea227f6
789c924def388fb760985f5e39c2464385dac00c
/truss/main.cpp
7921d2c8b2244194adaacbae27814f546b287cdb
[]
no_license
iicalgorithms/Truss-decomposition
a2e3bf0f883643c2c5cd84c8d6f912f777672491
fe70fcb1ee5194e8e45b41190778a235178dcb53
refs/heads/master
2022-02-23T09:07:41.072301
2019-10-12T09:50:05
2019-10-12T09:50:05
189,707,340
0
0
null
null
null
null
UTF-8
C++
false
false
7,971
cpp
#include "Graph.h" #include <map> #include <algorithm> #include <fstream> #include <iostream> #include <string.h> #include <sstream> #include <stdlib.h> #include <time.h> #include <cmath> #include <vector> #include <map> #define random(x) rand()%x; using namespace std; int seed = 100; Graph G; int node_num ,edge_num ;//边数,点数 string temp;//文件输出临时存储字符串 //在进行随机插入or删除的时候,需要进行抽样 int changeNum;//抽样数目 map<int,int > rdm; //用于随机抽样,map去重 vector<int > shhuffle_rdm;//用于随机抽样,进行shuffle随机排列 vector<int> v;//保存抽样出的数据的下标 vector<int > stId;//要插入/删除边的起点 vector<int > edId;//要插入/删除边的终点 set<pair<int,int> > clearSet; set<int > clearNodeSet; char * filename ;//文件路径 int method = -1;//求解方法 0-贪心 1-分布式 int graphType = -1;//图类型:0-static graph 1-temporal graph int computeType = -1;//0-不插入不删除 1-插入:逐条初始化并分布式计算 2-插入:批次插入初始化并分布式计算 3-插入:批次插入,初始化为Sup+2并分布式计算 4-删除:批次删除并分布式计算 5-删除:初始化min{sup+2,truss(e)}并分布式计算 int number = -1; //插入/删除 数量级 char write; //'w'-将truss值写入"output.txt"文件 int Pow(int k){ int res = 1; while(k--) res=res*10; return res; } string getName(char *filename){ int len = strlen(filename); int st=-1,ed = -1; int fg1 = 0,fg2 = 0; for(int i = len-1;i>=0;i--){ if(filename[i]=='.'&&!fg1) { fg1 = 1; ed = i-1; } if((filename[i]=='/'||filename[i]=='\\')&&!fg2) { fg2 = 1; st = i+1; } } if(st == -1) st = 0; string res = ""; for(int i = st;i<=ed;i++) res += filename[i]; return res; } int main(int argc,char * argv[]){ //strcat(filename,argv[1]); filename = argv[1]; method = argv[2][0] - '0'; graphType = argv[3][0] - '0'; computeType = argv[4][0] - '0'; number = argv[5][0] - '0'; write = argv[6][0]; seed = atoi(argv[7]); G.recoard(filename,method,graphType,computeType,number); ifstream in(filename); if(!in.is_open()) cout<<"fail to open file!\n"<<endl; if(argv[2][0] == '2'|| argv[2][0] == '3'){//概率图 getline(in,temp); istringstream strs(temp); int node_num; int node; strs>>node_num>>node; G.buildGraph(0,node_num); } //读入文件头,确定点数和边数,建图 while(getline(in,temp)){ istringstream str(temp); if(temp[0] == '#'){ if(temp[2]=='N'&&temp[3]=='o'&&temp[4]=='d'){ string t1,t2,t3; str>>t1>>t2>>node_num>>t3>>edge_num; //cout<<temp<<endl; //cout<<t1<<" "<<t2<<" "<<node_num<<" "<<t3<<" "<<edge_num<<" ss"<<endl; }else continue; }else break; } do{ istringstream str(temp); if(temp[0] != '#'){ int st,ed; str>>st>>ed; int a = min(st,ed); int b = max(st,ed); clearSet.insert(make_pair(a,b)); clearNodeSet.insert(a); clearNodeSet.insert(b); //cout<<a<<" "<<b<<" "<<clearSet.size()<<endl; } }while(getline(in,temp)); edge_num = clearSet.size(); G.buildGraph(edge_num,node_num); changeNum = number; changeNum = Pow(changeNum); int RandomUpBound = 0; if(graphType == 3) RandomUpBound = node_num; else RandomUpBound = edge_num; srand(seed); if(graphType == 0 || graphType == 3){ for(int i=0;i<RandomUpBound;i++) shhuffle_rdm.push_back(i); random_shuffle(shhuffle_rdm.begin(),shhuffle_rdm.end()); for(int i=0;i<changeNum;i++) v.push_back(shhuffle_rdm[i]); if(!v.empty()) sort(v.begin(),v.end()); }else if(graphType == 1){ for(int i=0;i<changeNum;i++){ v.push_back(RandomUpBound-changeNum+i); } }else if(graphType == 2){ v.push_back(rand()%RandomUpBound); } //for (int i = 0; i < v.size(); i++) cout<<v[i]<<endl; if(graphType == 3) { set<int>::iterator it; int vcnt = 0; int cnt = 0; for(it = clearNodeSet.begin();it!=clearNodeSet.end();it++){ if (v[vcnt]==cnt) { v[vcnt++] = (*it); } cnt++; } vector<set<pair<int,int> > > edgeFromNodeToBeInserted; for(int i=0;i<v.size();i++){ set<pair<int,int> > tempset; edgeFromNodeToBeInserted.push_back(tempset); } set<pair<int,int> >::iterator iter = clearSet.begin(); //cout<<1<<endl; while(iter!=clearSet.end()){ int st = (*iter).first; int ed = (*iter).second; int flg = 0; for(int i=0;i<v.size();i++){ if(st == v[i]||ed == v[i]){ edgeFromNodeToBeInserted[i].insert(make_pair((*iter).first,(*iter).second)); flg = 1; break; } } if(flg) { set<pair<int,int> >::iterator tempIt = iter; iter++; clearSet.erase(tempIt); }else iter++; } //cout<<2<<endl; for(iter = clearSet.begin();iter!=clearSet.end();iter++){ int st = (*iter).first; int ed = (*iter).second; G.addEdge(st,ed); } if(method == 0){ G.initSup(); G.cover(); G.greed(); }else if(method == 1){ G.initSup(); G.cover(); G.distribute(); }else cout<<"Wrong modle."<<endl; G.enableAllNodes(); switch (computeType) { case 0: for(int i=0;i<edgeFromNodeToBeInserted.size();i++){ G.SingleNodeInsert(edgeFromNodeToBeInserted[i],v[i]); } G.log(changeNum,changeNum,G.totalTime); break; case 1: G.MultNodeInsert(edgeFromNodeToBeInserted,v); break; default: break; } }else{ int rNum = 0; int pNum = 0; set<pair<int,int> >::iterator iter; for(iter = clearSet.begin();iter!=clearSet.end();iter++){ int needInsert = 0; int needDelete = 0; if(((computeType<=3 && computeType>=1)||computeType == 6 ||computeType == 7||computeType ==8 || computeType ==9) && !v.empty() && v[pNum] == rNum && pNum<changeNum ){ //cout<<rNum<<" "<<pNum<<endl; pNum++; needInsert = 1; if(computeType ==8 || computeType ==9){ needDelete = 1; needInsert = 0; } } int st = (*iter).first; int ed = (*iter).second; //if(needInsert) cout<<st<<" "<<ed<<endl;; if(!needInsert) { G.addEdge(st,ed); } if(needInsert||computeType==4||computeType==5||needDelete){//如果需要插入或者删除 stId.push_back(min(st,ed)); edId.push_back(max(st,ed)); } rNum ++; //cout<<rNum<<endl; } if(method == 0){ G.initSup(); G.cover(); G.greed(); }else if(method == 1){ G.initSup(); G.cover(); G.distribute(); }else cout<<"Wrong modle."<<endl; G.enableAllNodes(); G.startCntSteps = 1; switch (computeType) { case 0: break; case 1: for(int i=0;i<changeNum;i++){ G.dynamicInsert(stId[i],edId[i]); G.distribute(); } break; case 2: for(int i=0;i<changeNum;i++) G.dynamicInsert(stId[i],edId[i]); G.distribute(); break; case 3: for(int i=0;i<changeNum;i++) G.addEdge(stId[i],edId[i],0); G.initSup(); G.cover(); G.distribute(); break; case 4: for(int i=0;i<changeNum;i++){ G.dynamicDelete(stId[i],edId[i]); G.distribute(); } break; case 5: for(int i=0;i<changeNum;i++){ G.supInitDelete(stId[i],edId[i]); } G.distribute(); break; case 6: for(int i=0;i<changeNum;i++){ G.centerInsert(stId[i],edId[i],0); } G.log(changeNum,changeNum,G.totalTime); break; case 7: G.centerMultInsert(stId,edId); break; case 8: for(int i=0;i<changeNum;i++){ G.centerDelete(stId[i],edId[i],0); } G.log(changeNum,changeNum,G.totalTime); break; case 9: //cout<<stId.size()<<" "<<edId.size()<<endl; G.centerMultDelete(stId,edId); break; default: if(graphType!=2) cout<<"Wrong modle!"<<endl; break; } if(computeType!=0 &&graphType!=2 &&computeType !=6 &&computeType!=7 &&computeType!=8 &&computeType!=9) G.outputDynamicInfo(computeType); } if(write == 'w'){ string str = getName(filename); str = argv[5][0] + str; //cout<<str<<endl; G.writeFile((char *)str.c_str()); } }
c1f50da97d8be27015d66d945985365b2ca7418b
93a113f11d064f099b96031c2eeafb76d41ac948
/summer/7.25.1.cpp
3449a474dc42ac0dddf792649bf63ad0bd1459d4
[]
no_license
yyc794990923/Algorithm
00905cc64351f8342059594adfa02e51714c070b
9c31f315540c4797fdc4336cebc1361a3765cc8e
refs/heads/master
2021-01-20T01:53:38.108368
2017-07-25T09:37:32
2017-07-25T09:37:32
89,342,048
0
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
/************************************************************************* > File Name: 7.25.1.cpp > Author: yanyuchen > Mail: [email protected] > Created Time: 2017年07月25日 星期二 14时51分13秒 ************************************************************************/ #include<iostream> using namespace std; int gcd(int a, int b) { return b==0?a:(gcd(b,a%b)); } int main() { int time; int a,b,c; cin >> time; while(time--) { cin >> a >> b; c = 2*b; while (gcd(a,c) != b) { c += b; } cout << c <<endl; } return 0; }
a26d1be3547adc999df23c3bd4b5dec0f46538d3
1577e1cf4e89584a125cffb855ca50a9654c6d55
/WebKit/Source/ThirdParty/ANGLE/src/libANGLE/angletypes.cpp
95f9c9501b6b1442b71774e3ae98a5a3f6c51222
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apple-open-source/macos
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
2d2b15f13487673de33297e49f00ef94af743a9a
refs/heads/master
2023-08-01T11:03:26.870408
2023-03-27T00:00:00
2023-03-27T00:00:00
180,595,052
124
24
null
2022-12-27T14:54:09
2019-04-10T14:06:23
null
UTF-8
C++
false
false
33,271
cpp
// // Copyright 2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // angletypes.h : Defines a variety of structures and enum types that are used throughout libGLESv2 #include "libANGLE/angletypes.h" #include "libANGLE/Program.h" #include "libANGLE/State.h" #include "libANGLE/VertexArray.h" #include "libANGLE/VertexAttribute.h" #include <limits> namespace gl { namespace { bool IsStencilNoOp(GLenum stencilFunc, GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass) { const bool isNeverAndKeep = stencilFunc == GL_NEVER && stencilFail == GL_KEEP; const bool isAlwaysAndKeepOrAllKeep = (stencilFunc == GL_ALWAYS || stencilFail == GL_KEEP) && stencilPassDepthFail == GL_KEEP && stencilPassDepthPass == GL_KEEP; return isNeverAndKeep || isAlwaysAndKeepOrAllKeep; } // Calculate whether the range [outsideLow, outsideHigh] encloses the range [insideLow, insideHigh] bool EnclosesRange(int outsideLow, int outsideHigh, int insideLow, int insideHigh) { return outsideLow <= insideLow && outsideHigh >= insideHigh; } bool IsAdvancedBlendEquation(gl::BlendEquationType blendEquation) { return blendEquation >= gl::BlendEquationType::Multiply && blendEquation <= gl::BlendEquationType::HslLuminosity; } } // anonymous namespace RasterizerState::RasterizerState() { memset(this, 0, sizeof(RasterizerState)); rasterizerDiscard = false; cullFace = false; cullMode = CullFaceMode::Back; frontFace = GL_CCW; polygonOffsetFill = false; polygonOffsetFactor = 0.0f; polygonOffsetUnits = 0.0f; polygonOffsetClamp = 0.0f; pointDrawMode = false; multiSample = false; dither = true; } RasterizerState::RasterizerState(const RasterizerState &other) { memcpy(this, &other, sizeof(RasterizerState)); } RasterizerState &RasterizerState::operator=(const RasterizerState &other) { memcpy(this, &other, sizeof(RasterizerState)); return *this; } bool operator==(const RasterizerState &a, const RasterizerState &b) { return memcmp(&a, &b, sizeof(RasterizerState)) == 0; } bool operator!=(const RasterizerState &a, const RasterizerState &b) { return !(a == b); } BlendState::BlendState() { memset(this, 0, sizeof(BlendState)); blend = false; sourceBlendRGB = GL_ONE; sourceBlendAlpha = GL_ONE; destBlendRGB = GL_ZERO; destBlendAlpha = GL_ZERO; blendEquationRGB = GL_FUNC_ADD; blendEquationAlpha = GL_FUNC_ADD; colorMaskRed = true; colorMaskGreen = true; colorMaskBlue = true; colorMaskAlpha = true; } BlendState::BlendState(const BlendState &other) { memcpy(this, &other, sizeof(BlendState)); } bool operator==(const BlendState &a, const BlendState &b) { return memcmp(&a, &b, sizeof(BlendState)) == 0; } bool operator!=(const BlendState &a, const BlendState &b) { return !(a == b); } DepthStencilState::DepthStencilState() { memset(this, 0, sizeof(DepthStencilState)); depthTest = false; depthFunc = GL_LESS; depthMask = true; stencilTest = false; stencilFunc = GL_ALWAYS; stencilMask = static_cast<GLuint>(-1); stencilWritemask = static_cast<GLuint>(-1); stencilBackFunc = GL_ALWAYS; stencilBackMask = static_cast<GLuint>(-1); stencilBackWritemask = static_cast<GLuint>(-1); stencilFail = GL_KEEP; stencilPassDepthFail = GL_KEEP; stencilPassDepthPass = GL_KEEP; stencilBackFail = GL_KEEP; stencilBackPassDepthFail = GL_KEEP; stencilBackPassDepthPass = GL_KEEP; } DepthStencilState::DepthStencilState(const DepthStencilState &other) { memcpy(this, &other, sizeof(DepthStencilState)); } DepthStencilState &DepthStencilState::operator=(const DepthStencilState &other) { memcpy(this, &other, sizeof(DepthStencilState)); return *this; } bool DepthStencilState::isDepthMaskedOut() const { return !depthMask; } bool DepthStencilState::isStencilMaskedOut() const { return (stencilMask & stencilWritemask) == 0; } bool DepthStencilState::isStencilNoOp() const { return isStencilMaskedOut() || IsStencilNoOp(stencilFunc, stencilFail, stencilPassDepthFail, stencilPassDepthPass); } bool DepthStencilState::isStencilBackNoOp() const { const bool isStencilBackMaskedOut = (stencilBackMask & stencilBackWritemask) == 0; return isStencilBackMaskedOut || IsStencilNoOp(stencilBackFunc, stencilBackFail, stencilBackPassDepthFail, stencilBackPassDepthPass); } bool operator==(const DepthStencilState &a, const DepthStencilState &b) { return memcmp(&a, &b, sizeof(DepthStencilState)) == 0; } bool operator!=(const DepthStencilState &a, const DepthStencilState &b) { return !(a == b); } SamplerState::SamplerState() { memset(this, 0, sizeof(SamplerState)); setMinFilter(GL_NEAREST_MIPMAP_LINEAR); setMagFilter(GL_LINEAR); setWrapS(GL_REPEAT); setWrapT(GL_REPEAT); setWrapR(GL_REPEAT); setMaxAnisotropy(1.0f); setMinLod(-1000.0f); setMaxLod(1000.0f); setCompareMode(GL_NONE); setCompareFunc(GL_LEQUAL); setSRGBDecode(GL_DECODE_EXT); } SamplerState::SamplerState(const SamplerState &other) = default; SamplerState &SamplerState::operator=(const SamplerState &other) = default; // static SamplerState SamplerState::CreateDefaultForTarget(TextureType type) { SamplerState state; // According to OES_EGL_image_external and ARB_texture_rectangle: For external textures, the // default min filter is GL_LINEAR and the default s and t wrap modes are GL_CLAMP_TO_EDGE. if (type == TextureType::External || type == TextureType::Rectangle) { state.mMinFilter = GL_LINEAR; state.mWrapS = GL_CLAMP_TO_EDGE; state.mWrapT = GL_CLAMP_TO_EDGE; } return state; } bool SamplerState::setMinFilter(GLenum minFilter) { if (mMinFilter != minFilter) { mMinFilter = minFilter; mCompleteness.typed.minFilter = static_cast<uint8_t>(FromGLenum<FilterMode>(minFilter)); return true; } return false; } bool SamplerState::setMagFilter(GLenum magFilter) { if (mMagFilter != magFilter) { mMagFilter = magFilter; mCompleteness.typed.magFilter = static_cast<uint8_t>(FromGLenum<FilterMode>(magFilter)); return true; } return false; } bool SamplerState::setWrapS(GLenum wrapS) { if (mWrapS != wrapS) { mWrapS = wrapS; mCompleteness.typed.wrapS = static_cast<uint8_t>(FromGLenum<WrapMode>(wrapS)); return true; } return false; } bool SamplerState::setWrapT(GLenum wrapT) { if (mWrapT != wrapT) { mWrapT = wrapT; updateWrapTCompareMode(); return true; } return false; } bool SamplerState::setWrapR(GLenum wrapR) { if (mWrapR != wrapR) { mWrapR = wrapR; return true; } return false; } bool SamplerState::setMaxAnisotropy(float maxAnisotropy) { if (mMaxAnisotropy != maxAnisotropy) { mMaxAnisotropy = maxAnisotropy; return true; } return false; } bool SamplerState::setMinLod(GLfloat minLod) { if (mMinLod != minLod) { mMinLod = minLod; return true; } return false; } bool SamplerState::setMaxLod(GLfloat maxLod) { if (mMaxLod != maxLod) { mMaxLod = maxLod; return true; } return false; } bool SamplerState::setCompareMode(GLenum compareMode) { if (mCompareMode != compareMode) { mCompareMode = compareMode; updateWrapTCompareMode(); return true; } return false; } bool SamplerState::setCompareFunc(GLenum compareFunc) { if (mCompareFunc != compareFunc) { mCompareFunc = compareFunc; return true; } return false; } bool SamplerState::setSRGBDecode(GLenum sRGBDecode) { if (mSRGBDecode != sRGBDecode) { mSRGBDecode = sRGBDecode; return true; } return false; } bool SamplerState::setBorderColor(const ColorGeneric &color) { if (mBorderColor != color) { mBorderColor = color; return true; } return false; } void SamplerState::updateWrapTCompareMode() { uint8_t wrap = static_cast<uint8_t>(FromGLenum<WrapMode>(mWrapT)); uint8_t compare = static_cast<uint8_t>(mCompareMode == GL_NONE ? 0x10 : 0x00); mCompleteness.typed.wrapTCompareMode = wrap | compare; } ImageUnit::ImageUnit() : texture(), level(0), layered(false), layer(0), access(GL_READ_ONLY), format(GL_R32UI) {} ImageUnit::ImageUnit(const ImageUnit &other) = default; ImageUnit::~ImageUnit() = default; BlendStateExt::BlendStateExt(const size_t drawBufferCount) : mParameterMask(FactorStorage::GetMask(drawBufferCount)), mSrcColor(FactorStorage::GetReplicatedValue(BlendFactorType::One, mParameterMask)), mDstColor(FactorStorage::GetReplicatedValue(BlendFactorType::Zero, mParameterMask)), mSrcAlpha(FactorStorage::GetReplicatedValue(BlendFactorType::One, mParameterMask)), mDstAlpha(FactorStorage::GetReplicatedValue(BlendFactorType::Zero, mParameterMask)), mEquationColor(EquationStorage::GetReplicatedValue(BlendEquationType::Add, mParameterMask)), mEquationAlpha(EquationStorage::GetReplicatedValue(BlendEquationType::Add, mParameterMask)), mAllColorMask( ColorMaskStorage::GetReplicatedValue(PackColorMask(true, true, true, true), ColorMaskStorage::GetMask(drawBufferCount))), mColorMask(mAllColorMask), mAllEnabledMask(0xFF >> (8 - drawBufferCount)), mDrawBufferCount(drawBufferCount) {} BlendStateExt::BlendStateExt(const BlendStateExt &other) = default; BlendStateExt &BlendStateExt::operator=(const BlendStateExt &other) = default; void BlendStateExt::setEnabled(const bool enabled) { mEnabledMask = enabled ? mAllEnabledMask : DrawBufferMask::Zero(); } void BlendStateExt::setEnabledIndexed(const size_t index, const bool enabled) { ASSERT(index < mDrawBufferCount); mEnabledMask.set(index, enabled); } BlendStateExt::ColorMaskStorage::Type BlendStateExt::expandColorMaskValue(const bool red, const bool green, const bool blue, const bool alpha) const { return BlendStateExt::ColorMaskStorage::GetReplicatedValue( PackColorMask(red, green, blue, alpha), mAllColorMask); } BlendStateExt::ColorMaskStorage::Type BlendStateExt::expandColorMaskIndexed( const size_t index) const { return ColorMaskStorage::GetReplicatedValue( ColorMaskStorage::GetValueIndexed(index, mColorMask), mAllColorMask); } void BlendStateExt::setColorMask(const bool red, const bool green, const bool blue, const bool alpha) { mColorMask = expandColorMaskValue(red, green, blue, alpha); } void BlendStateExt::setColorMaskIndexed(const size_t index, const uint8_t value) { ASSERT(index < mDrawBufferCount); ASSERT(value <= 0xF); ColorMaskStorage::SetValueIndexed(index, value, &mColorMask); } void BlendStateExt::setColorMaskIndexed(const size_t index, const bool red, const bool green, const bool blue, const bool alpha) { ASSERT(index < mDrawBufferCount); ColorMaskStorage::SetValueIndexed(index, PackColorMask(red, green, blue, alpha), &mColorMask); } uint8_t BlendStateExt::getColorMaskIndexed(const size_t index) const { ASSERT(index < mDrawBufferCount); return ColorMaskStorage::GetValueIndexed(index, mColorMask); } void BlendStateExt::getColorMaskIndexed(const size_t index, bool *red, bool *green, bool *blue, bool *alpha) const { ASSERT(index < mDrawBufferCount); UnpackColorMask(ColorMaskStorage::GetValueIndexed(index, mColorMask), red, green, blue, alpha); } DrawBufferMask BlendStateExt::compareColorMask(ColorMaskStorage::Type other) const { return ColorMaskStorage::GetDiffMask(mColorMask, other); } BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationValue(const GLenum mode) const { return EquationStorage::GetReplicatedValue(FromGLenum<BlendEquationType>(mode), mParameterMask); } BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationValue( const gl::BlendEquationType equation) const { return EquationStorage::GetReplicatedValue(equation, mParameterMask); } BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationColorIndexed( const size_t index) const { return EquationStorage::GetReplicatedValue( EquationStorage::GetValueIndexed(index, mEquationColor), mParameterMask); } BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationAlphaIndexed( const size_t index) const { return EquationStorage::GetReplicatedValue( EquationStorage::GetValueIndexed(index, mEquationAlpha), mParameterMask); } void BlendStateExt::setEquations(const GLenum modeColor, const GLenum modeAlpha) { const gl::BlendEquationType colorEquation = FromGLenum<BlendEquationType>(modeColor); const gl::BlendEquationType alphaEquation = FromGLenum<BlendEquationType>(modeAlpha); mEquationColor = expandEquationValue(colorEquation); mEquationAlpha = expandEquationValue(alphaEquation); // Note that advanced blend equations cannot be independently set for color and alpha, so only // the color equation can be checked. if (IsAdvancedBlendEquation(colorEquation)) { mUsesAdvancedBlendEquationMask = mAllEnabledMask; } else { mUsesAdvancedBlendEquationMask.reset(); } } void BlendStateExt::setEquationsIndexed(const size_t index, const GLenum modeColor, const GLenum modeAlpha) { ASSERT(index < mDrawBufferCount); const gl::BlendEquationType colorEquation = FromGLenum<BlendEquationType>(modeColor); const gl::BlendEquationType alphaEquation = FromGLenum<BlendEquationType>(modeAlpha); EquationStorage::SetValueIndexed(index, colorEquation, &mEquationColor); EquationStorage::SetValueIndexed(index, alphaEquation, &mEquationAlpha); mUsesAdvancedBlendEquationMask.set(index, IsAdvancedBlendEquation(colorEquation)); } void BlendStateExt::setEquationsIndexed(const size_t index, const size_t sourceIndex, const BlendStateExt &source) { ASSERT(index < mDrawBufferCount); ASSERT(sourceIndex < source.mDrawBufferCount); const gl::BlendEquationType colorEquation = EquationStorage::GetValueIndexed(sourceIndex, source.mEquationColor); const gl::BlendEquationType alphaEquation = EquationStorage::GetValueIndexed(sourceIndex, source.mEquationAlpha); EquationStorage::SetValueIndexed(index, colorEquation, &mEquationColor); EquationStorage::SetValueIndexed(index, alphaEquation, &mEquationAlpha); mUsesAdvancedBlendEquationMask.set(index, IsAdvancedBlendEquation(colorEquation)); } GLenum BlendStateExt::getEquationColorIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(EquationStorage::GetValueIndexed(index, mEquationColor)); } GLenum BlendStateExt::getEquationAlphaIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(EquationStorage::GetValueIndexed(index, mEquationAlpha)); } DrawBufferMask BlendStateExt::compareEquations(const EquationStorage::Type color, const EquationStorage::Type alpha) const { return EquationStorage::GetDiffMask(mEquationColor, color) | EquationStorage::GetDiffMask(mEquationAlpha, alpha); } BlendStateExt::FactorStorage::Type BlendStateExt::expandFactorValue(const GLenum func) const { return FactorStorage::GetReplicatedValue(FromGLenum<BlendFactorType>(func), mParameterMask); } BlendStateExt::FactorStorage::Type BlendStateExt::expandSrcColorIndexed(const size_t index) const { ASSERT(index < mDrawBufferCount); return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mSrcColor), mParameterMask); } BlendStateExt::FactorStorage::Type BlendStateExt::expandDstColorIndexed(const size_t index) const { ASSERT(index < mDrawBufferCount); return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mDstColor), mParameterMask); } BlendStateExt::FactorStorage::Type BlendStateExt::expandSrcAlphaIndexed(const size_t index) const { ASSERT(index < mDrawBufferCount); return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mSrcAlpha), mParameterMask); } BlendStateExt::FactorStorage::Type BlendStateExt::expandDstAlphaIndexed(const size_t index) const { ASSERT(index < mDrawBufferCount); return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mDstAlpha), mParameterMask); } void BlendStateExt::setFactors(const GLenum srcColor, const GLenum dstColor, const GLenum srcAlpha, const GLenum dstAlpha) { mSrcColor = expandFactorValue(srcColor); mDstColor = expandFactorValue(dstColor); mSrcAlpha = expandFactorValue(srcAlpha); mDstAlpha = expandFactorValue(dstAlpha); } void BlendStateExt::setFactorsIndexed(const size_t index, const GLenum srcColor, const GLenum dstColor, const GLenum srcAlpha, const GLenum dstAlpha) { ASSERT(index < mDrawBufferCount); FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(srcColor), &mSrcColor); FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(dstColor), &mDstColor); FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(srcAlpha), &mSrcAlpha); FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(dstAlpha), &mDstAlpha); } void BlendStateExt::setFactorsIndexed(const size_t index, const size_t sourceIndex, const BlendStateExt &source) { ASSERT(index < mDrawBufferCount); ASSERT(sourceIndex < source.mDrawBufferCount); FactorStorage::SetValueIndexed( index, FactorStorage::GetValueIndexed(sourceIndex, source.mSrcColor), &mSrcColor); FactorStorage::SetValueIndexed( index, FactorStorage::GetValueIndexed(sourceIndex, source.mDstColor), &mDstColor); FactorStorage::SetValueIndexed( index, FactorStorage::GetValueIndexed(sourceIndex, source.mSrcAlpha), &mSrcAlpha); FactorStorage::SetValueIndexed( index, FactorStorage::GetValueIndexed(sourceIndex, source.mDstAlpha), &mDstAlpha); } GLenum BlendStateExt::getSrcColorIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(FactorStorage::GetValueIndexed(index, mSrcColor)); } GLenum BlendStateExt::getDstColorIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(FactorStorage::GetValueIndexed(index, mDstColor)); } GLenum BlendStateExt::getSrcAlphaIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(FactorStorage::GetValueIndexed(index, mSrcAlpha)); } GLenum BlendStateExt::getDstAlphaIndexed(size_t index) const { ASSERT(index < mDrawBufferCount); return ToGLenum(FactorStorage::GetValueIndexed(index, mDstAlpha)); } DrawBufferMask BlendStateExt::compareFactors(const FactorStorage::Type srcColor, const FactorStorage::Type dstColor, const FactorStorage::Type srcAlpha, const FactorStorage::Type dstAlpha) const { return FactorStorage::GetDiffMask(mSrcColor, srcColor) | FactorStorage::GetDiffMask(mDstColor, dstColor) | FactorStorage::GetDiffMask(mSrcAlpha, srcAlpha) | FactorStorage::GetDiffMask(mDstAlpha, dstAlpha); } static void MinMax(int a, int b, int *minimum, int *maximum) { if (a < b) { *minimum = a; *maximum = b; } else { *minimum = b; *maximum = a; } } template <> bool RectangleImpl<int>::empty() const { return width == 0 && height == 0; } template <> bool RectangleImpl<float>::empty() const { return std::abs(width) < std::numeric_limits<float>::epsilon() && std::abs(height) < std::numeric_limits<float>::epsilon(); } bool ClipRectangle(const Rectangle &source, const Rectangle &clip, Rectangle *intersection) { angle::CheckedNumeric<int> sourceX2(source.x); sourceX2 += source.width; if (!sourceX2.IsValid()) { return false; } angle::CheckedNumeric<int> sourceY2(source.y); sourceY2 += source.height; if (!sourceY2.IsValid()) { return false; } int minSourceX, maxSourceX, minSourceY, maxSourceY; MinMax(source.x, sourceX2.ValueOrDie(), &minSourceX, &maxSourceX); MinMax(source.y, sourceY2.ValueOrDie(), &minSourceY, &maxSourceY); angle::CheckedNumeric<int> clipX2(clip.x); clipX2 += clip.width; if (!clipX2.IsValid()) { return false; } angle::CheckedNumeric<int> clipY2(clip.y); clipY2 += clip.height; if (!clipY2.IsValid()) { return false; } int minClipX, maxClipX, minClipY, maxClipY; MinMax(clip.x, clipX2.ValueOrDie(), &minClipX, &maxClipX); MinMax(clip.y, clipY2.ValueOrDie(), &minClipY, &maxClipY); if (minSourceX >= maxClipX || maxSourceX <= minClipX || minSourceY >= maxClipY || maxSourceY <= minClipY) { return false; } int x = std::max(minSourceX, minClipX); int y = std::max(minSourceY, minClipY); int width = std::min(maxSourceX, maxClipX) - x; int height = std::min(maxSourceY, maxClipY) - y; if (intersection) { intersection->x = x; intersection->y = y; intersection->width = width; intersection->height = height; } return width != 0 && height != 0; } void GetEnclosingRectangle(const Rectangle &rect1, const Rectangle &rect2, Rectangle *rectUnion) { // All callers use non-flipped framebuffer-size-clipped rectangles, so both flip and overflow // are impossible. ASSERT(!rect1.isReversedX() && !rect1.isReversedY()); ASSERT(!rect2.isReversedX() && !rect2.isReversedY()); ASSERT((angle::CheckedNumeric<int>(rect1.x) + rect1.width).IsValid()); ASSERT((angle::CheckedNumeric<int>(rect1.y) + rect1.height).IsValid()); ASSERT((angle::CheckedNumeric<int>(rect2.x) + rect2.width).IsValid()); ASSERT((angle::CheckedNumeric<int>(rect2.y) + rect2.height).IsValid()); // This function calculates a rectangle that covers both input rectangles: // // +---------+ // rect1 --> | | // | +---+-----+ // | | | | <-- rect2 // +-----+---+ | // | | // +---------+ // // xy0 = min(rect1.xy0, rect2.xy0) // \ // +---------+-----+ // union --> | . | // | + . + . . + // | . . | // + . . + . + | // | . | // +-----+---------+ // / // xy1 = max(rect1.xy1, rect2.xy1) int x0 = std::min(rect1.x0(), rect2.x0()); int y0 = std::min(rect1.y0(), rect2.y0()); int x1 = std::max(rect1.x1(), rect2.x1()); int y1 = std::max(rect1.y1(), rect2.y1()); rectUnion->x = x0; rectUnion->y = y0; rectUnion->width = x1 - x0; rectUnion->height = y1 - y0; } void ExtendRectangle(const Rectangle &source, const Rectangle &extend, Rectangle *extended) { // All callers use non-flipped framebuffer-size-clipped rectangles, so both flip and overflow // are impossible. ASSERT(!source.isReversedX() && !source.isReversedY()); ASSERT(!extend.isReversedX() && !extend.isReversedY()); ASSERT((angle::CheckedNumeric<int>(source.x) + source.width).IsValid()); ASSERT((angle::CheckedNumeric<int>(source.y) + source.height).IsValid()); ASSERT((angle::CheckedNumeric<int>(extend.x) + extend.width).IsValid()); ASSERT((angle::CheckedNumeric<int>(extend.y) + extend.height).IsValid()); int x0 = source.x0(); int x1 = source.x1(); int y0 = source.y0(); int y1 = source.y1(); const int extendX0 = extend.x0(); const int extendX1 = extend.x1(); const int extendY0 = extend.y0(); const int extendY1 = extend.y1(); // For each side of the rectangle, calculate whether it can be extended by the second rectangle. // If so, extend it and continue for the next side with the new dimensions. // Left: Reduce x0 if the second rectangle's vertical edge covers the source's: // // +--- - - - +--- - - - // | | // | +--------------+ +-----------------+ // | | source | --> | source | // | +--------------+ +-----------------+ // | | // +--- - - - +--- - - - // const bool enclosesHeight = EnclosesRange(extendY0, extendY1, y0, y1); if (extendX0 < x0 && extendX1 >= x0 && enclosesHeight) { x0 = extendX0; } // Right: Increase x1 simiarly. if (extendX0 <= x1 && extendX1 > x1 && enclosesHeight) { x1 = extendX1; } // Top: Reduce y0 if the second rectangle's horizontal edge covers the source's potentially // extended edge. const bool enclosesWidth = EnclosesRange(extendX0, extendX1, x0, x1); if (extendY0 < y0 && extendY1 >= y0 && enclosesWidth) { y0 = extendY0; } // Right: Increase y1 simiarly. if (extendY0 <= y1 && extendY1 > y1 && enclosesWidth) { y1 = extendY1; } extended->x = x0; extended->y = y0; extended->width = x1 - x0; extended->height = y1 - y0; } bool Box::valid() const { return width != 0 && height != 0 && depth != 0; } bool Box::operator==(const Box &other) const { return (x == other.x && y == other.y && z == other.z && width == other.width && height == other.height && depth == other.depth); } bool Box::operator!=(const Box &other) const { return !(*this == other); } Rectangle Box::toRect() const { ASSERT(z == 0 && depth == 1); return Rectangle(x, y, width, height); } bool Box::coversSameExtent(const Extents &size) const { return x == 0 && y == 0 && z == 0 && width == size.width && height == size.height && depth == size.depth; } bool Box::contains(const Box &other) const { return x <= other.x && y <= other.y && z <= other.z && x + width >= other.x + other.width && y + height >= other.y + other.height && z + depth >= other.z + other.depth; } size_t Box::volume() const { return width * height * depth; } void Box::extend(const Box &other) { // This extends the logic of "ExtendRectangle" to 3 dimensions int x0 = x; int x1 = x + width; int y0 = y; int y1 = y + height; int z0 = z; int z1 = z + depth; const int otherx0 = other.x; const int otherx1 = other.x + other.width; const int othery0 = other.y; const int othery1 = other.y + other.height; const int otherz0 = other.z; const int otherz1 = other.z + other.depth; // For each side of the box, calculate whether it can be extended by the other box. // If so, extend it and continue to the next side with the new dimensions. const bool enclosesWidth = EnclosesRange(otherx0, otherx1, x0, x1); const bool enclosesHeight = EnclosesRange(othery0, othery1, y0, y1); const bool enclosesDepth = EnclosesRange(otherz0, otherz1, z0, z1); // Left: Reduce x0 if the other box's Y and Z plane encloses the source if (otherx0 < x0 && otherx1 >= x0 && enclosesHeight && enclosesDepth) { x0 = otherx0; } // Right: Increase x1 simiarly. if (otherx0 <= x1 && otherx1 > x1 && enclosesHeight && enclosesDepth) { x1 = otherx1; } // Bottom: Reduce y0 if the other box's X and Z plane encloses the source if (othery0 < y0 && othery1 >= y0 && enclosesWidth && enclosesDepth) { y0 = othery0; } // Top: Increase y1 simiarly. if (othery0 <= y1 && othery1 > y1 && enclosesWidth && enclosesDepth) { y1 = othery1; } // Front: Reduce z0 if the other box's X and Y plane encloses the source if (otherz0 < z0 && otherz1 >= z0 && enclosesWidth && enclosesHeight) { z0 = otherz0; } // Back: Increase z1 simiarly. if (otherz0 <= z1 && otherz1 > z1 && enclosesWidth && enclosesHeight) { z1 = otherz1; } // Update member var with new dimensions x = x0; width = x1 - x0; y = y0; height = y1 - y0; z = z0; depth = z1 - z0; } bool operator==(const Offset &a, const Offset &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } bool operator!=(const Offset &a, const Offset &b) { return !(a == b); } bool operator==(const Extents &lhs, const Extents &rhs) { return lhs.width == rhs.width && lhs.height == rhs.height && lhs.depth == rhs.depth; } bool operator!=(const Extents &lhs, const Extents &rhs) { return !(lhs == rhs); } bool ValidateComponentTypeMasks(unsigned long outputTypes, unsigned long inputTypes, unsigned long outputMask, unsigned long inputMask) { static_assert(IMPLEMENTATION_MAX_DRAW_BUFFERS <= kMaxComponentTypeMaskIndex, "Output/input masks should fit into 16 bits - 1 bit per draw buffer. The " "corresponding type masks should fit into 32 bits - 2 bits per draw buffer."); static_assert(MAX_VERTEX_ATTRIBS <= kMaxComponentTypeMaskIndex, "Output/input masks should fit into 16 bits - 1 bit per attrib. The " "corresponding type masks should fit into 32 bits - 2 bits per attrib."); // For performance reasons, draw buffer and attribute type validation is done using bit masks. // We store two bits representing the type split, with the low bit in the lower 16 bits of the // variable, and the high bit in the upper 16 bits of the variable. This is done so we can AND // with the elswewhere used DrawBufferMask or AttributeMask. // OR the masks with themselves, shifted 16 bits. This is to match our split type bits. outputMask |= (outputMask << kMaxComponentTypeMaskIndex); inputMask |= (inputMask << kMaxComponentTypeMaskIndex); // To validate: // 1. Remove any indexes that are not enabled in the input (& inputMask) // 2. Remove any indexes that exist in output, but not in input (& outputMask) // 3. Use == to verify equality return (outputTypes & inputMask) == ((inputTypes & outputMask) & inputMask); } GLsizeiptr GetBoundBufferAvailableSize(const OffsetBindingPointer<Buffer> &binding) { Buffer *buffer = binding.get(); if (buffer == nullptr) { return 0; } const GLsizeiptr bufferSize = static_cast<GLsizeiptr>(buffer->getSize()); if (binding.getSize() == 0) { return bufferSize; } const GLintptr offset = binding.getOffset(); const GLsizeiptr size = binding.getSize(); ASSERT(offset >= 0 && bufferSize >= 0); if (bufferSize <= offset) { return 0; } return std::min(size, bufferSize - offset); } } // namespace gl
ba3e2faf1e9da7916bac5c828ad40c5cfde34cab
5b3bf81b22f4eb78a1d9e801b2d1d6a48509a236
/codeforces/global_round_2/fret.cc
a6e771b030f66a1deb7cbee1711ba9a99f1b46fd
[]
no_license
okoks9011/problem_solving
42a0843cfdf58846090dff1a2762b6e02362d068
e86d86bb5e3856fcaaa5e20fe19194871d3981ca
refs/heads/master
2023-01-21T19:06:14.143000
2023-01-08T17:45:16
2023-01-08T17:45:16
141,427,667
1
1
null
null
null
null
UTF-8
C++
false
false
1,090
cc
#include <iostream> #include <vector> #include <algorithm> using namespace std; long long CountUnique(long long w, const vector<long long>& d, const vector<long long>& acc) { auto p = lower_bound(d.begin(), d.end(), w) - d.begin() - 1; long long result = 0; if (p >= 0) result += acc[p]; result += (acc.size()-p) * w; return result; } int main() { int n; cin >> n; vector<long long> s(n); for (auto& si : s) cin >> si; sort(s.begin(), s.end()); int q; cin >> q; vector<long long> w(q); for (int i = 0; i < q; ++i) { long long lk, rk; cin >> lk >> rk; w[i] = rk - lk + 1; } vector<long long> d(n-1); for (int i = 0; i < n-1; ++i) d[i] = s[i+1] - s[i]; sort(d.begin(), d.end()); vector<long long> acc(n-1); if (n > 1) acc[0] = d[0]; for (int i = 1; i < n-1; ++i) acc[i] = acc[i-1] + d[i]; for (int i = 0; i < q; ++i) cout << CountUnique(w[i], d, acc) << " "; cout << endl; }
3f56224b3e8961519cc5fa891cb19209e510b2cc
0f7d29777eee0ddd40a563b77df2a77d8a7aea3b
/src/Wallet.hpp
895f86e2a3ca20c3fe7c6c948bd28bf193aa17c9
[ "MIT" ]
permissive
rvillegasm/blocky
f5827c4604d3fb330ec27658d08e0d4e6c86e8df
ca12c4ca7197b7d03d7f360003c4bc1b87890391
refs/heads/main
2023-07-11T13:44:43.423524
2021-08-16T01:56:15
2021-08-16T01:56:15
392,487,660
0
0
null
null
null
null
UTF-8
C++
false
false
307
hpp
#pragma once #include "utils/SignatureKeypair.hpp" namespace blocky { class Wallet { private: utils::SignatureKeypair m_keypair = {}; public: Wallet() = default; [[nodiscard]] const utils::SignatureKeypair &getKeypair() const { return m_keypair; } }; }
7d1ed56a00248f1c397d15636ff95441952686df
5e007aa448d05ef39b1c7731a92be2075df09801
/Test/UnitMovementFilterTest.cpp
9fdfca8b118517d89a09377f4324f853f0847721
[]
no_license
AlvaroChambi/ProjectAI
04a881047a1a7feabdd4850b09318c676e1686f1
b5a31d358d91a071ac857afb0c18ce25eb985687
refs/heads/develop
2020-04-03T23:31:43.567379
2016-09-19T10:03:14
2016-09-19T10:03:14
32,091,207
2
0
null
2016-09-12T19:40:59
2015-03-12T17:29:49
C++
UTF-8
C++
false
false
472
cpp
// // UnitMovementFilterTest.cpp // ProjectWar // // Created by Alvaro Chambi Campos on 8/6/16. // Copyright © 2016 Alvaro Chambi Campos. All rights reserved. // #include "gtest/gtest.h" #include "UnitFilter.h" #include "MockIterator.h" #include "MockMap.h" class UnitMovementFilterTest : public ::testing::Test { public: UnitMovementFilterTest() { } virtual void SetUp() { } virtual void TearDown() { } };
86c0dc1b98d4c8e072495a2448e4983d334ef9a8
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-cognito-sync/include/aws/cognito-sync/model/BulkPublishRequest.h
c51aeb5773ee4263ab7e229fae4c1b05d35765ff
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
3,399
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 #include <aws/cognito-sync/CognitoSync_EXPORTS.h> #include <aws/cognito-sync/CognitoSyncRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace CognitoSync { namespace Model { /** * The input for the BulkPublish operation.<p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/BulkPublishRequest">AWS * API Reference</a></p> */ class AWS_COGNITOSYNC_API BulkPublishRequest : public CognitoSyncRequest { public: BulkPublishRequest(); Aws::String SerializePayload() const override; /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline const Aws::String& GetIdentityPoolId() const{ return m_identityPoolId; } /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline void SetIdentityPoolId(const Aws::String& value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId = value; } /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline void SetIdentityPoolId(Aws::String&& value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId = value; } /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline void SetIdentityPoolId(const char* value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId.assign(value); } /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline BulkPublishRequest& WithIdentityPoolId(const Aws::String& value) { SetIdentityPoolId(value); return *this;} /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline BulkPublishRequest& WithIdentityPoolId(Aws::String&& value) { SetIdentityPoolId(value); return *this;} /** * A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) * created by Amazon Cognito. GUID generation is unique within a region. */ inline BulkPublishRequest& WithIdentityPoolId(const char* value) { SetIdentityPoolId(value); return *this;} private: Aws::String m_identityPoolId; bool m_identityPoolIdHasBeenSet; }; } // namespace Model } // namespace CognitoSync } // namespace Aws
39d605c2caa1c272705289bd86a3dd7e0a4b7c2b
b9264aa2552272b19ca393ba818f9dcb8d91da10
/hashmap/lib/seqan3/test/unit/core/algorithm/algorithm_result_generator_range_test.cpp
d106ca551f52a6936cfaea989d40484cf9994252
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-public-domain", "CC0-1.0", "CC-BY-4.0", "MIT" ]
permissive
eaasna/low-memory-prefilter
c29b3aeb76f70afc4f26da3d9f063b0bc2e251e0
efa20dc8a95ce688d2a9d08773d120dff4cccbb6
refs/heads/master
2023-07-04T16:45:05.817237
2021-08-12T12:01:11
2021-08-12T12:01:11
383,427,746
0
0
BSD-3-Clause
2021-07-06T13:24:31
2021-07-06T10:22:54
C++
UTF-8
C++
false
false
4,490
cpp
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <optional> #include <vector> #include <seqan3/core/algorithm/algorithm_result_generator_range.hpp> #include <seqan3/utility/views/single_pass_input.hpp> #include "../../range/iterator_test_template.hpp" // ---------------------------------------------------------------------------- // Simple executor used as mock for the test. // ---------------------------------------------------------------------------- struct dummy_executor { using value_type = size_t; using reference = value_type; using difference_type = std::ptrdiff_t; std::optional<size_t> next_result() { auto it = std::ranges::begin(generator); if (it == std::ranges::end(generator)) { return {}; } else { std::optional<size_t> opt{*it}; ++it; return opt; } } private: seqan3::detail::single_pass_input_view<decltype(std::views::iota(0u, 10u))> generator{std::views::iota(0u, 10u)}; }; // ---------------------------------------------------------------------------- // Testing iterator. // ---------------------------------------------------------------------------- using algorithm_result_generator_range_t = seqan3::algorithm_result_generator_range<dummy_executor>; using algorithm_result_generator_range_iterator = std::ranges::iterator_t<algorithm_result_generator_range_t>; template <> struct iterator_fixture<algorithm_result_generator_range_iterator> : ::testing::Test { using iterator_tag = std::input_iterator_tag; static constexpr bool const_iterable = false; algorithm_result_generator_range_t test_range{dummy_executor{}}; std::vector<size_t> expected_range{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; }; INSTANTIATE_TYPED_TEST_SUITE_P(algorithm_result_generator_range_iterator, iterator_fixture, algorithm_result_generator_range_iterator, ); // ---------------------------------------------------------------------------- // Testing alignment range concepts and interfaces. // ---------------------------------------------------------------------------- TEST(algorithm_result_generator_range, concept_test) { EXPECT_TRUE(std::ranges::input_range<algorithm_result_generator_range_t>); EXPECT_FALSE(std::ranges::forward_range<algorithm_result_generator_range_t>); } TEST(algorithm_result_generator_range, construction) { EXPECT_TRUE(std::is_default_constructible_v<algorithm_result_generator_range_t>); EXPECT_FALSE(std::is_copy_constructible_v<algorithm_result_generator_range_t>); EXPECT_TRUE(std::is_move_constructible_v<algorithm_result_generator_range_t>); EXPECT_FALSE(std::is_copy_assignable_v<algorithm_result_generator_range_t>); EXPECT_TRUE(std::is_move_assignable_v<algorithm_result_generator_range_t>); EXPECT_TRUE((std::is_constructible_v<algorithm_result_generator_range_t, dummy_executor>)); } TEST(algorithm_result_generator_range, type_deduction) { seqan3::algorithm_result_generator_range rng{dummy_executor{}}; EXPECT_TRUE((std::is_same_v<decltype(rng), seqan3::algorithm_result_generator_range<dummy_executor>>)); } TEST(algorithm_result_generator_range, begin) { seqan3::algorithm_result_generator_range rng{dummy_executor{}}; auto it = rng.begin(); EXPECT_EQ(*it, 0u); } TEST(algorithm_result_generator_range, end) { seqan3::algorithm_result_generator_range rng{dummy_executor{}}; auto it = rng.end(); EXPECT_FALSE(it == rng.begin()); EXPECT_FALSE(rng.begin() == it); } TEST(algorithm_result_generator_range, iterable) { seqan3::algorithm_result_generator_range rng{dummy_executor{}}; size_t sum = 0; for (size_t res : rng) sum += res; EXPECT_EQ(sum, 45u); } TEST(algorithm_result_generator_range, default_construction) { seqan3::algorithm_result_generator_range<dummy_executor> rng{}; EXPECT_THROW(rng.begin(), std::runtime_error); }
1fa82df89068db26adb7718d7a77a5a882480b65
0400f3ae3051b5e34872e657e9260c0c6784d8d4
/Assignment 2/HW2PR2.cpp
eb60684dadd5aeafaa237414f20960ff88c68041
[]
no_license
pionoor/CSCE121
d4341b870db821214e8694aa8095634bd66d10ff
1eb8d4ebbc2a3145974459714f0b7498e9c52e45
refs/heads/master
2021-01-20T02:20:31.911785
2015-05-20T01:57:00
2015-05-20T01:57:00
35,919,690
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
// // main.cpp // HW2PR1 // // Created by Noor Thabit on 2/7/13. // Copyright (c) 2013 Noor Thabit. All rights reserved. // #include <iostream> #include <math.h> using namespace std; double my_sqrt_1(double n) //creat a function accept double and return adouble { double x=n-1; double result = 1 + (1/2)*pow(x,1.0) - (1/8)*pow(x,2.0) + (1/16)*pow(x,3.0) - (5/128)*pow(x,4.0); return result; } int main() { double n; double relative_error_per_cent; for(auto k: {-100,-10,-1,0,1,10,100}) { n = 3.14159 * pow(10.0,k); relative_error_per_cent = 100 * ((my_sqrt_1(n) - sqrt(n))/sqrt(n)); //the relative error as a per cent cout<<n<<'\t'<<sqrt(n)<<'\t'<<my_sqrt_1(n)<<'\t'<<relative_error_per_cent<<endl ; //prints n, sqrt(n), and my_sqrt_1(n) for n } return 0; }
6a261b087866665c9715f5e1aa111337c608d222
dc603c5e4b8c05b319359b6588e2eadbe3a0f745
/simple_navigation_goals/src/point_b_navigation_goal.cpp
facf63b40930ac11dd957718728e11f3303cd3a5
[]
no_license
japerezg86/warehouse_navigation
ebf01515085a56b57eb301f53d6882fa41c5a794
3c5100d80e361643255a77f59c1f0a2c37f1d83b
refs/heads/main
2023-04-18T15:12:16.905864
2021-05-02T17:32:10
2021-05-02T17:32:10
363,567,082
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> using namespace std; typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient; int main(int argc, char** argv){ ros::init(argc, argv, "point_b_navigation_goal"); //tell the action client that we want to spin a thread by default MoveBaseClient ac("move_base", true); //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } ros::Time begin; ros::Time end; ros::Duration duration; //define the move base goals for each room move_base_msgs::MoveBaseGoal point_b_goal; //send the first goal point_b_goal.target_pose.header.frame_id = "map"; point_b_goal.target_pose.header.stamp = ros::Time::now(); point_b_goal.target_pose.pose.position.x = -13.2508673897; point_b_goal.target_pose.pose.position.y = -6.03139311508; point_b_goal.target_pose.pose.orientation.w = 1.0; ROS_INFO("Sending point_b_goal"); begin = ros::Time::now(); ac.sendGoal(point_b_goal); ac.waitForResult(); end = ros::Time::now(); duration = end - begin; cout << "Time to reach goal in sec: " << duration.toSec() << endl; if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("Hooray, the task has been achieved"); else ROS_INFO("The base failed to achieve task for some reason"); return 0; }
349ef8d8bb00fe3e56f0f7d5e8040e80c16d903d
de7e771699065ec21a340ada1060a3cf0bec3091
/demo/src/java/org/apache/lucene/demo/facet/SimpleSortedSetFacetsExample.cpp
fb5961262ce8f23262fef9fd8ca2c6810e9f0cf9
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
6,112
cpp
using namespace std; #include "SimpleSortedSetFacetsExample.h" namespace org::apache::lucene::demo::facet { using WhitespaceAnalyzer = org::apache::lucene::analysis::core::WhitespaceAnalyzer; using Document = org::apache::lucene::document::Document; using DrillDownQuery = org::apache::lucene::facet::DrillDownQuery; using FacetResult = org::apache::lucene::facet::FacetResult; using Facets = org::apache::lucene::facet::Facets; using FacetsCollector = org::apache::lucene::facet::FacetsCollector; using FacetsConfig = org::apache::lucene::facet::FacetsConfig; using DefaultSortedSetDocValuesReaderState = org::apache::lucene::facet::sortedset::DefaultSortedSetDocValuesReaderState; using SortedSetDocValuesFacetCounts = org::apache::lucene::facet::sortedset::SortedSetDocValuesFacetCounts; using SortedSetDocValuesFacetField = org::apache::lucene::facet::sortedset::SortedSetDocValuesFacetField; using SortedSetDocValuesReaderState = org::apache::lucene::facet::sortedset::SortedSetDocValuesReaderState; using DirectoryReader = org::apache::lucene::index::DirectoryReader; using IndexWriter = org::apache::lucene::index::IndexWriter; using IndexWriterConfig = org::apache::lucene::index::IndexWriterConfig; using OpenMode = org::apache::lucene::index::IndexWriterConfig::OpenMode; using IndexSearcher = org::apache::lucene::search::IndexSearcher; using MatchAllDocsQuery = org::apache::lucene::search::MatchAllDocsQuery; using Directory = org::apache::lucene::store::Directory; using RAMDirectory = org::apache::lucene::store::RAMDirectory; SimpleSortedSetFacetsExample::SimpleSortedSetFacetsExample() {} void SimpleSortedSetFacetsExample::index() { shared_ptr<IndexWriter> indexWriter = make_shared<IndexWriter>( indexDir, (make_shared<IndexWriterConfig>(make_shared<WhitespaceAnalyzer>())) ->setOpenMode(IndexWriterConfig::OpenMode::CREATE)); shared_ptr<Document> doc = make_shared<Document>(); doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Bob")); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2010")); indexWriter->addDocument(config->build(doc)); doc = make_shared<Document>(); doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Lisa")); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2010")); indexWriter->addDocument(config->build(doc)); doc = make_shared<Document>(); doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Lisa")); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2012")); indexWriter->addDocument(config->build(doc)); doc = make_shared<Document>(); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Author", L"Susan")); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2012")); indexWriter->addDocument(config->build(doc)); doc = make_shared<Document>(); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Author", L"Frank")); doc->push_back( make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"1999")); indexWriter->addDocument(config->build(doc)); delete indexWriter; } deque<std::shared_ptr<FacetResult>> SimpleSortedSetFacetsExample::search() { shared_ptr<DirectoryReader> indexReader = DirectoryReader::open(indexDir); shared_ptr<IndexSearcher> searcher = make_shared<IndexSearcher>(indexReader); shared_ptr<SortedSetDocValuesReaderState> state = make_shared<DefaultSortedSetDocValuesReaderState>(indexReader); // Aggregatses the facet counts shared_ptr<FacetsCollector> fc = make_shared<FacetsCollector>(); // MatchAllDocsQuery is for "browsing" (counts facets // for all non-deleted docs in the index); normally // you'd use a "normal" query: FacetsCollector::search(searcher, make_shared<MatchAllDocsQuery>(), 10, fc); // Retrieve results shared_ptr<Facets> facets = make_shared<SortedSetDocValuesFacetCounts>(state, fc); deque<std::shared_ptr<FacetResult>> results = deque<std::shared_ptr<FacetResult>>(); results.push_back(facets->getTopChildren(10, L"Author")); results.push_back(facets->getTopChildren(10, L"Publish Year")); indexReader->close(); return results; } shared_ptr<FacetResult> SimpleSortedSetFacetsExample::drillDown() { shared_ptr<DirectoryReader> indexReader = DirectoryReader::open(indexDir); shared_ptr<IndexSearcher> searcher = make_shared<IndexSearcher>(indexReader); shared_ptr<SortedSetDocValuesReaderState> state = make_shared<DefaultSortedSetDocValuesReaderState>(indexReader); // Now user drills down on Publish Year/2010: shared_ptr<DrillDownQuery> q = make_shared<DrillDownQuery>(config); q->add(L"Publish Year", {L"2010"}); shared_ptr<FacetsCollector> fc = make_shared<FacetsCollector>(); FacetsCollector::search(searcher, q, 10, fc); // Retrieve results shared_ptr<Facets> facets = make_shared<SortedSetDocValuesFacetCounts>(state, fc); shared_ptr<FacetResult> result = facets->getTopChildren(10, L"Author"); indexReader->close(); return result; } deque<std::shared_ptr<FacetResult>> SimpleSortedSetFacetsExample::runSearch() { index(); return search(); } shared_ptr<FacetResult> SimpleSortedSetFacetsExample::runDrillDown() { index(); return drillDown(); } void SimpleSortedSetFacetsExample::main(std::deque<wstring> &args) throw( runtime_error) { wcout << L"Facet counting example:" << endl; wcout << L"-----------------------" << endl; shared_ptr<SimpleSortedSetFacetsExample> example = make_shared<SimpleSortedSetFacetsExample>(); deque<std::shared_ptr<FacetResult>> results = example->runSearch(); wcout << L"Author: " << results[0] << endl; wcout << L"Publish Year: " << results[0] << endl; wcout << L"\n" << endl; wcout << L"Facet drill-down example (Publish Year/2010):" << endl; wcout << L"---------------------------------------------" << endl; wcout << L"Author: " << example->runDrillDown() << endl; } } // namespace org::apache::lucene::demo::facet
a3e0e795c91fede0bf0f6ace87a8d4ffb9bbfd9c
1cf5f0ca5ba9422dfc56ecc524bb72fd56e28312
/CvGameCoreDLL/CvBuildingClasses.cpp
057ebbc542195c5ad49cd11b4c244c6e4038a4c5
[]
no_license
djcolumbia/Community-Patch-DLL
46ea6f334b0a8c7c214e2cb5e89f3fa97fcffdf7
a8a5c31bf86e327761ca9c3de3038e2a0b1c9ee7
refs/heads/master
2020-12-25T04:27:20.862151
2015-02-16T05:19:35
2015-02-16T05:19:35
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
86,045
cpp
/* ------------------------------------------------------------------------------------------------------- © 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games. Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software and their respective logos are all trademarks of Take-Two interactive Software, Inc. All other marks and trademarks are the property of their respective owners. All rights reserved. ------------------------------------------------------------------------------------------------------- */ #include "CvGameCoreDLLPCH.h" #include "ICvDLLUserInterface.h" #include "CvGameCoreUtils.h" #include "CvInternalGameCoreUtils.h" #include "FStlContainerSerialization.h" #include "CvEnumSerialization.h" #include "CvDLLUtilDefines.h" #include "CvDllCity.h" #include "CvDllPlot.h" // include after all other headers #include "LintFree.h" /// Constructor CvBuildingEntry::CvBuildingEntry(void): m_iBuildingClassType(NO_BUILDINGCLASS), m_pkBuildingClassInfo(NULL), m_iNearbyTerrainRequired(NO_VICTORY), m_iProhibitedCityTerrain(NO_VICTORY), m_iVictoryPrereq(NO_VICTORY), m_iFreeStartEra(NO_ERA), m_iMaxStartEra(NO_ERA), m_iObsoleteTech(NO_TECH), m_iEnhancedYieldTech(NO_TECH), m_iGoldMaintenance(0), m_iMutuallyExclusiveGroup(0), m_iReplacementBuildingClass(NO_BUILDINGCLASS), m_iPrereqAndTech(NO_TECH), m_iSpecialistType(NO_SPECIALIST), m_iSpecialistCount(0), m_iSpecialistExtraCulture(0), m_iGreatPeopleRateChange(0), m_iFreeBuildingClass(NO_BUILDINGCLASS), m_iFreeBuildingThisCity(NO_BUILDINGCLASS), m_iFreePromotion(NO_PROMOTION), m_iTrainedFreePromotion(NO_PROMOTION), m_iFreePromotionRemoved(NO_PROMOTION), m_iProductionCost(0), m_iNumCityCostMod(0), m_iHurryCostModifier(0), m_iNumCitiesPrereq(0), m_iUnitLevelPrereq(0), m_iJONSCulture(0), m_iCultureRateModifier(0), m_iGlobalCultureRateModifier(0), m_iGreatPeopleRateModifier(0), m_iGlobalGreatPeopleRateModifier(0), m_iGreatGeneralRateModifier(0), m_iGreatPersonExpendGold(0), m_iUnitUpgradeCostMod(0), m_iGoldenAgeModifier(0), m_iFreeExperience(0), m_iGlobalFreeExperience(0), m_iFoodKept(0), m_iAirlift(0), m_iAirModifier(0), m_iNukeModifier(0), m_iNukeExplosionRand(0), m_iWorkerSpeedModifier(0), m_iMilitaryProductionModifier(0), m_iSpaceProductionModifier(0), m_iMinAreaSize(0), m_iConquestProbability(0), m_iHealRateChange(0), m_iHappiness(0), m_iUnmoddedHappiness(0), m_iUnhappinessModifier(0), m_iHappinessPerCity(0), m_iHappinessPerXPolicies(0), m_iCityCountUnhappinessMod(0), m_bNoOccupiedUnhappiness(false), m_iGlobalPopulationChange(0), m_iTechShare(0), m_iFreeTechs(0), m_iFreePolicies(0), m_iFreeGreatPeople(0), m_iMedianTechPercentChange(0), m_iGold(0), m_bNearbyMountainRequired(false), m_bAllowsRangeStrike(false), m_iDefenseModifier(0), m_iGlobalDefenseModifier(0), m_iMissionType(NO_MISSION), m_iMinorFriendshipChange(0), m_iVictoryPoints(0), m_iPreferredDisplayPosition(0), m_iPortraitIndex(-1), m_bTeamShare(false), m_bWater(false), m_bRiver(false), m_bFreshWater(false), m_bMountain(false), m_bHill(false), m_bFlat(false), m_bFoundsReligion(false), m_bIsReligious(false), m_bBorderObstacle(false), m_bPlayerBorderObstacle(false), m_bCapital(false), m_bGoldenAge(false), m_bMapCentering(false), m_bNeverCapture(false), m_bNukeImmune(false), m_bExtraLuxuries(false), m_bDiplomaticVoting(false), m_bAllowsWaterRoutes(false), m_bCityWall(false), m_piLockedBuildingClasses(NULL), m_piPrereqAndTechs(NULL), m_piResourceQuantityRequirements(NULL), m_piResourceCultureChanges(NULL), m_piProductionTraits(NULL), m_piSeaPlotYieldChange(NULL), m_piRiverPlotYieldChange(NULL), m_piLakePlotYieldChange(NULL), m_piSeaResourceYieldChange(NULL), m_piYieldChange(NULL), m_piYieldChangePerPop(NULL), m_piYieldModifier(NULL), m_piAreaYieldModifier(NULL), m_piGlobalYieldModifier(NULL), m_piTechEnhancedYieldChange(NULL), m_piUnitCombatFreeExperience(NULL), m_piUnitCombatProductionModifiers(NULL), m_piDomainFreeExperience(NULL), m_piDomainProductionModifier(NULL), m_piPrereqNumOfBuildingClass(NULL), m_piFlavorValue(NULL), m_piLocalResourceAnds(NULL), m_piLocalResourceOrs(NULL), m_paiHurryModifier(NULL), m_pbBuildingClassNeededInCity(NULL), m_piNumFreeUnits(NULL), m_bArtInfoEraVariation(false), m_bArtInfoCulturalVariation(false), m_bArtInfoRandomVariation(false), m_ppaiResourceYieldChange(NULL), m_ppaiFeatureYieldChange(NULL), m_ppaiSpecialistYieldChange(NULL), m_ppaiResourceYieldModifier(NULL) { } /// Destructor CvBuildingEntry::~CvBuildingEntry(void) { SAFE_DELETE_ARRAY(m_piLockedBuildingClasses); SAFE_DELETE_ARRAY(m_piPrereqAndTechs); SAFE_DELETE_ARRAY(m_piResourceQuantityRequirements); SAFE_DELETE_ARRAY(m_piResourceCultureChanges); SAFE_DELETE_ARRAY(m_piProductionTraits); SAFE_DELETE_ARRAY(m_piSeaPlotYieldChange); SAFE_DELETE_ARRAY(m_piRiverPlotYieldChange); SAFE_DELETE_ARRAY(m_piLakePlotYieldChange); SAFE_DELETE_ARRAY(m_piSeaResourceYieldChange); SAFE_DELETE_ARRAY(m_piYieldChange); SAFE_DELETE_ARRAY(m_piYieldChangePerPop); SAFE_DELETE_ARRAY(m_piYieldModifier); SAFE_DELETE_ARRAY(m_piAreaYieldModifier); SAFE_DELETE_ARRAY(m_piGlobalYieldModifier); SAFE_DELETE_ARRAY(m_piTechEnhancedYieldChange); SAFE_DELETE_ARRAY(m_piUnitCombatFreeExperience); SAFE_DELETE_ARRAY(m_piUnitCombatProductionModifiers); SAFE_DELETE_ARRAY(m_piDomainFreeExperience); SAFE_DELETE_ARRAY(m_piDomainProductionModifier); SAFE_DELETE_ARRAY(m_piPrereqNumOfBuildingClass); SAFE_DELETE_ARRAY(m_piFlavorValue); SAFE_DELETE_ARRAY(m_piLocalResourceAnds); SAFE_DELETE_ARRAY(m_piLocalResourceOrs); SAFE_DELETE_ARRAY(m_paiHurryModifier); SAFE_DELETE_ARRAY(m_pbBuildingClassNeededInCity); SAFE_DELETE_ARRAY(m_piNumFreeUnits); CvDatabaseUtility::SafeDelete2DArray( m_ppaiResourceYieldChange ); CvDatabaseUtility::SafeDelete2DArray( m_ppaiFeatureYieldChange ); CvDatabaseUtility::SafeDelete2DArray( m_ppaiSpecialistYieldChange ); CvDatabaseUtility::SafeDelete2DArray( m_ppaiResourceYieldModifier ); } /// Read from XML file bool CvBuildingEntry::CacheResults(Database::Results& kResults, CvDatabaseUtility& kUtility) { if (!CvBaseInfo::CacheResults(kResults, kUtility)) return false; //Basic Properties m_iGoldMaintenance = kResults.GetInt("GoldMaintenance"); m_iMutuallyExclusiveGroup = kResults.GetInt("MutuallyExclusiveGroup"); m_bTeamShare = kResults.GetBool("TeamShare"); m_bWater = kResults.GetBool("Water"); m_bRiver = kResults.GetBool("River"); m_bFreshWater = kResults.GetBool("FreshWater"); m_bMountain = kResults.GetBool("Mountain"); m_bHill = kResults.GetBool("Hill"); m_bFlat = kResults.GetBool("Flat"); m_bFoundsReligion = kResults.GetBool("FoundsReligion"); m_bIsReligious = kResults.GetBool("IsReligious"); m_bBorderObstacle = kResults.GetBool("BorderObstacle"); m_bPlayerBorderObstacle = kResults.GetBool("PlayerBorderObstacle"); m_bCapital = kResults.GetBool("Capital"); m_bGoldenAge = kResults.GetBool("GoldenAge"); m_bMapCentering = kResults.GetBool("MapCentering"); m_bNeverCapture = kResults.GetBool("NeverCapture"); m_bNukeImmune = kResults.GetBool("NukeImmune"); m_bCityWall = kResults.GetBool("CityWall"); m_bExtraLuxuries = kResults.GetBool("ExtraLuxuries"); m_bDiplomaticVoting = kResults.GetBool("DiplomaticVoting"); m_bAllowsWaterRoutes = kResults.GetBool("AllowsWaterRoutes"); m_iProductionCost = kResults.GetInt("Cost"); m_iNumCityCostMod = kResults.GetInt("NumCityCostMod"); m_iHurryCostModifier = kResults.GetInt("HurryCostModifier"); m_iMinAreaSize = kResults.GetInt("MinAreaSize"); m_iConquestProbability = kResults.GetInt("ConquestProb"); m_iNumCitiesPrereq = kResults.GetInt("CitiesPrereq"); m_iUnitLevelPrereq = kResults.GetInt("LevelPrereq"); m_iJONSCulture = kResults.GetInt("Culture"); m_iCultureRateModifier = kResults.GetInt("CultureRateModifier"); m_iGlobalCultureRateModifier = kResults.GetInt("GlobalCultureRateModifier"); m_iGreatPeopleRateModifier = kResults.GetInt("GreatPeopleRateModifier"); m_iGlobalGreatPeopleRateModifier = kResults.GetInt("GlobalGreatPeopleRateModifier"); m_iGreatGeneralRateModifier = kResults.GetInt("GreatGeneralRateModifier"); m_iGreatPersonExpendGold = kResults.GetInt("GreatPersonExpendGold"); m_iUnitUpgradeCostMod = kResults.GetInt("UnitUpgradeCostMod"); m_iGoldenAgeModifier = kResults.GetInt("GoldenAgeModifier"); m_iFreeExperience = kResults.GetInt("Experience"); m_iGlobalFreeExperience = kResults.GetInt("GlobalExperience"); m_iFoodKept = kResults.GetInt("FoodKept"); m_iAirlift = kResults.GetInt("Airlift"); m_iAirModifier = kResults.GetInt("AirModifier"); m_iNukeModifier = kResults.GetInt("NukeModifier"); m_iNukeExplosionRand = kResults.GetInt("NukeExplosionRand"); m_iHealRateChange = kResults.GetInt("HealRateChange"); m_iHappiness = kResults.GetInt("Happiness"); m_iUnmoddedHappiness = kResults.GetInt("UnmoddedHappiness"); m_iUnhappinessModifier = kResults.GetInt("UnhappinessModifier"); m_iHappinessPerCity = kResults.GetInt("HappinessPerCity"); m_iHappinessPerXPolicies = kResults.GetInt("HappinessPerXPolicies"); m_iCityCountUnhappinessMod = kResults.GetInt("CityCountUnhappinessMod"); m_bNoOccupiedUnhappiness = kResults.GetBool("NoOccupiedUnhappiness"); m_iWorkerSpeedModifier = kResults.GetInt("WorkerSpeedModifier"); m_iMilitaryProductionModifier = kResults.GetInt("MilitaryProductionModifier"); m_iSpaceProductionModifier = kResults.GetInt("SpaceProductionModifier"); m_iBuildingProductionModifier = kResults.GetInt("BuildingProductionModifier"); m_iWonderProductionModifier = kResults.GetInt("WonderProductionModifier"); m_iTradeRouteModifier = kResults.GetInt("TradeRouteModifier"); m_iCapturePlunderModifier = kResults.GetInt("CapturePlunderModifier"); m_iPolicyCostModifier = kResults.GetInt("PolicyCostModifier"); m_iPlotCultureCostModifier = kResults.GetInt("PlotCultureCostModifier"); m_iGlobalPlotCultureCostModifier = kResults.GetInt("GlobalPlotCultureCostModifier"); m_iPlotBuyCostModifier = kResults.GetInt("PlotBuyCostModifier"); m_iGlobalPlotBuyCostModifier = kResults.GetInt("GlobalPlotBuyCostModifier"); m_iGlobalPopulationChange = kResults.GetInt("GlobalPopulationChange"); m_iTechShare = kResults.GetInt("TechShare"); m_iFreeTechs = kResults.GetInt("FreeTechs"); m_iFreePolicies = kResults.GetInt("FreePolicies"); m_iFreeGreatPeople = kResults.GetInt("FreeGreatPeople"); m_iMedianTechPercentChange = kResults.GetInt("MedianTechPercentChange"); m_iGold = kResults.GetInt("Gold"); m_bNearbyMountainRequired = kResults.GetInt("NearbyMountainRequired"); m_bAllowsRangeStrike = kResults.GetInt("AllowsRangeStrike"); m_iDefenseModifier = kResults.GetInt("Defense"); m_iGlobalDefenseModifier = kResults.GetInt("GlobalDefenseMod"); m_iMinorFriendshipChange = kResults.GetInt("MinorFriendshipChange"); m_iVictoryPoints = kResults.GetInt("VictoryPoints"); m_iPreferredDisplayPosition = kResults.GetInt("DisplayPosition"); m_iPortraitIndex = kResults.GetInt("PortraitIndex"); m_bArtInfoCulturalVariation = kResults.GetBool("ArtInfoCulturalVariation"); m_bArtInfoEraVariation = kResults.GetBool("ArtInfoEraVariation"); m_bArtInfoRandomVariation = kResults.GetBool("ArtInfoRandomVariation"); //References const char* szTextVal; szTextVal = kResults.GetText("BuildingClass"); m_iBuildingClassType = GC.getInfoTypeForString(szTextVal, true); //This may need to be deferred to a routine that is called AFTER pre-fetch has been called for all infos. m_pkBuildingClassInfo = GC.getBuildingClassInfo(static_cast<BuildingClassTypes>(m_iBuildingClassType)); CvAssertMsg(m_pkBuildingClassInfo, "Could not find BuildingClassInfo for BuildingType. Have BuildingClasses been prefetched yet?"); szTextVal = kResults.GetText("ArtDefineTag"); SetArtDefineTag(szTextVal); szTextVal = kResults.GetText("WonderSplashAudio"); m_strWonderSplashAudio = szTextVal; szTextVal = kResults.GetText("NearbyTerrainRequired"); m_iNearbyTerrainRequired = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("ProhibitedCityTerrain"); m_iProhibitedCityTerrain = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("VictoryPrereq"); m_iVictoryPrereq = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("FreeStartEra"); m_iFreeStartEra = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("MaxStartEra"); m_iMaxStartEra = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("ObsoleteTech"); m_iObsoleteTech = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("EnhancedYieldTech"); m_iEnhancedYieldTech = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("FreeBuilding"); m_iFreeBuildingClass = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("FreeBuildingThisCity"); m_iFreeBuildingThisCity = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("FreePromotion"); m_iFreePromotion = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("TrainedFreePromotion"); m_iTrainedFreePromotion = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("FreePromotionRemoved"); m_iFreePromotionRemoved = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("ReplacementBuildingClass"); m_iReplacementBuildingClass= GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("PrereqTech"); m_iPrereqAndTech = GC.getInfoTypeForString(szTextVal, true); szTextVal = kResults.GetText("SpecialistType"); m_iSpecialistType = GC.getInfoTypeForString(szTextVal, true); m_iSpecialistCount = kResults.GetInt("SpecialistCount"); m_iSpecialistExtraCulture = kResults.GetInt("SpecialistExtraCulture"); m_iGreatPeopleRateChange= kResults.GetInt("GreatPeopleRateChange"); //Arrays const char* szBuildingType = GetType(); kUtility.SetFlavors(m_piFlavorValue, "Building_Flavors", "BuildingType", szBuildingType); kUtility.SetYields(m_piSeaPlotYieldChange, "Building_SeaPlotYieldChanges", "BuildingType", szBuildingType); kUtility.SetYields(m_piRiverPlotYieldChange, "Building_RiverPlotYieldChanges", "BuildingType", szBuildingType); kUtility.SetYields(m_piLakePlotYieldChange, "Building_LakePlotYieldChanges", "BuildingType", szBuildingType); kUtility.SetYields(m_piSeaResourceYieldChange, "Building_SeaResourceYieldChanges", "BuildingType", szBuildingType); kUtility.SetYields(m_piYieldChange, "Building_YieldChanges", "BuildingType", szBuildingType); kUtility.SetYields(m_piYieldChangePerPop, "Building_YieldChangesPerPop", "BuildingType", szBuildingType); kUtility.SetYields(m_piYieldModifier, "Building_YieldModifiers", "BuildingType", szBuildingType); kUtility.SetYields(m_piAreaYieldModifier, "Building_AreaYieldModifiers", "BuildingType", szBuildingType); kUtility.SetYields(m_piGlobalYieldModifier, "Building_GlobalYieldModifiers", "BuildingType", szBuildingType); kUtility.SetYields(m_piTechEnhancedYieldChange, "Building_TechEnhancedYieldChanges", "BuildingType", szBuildingType); kUtility.PopulateArrayByValue(m_piResourceQuantityRequirements, "Resources", "Building_ResourceQuantityRequirements", "ResourceType", "BuildingType", szBuildingType, "Cost"); kUtility.PopulateArrayByValue(m_piResourceCultureChanges, "Resources", "Building_ResourceCultureChanges", "ResourceType", "BuildingType", szBuildingType, "CultureChange"); kUtility.PopulateArrayByValue(m_paiHurryModifier, "HurryInfos", "Building_HurryModifiers", "HurryType", "BuildingType", szBuildingType, "HurryCostModifier"); //kUtility.PopulateArrayByValue(m_piProductionTraits, "Traits", "Building_ProductionTraits", "TraitType", "BuildingType", szBuildingType, "Trait"); kUtility.PopulateArrayByValue(m_piUnitCombatFreeExperience, "UnitCombatInfos", "Building_UnitCombatFreeExperiences", "UnitCombatType", "BuildingType", szBuildingType, "Experience"); kUtility.PopulateArrayByValue(m_piUnitCombatProductionModifiers, "UnitCombatInfos", "Building_UnitCombatProductionModifiers", "UnitCombatType", "BuildingType", szBuildingType, "Modifier"); kUtility.PopulateArrayByValue(m_piDomainFreeExperience, "Domains", "Building_DomainFreeExperiences", "DomainType", "BuildingType", szBuildingType, "Experience", 0, NUM_DOMAIN_TYPES); kUtility.PopulateArrayByValue(m_piDomainProductionModifier, "Domains", "Building_DomainProductionModifiers", "DomainType", "BuildingType", szBuildingType, "Modifier", 0, NUM_DOMAIN_TYPES); kUtility.PopulateArrayByValue(m_piPrereqNumOfBuildingClass, "BuildingClasses", "Building_PrereqBuildingClasses", "BuildingClassType", "BuildingType", szBuildingType, "NumBuildingNeeded"); kUtility.PopulateArrayByExistence(m_pbBuildingClassNeededInCity, "BuildingClasses", "Building_ClassesNeededInCity", "BuildingClassType", "BuildingType", szBuildingType); //kUtility.PopulateArrayByExistence(m_piNumFreeUnits, "Units", "Building_FreeUnits", "UnitType", "BuildingType", szBuildingType); kUtility.PopulateArrayByValue(m_piNumFreeUnits, "Units", "Building_FreeUnits", "UnitType", "BuildingType", szBuildingType, "NumUnits"); kUtility.PopulateArrayByExistence(m_piLockedBuildingClasses, "BuildingClasses", "Building_LockedBuildingClasses", "BuildingClassType", "BuildingType", szBuildingType); kUtility.PopulateArrayByExistence(m_piPrereqAndTechs, "Technologies", "Building_TechAndPrereqs", "TechType", "BuildingType", szBuildingType); kUtility.PopulateArrayByExistence(m_piLocalResourceAnds, "Resources", "Building_LocalResourceAnds", "ResourceType", "BuildingType", szBuildingType); kUtility.PopulateArrayByExistence(m_piLocalResourceOrs, "Resources", "Building_LocalResourceOrs", "ResourceType", "BuildingType", szBuildingType); //ResourceYieldChanges { kUtility.Initialize2DArray(m_ppaiResourceYieldChange, "Resources", "Yields"); std::string strKey("Building_ResourceYieldChanges"); Database::Results* pResults = kUtility.GetResults(strKey); if(pResults == NULL) { pResults = kUtility.PrepareResults(strKey, "select Resources.ID as ResourceID, Yields.ID as YieldID, Yield from Building_ResourceYieldChanges inner join Resources on Resources.Type = ResourceType inner join Yields on Yields.Type = YieldType where BuildingType = ?"); } pResults->Bind(1, szBuildingType); while(pResults->Step()) { const int ResourceID = pResults->GetInt(0); const int YieldID = pResults->GetInt(1); const int yield = pResults->GetInt(2); m_ppaiResourceYieldChange[ResourceID][YieldID] = yield; } } //FeatureYieldChanges { kUtility.Initialize2DArray(m_ppaiFeatureYieldChange, "Features", "Yields"); std::string strKey("Building_FeatureYieldChanges"); Database::Results* pResults = kUtility.GetResults(strKey); if(pResults == NULL) { pResults = kUtility.PrepareResults(strKey, "select Features.ID as FeatureID, Yields.ID as YieldID, Yield from Building_FeatureYieldChanges inner join Features on Features.Type = FeatureType inner join Yields on Yields.Type = YieldType where BuildingType = ?"); } pResults->Bind(1, szBuildingType); while(pResults->Step()) { const int FeatureID = pResults->GetInt(0); const int YieldID = pResults->GetInt(1); const int yield = pResults->GetInt(2); m_ppaiFeatureYieldChange[FeatureID][YieldID] = yield; } } //SpecialistYieldChanges { kUtility.Initialize2DArray(m_ppaiSpecialistYieldChange, "Specialists", "Yields"); std::string strKey("Building_SpecialistYieldChanges"); Database::Results* pResults = kUtility.GetResults(strKey); if(pResults == NULL) { pResults = kUtility.PrepareResults(strKey, "select Specialists.ID as SpecialistID, Yields.ID as YieldID, Yield from Building_SpecialistYieldChanges inner join Specialists on Specialists.Type = SpecialistType inner join Yields on Yields.Type = YieldType where BuildingType = ?"); } pResults->Bind(1, szBuildingType); while(pResults->Step()) { const int SpecialistID = pResults->GetInt(0); const int YieldID = pResults->GetInt(1); const int yield = pResults->GetInt(2); m_ppaiSpecialistYieldChange[SpecialistID][YieldID] = yield; } } //ResourceYieldModifiers { kUtility.Initialize2DArray(m_ppaiResourceYieldModifier, "Resources", "Yields"); std::string strKey("Building_ResourceYieldModifiers"); Database::Results* pResults = kUtility.GetResults(strKey); if(pResults == NULL) { pResults = kUtility.PrepareResults(strKey, "select Resources.ID as ResourceID, Yields.ID as YieldID, Yield from Building_ResourceYieldModifiers inner join Resources on Resources.Type = ResourceType inner join Yields on Yields.Type = YieldType where BuildingType = ?"); } pResults->Bind(1, szBuildingType); while(pResults->Step()) { const int ResourceID = pResults->GetInt(0); const int YieldID = pResults->GetInt(1); const int yield = pResults->GetInt(2); m_ppaiResourceYieldModifier[ResourceID][YieldID] = yield; } } return true; } /// Class of this building int CvBuildingEntry::GetBuildingClassType() const { return m_iBuildingClassType; } const CvBuildingClassInfo& CvBuildingEntry::GetBuildingClassInfo() const { if(m_pkBuildingClassInfo == NULL) { const char* szError = "ERROR: Building does not contain valid BuildingClass type!!"; GC.LogMessage(szError); CvAssertMsg(false, szError); } #pragma warning ( push ) #pragma warning ( disable : 6011 ) // Dereferencing NULL pointer return *m_pkBuildingClassInfo; #pragma warning ( pop ) } /// Does this building require a city built on or next to a specific terrain type? int CvBuildingEntry::GetNearbyTerrainRequired() const { return m_iNearbyTerrainRequired; } /// Does this building need the absence of a terrain under the city? int CvBuildingEntry::GetProhibitedCityTerrain() const { return m_iProhibitedCityTerrain; } /// Does a Victory need to be active for this building to be buildable? int CvBuildingEntry::GetVictoryPrereq() const { return m_iVictoryPrereq; } /// Do you get this building for free if start in a later era? int CvBuildingEntry::GetFreeStartEra() const { return m_iFreeStartEra; } /// Is this building unbuildable if start in a later era? int CvBuildingEntry::GetMaxStartEra() const { return m_iMaxStartEra; } /// Tech that makes this building obsolete int CvBuildingEntry::GetObsoleteTech() const { return m_iObsoleteTech; } /// Tech that improves the yield from this building int CvBuildingEntry::GetEnhancedYieldTech() const { return m_iEnhancedYieldTech; } /// How much GPT does this Building cost? int CvBuildingEntry::GetGoldMaintenance() const { return m_iGoldMaintenance; } /// Only one Building from each Group may be constructed in a City int CvBuildingEntry::GetMutuallyExclusiveGroup() const { return m_iMutuallyExclusiveGroup; } /// Upgraded version of this building int CvBuildingEntry::GetReplacementBuildingClass() const { return m_iReplacementBuildingClass; } /// Techs required for this building int CvBuildingEntry::GetPrereqAndTech() const { return m_iPrereqAndTech; } /// What SpecialistType is allowed by this Building int CvBuildingEntry::GetSpecialistType() const { return m_iSpecialistType; } /// How many SpecialistTypes are allowed by this Building int CvBuildingEntry::GetSpecialistCount() const { return m_iSpecialistCount; } /// Extra culture from every specialist int CvBuildingEntry::GetSpecialistExtraCulture() const { return m_iSpecialistExtraCulture; } /// How many GPP does this Building provide (linked to the SpecialistType) int CvBuildingEntry::GetGreatPeopleRateChange() const { return m_iGreatPeopleRateChange; } /// Free building in each city from this building/wonder int CvBuildingEntry::GetFreeBuildingClass() const { return m_iFreeBuildingClass; } /// Free building in the city that builds this building/wonder int CvBuildingEntry::GetFreeBuildingThisCity() const { return m_iFreeBuildingThisCity; } /// Does this building give all units a promotion for free instantly? int CvBuildingEntry::GetFreePromotion() const { return m_iFreePromotion; } /// Does this building give units a promotion when trained from this city? int CvBuildingEntry::GetTrainedFreePromotion() const { return m_iTrainedFreePromotion; } /// Does this building get rid of an undesirable promotion? int CvBuildingEntry::GetFreePromotionRemoved() const { return m_iFreePromotionRemoved; } /// Shields to construct the building int CvBuildingEntry::GetProductionCost() const { return m_iProductionCost; } /// Additional cost based on the number of cities in the empire int CvBuildingEntry::GetNumCityCostMod() const { return m_iNumCityCostMod; } /// Does this Building modify any hurry costs int CvBuildingEntry::GetHurryCostModifier() const { return m_iHurryCostModifier; } /// Number of cities required to build this? int CvBuildingEntry::GetNumCitiesPrereq() const { return m_iNumCitiesPrereq; } /// Do we need a unit at a certain level to build this? int CvBuildingEntry::GetUnitLevelPrereq() const { return m_iUnitLevelPrereq; } // Culture (for policies) generated per turn int CvBuildingEntry::GetJONSCulture() const { return m_iJONSCulture; } /// Multiplier to the rate of accumulating culture for policies int CvBuildingEntry::GetCultureRateModifier() const { return m_iCultureRateModifier; } /// Multiplier to the rate of accumulating culture for policies in all Cities int CvBuildingEntry::GetGlobalCultureRateModifier() const { return m_iGlobalCultureRateModifier; } /// Change in spawn rate for great people int CvBuildingEntry::GetGreatPeopleRateModifier() const { return m_iGreatPeopleRateModifier; } /// Change global spawn rate for great people int CvBuildingEntry::GetGlobalGreatPeopleRateModifier() const { return m_iGlobalGreatPeopleRateModifier; } /// Change in spawn rate for great generals int CvBuildingEntry::GetGreatGeneralRateModifier() const { return m_iGreatGeneralRateModifier; } /// Gold received when great person expended int CvBuildingEntry::GetGreatPersonExpendGold() const { return m_iGreatPersonExpendGold; } /// Reduces cost of unit upgrades? int CvBuildingEntry::GetUnitUpgradeCostMod() const { return m_iUnitUpgradeCostMod; } /// Percentage increase in the length of Golden Ages int CvBuildingEntry::GetGoldenAgeModifier() const { return m_iGoldenAgeModifier; } /// Free experience for units built in this city int CvBuildingEntry::GetFreeExperience() const { return m_iFreeExperience; } /// Free experience for all player units int CvBuildingEntry::GetGlobalFreeExperience() const { return m_iGlobalFreeExperience; } /// Percentage of food retained after city growth int CvBuildingEntry::GetFoodKept() const { return m_iFoodKept; } /// Does this building allow airlifts? int CvBuildingEntry::GetAirlift() const { return m_iAirlift; } /// Modifier to city air defense int CvBuildingEntry::GetAirModifier() const { return m_iAirModifier; } /// Modifier to city nuke defense int CvBuildingEntry::GetNukeModifier() const { return m_iNukeModifier; } /// Will this building cause a big problem (meltdown) if the city is hit with a nuke? int CvBuildingEntry::GetNukeExplosionRand() const { return m_iNukeExplosionRand; } /// Improvement in worker speed int CvBuildingEntry::GetWorkerSpeedModifier() const { return m_iWorkerSpeedModifier; } /// Improvement in military unit production int CvBuildingEntry::GetMilitaryProductionModifier() const { return m_iMilitaryProductionModifier; } /// Improvement in space race component production int CvBuildingEntry::GetSpaceProductionModifier() const { return m_iSpaceProductionModifier; } /// Improvement in building production int CvBuildingEntry::GetBuildingProductionModifier() const { return m_iBuildingProductionModifier; } /// Improvement in wonder production int CvBuildingEntry::GetWonderProductionModifier() const { return m_iWonderProductionModifier; } /// Trade route gold modifier int CvBuildingEntry::GetTradeRouteModifier() const { return m_iTradeRouteModifier; } /// Increased plunder if city captured int CvBuildingEntry::GetCapturePlunderModifier() const { return m_iCapturePlunderModifier; } /// Change in culture cost to earn a new policy int CvBuildingEntry::GetPolicyCostModifier() const { return m_iPolicyCostModifier; } /// Change in culture cost to earn a new tile int CvBuildingEntry::GetPlotCultureCostModifier() const { return m_iPlotCultureCostModifier; } /// Change in culture cost to earn a new tile int CvBuildingEntry::GetGlobalPlotCultureCostModifier() const { return m_iGlobalPlotCultureCostModifier; } /// Change in gold cost to earn a new tile int CvBuildingEntry::GetPlotBuyCostModifier() const { return m_iPlotBuyCostModifier; } /// Change in gold cost to earn a new tile across the empire int CvBuildingEntry::GetGlobalPlotBuyCostModifier() const { return m_iGlobalPlotBuyCostModifier; } /// Required Plot count of the CvArea this City belongs to (Usually used for Water Buildings to prevent Harbors in tiny lakes and such) int CvBuildingEntry::GetMinAreaSize() const { return m_iMinAreaSize; } /// Chance of building surviving after conquest int CvBuildingEntry::GetConquestProbability() const { return m_iConquestProbability; } /// Improvement in unit heal rate from this building int CvBuildingEntry::GetHealRateChange() const { return m_iHealRateChange; } /// Happiness provided by this building int CvBuildingEntry::GetHappiness() const { return m_iHappiness; } /// UnmoddedHappiness provided by this building - NOT affected by a city's pop int CvBuildingEntry::GetUnmoddedHappiness() const { return m_iUnmoddedHappiness; } /// Get percentage modifier to overall player happiness int CvBuildingEntry::GetUnhappinessModifier() const { return m_iUnhappinessModifier; } /// HappinessPerCity provided by this building int CvBuildingEntry::GetHappinessPerCity() const { return m_iHappinessPerCity; } /// Happiness per X number of Policies provided by this building int CvBuildingEntry::GetHappinessPerXPolicies() const { return m_iHappinessPerXPolicies; } /// CityCountUnhappinessMod provided by this building int CvBuildingEntry::GetCityCountUnhappinessMod() const { return m_iCityCountUnhappinessMod; } /// NoOccupiedUnhappiness bool CvBuildingEntry::IsNoOccupiedUnhappiness() const { return m_bNoOccupiedUnhappiness; } /// Population added to every City in the player's empire int CvBuildingEntry::GetGlobalPopulationChange() const { return m_iGlobalPopulationChange; } /// If this # of players have a Tech then the owner of this Building gets that Tech as well int CvBuildingEntry::GetTechShare() const { return m_iTechShare; } /// Number of free techs granted by this building int CvBuildingEntry::GetFreeTechs() const { return m_iFreeTechs; } /// Number of free Policies granted by this building int CvBuildingEntry::GetFreePolicies() const { return m_iFreePolicies; } /// Number of free Great People granted by this building int CvBuildingEntry::GetFreeGreatPeople() const { return m_iFreeGreatPeople; } /// Boost to median tech received from research agreements int CvBuildingEntry::GetMedianTechPercentChange() const { return m_iMedianTechPercentChange; } /// Gold generated by this building int CvBuildingEntry::GetGold() const { return m_iGold; } /// Does a city need to be near a mountain to build this? bool CvBuildingEntry::IsNearbyMountainRequired() const { return m_bNearbyMountainRequired; } /// Does this Building allow us to Range Strike? bool CvBuildingEntry::IsAllowsRangeStrike() const { return m_bAllowsRangeStrike; } /// Modifier to city defense int CvBuildingEntry::GetDefenseModifier() const { return m_iDefenseModifier; } /// Modifier to every City's Building defense int CvBuildingEntry::GetGlobalDefenseModifier() const { return m_iGlobalDefenseModifier; } /// Instant Friendship mod change with City States int CvBuildingEntry::GetMinorFriendshipChange() const { return m_iMinorFriendshipChange; } /// VPs added to overall Team score int CvBuildingEntry::GetVictoryPoints() const { return m_iVictoryPoints; } /// wWhat ring the engine will try to display this building int CvBuildingEntry::GetPreferredDisplayPosition() const { return m_iPreferredDisplayPosition; } /// index of portrait in the texture sheet int CvBuildingEntry::GetPortraitIndex() const { return m_iPortraitIndex; } /// Is the presence of this building shared with team allies? bool CvBuildingEntry::IsTeamShare() const { return m_bTeamShare; } /// Must this be built in a coastal city? bool CvBuildingEntry::IsWater() const { return m_bWater; } /// Must this be built in a river city? bool CvBuildingEntry::IsRiver() const { return m_bRiver; } /// Must this be built in a city next to FreshWater? bool CvBuildingEntry::IsFreshWater() const { return m_bFreshWater; } /// Must this be built in a city next to Mountain? bool CvBuildingEntry::IsMountain() const { return m_bMountain; } /// Must this be built in a city on a hill? bool CvBuildingEntry::IsHill() const { return m_bHill; } /// Must this be built in a city on Flat ground? bool CvBuildingEntry::IsFlat() const { return m_bFlat; } /// Does this Building Found a Religion? bool CvBuildingEntry::IsFoundsReligion() const { return m_bFoundsReligion; } /// Is this a "Religous" Building? (qualifies it for Production bonuses for Policies, etc.) bool CvBuildingEntry::IsReligious() const { return m_bIsReligious; } /// Is this an obstacle at the edge of your empire (e.g. Great Wall) -- for you AND your teammates bool CvBuildingEntry::IsBorderObstacle() const { return m_bBorderObstacle; } /// Is this an obstacle at the edge of your empire (e.g. Great Wall) -- for just the owning player bool CvBuildingEntry::IsPlayerBorderObstacle() const { return m_bPlayerBorderObstacle; } /// Does this trigger drawing a wall around the city bool CvBuildingEntry::IsCityWall() const { return m_bCityWall; } /// Does this building define the capital? bool CvBuildingEntry::IsCapital() const { return m_bCapital; } /// Does this building spawn a golden age? bool CvBuildingEntry::IsGoldenAge() const { return m_bGoldenAge; } /// Is the map centered after this building is constructed? bool CvBuildingEntry::IsMapCentering() const { return m_bMapCentering; } /// Can this building never be captured? bool CvBuildingEntry::IsNeverCapture() const { return m_bNeverCapture; } /// Is the building immune to nukes? bool CvBuildingEntry::IsNukeImmune() const { return m_bNukeImmune; } /// Does the building add an additional of each luxury in city radius bool CvBuildingEntry::IsExtraLuxuries() const { return m_bExtraLuxuries; } /// Begins voting for the diplo victory? bool CvBuildingEntry::IsDiplomaticVoting() const { return m_bDiplomaticVoting; } /// Does the building allow routes over the water bool CvBuildingEntry::AllowsWaterRoutes() const { return m_bAllowsWaterRoutes; } /// Derive property: is this considered a science building? bool CvBuildingEntry::IsScienceBuilding() const { bool bRtnValue = false; if (IsCapital()) { bRtnValue = false; } else if (GetYieldChange(YIELD_SCIENCE) > 0) { bRtnValue = true; } else if (GetYieldChangePerPop(YIELD_SCIENCE) > 0) { bRtnValue = true; } else if (GetTechEnhancedYieldChange(YIELD_SCIENCE) > 0) { bRtnValue = true; } else if (GetYieldModifier(YIELD_SCIENCE) > 0) { bRtnValue = true; } return bRtnValue; } /// Retrieve art tag const char* CvBuildingEntry::GetArtDefineTag() const { return m_strArtDefineTag.c_str(); } /// Set art tag void CvBuildingEntry::SetArtDefineTag(const char* szVal) { m_strArtDefineTag = szVal; } /// Return whether we should try to find a culture specific variant art tag const bool CvBuildingEntry::GetArtInfoCulturalVariation() const { return m_bArtInfoCulturalVariation; } /// Return whether we should try to find an era specific variant art tag const bool CvBuildingEntry::GetArtInfoEraVariation() const { return m_bArtInfoEraVariation; } /// Return whether we should try to find an era specific variant art tag const bool CvBuildingEntry::GetArtInfoRandomVariation() const { return m_bArtInfoRandomVariation; } const char* CvBuildingEntry::GetWonderSplashAudio () const { return m_strWonderSplashAudio.c_str(); } // ARRAYS /// Change to yield by type int CvBuildingEntry::GetYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piYieldChange ? m_piYieldChange[i] : -1; } /// Array of yield changes int* CvBuildingEntry::GetYieldChangeArray() const { return m_piYieldChange; } /// Change to yield by type int CvBuildingEntry::GetYieldChangePerPop(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piYieldChangePerPop ? m_piYieldChangePerPop[i] : -1; } /// Array of yield changes int* CvBuildingEntry::GetYieldChangePerPopArray() const { return m_piYieldChangePerPop; } /// Modifier to yield by type int CvBuildingEntry::GetYieldModifier(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piYieldModifier ? m_piYieldModifier[i] : -1; } /// Array of yield modifiers int* CvBuildingEntry::GetYieldModifierArray() const { return m_piYieldModifier; } /// Modifier to yield by type in area int CvBuildingEntry::GetAreaYieldModifier(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piAreaYieldModifier ? m_piAreaYieldModifier[i] : -1; } /// Array of yield modifiers in area int* CvBuildingEntry::GetAreaYieldModifierArray() const { return m_piAreaYieldModifier; } /// Global modifier to yield by type int CvBuildingEntry::GetGlobalYieldModifier(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piGlobalYieldModifier ? m_piGlobalYieldModifier[i] : -1; } /// Array of global yield modifiers int* CvBuildingEntry::GetGlobalYieldModifierArray() const { return m_piGlobalYieldModifier; } /// Change to yield based on earning a tech int CvBuildingEntry::GetTechEnhancedYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piTechEnhancedYieldChange ? m_piTechEnhancedYieldChange[i] : -1; } /// Array of yield changes based on earning a tech int* CvBuildingEntry::GetTechEnhancedYieldChangeArray() const { return m_piTechEnhancedYieldChange; } /// Sea plot yield changes by type int CvBuildingEntry::GetSeaPlotYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piSeaPlotYieldChange ? m_piSeaPlotYieldChange[i] : -1; } /// Array of sea plot yield changes int* CvBuildingEntry::GetSeaPlotYieldChangeArray() const { return m_piSeaPlotYieldChange; } /// River plot yield changes by type int CvBuildingEntry::GetRiverPlotYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piRiverPlotYieldChange ? m_piRiverPlotYieldChange[i] : -1; } /// Array of river plot yield changes int* CvBuildingEntry::GetRiverPlotYieldChangeArray() const { return m_piRiverPlotYieldChange; } /// Lake plot yield changes by type int CvBuildingEntry::GetLakePlotYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piLakePlotYieldChange ? m_piLakePlotYieldChange[i] : -1; } /// Array of lake plot yield changes int* CvBuildingEntry::GetLakePlotYieldChangeArray() const { return m_piLakePlotYieldChange; } /// Sea resource yield changes by type int CvBuildingEntry::GetSeaResourceYieldChange(int i) const { CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piSeaResourceYieldChange ? m_piSeaResourceYieldChange[i] : -1; } /// Array of sea resource yield changes int* CvBuildingEntry::GetSeaResourceYieldChangeArray() const { return m_piSeaResourceYieldChange; } /// Free combat experience by unit combat type int CvBuildingEntry::GetUnitCombatFreeExperience(int i) const { CvAssertMsg(i < GC.getNumUnitCombatClassInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piUnitCombatFreeExperience ? m_piUnitCombatFreeExperience[i] : -1; } /// Free combat experience by unit combat type int CvBuildingEntry::GetUnitCombatProductionModifier(int i) const { CvAssertMsg(i < GC.getNumUnitCombatClassInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piUnitCombatProductionModifiers ? m_piUnitCombatProductionModifiers[i] : -1; } /// Free experience gained for units in this domain int CvBuildingEntry::GetDomainFreeExperience(int i) const { CvAssertMsg(i < NUM_DOMAIN_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piDomainFreeExperience ? m_piDomainFreeExperience[i] : -1; } /// Production modifier in this domain int CvBuildingEntry::GetDomainProductionModifier(int i) const { CvAssertMsg(i < NUM_DOMAIN_TYPES, "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piDomainProductionModifier ? m_piDomainProductionModifier[i] : -1; } /// BuildingClasses that may no longer be constructed after this Building is built in a City int CvBuildingEntry::GetLockedBuildingClasses(int i) const { CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piLockedBuildingClasses ? m_piLockedBuildingClasses[i] : -1; } /// Prerequisite techs with AND int CvBuildingEntry::GetPrereqAndTechs(int i) const { CvAssertMsg(i < GC.getNUM_BUILDING_AND_TECH_PREREQS(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piPrereqAndTechs ? m_piPrereqAndTechs[i] : -1; } /// Resources consumed to construct int CvBuildingEntry::GetResourceQuantityRequirement(int i) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piResourceQuantityRequirements ? m_piResourceQuantityRequirements[i] : -1; } /// Boost in Culture for each of these Resources int CvBuildingEntry::GetResourceCultureChange(int i) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piResourceCultureChanges ? m_piResourceCultureChanges[i] : -1; } /// Boost in production for leader with this trait int CvBuildingEntry::GetProductionTraits(int i) const { CvAssertMsg(i < GC.getNumTraitInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piProductionTraits ? m_piProductionTraits[i] : 0; } /// Number of prerequisite buildings of a particular class int CvBuildingEntry::GetPrereqNumOfBuildingClass(int i) const { CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piPrereqNumOfBuildingClass ? m_piPrereqNumOfBuildingClass[i] : -1; } /// Find value of flavors associated with this building int CvBuildingEntry::GetFlavorValue(int i) const { CvAssertMsg(i < GC.getNumFlavorTypes(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piFlavorValue ? m_piFlavorValue[i] : 0; } /// Prerequisite resources with AND int CvBuildingEntry::GetLocalResourceAnd(int i) const { CvAssertMsg(i < GC.getNUM_BUILDING_RESOURCE_PREREQS(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piLocalResourceAnds ? m_piLocalResourceAnds[i] : -1; } /// Prerequisite resources with OR int CvBuildingEntry::GetLocalResourceOr(int i) const { CvAssertMsg(i < GC.getNUM_BUILDING_RESOURCE_PREREQS(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piLocalResourceOrs ? m_piLocalResourceOrs[i] : -1; } /// Modifier to Hurry cost int CvBuildingEntry::GetHurryModifier(int i) const { CvAssertMsg(i < GC.getNumHurryInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_paiHurryModifier ? m_paiHurryModifier[i] : -1; } /// Can it only built if there is a building of this class in the city? bool CvBuildingEntry::IsBuildingClassNeededInCity(int i) const { CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_pbBuildingClassNeededInCity ? m_pbBuildingClassNeededInCity[i] : false; } /// Free units which appear near the capital int CvBuildingEntry::GetNumFreeUnits(int i) const { CvAssertMsg(i < GC.getNumUnitInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_piNumFreeUnits ? m_piNumFreeUnits[i] : -1; } /// Change to Resource yield by type int CvBuildingEntry::GetResourceYieldChange(int i, int j) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(j > -1, "Index out of bounds"); return m_ppaiResourceYieldChange ? m_ppaiResourceYieldChange[i][j] : -1; } /// Array of changes to Resource yield int* CvBuildingEntry::GetResourceYieldChangeArray(int i) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_ppaiResourceYieldChange[i]; } /// Change to Feature yield by type int CvBuildingEntry::GetFeatureYieldChange(int i, int j) const { CvAssertMsg(i < GC.getNumFeatureInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(j > -1, "Index out of bounds"); return m_ppaiFeatureYieldChange ? m_ppaiFeatureYieldChange[i][j] : -1; } /// Array of changes to Feature yield int* CvBuildingEntry::GetFeatureYieldChangeArray(int i) const { CvAssertMsg(i < GC.getNumFeatureInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_ppaiFeatureYieldChange[i]; } /// Change to specialist yield by type int CvBuildingEntry::GetSpecialistYieldChange(int i, int j) const { CvAssertMsg(i < GC.getNumSpecialistInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(j > -1, "Index out of bounds"); return m_ppaiSpecialistYieldChange ? m_ppaiSpecialistYieldChange[i][j] : -1; } /// Array of changes to specialist yield int* CvBuildingEntry::GetSpecialistYieldChangeArray(int i) const { CvAssertMsg(i < GC.getNumSpecialistInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_ppaiSpecialistYieldChange[i]; } /// Modifier to resource yield int CvBuildingEntry::GetResourceYieldModifier(int i, int j) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds"); CvAssertMsg(j > -1, "Index out of bounds"); return m_ppaiResourceYieldModifier ? m_ppaiResourceYieldModifier[i][j] : -1; } /// Array of modifiers to resource yield int* CvBuildingEntry::GetResourceYieldModifierArray(int i) const { CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds"); CvAssertMsg(i > -1, "Index out of bounds"); return m_ppaiResourceYieldModifier[i]; } //===================================== // CvBuildingXMLEntries //===================================== /// Constructor CvBuildingXMLEntries::CvBuildingXMLEntries(void) { } /// Destructor CvBuildingXMLEntries::~CvBuildingXMLEntries(void) { DeleteArray(); } /// Returns vector of policy entries std::vector<CvBuildingEntry*>& CvBuildingXMLEntries::GetBuildingEntries() { return m_paBuildingEntries; } /// Number of defined policies int CvBuildingXMLEntries::GetNumBuildings() { return m_paBuildingEntries.size(); } /// Clear policy entries void CvBuildingXMLEntries::DeleteArray() { for (std::vector<CvBuildingEntry*>::iterator it = m_paBuildingEntries.begin(); it != m_paBuildingEntries.end(); ++it) { SAFE_DELETE(*it); } m_paBuildingEntries.clear(); } /// Get a specific entry CvBuildingEntry *CvBuildingXMLEntries::GetEntry(int index) { return m_paBuildingEntries[index]; } //===================================== // CvCityBuildings //===================================== /// Constructor CvCityBuildings::CvCityBuildings (): m_paiBuildingProduction (NULL), m_paiBuildingProductionTime (NULL), m_paiBuildingOriginalOwner (NULL), m_paiBuildingOriginalTime (NULL), m_paiNumRealBuilding (NULL), m_paiNumFreeBuilding (NULL), m_iNumBuildings (0), m_iBuildingProductionModifier (0), m_iBuildingDefense (0), m_iBuildingDefenseMod (0), m_bSoldBuildingThisTurn (false), m_pBuildings (NULL), m_pCity (NULL) { } /// Destructor CvCityBuildings::~CvCityBuildings (void) { } /// Initialize void CvCityBuildings::Init(CvBuildingXMLEntries *pBuildings, CvCity *pCity) { // Store off the pointers to objects we'll need later m_pBuildings = pBuildings; m_pCity = pCity; // Initialize status arrays int iNumBuildings = m_pBuildings->GetNumBuildings(); CvAssertMsg((0 < iNumBuildings), "m_pBuildings->GetNumBuildings() is not greater than zero but an array is being allocated in CvCityBuildings::Init"); CvAssertMsg(m_paiBuildingProduction==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingProduction"); m_paiBuildingProduction = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); CvAssertMsg(m_paiBuildingProductionTime==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingProductionTime"); m_paiBuildingProductionTime = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); CvAssertMsg(m_paiBuildingOriginalOwner==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingOriginalOwner"); m_paiBuildingOriginalOwner = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); CvAssertMsg(m_paiBuildingOriginalTime==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingOriginalTime"); m_paiBuildingOriginalTime = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); CvAssertMsg(m_paiNumRealBuilding==NULL, "about to leak memory, CvCityBuildings::m_paiNumRealBuilding"); m_paiNumRealBuilding = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); CvAssertMsg(m_paiNumFreeBuilding==NULL, "about to leak memory, CvCityBuildings::m_paiNumFreeBuilding"); m_paiNumFreeBuilding = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0); m_aBuildingYieldChange.clear(); Reset(); } /// Deallocate memory created in initialize void CvCityBuildings::Uninit() { SAFE_DELETE_ARRAY (m_paiBuildingProduction); SAFE_DELETE_ARRAY (m_paiBuildingProductionTime); SAFE_DELETE_ARRAY (m_paiBuildingOriginalOwner); SAFE_DELETE_ARRAY (m_paiBuildingOriginalTime); SAFE_DELETE_ARRAY (m_paiNumRealBuilding); SAFE_DELETE_ARRAY (m_paiNumFreeBuilding); } /// Reset status arrays to all false void CvCityBuildings::Reset() { int iI; // Initialize non-arrays m_iNumBuildings = 0; m_iBuildingProductionModifier = 0; m_iBuildingDefense = 0; m_iBuildingDefenseMod = 0; m_bSoldBuildingThisTurn = false; for (iI = 0; iI < m_pBuildings->GetNumBuildings(); iI++) { m_paiBuildingProduction[iI] = 0; m_paiBuildingProductionTime[iI] = 0; m_paiBuildingOriginalOwner[iI] = NO_PLAYER; m_paiBuildingOriginalTime[iI] = MIN_INT; m_paiNumRealBuilding[iI] = 0; m_paiNumFreeBuilding[iI] = 0; } } /// Serialization read void CvCityBuildings::Read(FDataStream& kStream) { CvAssertMsg(m_pBuildings != NULL && m_pBuildings->GetNumBuildings() > 0, "Number of buildings to serialize is expected to greater than 0"); // Version number to maintain backwards compatibility uint uiVersion; kStream >> uiVersion; kStream >> m_iNumBuildings; kStream >> m_iBuildingProductionModifier; kStream >> m_iBuildingDefense; kStream >> m_iBuildingDefenseMod; if (uiVersion >= 3) kStream >> m_bSoldBuildingThisTurn; else m_bSoldBuildingThisTurn = false; if (uiVersion >= 2) { BuildingArrayHelpers::Read(kStream, m_paiBuildingProduction); BuildingArrayHelpers::Read(kStream, m_paiBuildingProductionTime); BuildingArrayHelpers::Read(kStream, m_paiBuildingOriginalOwner); BuildingArrayHelpers::Read(kStream, m_paiBuildingOriginalTime); BuildingArrayHelpers::Read(kStream, m_paiNumRealBuilding); BuildingArrayHelpers::Read(kStream, m_paiNumFreeBuilding); } else { ArrayWrapper<int>wrapm_paiBuildingProduction(89, m_paiBuildingProduction); kStream >> wrapm_paiBuildingProduction; ArrayWrapper<int>wrapm_paiBuildingProductionTime(89, m_paiBuildingProductionTime); kStream >> wrapm_paiBuildingProductionTime; ArrayWrapper<int>wrapm_paiBuildingOriginalOwner(89, m_paiBuildingOriginalOwner); kStream >> wrapm_paiBuildingOriginalOwner; ArrayWrapper<int>wrapm_paiBuildingOriginalTime(89, m_paiBuildingOriginalTime); kStream >> wrapm_paiBuildingOriginalTime; ArrayWrapper<int>wrapm_paiNumRealBuilding(89, m_paiNumRealBuilding); kStream >> wrapm_paiNumRealBuilding; ArrayWrapper<int>wrapm_paiNumFreeBuilding(89, m_paiNumFreeBuilding); kStream >> wrapm_paiNumFreeBuilding; } kStream >> m_aBuildingYieldChange; } /// Serialization write void CvCityBuildings::Write(FDataStream& kStream) { CvAssertMsg(m_pBuildings != NULL && m_pBuildings->GetNumBuildings() > 0, "Number of buildings to serialize is expected to greater than 0"); // Current version number uint uiVersion = 3; kStream << uiVersion; kStream << m_iNumBuildings; kStream << m_iBuildingProductionModifier; kStream << m_iBuildingDefense; kStream << m_iBuildingDefenseMod; if (uiVersion >= 3) kStream << m_bSoldBuildingThisTurn; #ifdef _MSC_VER #pragma warning ( push ) #pragma warning ( disable : 6011 ) // if m_pBuildings is NULL during load, we're screwed. Redesign the class or the loader code. #endif//_MSC_VER int iNumBuildings = m_pBuildings->GetNumBuildings(); #ifdef _MSC_VER #pragma warning ( pop ) #endif//_MSC_VER BuildingArrayHelpers::Write(kStream, m_paiBuildingProduction, iNumBuildings); BuildingArrayHelpers::Write(kStream, m_paiBuildingProductionTime, iNumBuildings); BuildingArrayHelpers::Write(kStream, m_paiBuildingOriginalOwner, iNumBuildings); BuildingArrayHelpers::Write(kStream, m_paiBuildingOriginalTime, iNumBuildings); BuildingArrayHelpers::Write(kStream, m_paiNumRealBuilding, iNumBuildings); BuildingArrayHelpers::Write(kStream, m_paiNumFreeBuilding, iNumBuildings); kStream << m_aBuildingYieldChange; } /// Accessor: Get full array of all building XML data CvBuildingXMLEntries *CvCityBuildings::GetBuildings() const { return m_pBuildings; } /// Accessor: Total number of buildings in the city int CvCityBuildings::GetNumBuildings() const { return m_iNumBuildings; } /// Accessor: Update total number of buildings in the city void CvCityBuildings::ChangeNumBuildings(int iChange) { m_iNumBuildings = (m_iNumBuildings + iChange); CvAssert(GetNumBuildings() >= 0); // GET_PLAYER(m_pCity->getOwner()).updateNumResourceUsed(); } /// Accessor: How many of these buildings in the city? int CvCityBuildings::GetNumBuilding(BuildingTypes eIndex) const { CvAssertMsg(eIndex != NO_BUILDING, "BuildingType eIndex is expected to not be NO_BUILDING"); if (GC.getCITY_MAX_NUM_BUILDINGS() <= 1) { return std::max(GetNumRealBuilding(eIndex), GetNumFreeBuilding(eIndex)); } else { return (GetNumRealBuilding(eIndex) + GetNumFreeBuilding(eIndex)); } } /// Accessor: How many of these buildings are not obsolete? int CvCityBuildings::GetNumActiveBuilding(BuildingTypes eIndex) const { CvAssertMsg(eIndex != NO_BUILDING, "BuildingType eIndex is expected to not be NO_BUILDING"); if (GET_TEAM(m_pCity->getTeam()).isObsoleteBuilding(eIndex)) { return 0; } return (GetNumBuilding(eIndex)); } /// Is the player allowed to sell building eIndex in this city? bool CvCityBuildings::IsBuildingSellable(const CvBuildingEntry& kBuilding) const { // Can't sell more than one building per turn if (IsSoldBuildingThisTurn()) return false; // Can't sell a building if it doesn't cost us anything (no exploits) if (kBuilding.GetGoldMaintenance() <= 0) return false; // Is this a free building? if (GetNumFreeBuilding((BuildingTypes)kBuilding.GetID()) > 0) return false; // Science building in capital that has given us a tech boost? if (m_pCity->isCapital() && kBuilding.IsScienceBuilding()) { return !(GET_PLAYER(m_pCity->getOwner()).GetPlayerTraits()->IsTechBoostFromCapitalScienceBuildings()); } return true; } /// Sell eIndex~! void CvCityBuildings::DoSellBuilding(BuildingTypes eIndex) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); CvBuildingEntry* pkBuildingEntry = GC.getBuildingInfo(eIndex); if(!pkBuildingEntry) return; // Can we actually do this? if (!IsBuildingSellable(*pkBuildingEntry)) return; // Gold refund int iRefund = GetSellBuildingRefund(eIndex); GET_PLAYER(m_pCity->getOwner()).GetTreasury()->ChangeGold(iRefund); // Kick everyone out m_pCity->GetCityCitizens()->DoRemoveAllSpecialistsFromBuilding(eIndex); SetNumRealBuilding(eIndex, 0); SetSoldBuildingThisTurn(true); } /// How much of a refund will the player get from selling eIndex? int CvCityBuildings::GetSellBuildingRefund(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); int iRefund = GET_PLAYER(m_pCity->getOwner()).getProductionNeeded(eIndex); iRefund /= /*10*/ GC.getBUILDING_SALE_DIVISOR(); return iRefund; } /// Has a building already been sold this turn? bool CvCityBuildings::IsSoldBuildingThisTurn() const { return m_bSoldBuildingThisTurn; } /// Has a building already been sold this turn? void CvCityBuildings::SetSoldBuildingThisTurn(bool bValue) { if (IsSoldBuildingThisTurn() != bValue) m_bSoldBuildingThisTurn = bValue; } /// What is the total maintenance? (no modifiers) int CvCityBuildings::GetTotalBaseBuildingMaintenance() const { int iTotalCost = 0; for (int iBuildingLoop = 0; iBuildingLoop < GC.getNumBuildingInfos(); iBuildingLoop++) { const BuildingTypes eBuilding = static_cast<BuildingTypes>(iBuildingLoop); CvBuildingEntry* pkBuildingInfo = GC.getBuildingInfo(eBuilding); if(pkBuildingInfo) { if (GetNumBuilding(eBuilding)) iTotalCost += (pkBuildingInfo->GetGoldMaintenance() * GetNumBuilding(eBuilding)); } } return iTotalCost; } /// Accessor: How far is construction of this building? int CvCityBuildings::GetBuildingProduction(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiBuildingProduction[eIndex] / 100; } /// Accessor: How far is construction of this building? (in hundredths) int CvCityBuildings::GetBuildingProductionTimes100(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiBuildingProduction[eIndex]; } /// Accessor: Set how much construction is complete for this building void CvCityBuildings::SetBuildingProduction(BuildingTypes eIndex, int iNewValue) { SetBuildingProductionTimes100(eIndex, iNewValue*100); } /// Accessor: Set how much construction is complete for this building (in hundredths) void CvCityBuildings::SetBuildingProductionTimes100(BuildingTypes eIndex, int iNewValue) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings())"); if (GetBuildingProductionTimes100(eIndex) != iNewValue) { if (GetBuildingProductionTimes100(eIndex) == 0) { NotifyNewBuildingStarted(eIndex); } m_paiBuildingProduction[eIndex] = iNewValue; CvAssert(GetBuildingProductionTimes100(eIndex) >= 0); if ((m_pCity->getOwner() == GC.getGame().getActivePlayer()) && m_pCity->isCitySelected()) { GC.GetEngineUserInterface()->setDirty(CityScreen_DIRTY_BIT, true); } auto_ptr<ICvCity1> pCity = GC.WrapCityPointer(m_pCity); GC.GetEngineUserInterface()->SetSpecificCityInfoDirty(pCity.get(), CITY_UPDATE_TYPE_BANNER); } } /// Accessor: Update construction progress for this building void CvCityBuildings::ChangeBuildingProduction(BuildingTypes eIndex, int iChange) { ChangeBuildingProductionTimes100(eIndex, iChange*100); } /// Accessor: Update construction progress for this building (in hundredths) void CvCityBuildings::ChangeBuildingProductionTimes100(BuildingTypes eIndex, int iChange) { SetBuildingProductionTimes100(eIndex, (GetBuildingProductionTimes100(eIndex) + iChange)); } /// Accessor: How many turns has this building been under production? int CvCityBuildings::GetBuildingProductionTime(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiBuildingProductionTime[eIndex]; } /// Accessor: Set number of turns this building been under production void CvCityBuildings::SetBuildingProductionTime(BuildingTypes eIndex, int iNewValue) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); m_paiBuildingProductionTime[eIndex] = iNewValue; CvAssert(GetBuildingProductionTime(eIndex) >= 0); } /// Accessor: Change number of turns this building been under production void CvCityBuildings::ChangeBuildingProductionTime(BuildingTypes eIndex, int iChange) { SetBuildingProductionTime(eIndex, (GetBuildingProductionTime(eIndex) + iChange)); } /// Accessor: Who owned the city when this building was built? int CvCityBuildings::GetBuildingOriginalOwner(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiBuildingOriginalOwner[eIndex]; } /// Accessor: Set who owned the city when this building was built void CvCityBuildings::SetBuildingOriginalOwner(BuildingTypes eIndex, int iNewValue) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); m_paiBuildingOriginalOwner[eIndex] = iNewValue; } /// Accessor: What year was this building built? int CvCityBuildings::GetBuildingOriginalTime(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiBuildingOriginalTime[eIndex]; } /// Accessor: Set year building was built void CvCityBuildings::SetBuildingOriginalTime(BuildingTypes eIndex, int iNewValue) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); m_paiBuildingOriginalTime[eIndex] = iNewValue; } /// Accessor: How many of these buildings have been constructed in the city? int CvCityBuildings::GetNumRealBuilding(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiNumRealBuilding[eIndex]; } /// Accessor: Set number of these buildings that have been constructed in the city void CvCityBuildings::SetNumRealBuilding(BuildingTypes eIndex, int iNewValue) { SetNumRealBuildingTimed(eIndex, iNewValue, true, m_pCity->getOwner(), GC.getGame().getGameTurnYear()); } /// Accessor: Set number of these buildings that have been constructed in the city (with date) void CvCityBuildings::SetNumRealBuildingTimed(BuildingTypes eIndex, int iNewValue, bool bFirst, PlayerTypes eOriginalOwner, int iOriginalTime) { CvPlayer* pPlayer = &GET_PLAYER(m_pCity->getOwner()); CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); int iChangeNumRealBuilding = iNewValue - GetNumRealBuilding(eIndex); CvBuildingEntry* buildingEntry = GC.getBuildingInfo(eIndex); const BuildingClassTypes buildingClassType = (BuildingClassTypes) buildingEntry->GetBuildingClassType(); const CvBuildingClassInfo& kBuildingClassInfo = buildingEntry->GetBuildingClassInfo(); if (iChangeNumRealBuilding != 0) { int iOldNumBuilding = GetNumBuilding(eIndex); m_paiNumRealBuilding[eIndex] = iNewValue; if (GetNumRealBuilding(eIndex) > 0) { SetBuildingOriginalOwner(eIndex, eOriginalOwner); SetBuildingOriginalTime(eIndex, iOriginalTime); } else { SetBuildingOriginalOwner(eIndex, NO_PLAYER); SetBuildingOriginalTime(eIndex, MIN_INT); } // Process building effects if (iOldNumBuilding != GetNumBuilding(eIndex)) { m_pCity->processBuilding(eIndex, iChangeNumRealBuilding, bFirst); } // Maintenance cost if (buildingEntry->GetGoldMaintenance() != 0) { pPlayer->GetTreasury()->ChangeBaseBuildingGoldMaintenance(buildingEntry->GetGoldMaintenance() * iChangeNumRealBuilding); } //Achievement for Temples const char* szBuildingTypeC = buildingEntry->GetType(); CvString szBuildingType = szBuildingTypeC; if(szBuildingType == "BUILDING_TEMPLE") { if(m_pCity->getOwner() == GC.getGame().getActivePlayer()) { gDLL->IncrementSteamStatAndUnlock( ESTEAMSTAT_TEMPLES, 1000, ACHIEVEMENT_1000TEMPLES ); } } if (buildingEntry->GetPreferredDisplayPosition() > 0) { auto_ptr<ICvCity1> pDllCity(new CvDllCity(m_pCity)); if (iNewValue > 0) { // if this is a WW that (likely has a half-built state) if (isWorldWonderClass(kBuildingClassInfo)) { if (GetBuildingProduction(eIndex)) { GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_EDITED, pDllCity.get(), eIndex, 1); } else { GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_CREATED, pDllCity.get(), eIndex, 1); } } else { GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_CREATED, pDllCity.get(), eIndex, 1); } } else { GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_REMOVED, pDllCity.get(), eIndex, 0); } } if (!(kBuildingClassInfo.isNoLimit())) { if (isWorldWonderClass(kBuildingClassInfo)) { m_pCity->changeNumWorldWonders(iChangeNumRealBuilding); pPlayer->ChangeNumWonders(iChangeNumRealBuilding); } else if (isTeamWonderClass(kBuildingClassInfo)) { m_pCity->changeNumTeamWonders(iChangeNumRealBuilding); } else if (isNationalWonderClass(kBuildingClassInfo)) { m_pCity->changeNumNationalWonders(iChangeNumRealBuilding); if(m_pCity->isHuman() && !GC.getGame().isGameMultiPlayer()) { IncrementWonderStats(buildingClassType); } } else { ChangeNumBuildings(iChangeNumRealBuilding); } } if (buildingEntry->IsCityWall()) { auto_ptr<ICvPlot1> pDllPlot(new CvDllPlot(m_pCity->plot())); gDLL->GameplayWallCreated(pDllPlot.get()); } // Update the amount of a Resource used up by this Building int iNumResources = GC.getNumResourceInfos(); for (int iResourceLoop = 0; iResourceLoop < iNumResources; iResourceLoop++) { if (buildingEntry->GetResourceQuantityRequirement(iResourceLoop) > 0) { pPlayer->changeNumResourceUsed((ResourceTypes) iResourceLoop, iChangeNumRealBuilding * buildingEntry->GetResourceQuantityRequirement(iResourceLoop)); } } if (iChangeNumRealBuilding > 0) { if (bFirst) { if (GC.getGame().isFinalInitialized()/* && !(gDLL->GetWorldBuilderMode() )*/) { // World Wonder Notification if (isWorldWonderClass(kBuildingClassInfo)) { Localization::String localizedText = Localization::Lookup("TXT_KEY_MISC_COMPLETES_WONDER"); localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey(); GC.getGame().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, m_pCity->getOwner(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY()); bool bDontShowRewardPopup = GC.GetEngineUserInterface()->IsOptionNoRewardPopups(); // Notification in MP games if(bDontShowRewardPopup || GC.getGame().isNetworkMultiPlayer()) // KWG: Candidate for !GC.getGame().IsOption(GAMEOPTION_SIMULTANEOUS_TURNS) { CvNotifications* pNotifications = GET_PLAYER(m_pCity->getOwner()).GetNotifications(); if (pNotifications) { localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED"); localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey(); pNotifications->Add(NOTIFICATION_WONDER_COMPLETED_ACTIVE_PLAYER, localizedText.toUTF8(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY(), eIndex, pPlayer->GetID()); } } // Popup in SP games else { if (m_pCity->getOwner() == GC.getGame().getActivePlayer()) { CvPopupInfo kPopup(BUTTONPOPUP_WONDER_COMPLETED_ACTIVE_PLAYER, eIndex); GC.GetEngineUserInterface()->AddPopup(kPopup); if(GET_PLAYER(GC.getGame().getActivePlayer()).isHuman()) { gDLL->UnlockAchievement( ACHIEVEMENT_BUILD_WONDER ); //look to see if all wonders have been built to unlock the other one IncrementWonderStats(buildingClassType); } } } // Wonder notification for all other players for (int iI = 0; iI < MAX_MAJOR_CIVS; iI++) { CvPlayerAI& thisPlayer = GET_PLAYER((PlayerTypes)iI); if (thisPlayer.isAlive()) { // Owner already got his messaging if (iI != m_pCity->getOwner()) { // If the builder is met, and the city is revealed // Special case for DLC_06 Scenario: Always show the more informative notification if ((m_pCity->isRevealed(thisPlayer.getTeam(), false) && GET_TEAM(thisPlayer.getTeam()).isHasMet(m_pCity->getTeam())) || gDLL->IsModActivated(CIV5_DLC_06_SCENARIO_MODID)) { CvNotifications* pNotifications = thisPlayer.GetNotifications(); if (pNotifications) { localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED"); localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey(); pNotifications->Add(NOTIFICATION_WONDER_COMPLETED, localizedText.toUTF8(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY(), eIndex, pPlayer->GetID()); } } else { CvNotifications* pNotifications = thisPlayer.GetNotifications(); if (pNotifications) { localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED_UNKNOWN"); localizedText << buildingEntry->GetTextKey(); pNotifications->Add(NOTIFICATION_WONDER_COMPLETED, localizedText.toUTF8(), localizedText.toUTF8(), -1, -1, eIndex, -1); } } } } } } } GC.getGame().incrementBuildingClassCreatedCount(buildingClassType); } } m_pCity->updateStrengthValue(); // Building might affect City Banner stats auto_ptr<ICvCity1> pCity = GC.WrapCityPointer(m_pCity); GC.GetEngineUserInterface()->SetSpecificCityInfoDirty(pCity.get(), CITY_UPDATE_TYPE_BANNER); } } /// Accessor: Get number of free buildings of this type in city int CvCityBuildings::GetNumFreeBuilding(BuildingTypes eIndex) const { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); return m_paiNumFreeBuilding[eIndex]; } /// Accessor: Set number of free buildings of this type in city void CvCityBuildings::SetNumFreeBuilding(BuildingTypes eIndex, int iNewValue) { CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0"); CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()"); if (GetNumFreeBuilding(eIndex) != iNewValue) { int iOldNumBuilding = GetNumBuilding(eIndex); m_paiNumFreeBuilding[eIndex] = iNewValue; if (iOldNumBuilding != GetNumBuilding(eIndex)) { m_pCity->processBuilding(eIndex, iNewValue - iOldNumBuilding, true); } } } /// Accessor: Get yield boost for a specific building by yield type int CvCityBuildings::GetBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield) const { for (std::vector<BuildingYieldChange>::const_iterator it = m_aBuildingYieldChange.begin(); it != m_aBuildingYieldChange.end(); ++it) { if ((*it).eBuildingClass == eBuildingClass && (*it).eYield == eYield) { return (*it).iChange; } } return 0; } /// Accessor: Set yield boost for a specific building by yield type void CvCityBuildings::SetBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield, int iChange) { for (std::vector<BuildingYieldChange>::iterator it = m_aBuildingYieldChange.begin(); it != m_aBuildingYieldChange.end(); ++it) { if ((*it).eBuildingClass == eBuildingClass && (*it).eYield == eYield) { int iOldChange = (*it).iChange; if (iOldChange != iChange) { if (iChange == 0) { m_aBuildingYieldChange.erase(it); } else { (*it).iChange = iChange; } BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(m_pCity->getCivilizationType())->getCivilizationBuildings(eBuildingClass); if (NO_BUILDING != eBuilding) { if (GetNumActiveBuilding(eBuilding) > 0) { m_pCity->ChangeBaseYieldRateFromBuildings(eYield, (iChange - iOldChange) * GetNumActiveBuilding(eBuilding)); } } } return; } } if (0 != iChange) { BuildingYieldChange kChange; kChange.eBuildingClass = eBuildingClass; kChange.eYield = eYield; kChange.iChange = iChange; m_aBuildingYieldChange.push_back(kChange); BuildingTypes eBuilding = (BuildingTypes)m_pCity->getCivilizationInfo().getCivilizationBuildings(eBuildingClass); if (NO_BUILDING != eBuilding) { if (GetNumActiveBuilding(eBuilding) > 0) { m_pCity->ChangeBaseYieldRateFromBuildings(eYield, iChange * GetNumActiveBuilding(eBuilding)); } } } } /// Accessor: Change yield boost for a specific building by yield type void CvCityBuildings::ChangeBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield, int iChange) { SetBuildingYieldChange(eBuildingClass, eYield, GetBuildingYieldChange(eBuildingClass, eYield) + iChange); } /// Accessor: Get current production modifier from buildings int CvCityBuildings::GetBuildingProductionModifier() const { return m_iBuildingProductionModifier; } /// Accessor: Change current production modifier from buildings void CvCityBuildings::ChangeBuildingProductionModifier(int iChange) { m_iBuildingProductionModifier = (m_iBuildingProductionModifier + iChange); CvAssert(GetBuildingProductionModifier() >= 0); } /// Accessor: Get current defense boost from buildings int CvCityBuildings::GetBuildingDefense() const { return m_iBuildingDefense; } /// Accessor: Change current defense boost from buildings void CvCityBuildings::ChangeBuildingDefense(int iChange) { if (iChange != 0) { m_iBuildingDefense = (m_iBuildingDefense + iChange); CvAssert(GetBuildingDefense() >= 0); m_pCity->plot()->plotAction(PUF_makeInfoBarDirty); } } /// Accessor: Get current defense boost Mod from buildings int CvCityBuildings::GetBuildingDefenseMod() const { return m_iBuildingDefenseMod; } /// Accessor: Change current defense boost mod from buildings void CvCityBuildings::ChangeBuildingDefenseMod(int iChange) { if (iChange != 0) { m_iBuildingDefenseMod = (m_iBuildingDefenseMod + iChange); CvAssert(m_iBuildingDefenseMod >= 0); m_pCity->plot()->plotAction(PUF_makeInfoBarDirty); } } void CvCityBuildings::IncrementWonderStats(BuildingClassTypes eIndex) { CvBuildingClassInfo* pkBuildingClassInfo = GC.getBuildingClassInfo(eIndex); if(pkBuildingClassInfo == NULL) return; const char* szWonderTypeChar = pkBuildingClassInfo->GetType(); CvString szWonderType = szWonderTypeChar; if( szWonderType == "BUILDINGCLASS_HEROIC_EPIC" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_HEROICEPIC ); } else if( szWonderType == "BUILDINGCLASS_NATIONAL_COLLEGE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_NATIONALCOLLEGE ); } else if( szWonderType == "BUILDINGCLASS_NATIONAL_EPIC" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_NATIONALEPIC ); } else if( szWonderType == "BUILDINGCLASS_IRONWORKS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_IRONWORKS ); } else if( szWonderType == "BUILDINGCLASS_OXFORD_UNIVERSITY" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_OXFORDUNIVERSITY ); } else if( szWonderType == "BUILDINGCLASS_HERMITAGE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_HERMITAGE ); } else if( szWonderType == "BUILDINGCLASS_GREAT_LIGHTHOUSE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_GREATLIGHTHOUSE ); } else if( szWonderType == "BUILDINGCLASS_STONEHENGE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_STONEHENGE ); } else if( szWonderType == "BUILDINGCLASS_GREAT_LIBRARY" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_GREATLIBRARY ); } else if( szWonderType == "BUILDINGCLASS_PYRAMID" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_PYRAMIDS ); } else if( szWonderType == "BUILDINGCLASS_COLOSSUS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_COLOSSUS ); } else if( szWonderType == "BUILDINGCLASS_ORACLE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_ORACLE ); } else if( szWonderType == "BUILDINGCLASS_HANGING_GARDEN" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_HANGINGGARDENS ); } else if( szWonderType == "BUILDINGCLASS_GREAT_WALL" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_GREATWALL); } else if( szWonderType == "BUILDINGCLASS_ANGKOR_WAT" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_ANGKORWAT); } else if( szWonderType == "BUILDINGCLASS_HAGIA_SOPHIA" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_HAGIASOPHIA); } else if( szWonderType == "BUILDINGCLASS_CHICHEN_ITZA" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_CHICHENITZA); } else if( szWonderType == "BUILDINGCLASS_MACHU_PICHU" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_MACHUPICCHU); } else if( szWonderType == "BUILDINGCLASS_NOTRE_DAME" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_NOTREDAME); } else if( szWonderType == "BUILDINGCLASS_PORCELAIN_TOWER" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_PORCELAINTOWER); } else if( szWonderType == "BUILDINGCLASS_HIMEJI_CASTLE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_HIMEJICASTLE); } else if( szWonderType == "BUILDINGCLASS_SISTINE_CHAPEL" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_SISTINECHAPEL); } else if( szWonderType == "BUILDINGCLASS_KREMLIN" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_KREMLIN ); } else if( szWonderType == "BUILDINGCLASS_FORBIDDEN_PALACE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_FORBIDDENPALACE); } else if( szWonderType == "BUILDINGCLASS_TAJ_MAHAL" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_TAJMAHAL); } else if( szWonderType == "BUILDINGCLASS_BIG_BEN" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_BIGBEN); } else if( szWonderType == "BUILDINGCLASS_LOUVRE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_LOUVRE); } else if( szWonderType == "BUILDINGCLASS_BRANDENBURG_GATE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_BRANDENBURGGATE); } else if( szWonderType == "BUILDINGCLASS_STATUE_OF_LIBERTY" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_STATUEOFLIBERTY); } else if( szWonderType == "BUILDINGCLASS_CRISTO_REDENTOR" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_CRISTOREDENTOR); } else if( szWonderType == "BUILDINGCLASS_EIFFEL_TOWER" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_EIFFELTOWER); } else if( szWonderType == "BUILDINGCLASS_PENTAGON" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_PENTAGON); } else if( szWonderType == "BUILDINGCLASS_UNITED_NATIONS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_UNITEDNATION ); } else if( szWonderType == "BUILDINGCLASS_SYDNEY_OPERA_HOUSE" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_SYDNEYOPERAHOUSE); } else if( szWonderType == "BUILDINGCLASS_STATUE_ZEUS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_STATUEOFZEUS ); } else if( szWonderType == "BUILDINGCLASS_TEMPLE_ARTEMIS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_TEMPLEOFARTEMIS ); } else if( szWonderType == "BUILDINGCLASS_MAUSOLEUM_HALICARNASSUS" ) { gDLL->IncrementSteamStat( ESTEAMSTAT_MAUSOLEUMOFHALICARNASSUS ); } else { OutputDebugString("\nNo Stat for selected Wonder: "); OutputDebugString(szWonderType); OutputDebugString("\n"); } bool bCheckForWonders = false; bCheckForWonders = CheckForAllWondersBuilt(); if (bCheckForWonders) { gDLL->UnlockAchievement(ACHIEVEMENT_ALL_WONDERS); } //DLC_06 bool bCheckForAncientWonders = false; bCheckForAncientWonders = CheckForSevenAncientWondersBuilt(); if (bCheckForAncientWonders) { gDLL->UnlockAchievement(ACHIEVEMENT_SPECIAL_ANCIENT_WONDERS); } } bool CvCityBuildings::CheckForAllWondersBuilt() { int iI; int iStartStatWonder = 80; //As defined on the backend int iEndStatWonder = 113; int32 nStat; for(iI = iStartStatWonder; iI < iEndStatWonder; iI++) { if(gDLL->GetSteamStat( (ESteamStat)iI, &nStat )) { if(nStat <= 0 ) { return false; } } } return true; } bool CvCityBuildings::CheckForSevenAncientWondersBuilt() { GUID guid; ExtractGUID(CIV5_DLC_06_PACKAGEID, guid); if (gDLL->IsDLCValid(guid)) { ESteamStat arrWonderStats[7] = { ESTEAMSTAT_COLOSSUS, ESTEAMSTAT_GREATLIGHTHOUSE, ESTEAMSTAT_HANGINGGARDENS, ESTEAMSTAT_PYRAMIDS, ESTEAMSTAT_STATUEOFZEUS, ESTEAMSTAT_TEMPLEOFARTEMIS, ESTEAMSTAT_MAUSOLEUMOFHALICARNASSUS }; int32 nStat; for (int iI = 0; iI < 7; iI++ ) { if (gDLL->GetSteamStat(arrWonderStats[iI], &nStat)) { if (nStat <= 0) { return false; } } else { // Couldn't get one of the SteamStats for some reason return false; } } return true; } return false; } /// Uses the notification system to send information out when other players need to know a building has been started void CvCityBuildings::NotifyNewBuildingStarted (BuildingTypes /*eIndex*/) { // JON: Disabling this notification return; // is this city starting a wonder? If so, send a notification //CvBuildingEntry* buildingEntry = GC.getBuildingInfo(eIndex); //if (isLimitedWonderClass((BuildingClassTypes)(buildingEntry->GetBuildingClassType())) && GetBuildingProductionTimes100(eIndex) == 0) //{ // Localization::String locString; // Localization::String locSummaryString; // for (uint ui = 0; ui < MAX_MAJOR_CIVS; ui++) // { // PlayerTypes ePlayer = (PlayerTypes)ui; // if (ePlayer == m_pCity->getOwner() || !GET_PLAYER(ePlayer).isAlive()) // { // continue; // } // int iX = -1; // int iY = -1; // int iPlayerID = -1; // if (GET_TEAM(m_pCity->getTeam()).isHasMet(GET_PLAYER(ePlayer).getTeam())) // { // if (m_pCity->isRevealed(GET_PLAYER(ePlayer).getTeam(), false)) // { // locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED"); // locString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey() << m_pCity->getNameKey(); // } // else // { // locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED_UNKNOWN_LOCATION"); // locString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey(); // } // locSummaryString = Localization::Lookup("TXT_KEY_NOTIFICATION_SUMMARY_WONDER_STARTED"); // locSummaryString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey(); // } // else // { // locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED_UNMET"); // locString << buildingEntry->GetTextKey(); // locSummaryString = Localization::Lookup("TXT_KEY_NOTIFICATION_SUMMARY_WONDER_STARTED_UNKNOWN"); // locSummaryString << buildingEntry->GetTextKey(); // } // CvNotifications* pNotifications = GET_PLAYER(ePlayer).GetNotifications(); // if (pNotifications) // { // pNotifications->Add(NOTIFICATION_WONDER_STARTED, locString.toUTF8(), locSummaryString.toUTF8(), iX, iY, eIndex); // } // } //} } /// Helper function to read in an integer array of data sized according to number of building types void BuildingArrayHelpers::Read(FDataStream &kStream, int *paiBuildingArray) { int iNumEntries; FStringFixedBuffer(sTemp, 64); int iType; kStream >> iNumEntries; for (int iI = 0; iI < iNumEntries; iI++) { kStream >> sTemp; if (sTemp != "NO_BUILDING") { iType = GC.getInfoTypeForString(sTemp); if (iType != -1) { kStream >> paiBuildingArray[iType]; } else { CvString szError; szError.Format("LOAD ERROR: Building Type not found: %s", sTemp); GC.LogMessage(szError.GetCString()); CvAssertMsg(false, szError); int iDummy; kStream >> iDummy; // Skip it. } } } } /// Helper function to write out an integer array of data sized according to number of building types void BuildingArrayHelpers::Write(FDataStream &kStream, int *paiBuildingArray, int iArraySize) { FStringFixedBuffer(sTemp, 64); kStream << iArraySize; for (int iI = 0; iI < iArraySize; iI++) { const BuildingTypes eBuilding = static_cast<BuildingTypes>(iI); CvBuildingEntry* pkBuildingInfo = GC.getBuildingInfo(eBuilding); if(pkBuildingInfo) { sTemp = pkBuildingInfo->GetType(); kStream << sTemp; kStream << paiBuildingArray[iI]; } else { sTemp = "NO_BUILDING"; kStream << sTemp; } } }
98099a5d956f847736ed9fa9b39b5c6251116347
24f8cfae88683b91c55b027fd2ad39316d90906c
/features/sift.cc
492f32a9f1bd30fd577f510d048d9ba75f074a89
[]
no_license
sld66320/mySFM
63afb83f8f657c893c815678b76e5cb98df5f679
9be8469d5f1bda95b4339c2095d919820263b29c
refs/heads/master
2023-05-04T19:22:41.140674
2021-05-03T08:02:53
2021-05-03T08:02:53
337,611,143
9
3
null
null
null
null
UTF-8
C++
false
false
35,055
cc
/* * Copyright (C) 2015, Simon Fuhrmann * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <iostream> #include <fstream> #include <stdexcept> #include "util/timer.h" #include "math/functions.h" #include "math/matrix.h" #include "math/matrix_tools.h" #include "core/image_io.h" #include "core/image_tools.h" #include "features/sift.h" FEATURES_NAMESPACE_BEGIN Sift::Sift (Options const& options) : options(options) { if (this->options.min_octave < -1 || this->options.min_octave > this->options.max_octave) throw std::invalid_argument("Invalid octave range"); if (this->options.contrast_threshold < 0.0f) this->options.contrast_threshold = 0.02f / static_cast<float>(this->options.num_samples_per_octave); if (this->options.debug_output) this->options.verbose_output = true; } /* ---------------------------------------------------------------- */ void Sift::process (void) { util::ClockTimer timer, total_timer; /* * Creates the scale space representation of the image by * sampling the scale space and computing the DoG images. * See Section 3, 3.2 and 3.3 in SIFT article. */ if (this->options.verbose_output) { std::cout << "SIFT: Creating " << (this->options.max_octave - this->options.min_octave) << " octaves (" << this->options.min_octave << " to " << this->options.max_octave << ")..." << std::endl; } timer.reset(); this->create_octaves(); if (this->options.debug_output) { std::cout << "SIFT: Creating octaves took " << timer.get_elapsed() << "ms." << std::endl; } /* * Detects local extrema in the DoG function as described in Section 3.1. */ if (this->options.debug_output) { std::cout << "SIFT: Detecting local extrema..." << std::endl; } timer.reset(); this->extrema_detection(); if (this->options.debug_output) { std::cout << "SIFT: Detected " << this->keypoints.size() << " keypoints, took " << timer.get_elapsed() << "ms." << std::endl; } /* * Accurate keypoint localization and filtering. * According to Section 4 in SIFT article. */ if (this->options.debug_output) { std::cout << "SIFT: Localizing and filtering keypoints..." << std::endl; } timer.reset(); this->keypoint_localization(); if (this->options.debug_output) { std::cout << "SIFT: Retained " << this->keypoints.size() << " stable " << "keypoints, took " << timer.get_elapsed() << "ms." << std::endl; } /* * Difference of Gaussian images are not needed anymore. */ for (std::size_t i = 0; i < this->octaves.size(); ++i) this->octaves[i].dog.clear(); /* * Generate the list of keypoint descriptors. * See Section 5 and 6 in the SIFT article. * This list can in general be larger than the amount of keypoints, * since for each keypoint several descriptors may be created. */ if (this->options.verbose_output) { std::cout << "SIFT: Generating keypoint descriptors..." << std::endl; } timer.reset(); this->descriptor_generation(); if (this->options.debug_output) { std::cout << "SIFT: Generated " << this->descriptors.size() << " descriptors, took " << timer.get_elapsed() << "ms." << std::endl; } if (this->options.verbose_output) { std::cout << "SIFT: Generated " << this->descriptors.size() << " descriptors from " << this->keypoints.size() << " keypoints," << " took " << total_timer.get_elapsed() << "ms." << std::endl; } /* Free memory. */ this->octaves.clear(); } /* ---------------------------------------------------------------- */ void Sift::set_image (core::ByteImage::ConstPtr img) { if (img->channels() != 1 && img->channels() != 3) throw std::invalid_argument("Gray or color image expected"); // 将图像转化成灰度图 this->orig = core::image::byte_to_float_image(img); if (img->channels() == 3) { this->orig = core::image::desaturate<float> (this->orig, core::image::DESATURATE_AVERAGE); } } /* ---------------------------------------------------------------- */ void Sift::set_float_image (core::FloatImage::ConstPtr img) { if (img->channels() != 1 && img->channels() != 3) throw std::invalid_argument("Gray or color image expected"); if (img->channels() == 3) { this->orig = core::image::desaturate<float> (img, core::image::DESATURATE_AVERAGE); } else { this->orig = img->duplicate(); } } /* ---------------------------------------------------------------- */ void Sift::create_octaves (void) { this->octaves.clear(); /* * Create octave -1. The original image is assumed to have blur * sigma = 0.5. The double size image therefore has sigma = 1. */ if (this->options.min_octave < 0) { //std::cout << "Creating octave -1..." << std::endl; core::FloatImage::Ptr img = core::image::rescale_double_size_supersample<float>(this->orig); this->add_octave(img, this->options.inherent_blur_sigma * 2.0f, this->options.base_blur_sigma); } /* * Prepare image for the first positive octave by downsampling. * This code is executed only if min_octave > 0. */ core::FloatImage::ConstPtr img = this->orig; for (int i = 0; i < this->options.min_octave; ++i) img = core::image::rescale_half_size_gaussian<float>(img); /* * Create new octave from 'img', then subsample octave image where * sigma is doubled to get a new base image for the next octave. */ float img_sigma = this->options.inherent_blur_sigma; for (int i = std::max(0, this->options.min_octave); i <= this->options.max_octave; ++i) { //std::cout << "Creating octave " << i << "..." << std::endl; this->add_octave(img, img_sigma, this->options.base_blur_sigma); core::FloatImage::ConstPtr pre_base = octaves[octaves.size()-1].img[0]; img = core::image::rescale_half_size_gaussian<float>(pre_base); img_sigma = this->options.base_blur_sigma; } } /* ---------------------------------------------------------------- */ void Sift::add_octave (core::FloatImage::ConstPtr image, float has_sigma, float target_sigma) { /* * First, bring the provided image to the target blur. * Since L * g(sigma1) * g(sigma2) = L * g(sqrt(sigma1^2 + sigma2^2)), * we need to blur with sigma = sqrt(target_sigma^2 - has_sigma^2). */ float sigma = std::sqrt(MATH_POW2(target_sigma) - MATH_POW2(has_sigma)); //std::cout << "Pre-blurring image to sigma " << target_sigma << " (has " // << has_sigma << ", blur = " << sigma << ")..." << std::endl; core::FloatImage::Ptr base = (target_sigma > has_sigma ? core::image::blur_gaussian<float>(image, sigma) : image->duplicate()); /* Create the new octave and add initial image. */ this->octaves.push_back(Octave()); Octave& oct = this->octaves.back(); oct.img.push_back(base); /* 'k' is the constant factor between the scales in scale space. */ float const k = std::pow(2.0f, 1.0f / this->options.num_samples_per_octave); sigma = target_sigma; /* Create other (s+2) samples of the octave to get a total of (s+3). */ for (int i = 1; i < this->options.num_samples_per_octave + 3; ++i) { /* Calculate the blur sigma the image will get. */ float sigmak = sigma * k; float blur_sigma = std::sqrt(MATH_POW2(sigmak) - MATH_POW2(sigma)); /* Blur the image to create a new scale space sample. */ //std::cout << "Blurring image to sigma " << sigmak << " (has " << sigma // << ", blur = " << blur_sigma << ")..." << std::endl; core::FloatImage::Ptr img = core::image::blur_gaussian<float> (base, blur_sigma); oct.img.push_back(img); /* Create the Difference of Gaussian image (DoG). */ //计算差分拉普拉斯 // todo revised by sway core::FloatImage::Ptr dog = core::image::subtract<float>(img, base); oct.dog.push_back(dog); /* Update previous image and sigma for next round. */ base = img; sigma = sigmak; } } /* ---------------------------------------------------------------- */ void Sift::extrema_detection (void) { /* Delete previous keypoints. */ this->keypoints.clear(); /* Detect keypoints in each octave... */ for (std::size_t i = 0; i < this->octaves.size(); ++i) { Octave const& oct(this->octaves[i]); /* In each octave, take three subsequent DoG images and detect. */ for (int s = 0; s < (int)oct.dog.size() - 2; ++s) { core::FloatImage::ConstPtr samples[3] = { oct.dog[s + 0], oct.dog[s + 1], oct.dog[s + 2] }; this->extrema_detection(samples, static_cast<int>(i) + this->options.min_octave, s); } } } /* ---------------------------------------------------------------- */ std::size_t Sift::extrema_detection (core::FloatImage::ConstPtr s[3], int oi, int si) { int const w = s[1]->width(); int const h = s[1]->height(); /* Offsets for the 9-neighborhood w.r.t. center pixel. */ int noff[9] = { -1 - w, 0 - w, 1 - w, -1, 0, 1, -1 + w, 0 + w, 1 + w }; /* * Iterate over all pixels in s[1], and check if pixel is maximum * (or minumum) in its 27-neighborhood. */ int detected = 0; int off = w; for (int y = 1; y < h - 1; ++y, off += w) for (int x = 1; x < w - 1; ++x) { int idx = off + x; bool largest = true; bool smallest = true; float center_value = s[1]->at(idx); for (int l = 0; (largest || smallest) && l < 3; ++l) for (int i = 0; (largest || smallest) && i < 9; ++i) { if (l == 1 && i == 4) // Skip center pixel continue; if (s[l]->at(idx + noff[i]) >= center_value) largest = false; if (s[l]->at(idx + noff[i]) <= center_value) smallest = false; } /* Skip non-maximum values. */ if (!smallest && !largest) continue; /* Yummy. Add detected scale space extremum. */ Keypoint kp; kp.octave = oi; kp.x = static_cast<float>(x); kp.y = static_cast<float>(y); kp.sample = static_cast<float>(si); this->keypoints.push_back(kp); detected += 1; } return detected; } /* ---------------------------------------------------------------- */ void Sift::keypoint_localization (void) { /* * Iterate over all keypoints, accurately localize minima and maxima * in the DoG function by fitting a quadratic Taylor polynomial * around the keypoint. */ int num_singular = 0; int num_keypoints = 0; // Write iterator for (std::size_t i = 0; i < this->keypoints.size(); ++i) { /* Copy keypoint. */ Keypoint kp(this->keypoints[i]); /* Get corresponding octave and DoG images. */ Octave const& oct(this->octaves[kp.octave - this->options.min_octave]); int sample = static_cast<int>(kp.sample); core::FloatImage::ConstPtr dogs[3] = { oct.dog[sample + 0], oct.dog[sample + 1], oct.dog[sample + 2] }; /* Shorthand for image width and height. */ int const w = dogs[0]->width(); int const h = dogs[0]->height(); /* The integer and floating point location of the keypoints. */ int ix = static_cast<int>(kp.x); int iy = static_cast<int>(kp.y); int is = static_cast<int>(kp.sample); float delta_x, delta_y, delta_s; /* The first and second order derivatives. */ float Dx, Dy, Ds; float Dxx, Dyy, Dss; float Dxy, Dxs, Dys; /* * Locate the keypoint using second order Taylor approximation. * The procedure might get iterated around a neighboring pixel if * the accurate keypoint is off by >0.6 from the center pixel. */ # define AT(S,OFF) (dogs[S]->at(px + OFF)) for (int j = 0; j < 5; ++j) { std::size_t px = iy * w + ix; /* Compute first and second derivatives. */ Dx = (AT(1,1) - AT(1,-1)) * 0.5f; Dy = (AT(1,w) - AT(1,-w)) * 0.5f; Ds = (AT(2,0) - AT(0,0)) * 0.5f; Dxx = AT(1,1) + AT(1,-1) - 2.0f * AT(1,0); Dyy = AT(1,w) + AT(1,-w) - 2.0f * AT(1,0); Dss = AT(2,0) + AT(0,0) - 2.0f * AT(1,0); Dxy = (AT(1,1+w) + AT(1,-1-w) - AT(1,-1+w) - AT(1,1-w)) * 0.25f; Dxs = (AT(2,1) + AT(0,-1) - AT(2,-1) - AT(0,1)) * 0.25f; Dys = (AT(2,w) + AT(0,-w) - AT(2,-w) - AT(0,w)) * 0.25f; /* Setup the Hessian matrix. */ math::Matrix3f H; /****************************task-1-0 构造Hessian矩阵 ******************************/ /* * 参考第32页slide的Hessian矩阵构造方式填充H矩阵,其中dx=dy=d_sigma=1, 其中A矩阵按照行顺序存储,即 * H=[H[0], H[1], H[2]] * [H[3], H[4], H[5]] * [H[6], H[7], H[8]] */ /**********************************************************************************/ H[0] = Dxx; H[1] = Dxy; H[2] = Dxs; H[3] = Dxy; H[4] = Dyy; H[5] = Dys; H[6] = Dxs; H[7] = Dys; H[8] = Dss; /* Compute determinant to detect singular matrix. */ float detH = math::matrix_determinant(H); if (MATH_EPSILON_EQ(detH, 0.0f, 1e-15f)) { num_singular += 1; delta_x = delta_y = delta_s = 0.0f; // FIXME: Handle this case? break; } /* Invert the matrix to get the accurate keypoint. */ math::Matrix3f H_inv = math::matrix_inverse(H, detH); math::Vec3f b(-Dx, -Dy, -Ds); //math::Vec3f delta; /****************************task-1-1 求解偏移量deta ******************************/ /* 参考第30页slide delta_x的求解方式 delta_x = inv(H)*b * 请在此处给出delta的表达式 */ /* */ /* 此处添加代码 */ /* */ /**********************************************************************************/ math::Vec3f delta = H_inv * b; delta_x = delta[0]; delta_y = delta[1]; delta_s = delta[2]; /* Check if accurate location is far away from pixel center. */ // dx =0 表示|dx|>0.6f int dx = (delta_x > 0.6f && ix < w-2) * 1 + (delta_x < -0.6f && ix > 1) * -1; int dy = (delta_y > 0.6f && iy < h-2) * 1 + (delta_y < -0.6f && iy > 1) * -1; /* If the accurate location is closer to another pixel, * repeat localization around the other pixel. */ if (dx != 0 || dy != 0) { ix += dx; iy += dy; continue; } /* Accurate location looks good. */ break; } /* Calcualte function value D(x) at accurate keypoint x. */ /*****************************task1-2求解极值点处的DoG值val ***************************/ /* * 参考第30页slides的机极值点f(x)的求解公式f(x) = f(x0) + 0.5* delta.dot(D) * 其中 * f(x0)--表示插值点(ix, iy, is) 处的DoG值,可通过dogs[1]->at(ix, iy, 0)获取 * delta--为上述求得的delta=[delta_x, delta_y, delta_s] * D--为一阶导数,表示为(Dx, Dy, Ds) * 请给出求解val的代码 */ //float val = 0.0; /* */ /* 此处添加代码 */ /* */ /************************************************************************************/ float val = dogs[1]->at(ix, iy, 0) + 0.5f * (Dx * delta_x + Dy * delta_y + Ds * delta_s); /* Calcualte edge response score Tr(H)^2 / Det(H), see Section 4.1. */ /**************************去除边缘点,参考第33页slide 仔细阅读代码 ****************************/ float hessian_trace = Dxx + Dyy; float hessian_det = Dxx * Dyy - MATH_POW2(Dxy); float hessian_score = MATH_POW2(hessian_trace) / hessian_det; float score_thres = MATH_POW2(this->options.edge_ratio_threshold + 1.0f) / this->options.edge_ratio_threshold; /********************************************************************************/ /* * Set accurate final keypoint location. */ kp.x = (float)ix + delta_x; kp.y = (float)iy + delta_y; kp.sample = (float)is + delta_s; /* * Discard keypoints with: * 1. low contrast (value of DoG function at keypoint), * 2. negative hessian determinant (curvatures with different sign), * Note that negative score implies negative determinant. * 3. large edge response (large hessian score), * 4. unstable keypoint accurate locations, * 5. keypoints beyond the scale space boundary. */ if (std::abs(val) < this->options.contrast_threshold || hessian_score < 0.0f || hessian_score > score_thres || std::abs(delta_x) > 1.5f || std::abs(delta_y) > 1.5f || std::abs(delta_s) > 1.0f || kp.sample < -1.0f || kp.sample > (float)this->options.num_samples_per_octave || kp.x < 0.0f || kp.x > (float)(w - 1) || kp.y < 0.0f || kp.y > (float)(h - 1)) { //std::cout << " REJECTED!" << std::endl; continue; } /* Keypoint is accepted, copy to write iter and advance. */ this->keypoints[num_keypoints] = kp; num_keypoints += 1; } /* Limit vector size to number of accepted keypoints. */ this->keypoints.resize(num_keypoints); if (this->options.debug_output && num_singular > 0) { std::cout << "SIFT: Warning: " << num_singular << " singular matrices detected!" << std::endl; } } /* ---------------------------------------------------------------- */ void Sift::descriptor_generation (void) { if (this->octaves.empty()) throw std::runtime_error("Octaves not available!"); if (this->keypoints.empty()) return; this->descriptors.clear(); this->descriptors.reserve(this->keypoints.size() * 3 / 2); /* * Keep a buffer of S+3 gradient and orientation images for the current * octave. Once the octave is changed, these images are recomputed. * To ensure efficiency, the octave index must always increase, never * decrease, which is enforced during the algorithm. */ int octave_index = this->keypoints[0].octave; Octave* octave = &this->octaves[octave_index - this->options.min_octave]; // todo 计算每个octave中所有图像的梯度值和方向,具体得, octave::grad存储图像的梯度响应值,octave::ori存储梯度方向 this->generate_grad_ori_images(octave); /* Walk over all keypoints and compute descriptors. */ for (std::size_t i = 0; i < this->keypoints.size(); ++i) { Keypoint const& kp(this->keypoints[i]); /* Generate new gradient and orientation images if octave changed. */ if (kp.octave > octave_index) { /* Clear old octave gradient and orientation images. */ if (octave) { octave->grad.clear(); octave->ori.clear(); } /* Setup new octave gradient and orientation images. */ octave_index = kp.octave; octave = &this->octaves[octave_index - this->options.min_octave]; this->generate_grad_ori_images(octave); } else if (kp.octave < octave_index) { throw std::runtime_error("Decreasing octave index!"); } /* Orientation assignment. This returns multiple orientations. */ /* todo 统计直方图找到特征点主方向,找到几个主方向*/ std::vector<float> orientations; orientations.reserve(8); this->orientation_assignment(kp, octave, orientations); /* todo 生成特征向量,同一个特征点可能有多个描述子,为了提升匹配的稳定性*/ /* Feature vector extraction. */ for (std::size_t j = 0; j < orientations.size(); ++j) { Descriptor desc; float const scale_factor = std::pow(2.0f, kp.octave); desc.x = scale_factor * (kp.x + 0.5f) - 0.5f; desc.y = scale_factor * (kp.y + 0.5f) - 0.5f; desc.scale = this->keypoint_absolute_scale(kp); desc.orientation = orientations[j]; if (this->descriptor_assignment(kp, desc, octave)) this->descriptors.push_back(desc); } } } /* ---------------------------------------------------------------- */ void Sift::generate_grad_ori_images (Octave* octave) { octave->grad.clear(); octave->grad.reserve(octave->img.size()); octave->ori.clear(); octave->ori.reserve(octave->img.size()); int const width = octave->img[0]->width(); int const height = octave->img[0]->height(); //std::cout << "Generating gradient and orientation images..." << std::endl; for (std::size_t i = 0; i < octave->img.size(); ++i) { core::FloatImage::ConstPtr img = octave->img[i]; core::FloatImage::Ptr grad = core::FloatImage::create(width, height, 1); core::FloatImage::Ptr ori = core::FloatImage::create(width, height, 1); int image_iter = width + 1; for (int y = 1; y < height - 1; ++y, image_iter += 2) for (int x = 1; x < width - 1; ++x, ++image_iter) { float m1x = img->at(image_iter - 1); float p1x = img->at(image_iter + 1); float m1y = img->at(image_iter - width); float p1y = img->at(image_iter + width); float dx = 0.5f * (p1x - m1x); float dy = 0.5f * (p1y - m1y); float atan2f = std::atan2(dy, dx); grad->at(image_iter) = std::sqrt(dx * dx + dy * dy); ori->at(image_iter) = atan2f < 0.0f ? atan2f + MATH_PI * 2.0f : atan2f; } octave->grad.push_back(grad); octave->ori.push_back(ori); } } /* ---------------------------------------------------------------- */ void Sift::orientation_assignment (Keypoint const& kp, Octave const* octave, std::vector<float>& orientations) { int const nbins = 36; float const nbinsf = static_cast<float>(nbins); /* Prepare 36-bin histogram. */ float hist[nbins]; std::fill(hist, hist + nbins, 0.0f); /* Integral x and y coordinates and closest scale sample. */ int const ix = static_cast<int>(kp.x + 0.5f); int const iy = static_cast<int>(kp.y + 0.5f); int const is = static_cast<int>(math::round(kp.sample)); float const sigma = this->keypoint_relative_scale(kp); /* Images with its dimension for the keypoint. */ core::FloatImage::ConstPtr grad(octave->grad[is + 1]); core::FloatImage::ConstPtr ori(octave->ori[is + 1]); int const width = grad->width(); int const height = grad->height(); /* * Compute window size 'win', the full window has 2 * win + 1 pixel. * The factor 3 makes the window large enough such that the gaussian * has very little weight beyond the window. The value 1.5 is from * the SIFT paper. If the window goes beyond the image boundaries, * the keypoint is discarded. */ float const sigma_factor = 1.5f; int win = static_cast<int>(sigma * sigma_factor * 3.0f); if (ix < win || ix + win >= width || iy < win || iy + win >= height) return; /* Center of keypoint index. */ int center = iy * width + ix; float const dxf = kp.x - static_cast<float>(ix); float const dyf = kp.y - static_cast<float>(iy); float const maxdist = static_cast<float>(win*win) + 0.5f; /* Populate histogram over window, intersected with (1,1), (w-2,h-2). */ for (int dy = -win; dy <= win; ++dy) { int const yoff = dy * width; for (int dx = -win; dx <= win; ++dx) { /* Limit to circular window (centered at accurate keypoint). */ float const dist = MATH_POW2(dx-dxf) + MATH_POW2(dy-dyf); if (dist > maxdist) continue; float gm = grad->at(center + yoff + dx); // gradient magnitude float go = ori->at(center + yoff + dx); // gradient orientation float weight = math::gaussian_xx(dist, sigma * sigma_factor); int bin = static_cast<int>(nbinsf * go / (2.0f * MATH_PI)); bin = math::clamp(bin, 0, nbins - 1); hist[bin] += gm * weight; } } /* Smooth histogram. */ for (int i = 0; i < 6; ++i) { float first = hist[0]; float prev = hist[nbins - 1]; for (int j = 0; j < nbins - 1; ++j) { float current = hist[j]; hist[j] = (prev + current + hist[j + 1]) / 3.0f; prev = current; } hist[nbins - 1] = (prev + hist[nbins - 1] + first) / 3.0f; } /* Find maximum element. */ float maxh = *std::max_element(hist, hist + nbins); /* Find peaks within 80% of max element. */ for (int i = 0; i < nbins; ++i) { float h0 = hist[(i + nbins - 1) % nbins]; float h1 = hist[i]; float h2 = hist[(i + 1) % nbins]; /* These peaks must be a local maximum! */ if (h1 <= 0.8f * maxh || h1 <= h0 || h1 <= h2) continue; /* * Quadratic interpolation to find accurate maximum. * f(x) = ax^2 + bx + c, f(-1) = h0, f(0) = h1, f(1) = h2 * --> a = 1/2 (h0 - 2h1 + h2), b = 1/2 (h2 - h0), c = h1. * x = f'(x) = 2ax + b = 0 --> x = -1/2 * (h2 - h0) / (h0 - 2h1 + h2) */ float x = -0.5f * (h2 - h0) / (h0 - 2.0f * h1 + h2); float o = 2.0f * MATH_PI * (x + (float)i + 0.5f) / nbinsf; orientations.push_back(o); } } /* ---------------------------------------------------------------- */ bool Sift::descriptor_assignment (Keypoint const& kp, Descriptor& desc, Octave const* octave) { /* * The final feature vector has size PXB * PXB * OHB. * The following constants should not be changed yet, as the * (PXB^2 * OHB = 128) element feature vector is still hard-coded. */ //int const PIX = 16; // Descriptor region with 16x16 pixel int const PXB = 4; // Pixel bins with 4x4 bins int const OHB = 8; // Orientation histogram with 8 bins /* Integral x and y coordinates and closest scale sample. */ int const ix = static_cast<int>(kp.x + 0.5f); int const iy = static_cast<int>(kp.y + 0.5f); int const is = static_cast<int>(math::round(kp.sample)); float const dxf = kp.x - static_cast<float>(ix); float const dyf = kp.y - static_cast<float>(iy); float const sigma = this->keypoint_relative_scale(kp); /* Images with its dimension for the keypoint. */ core::FloatImage::ConstPtr grad(octave->grad[is + 1]); core::FloatImage::ConstPtr ori(octave->ori[is + 1]); int const width = grad->width(); int const height = grad->height(); /* Clear feature vector. */ desc.data.fill(0.0f); /* Rotation constants given by descriptor orientation. */ float const sino = std::sin(desc.orientation); float const coso = std::cos(desc.orientation); /* * Compute window size. * Each spacial bin has an extension of 3 * sigma (sigma is the scale * of the keypoint). For interpolation we need another half bin at * both ends in each dimension. And since the window can be arbitrarily * rotated, we need to multiply with sqrt(2). The window size is: * 2W = sqrt(2) * 3 * sigma * (PXB + 1). */ float const binsize = 3.0f * sigma; int win = MATH_SQRT2 * binsize * (float)(PXB + 1) * 0.5f; if (ix < win || ix + win >= width || iy < win || iy + win >= height) return false; /* * Iterate over the window, intersected with the image region * from (1,1) to (w-2, h-2) since gradients/orientations are * not defined at the boundary pixels. Add all samples to the * corresponding bin. */ int const center = iy * width + ix; // Center pixel at KP location for (int dy = -win; dy <= win; ++dy) { int const yoff = dy * width; for (int dx = -win; dx <= win; ++dx) { /* Get pixel gradient magnitude and orientation. */ float const mod = grad->at(center + yoff + dx); float const angle = ori->at(center + yoff + dx); float theta = angle - desc.orientation; if (theta < 0.0f) theta += 2.0f * MATH_PI; /* Compute fractional coordinates w.r.t. the window. */ float const winx = (float)dx - dxf; float const winy = (float)dy - dyf; /* * Compute normalized coordinates w.r.t. bins. The window * coordinates are rotated around the keypoint. The bins are * chosen such that 0 is the coordinate of the first bins center * in each dimension. In other words, (0,0,0) is the coordinate * of the first bin center in the three dimensional histogram. */ float binoff = (float)(PXB - 1) / 2.0f; float binx = (coso * winx + sino * winy) / binsize + binoff; float biny = (-sino * winx + coso * winy) / binsize + binoff; float bint = theta * (float)OHB / (2.0f * MATH_PI) - 0.5f; /* Compute circular window weight for the sample. */ float gaussian_sigma = 0.5f * (float)PXB; float gaussian_weight = math::gaussian_xx (MATH_POW2(binx - binoff) + MATH_POW2(biny - binoff), gaussian_sigma); /* Total contribution of the sample in the histogram is now: */ float contrib = mod * gaussian_weight; /* * Distribute values into bins (using trilinear interpolation). * Each sample is inserted into 8 bins. Some of these bins may * not exist, because the sample is outside the keypoint window. */ int bxi[2] = { (int)std::floor(binx), (int)std::floor(binx) + 1 }; int byi[2] = { (int)std::floor(biny), (int)std::floor(biny) + 1 }; int bti[2] = { (int)std::floor(bint), (int)std::floor(bint) + 1 }; float weights[3][2] = { { (float)bxi[1] - binx, 1.0f - ((float)bxi[1] - binx) }, { (float)byi[1] - biny, 1.0f - ((float)byi[1] - biny) }, { (float)bti[1] - bint, 1.0f - ((float)bti[1] - bint) } }; // Wrap around orientation histogram if (bti[0] < 0) bti[0] += OHB; if (bti[1] >= OHB) bti[1] -= OHB; /* Iterate the 8 bins and add weighted contrib to each. */ int const xstride = OHB; int const ystride = OHB * PXB; for (int y = 0; y < 2; ++y) for (int x = 0; x < 2; ++x) for (int t = 0; t < 2; ++t) { if (bxi[x] < 0 || bxi[x] >= PXB || byi[y] < 0 || byi[y] >= PXB) continue; int idx = bti[t] + bxi[x] * xstride + byi[y] * ystride; desc.data[idx] += contrib * weights[0][x] * weights[1][y] * weights[2][t]; } } } /* Normalize the feature vector. */ desc.data.normalize(); /* Truncate descriptor values to 0.2. */ for (int i = 0; i < PXB * PXB * OHB; ++i) desc.data[i] = std::min(desc.data[i], 0.2f); /* Normalize once again. */ desc.data.normalize(); return true; } /* ---------------------------------------------------------------- */ /* * The scale of a keypoint is: scale = sigma0 * 2^(octave + (s+1)/S). * sigma0 is the initial blur (1.6), octave the octave index of the * keypoint (-1, 0, 1, ...) and scale space sample s in [-1,S+1] where * S is the amount of samples per octave. Since the initial blur 1.6 * corresponds to scale space sample -1, we add 1 to the scale index. */ float Sift::keypoint_relative_scale (Keypoint const& kp) { return this->options.base_blur_sigma * std::pow(2.0f, (kp.sample + 1.0f) / this->options.num_samples_per_octave); } float Sift::keypoint_absolute_scale (Keypoint const& kp) { return this->options.base_blur_sigma * std::pow(2.0f, kp.octave + (kp.sample + 1.0f) / this->options.num_samples_per_octave); } /* ---------------------------------------------------------------- */ void Sift::load_lowe_descriptors (std::string const& filename, Descriptors* result) { std::ifstream in(filename.c_str()); if (!in.good()) throw std::runtime_error("Cannot open descriptor file"); int num_descriptors; int num_dimensions; in >> num_descriptors >> num_dimensions; if (num_descriptors > 100000 || num_dimensions != 128) { in.close(); throw std::runtime_error("Invalid number of descriptors/dimensions"); } result->clear(); result->reserve(num_descriptors); for (int i = 0; i < num_descriptors; ++i) { Sift::Descriptor descriptor; in >> descriptor.y >> descriptor.x >> descriptor.scale >> descriptor.orientation; for (int j = 0; j < 128; ++j) in >> descriptor.data[j]; descriptor.data.normalize(); result->push_back(descriptor); } if (!in.good()) { result->clear(); in.close(); throw std::runtime_error("Error while reading descriptors"); } in.close(); } FEATURES_NAMESPACE_END
509a47bbffeea4e7a2ccc2c8024a22ab3de267da
78e649c37d6ed6635d480fc81d94e084f8d9c1cb
/CodingInterviewProblems/StringsAndArrays_Problem9.hpp
a5c360f6f5e20fd22a4633bb009873aaaa4a3e22
[]
no_license
Bukenberger/CodingInterviewProblems
eb08fb3d564485250daf007799127911d87fb050
d11366029f80d88a7e48a43c7ab463d5566cec26
refs/heads/main
2023-02-05T23:56:40.502318
2020-12-21T06:55:25
2020-12-21T06:55:25
322,975,541
0
1
null
null
null
null
UTF-8
C++
false
false
606
hpp
/* * @file StringsAndArrays_Problem9.hpp * @date 2020-12-19 * @author Teran Bukenberger * * @brief Contains function prototypes for the ninth problem of the Strings and Arrays category */ #ifndef __STRINGS_AND_ARRAYS_PROBLEM_9_HPP__ #define __STRINGS_AND_ARRAYS_PROBLEM_9_HPP__ #include <string> #include "Utilities.hpp" /* Function Name: string_rotation Purpose: Check is a string is a rotation of another Accepts: const string&, const string& Returns: bool */ bool string_rotation( const std::string& str1, const std::string& str2 ); #endif // !__STRINGS_AND_ARRAYS_PROBLEM_9_HPP__
9286a55f04f0e2e8f4c7bd511e02f4c52c99f74f
f5ec6ba1baf301e08728d8892d2a35e59f20b718
/src/talkcoin-wallet.cpp
d5171eff6dda3a7141fd780e2725c112c6964635
[ "MIT" ]
permissive
bitcointalkcoin/bitcointalkcoin
26434eb812e9cedaf174fcafe0409fc4ed5a4c76
c9112c3b8ce05ee78fe69822035cc3d8bdbca903
refs/heads/master
2020-06-26T14:37:43.515919
2019-12-02T17:46:15
2019-12-02T17:46:15
199,659,333
0
1
MIT
2019-12-02T17:46:17
2019-07-30T13:41:31
C++
UTF-8
C++
false
false
4,635
cpp
// Copyright (c) 2016-2018 The Talkcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/talkcoin-config.h> #endif #include <chainparams.h> #include <chainparamsbase.h> #include <logging.h> #include <util/strencodings.h> #include <util/system.h> #include <util/translation.h> #include <wallet/wallettool.h> #include <functional> #include <stdio.h> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; static void SetupWalletToolArgs() { SetupHelpOptions(gArgs); SetupChainParamsBaseOptions(); gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS); gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS); } static bool WalletAppInit(int argc, char* argv[]) { SetupWalletToolArgs(); std::string error_message; if (!gArgs.ParseParameters(argc, argv, error_message)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message.c_str()); return false; } if (argc < 2 || HelpRequested(gArgs)) { std::string usage = strprintf("%s talkcoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" + "wallet-tool is an offline tool for creating and interacting with Talkcoin Core wallet files.\n" + "By default wallet-tool will act on wallets in the default mainnet wallet directory in the datadir.\n" + "To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" + "Usage:\n" + " talkcoin-wallet [options] <command>\n\n" + gArgs.GetHelpMessage(); tfm::format(std::cout, "%s", usage.c_str()); return false; } // check for printtoconsole, allow -debug LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false)); if (!CheckDataDirOption()) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) SelectParams(gArgs.GetChainName()); return true; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); RandomInit(); try { if (!WalletAppInit(argc, argv)) return EXIT_FAILURE; } catch (const std::exception& e) { PrintExceptionContinue(&e, "WalletAppInit()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "WalletAppInit()"); return EXIT_FAILURE; } std::string method {}; for(int i = 1; i < argc; ++i) { if (!IsSwitchChar(argv[i][0])) { if (!method.empty()) { tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method.c_str(), argv[i]); return EXIT_FAILURE; } method = argv[i]; } } if (method.empty()) { tfm::format(std::cerr, "No method provided. Run `talkcoin-wallet -help` for valid methods.\n"); return EXIT_FAILURE; } // A name must be provided when creating a file if (method == "create" && !gArgs.IsArgSet("-wallet")) { tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n"); return EXIT_FAILURE; } std::string name = gArgs.GetArg("-wallet", ""); ECCVerifyHandle globalVerifyHandle; ECC_Start(); if (!WalletTool::ExecuteWalletToolFunc(method, name)) return EXIT_FAILURE; ECC_Stop(); return EXIT_SUCCESS; }
e877327bf0027b5ad78b8bb6e647a28b55d12d77
09d9b50726c2e5cdc768c57930a84edc984d2a6e
/CSACADEMY/CS_round_55_A.cpp
3c7d0f96d6d644d351201e209b221063bfbc42a4
[]
no_license
omar-sharif03/Competitive-Programming
86b4e99f16a6711131d503eb8e99889daa92b53d
c8bc015af372eeb328c572d16038d0d0aac6bb6a
refs/heads/master
2022-11-15T08:22:08.474648
2020-07-15T12:30:53
2020-07-15T12:30:53
279,789,803
0
0
null
null
null
null
UTF-8
C++
false
false
343
cpp
#include<bits/stdc++.h> using namespace std; int room[110]; int main() { int n,m; cin>>n>>m; for(int i=1;i<=m;i++) cin>>room[i]; int a,b,c; for(int i=1;i<=n;i++){ cin>>a>>b; c=0; for(int j=1;j<=m;j++){ if(room[j]>=a and room[j]<=b)c++; } cout<<c<<endl; } }
a33e1f0821911a67b8f9c5179c5889c7f6db4da7
e5c0c066460aca04a208fef22d44f9a6d1305ebf
/hw2_2/main.cpp
c7b2cd5458658fbd398aab7f6a4d8ea8fcf9c297
[]
no_license
kamanov/cgcourseau2014autumn
453152f94a3653d4efc6802a431ac2147425f0b8
229d6cdef39664f58c618382abfa79514dec5835
refs/heads/master
2020-06-04T14:44:42.727836
2015-02-09T09:12:02
2015-02-09T09:12:02
29,933,839
0
0
null
null
null
null
UTF-8
C++
false
false
199
cpp
#include "widget.h" #include "glwidget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); return 0; }
d64bb5cdc30d6ee2524867643459af1766ea65d0
d04ca01b62c9df153f0bf16748c28cc262ffba09
/USACO/friday.cpp
810ee042204ce255caafdafa13e3797ef8f55b1b
[]
no_license
PradCoder/Programming-Contests
33ae9fc81e26dbb3671d3b674ed293576263fec8
afbedd8d5db22446391a1efe2f954859540e9193
refs/heads/master
2023-01-18T15:26:21.977623
2023-01-18T04:44:20
2023-01-18T04:44:20
140,637,968
0
0
null
null
null
null
UTF-8
C++
false
false
2,301
cpp
/* ID: 2010pes1 TASK: friday LANG: C++ */ #include "bits/stdc++.h" #include <cstdint> #define F first #define S second #define PG push_back #define PPB pop_back #define PF push_front #define MP make_pair #define REP0(i,a,b) for (int i = a; i < b; i++) #define REP1(i,a,b) for (int i = a; i <= b; i++) #define PPC __builtin_popcount #define PPCLL __builtin_popcountll using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; void solveNotLeap(int state, int &n, vi &days){ int i = 1; //SEP,APR,JUN,NOV have 30, FEB has 28 except on leap years its 29 for(int month = 1; month <= 12;){ if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && i == 31){ i = 0; month++; }else if (month == 2 && ((state == 0 && i == 28) || (state == 1 && i == 29))){ i = 0; month++; }else if((month == 4 || month == 6 || month == 9 || month == 11) && i == 30){ i = 0; month++; } if(i == 13){ days[n%7] += 1; } i++; n++; } } int main(){ ios::sync_with_stdio(0); cin.tie(0); ifstream fin ("friday.in"); ofstream fout ("friday.out"); int n; fin >> n; vi days = vi(7); //January 1st 1900 was a Monday //SEP,APR,JUN,NOV have 30, FEB has 28 except on leap years its 29 //All other months have 31 //Every year evenly divisible by 4 is a leap year //The above rule doesn't apply for century years not divisible by 400 int day = 1; for(int i = 0 ; i < n; i++){ if((1900+i)%4 == 0){ if((1900+i)%100 == 0 && (1900+i)%400 == 0){ solveNotLeap(1,day,days); }else if ((1900+i)%100 == 0 && (1900+i)%400 != 0){ solveNotLeap(0,day,days); }else{ solveNotLeap(1,day,days); } }else{ solveNotLeap(0,day,days); } } for(int i = 0; i < 6; i++){ fout << days[(i+6)%7] << " "; } fout << days[(6+6)%7] << "\n"; return 0; }
43ae3189c32b6ac4a708fbbed9d7b9996ab7090a
a9c2e831585f1e66e9619e181743c1b99926f8c7
/ImageCropTest.cpp
f75d14be2ee3015efc75460fa650e040a0e755f6
[]
no_license
header-file/2D_Portfolio_6th
213186880744651427880716e98caecdbd8a5cb0
f746894446cd12d8d7d874c312204431276f3f0a
refs/heads/master
2020-06-02T02:22:43.816665
2019-06-09T12:38:01
2019-06-09T12:38:01
191,005,024
0
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
#include "Game.h" #include "ImageCropTest.h" ImageCropTest::ImageCropTest() { } ImageCropTest::~ImageCropTest() { } bool ImageCropTest::Init() { _background = new Image; _background->Init(TEXT("Image/BackGround.bmp"), WINSIZEX, WINSIZEY); _offsetX = _offsetY = 0; return true; } void ImageCropTest::Release() { SAFE_DELETE(_background); } void ImageCropTest::Update() { if (_offsetX <= 0) _offsetX = 0; if (_offsetY <= 0) _offsetY = 0; if (KEYMANAGER->isStayKeyDown(VK_LEFT)) _offsetX -= 3; if (KEYMANAGER->isStayKeyDown(VK_RIGHT)) _offsetX += 3; if (KEYMANAGER->isStayKeyDown(VK_UP)) _offsetY -= 3; if (KEYMANAGER->isStayKeyDown(VK_DOWN)) _offsetY += 3; } void ImageCropTest::Render(HDC hdc) { _background->Render(hdc, 0, 0); _background->Render(hdc, 100, 100, _offsetX, _offsetY, 200, 200); }
fc445c651c858eeeebf1cf2d8f6e49e503aa4a54
f812cd27b0568316e839f2ab4d6e82e47762db30
/Trabalho/3ºFase/Generator/Patch.cpp
469b22a707f0949da67cb3c9d25b81dd5cef49d4
[]
no_license
Komatsu52/CG
f52eccf841b1f58870db74ed99d3f62e28aeee25
9f9f25864f37e09065ffc26738d138a54f21143e
refs/heads/master
2021-02-12T17:53:40.340113
2020-06-18T05:42:20
2020-06-18T05:42:20
244,614,167
0
3
null
null
null
null
UTF-8
C++
false
false
4,598
cpp
#include "Patch.h" Patch :: Patch(){ } Patch :: Patch(vector<Point> p){ controlPoints = p; } void Patch :: multMatrixVector(float *m, float *v, float *res) { for(int i = 0; i < 4; ++i){ res[i] = 0; for(int j = 0; j < 4; ++j) res[i] += v[j] * m[i * 4 + j]; } } Patch ::Patch(int tess, string file) { tesselation = tess; parsePatchFile(file); } void Patch :: parsePatchFile(string filename) { int i; string line, x, y, z; string fileDir = "../../Files3d/" + filename; ifstream file(fileDir); if(file.is_open()){ getline(file, line); nPatches = stoi(line); for(i = 0; i < nPatches; i++){ vector<int> patchIndex; if(getline(file, line)){ char* str = strdup(line.c_str()); char* token = strtok(str, " ,"); while(token != NULL){ patchIndex.push_back(atoi(token)); token = strtok(NULL, " ,"); } patches[i] = patchIndex; free(str); } else cout << "Incapaz de obter todos os patchIndex." << endl; } getline(file, line); nPoints = stoi(line); for(i = 0; i < nPoints; i++){ if(getline(file, line)){ char* str = strdup(line.c_str()); char* token = strtok(str, " ,"); float xx = atof(token); token = strtok(NULL, " ,"); float yy = atof(token); token = strtok(NULL, " ,"); float zz = atof(token); Point *p = new Point(xx,yy,zz); controlPoints.push_back(*p); free(str); } else cout << "Incapaz de obter todos os controlPoint." << endl; } file.close(); } else cout << "Erro na abertura do ficheiro " << filename << endl; } Point* Patch :: getPoint(float ta, float tb, float (*coordX)[4], float (*coordY)[4], float (*coordZ)[4]) { float x = 0.0f, y = 0.0f, z = 0.0f; float m[4][4] = {{-1.0f, 3.0f, -3.0f, 1.0f}, { 3.0f, -6.0f, 3.0f, 0.0f}, {-3.0f, 3.0f, 0.0f, 0.0f}, { 1.0f, 0.0f, 0.0f, 0.0f}}; float a[4] = { ta*ta*ta, ta*ta, ta, 1.0f}; float b[4] = { tb*tb*tb, tb*tb, tb, 1.0f}; float am[4]; multMatrixVector(*m,a,am); float bm[4]; multMatrixVector(*m,b,bm); float amCoordenadaX[4], amCoordenadaY[4], amCoordenadaZ[4]; multMatrixVector(*coordX,am,amCoordenadaX); multMatrixVector(*coordY,am,amCoordenadaY); multMatrixVector(*coordZ,am,amCoordenadaZ); for (int i = 0; i < 4; i++) { x += amCoordenadaX[i] * bm[i]; y += amCoordenadaY[i] * bm[i]; z += amCoordenadaZ[i] * bm[i]; } Point *p = new Point(x,y,z); return p; } vector<Point> Patch::getPatchPoints(int patch) { vector<Point> points; vector<int> indexesControlPoints = patches.at(patch); float coordenadasX[4][4], coordenadasY[4][4], coordenadasZ[4][4]; float u,v,uu,vv; float t = 1.0f /(float)tesselation; int pos = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Point controlPoint = controlPoints[indexesControlPoints[pos]]; coordenadasX[i][j] = controlPoint.getX(); coordenadasY[i][j] = controlPoint.getY(); coordenadasZ[i][j] = controlPoint.getZ(); pos++; } } for(int i = 0; i < tesselation; i++) { for (int j = 0; j < tesselation; j++) { u = (float)i*t; v = (float)j*t; uu = (float)(i+1)*t; vv = (float)(j+1)*t; Point *p0,*p1,*p2,*p3; p0 = getPoint(u, v, coordenadasX, coordenadasY, coordenadasZ); p1 = getPoint(u, vv, coordenadasX, coordenadasY, coordenadasZ); p2 = getPoint(uu, v, coordenadasX, coordenadasY, coordenadasZ); p3 = getPoint(uu, vv, coordenadasX, coordenadasY, coordenadasZ); points.push_back(*p0); points.push_back(*p2); points.push_back(*p1); points.push_back(*p1); points.push_back(*p2); points.push_back(*p3); } } return points; } vector<Point> Patch :: BezierModelGenerator() { vector<Point> res; for(int i = 0; i < nPatches; i++){ vector<Point> aux = getPatchPoints(i); res.insert(res.end(), aux.begin(), aux.end()); } return res; }
bca3e7f30280e8392253449bc123dfa1f5c6a5bf
dd9ce079241a72419ba13db821f352df90c561d2
/Motor.cpp
04eacefff1e00d3ff92e361df5ed9b2521996301
[ "MIT" ]
permissive
Darival/hbridge-motor
f872e7ca288e7514afe13606fc81a503c56bad8b
5bed29577a84c55126ddac7af76b31e8ad73c094
refs/heads/master
2021-07-17T11:57:29.554868
2017-10-25T06:18:54
2017-10-25T06:18:54
108,227,641
1
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
#include "Arduino.h" #include "Motor.h" Motor::Motor(int pinA, int pinB) { pinMode(pinA, OUTPUT); pinMode(pinB, OUTPUT); _pinA = pinA; _pinB = pinB; digitalWrite(_pinA, LOW); digitalWrite(_pinB, LOW); } void Motor::brake(){ digitalWrite(_pinA, LOW); digitalWrite(_pinB, LOW); } void Motor::fordward(){ digitalWrite(_pinA, HIGH); digitalWrite(_pinB, LOW); }; void Motor::backward(){ digitalWrite(_pinA, LOW); digitalWrite(_pinB, HIGH); }; bool Motor::isMoving(){ return digitalRead(_pinA) != digitalRead(_pinB); }; bool Motor::isMovingFordward(){ return digitalRead(_pinA) == 1 && digitalRead(_pinB) == 0; }; bool Motor::isMovingBackward(){ return digitalRead(_pinA) == 0 && digitalRead(_pinB) == 1; };
af3ace7b92c73c5c73d47f92ebb17e875b83829b
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/quic/core/frames/quic_padding_frame.h
93fb990c451570b9d9ba6418ee8b116de20dd758
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
939
h
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_ #define NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_ #include <cstdint> #include <ostream> #include "net/quic/platform/api/quic_export.h" namespace net { // A padding frame contains no payload. struct QUIC_EXPORT_PRIVATE QuicPaddingFrame { QuicPaddingFrame() : num_padding_bytes(-1) {} explicit QuicPaddingFrame(int num_padding_bytes) : num_padding_bytes(num_padding_bytes) {} friend QUIC_EXPORT_PRIVATE std::ostream& operator<<( std::ostream& os, const QuicPaddingFrame& s); // -1: full padding to the end of a max-sized packet // otherwise: only pad up to num_padding_bytes bytes int num_padding_bytes; }; } // namespace net #endif // NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_
59b9a6f8195324e7fc5f637d7d56740d79a969b3
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/crashpad/crashpad/util/linux/ptrace_broker_test.cc
0b9e917c943a14420885713d934dc91dde9bce4f
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
8,568
cc
// Copyright 2017 The Crashpad Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/linux/ptrace_broker.h" #include <sys/socket.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <utility> #include "build/build_config.h" #include "gtest/gtest.h" #include "test/filesystem.h" #include "test/linux/get_tls.h" #include "test/multiprocess.h" #include "test/scoped_temp_dir.h" #include "util/file/file_io.h" #include "util/linux/ptrace_client.h" #include "util/posix/scoped_mmap.h" #include "util/synchronization/semaphore.h" #include "util/thread/thread.h" namespace crashpad { namespace test { namespace { class ScopedTimeoutThread : public Thread { public: ScopedTimeoutThread() : join_sem_(0) {} ScopedTimeoutThread(const ScopedTimeoutThread&) = delete; ScopedTimeoutThread& operator=(const ScopedTimeoutThread&) = delete; ~ScopedTimeoutThread() { EXPECT_TRUE(JoinWithTimeout(5.0)); } protected: void ThreadMain() override { join_sem_.Signal(); } private: bool JoinWithTimeout(double timeout) { if (!join_sem_.TimedWait(timeout)) { return false; } Join(); return true; } Semaphore join_sem_; }; class RunBrokerThread : public ScopedTimeoutThread { public: RunBrokerThread(PtraceBroker* broker) : ScopedTimeoutThread(), broker_(broker) {} RunBrokerThread(const RunBrokerThread&) = delete; RunBrokerThread& operator=(const RunBrokerThread&) = delete; ~RunBrokerThread() {} private: void ThreadMain() override { EXPECT_EQ(broker_->Run(), 0); ScopedTimeoutThread::ThreadMain(); } PtraceBroker* broker_; }; class BlockOnReadThread : public ScopedTimeoutThread { public: BlockOnReadThread(int readfd, int writefd) : ScopedTimeoutThread(), readfd_(readfd), writefd_(writefd) {} BlockOnReadThread(const BlockOnReadThread&) = delete; BlockOnReadThread& operator=(const BlockOnReadThread&) = delete; ~BlockOnReadThread() {} private: void ThreadMain() override { pid_t pid = syscall(SYS_gettid); LoggingWriteFile(writefd_, &pid, sizeof(pid)); LinuxVMAddress tls = GetTLS(); LoggingWriteFile(writefd_, &tls, sizeof(tls)); CheckedReadFileAtEOF(readfd_); ScopedTimeoutThread::ThreadMain(); } int readfd_; int writefd_; }; class SameBitnessTest : public Multiprocess { public: SameBitnessTest() : Multiprocess(), mapping_() {} SameBitnessTest(const SameBitnessTest&) = delete; SameBitnessTest& operator=(const SameBitnessTest&) = delete; ~SameBitnessTest() {} protected: void PreFork() override { ASSERT_NO_FATAL_FAILURE(Multiprocess::PreFork()); size_t page_size = getpagesize(); ASSERT_TRUE(mapping_.ResetMmap(nullptr, page_size * 3, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0)); ASSERT_TRUE(mapping_.ResetAddrLen(mapping_.addr(), page_size * 2)); auto buffer = mapping_.addr_as<char*>(); for (size_t index = 0; index < mapping_.len(); ++index) { buffer[index] = index % 256; } } private: void BrokerTests(bool set_broker_pid, LinuxVMAddress child1_tls, LinuxVMAddress child2_tls, pid_t child2_tid, const base::FilePath& file_dir, const base::FilePath& test_file, const std::string& expected_file_contents) { int socks[2]; ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, socks), 0); ScopedFileHandle broker_sock(socks[0]); ScopedFileHandle client_sock(socks[1]); #if defined(ARCH_CPU_64_BITS) constexpr bool am_64_bit = true; #else constexpr bool am_64_bit = false; #endif // ARCH_CPU_64_BITS PtraceBroker broker( broker_sock.get(), set_broker_pid ? ChildPID() : -1, am_64_bit); RunBrokerThread broker_thread(&broker); broker_thread.Start(); PtraceClient client; ASSERT_TRUE(client.Initialize(client_sock.get(), ChildPID())); EXPECT_EQ(client.GetProcessID(), ChildPID()); std::vector<pid_t> threads; ASSERT_TRUE(client.Threads(&threads)); EXPECT_EQ(threads.size(), 2u); if (threads[0] == ChildPID()) { EXPECT_EQ(threads[1], child2_tid); } else { EXPECT_EQ(threads[0], child2_tid); EXPECT_EQ(threads[1], ChildPID()); } EXPECT_TRUE(client.Attach(child2_tid)); EXPECT_EQ(client.Is64Bit(), am_64_bit); ThreadInfo info1; ASSERT_TRUE(client.GetThreadInfo(ChildPID(), &info1)); EXPECT_EQ(info1.thread_specific_data_address, child1_tls); ThreadInfo info2; ASSERT_TRUE(client.GetThreadInfo(child2_tid, &info2)); EXPECT_EQ(info2.thread_specific_data_address, child2_tls); auto expected_buffer = mapping_.addr_as<char*>(); char first; ASSERT_EQ( client.ReadUpTo(mapping_.addr_as<VMAddress>(), sizeof(first), &first), 1); EXPECT_EQ(first, expected_buffer[0]); char last; ASSERT_EQ( client.ReadUpTo(mapping_.addr_as<VMAddress>() + mapping_.len() - 1, sizeof(last), &last), 1); EXPECT_EQ(last, expected_buffer[mapping_.len() - 1]); char unmapped; EXPECT_EQ(client.ReadUpTo(mapping_.addr_as<VMAddress>() + mapping_.len(), sizeof(unmapped), &unmapped), -1); std::string file_root = file_dir.value() + '/'; broker.SetFileRoot(file_root.c_str()); std::string file_contents; ASSERT_TRUE(client.ReadFileContents(test_file, &file_contents)); EXPECT_EQ(file_contents, expected_file_contents); ScopedTempDir temp_dir2; base::FilePath test_file2(temp_dir2.path().Append("test_file2")); ASSERT_TRUE(CreateFile(test_file2)); EXPECT_FALSE(client.ReadFileContents(test_file2, &file_contents)); } void MultiprocessParent() override { LinuxVMAddress child1_tls; ASSERT_TRUE(LoggingReadFileExactly( ReadPipeHandle(), &child1_tls, sizeof(child1_tls))); pid_t child2_tid; ASSERT_TRUE(LoggingReadFileExactly( ReadPipeHandle(), &child2_tid, sizeof(child2_tid))); LinuxVMAddress child2_tls; ASSERT_TRUE(LoggingReadFileExactly( ReadPipeHandle(), &child2_tls, sizeof(child2_tls))); ScopedTempDir temp_dir; base::FilePath file_path(temp_dir.path().Append("test_file")); std::string expected_file_contents; { expected_file_contents.resize(4097); for (size_t i = 0; i < expected_file_contents.size(); ++i) { expected_file_contents[i] = static_cast<char>(i % 256); } ScopedFileHandle handle( LoggingOpenFileForWrite(file_path, FileWriteMode::kCreateOrFail, FilePermissions::kWorldReadable)); ASSERT_TRUE(LoggingWriteFile(handle.get(), expected_file_contents.data(), expected_file_contents.size())); } BrokerTests(true, child1_tls, child2_tls, child2_tid, temp_dir.path(), file_path, expected_file_contents); BrokerTests(false, child1_tls, child2_tls, child2_tid, temp_dir.path(), file_path, expected_file_contents); } void MultiprocessChild() override { LinuxVMAddress tls = GetTLS(); ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), &tls, sizeof(tls))); BlockOnReadThread thread(ReadPipeHandle(), WritePipeHandle()); thread.Start(); CheckedReadFileAtEOF(ReadPipeHandle()); } ScopedMmap mapping_; }; TEST(PtraceBroker, SameBitness) { SameBitnessTest test; test.Run(); } // TODO(jperaza): Test against a process with different bitness. } // namespace } // namespace test } // namespace crashpad
3df84a4828343df699e6734c430745b208531f78
ac0eac58bfff89e236ed152ba8853c672dfa0f17
/Laborator 2 - Gramatici/Gramatica.h
d09a73cad490b341fbbf35708df0640d61382f19
[]
no_license
robert-adrian99/FormalLanguagesAndCompilers
6e58b6806b73940fc444e6c86ddaf060a351a17c
f5d68906b5b7b6050a3561d398d053d2fe434c62
refs/heads/master
2022-04-12T12:24:03.273663
2020-03-12T18:31:37
2020-03-12T18:31:37
246,121,823
0
1
null
null
null
null
UTF-8
C++
false
false
480
h
#pragma once #include <iostream> #include <fstream> #include <vector> #include <random> #include <time.h> class Gramatica { public: Gramatica(); void citire(); void afisare(); int verificare(); void generare(bool optiune); private: void productiiAplicabile(const std::string& cuvantGenerat, std::vector<int>& prodAplicabile); private: std::vector<char> VN; std::vector<char> VT; char S; std::vector<std::string> prodStanga; std::vector<std::string> prodDreapta; };
c2ec7e9e7994f3d5fd8590ce7254dfb8c4d1b1af
e4e9d9e089ce7b6987c542d359df5c74d9b19e2d
/TemSensor/Storage.h
489747e7ffdfb5170219e7b03ffeaff23d2eb837
[]
no_license
DZdream64/TemSensor
fcc4a76fc52345d5b6a68097ea5ea787921642b7
bf71e022fd1ddd99bf509e99f73438984c520329
refs/heads/master
2021-01-18T14:14:12.437597
2016-04-19T04:08:29
2016-04-19T04:08:29
56,556,702
0
0
null
2016-04-19T02:04:12
2016-04-19T02:04:11
null
UTF-8
C++
false
false
117
h
#pragma once class CStorage { public: CStorage(); virtual ~CStorage(); public: virtual int storageData() = 0; };
9fb76c7d3cf96b9fe20d9e1e8f2a10f0c9e29aeb
003675a2e2be3f835efd723626f0ee6d862e914f
/Codeforces/A/466A.cpp
5584cc9644565bcc0e8ffa5b49cc9349b86b37b0
[]
no_license
AkibShahrear/Competitive-Programming
6f4b26af1ae011d3cf45885dc86c4f64fca4334d
7fba94f669881dd7e7cb63b264c288c380c5d544
refs/heads/main
2023-08-12T16:57:41.020418
2021-10-18T19:49:44
2021-10-18T19:49:44
323,955,265
0
0
null
2020-12-23T17:17:59
2020-12-23T16:49:51
null
UTF-8
C++
false
false
404
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,m,a,b,p=0,k; cin>>n>>m>>a>>b; k=b/m; if(k==a) { cout<<n*a; } else if(k<a) { int j=(n/m)*b; int c=n%m; int l=c*a; if(l>b){ cout<<j+b; } else{ cout<<j+l; } } else{ cout<<n*a; } }
41cb15b26a2cc28c060023b9ab6d1a22027645bb
5530d7a83cf7e7538452f8073c5a8902a0ff1616
/_archive_cpp/source/synthese_additive_decisionnelle.h
38517d83724b821cc07e81c9852e85a00c0b72bf
[ "MIT" ]
permissive
overetou/synthe_alea
eb7aa430e55b35c6d405e431ae9fd17eaa3f1c68
3f1e6ba3eb90f70bc7a475f092d2d160089e758e
refs/heads/master
2020-03-27T03:54:59.243487
2018-11-04T15:45:32
2018-11-04T15:45:32
145,898,440
1
1
MIT
2018-09-10T08:51:01
2018-08-23T19:31:36
C++
UTF-8
C++
false
false
14,017
h
#pragma once #include <vector> #include <algorithm> #include <functional> #include <iostream> #include <fstream> #define PI 3.1427 namespace synthese_additive_decisionnelle { #pragma region Base de données // A FAIRE : // - paramètres pour caractériser les spectres // - organisation du fichier texte // Ajoute un nouveau spectre à la collection et en calcule les paramètres bool ajouter_spectre_dans_la_collection( const std::vector<double> &amplitudes_brutes, const std::vector<double> &frequences_brutes, const double hauteur_enregistrement) { if (amplitudes_brutes.size() != frequences_brutes.size()) return false; // Pas le même nombre de points if (hauteur_enregistrement < 0) return false; // Fréquence négative std::vector<std::pair<double, double>> partiels; for (std::size_t i_partiel = 0; i_partiel < amplitudes_brutes.size(); i_partiel++) { partiels.push_back({ amplitudes_brutes[i_partiel], frequences_brutes[i_partiel] }); } // Etalonnage des amplitudes double max_amplitude = 0; for (std::size_t i_amplitude = 0; i_amplitude < partiels.size(); i_amplitude++) { max_amplitude = std::fmax(max_amplitude, partiels[i_amplitude].first); } std::transform( partiels.begin(), partiels.end(), partiels.begin(), std::bind(diviser_amplitudes, std::placeholders::_1, max_amplitude)); // Transformation des fréquences en ratios par rapport à la hauteur d'enregistrement std::transform( partiels.begin(), partiels.end(), partiels.begin(), std::bind(diviser_frequences, std::placeholders::_1, hauteur_enregistrement)); // Calcul de la puissance du spectre // Calcul de la dispersion du spectre //... autres paramètres ? double ecart_inharmonique; double somme_ecarts = 0; for (std::size_t i_partiel; i_partiel < partiels.size(); i_partiel++) { ecart_inharmonique = std::fmin(std::fmod(partiels[i_partiel].second, hauteur_enregistrement), std::fabs(hauteur_enregistrement - std::fmod(partiels[i_partiel].second, hauteur_enregistrement))) / hauteur_enregistrement; somme_ecarts += ecart_inharmonique * partiels[i_partiel].first; } double somme_amplitudes = 0; for (std::size_t i_partiel; i_partiel < partiels.size(); i_partiel++) { somme_amplitudes += partiels[i_partiel].first; } somme_ecarts /= somme_amplitudes; // Théorème de Rolle pour nettoyer le spectre for (std::size_t i_partiel = 1; i_partiel < partiels.size(); i_partiel++) { if (!(partiels.at(i_partiel++).first - partiels.at(i_partiel).first < 0 && 0 < partiels.at(i_partiel).first - partiels.at(i_partiel--).first)) { partiels.at(i_partiel).first = 0; } } // Tri par amplitude décroissante des partiels du spectre std::sort( partiels.begin(), partiels.end(), trier_partiels_amplitudes_descendant); // Ajout du nouveau spectre à la collection spectre nouveau_spectre; nouveau_spectre.partiels = partiels; collection_spectres.push_back(nouveau_spectre); return true; } // Charge la collection depuis un fichier sérialisé bool charger_collection_spectres(const std::string &url_collection) { std::ifstream lecture_fichier; lecture_fichier.open(url_collection, std::ios::in); if (!lecture_fichier.is_open()) return false; else { // charge le contenu du fichier dans collection_spectres //ajouter_spectre(); } lecture_fichier.close(); return true; } // Sauvegarde la collection vers un fichier sérialisé bool sauvegarder_collection_spectres(const std::string &url_collection) { std::ofstream ecriture_fichier; ecriture_fichier.open(url_collection, std::ios::out); if (!ecriture_fichier.is_open()) return false; ecriture_fichier << "nom_collection = " << url_collection << std::endl; ecriture_fichier << "nombre_spectres = " << collection_spectres.size() << std::endl; ecriture_fichier << std::endl; // Ecriture des spectres for (std::size_t i_spectre = 0; i_spectre < collection_spectres.size(); i_spectre++) { ecriture_fichier << "indice_spectre = " << i_spectre << std::endl; ecriture_fichier << std::endl; // Ecriture des amplitudes ecriture_fichier << "amplitudes = " << std::endl; for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++) { ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].first << std::endl; } ecriture_fichier << std::endl; // Ecriture des fréquences ecriture_fichier << "frequences = " << std::endl; for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++) { ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].second << std::endl; } ecriture_fichier << std::endl; // Ecriture des caractéristiques ecriture_fichier << "puissance = " << collection_spectres[i_spectre].puissance << std::endl; ecriture_fichier << "dispersion = " << collection_spectres[i_spectre].dispersion << std::endl; ecriture_fichier << std::endl; } ecriture_fichier.close(); return true; } #pragma endregion #pragma region IA décisionnelle // Construire le spectre évolutif dans le temps avec les spectres les plus appropriés bool calcul_collection_oscillateurs( const std::vector<double> &indices_temporels, const std::vector<double> &evolution_puissance, const std::vector<double> &evolution_dispersion, const std::size_t nombre_oscillateurs) { // Tests // std::size_t nombre_spectres = indices_temporels.size(); // Trouver pour chaque point temporel le spectre le plus approprié en fonction des paramètres de l'utilisateur à ce point // std::vector<std::vector<std::pair<double, double>>> spectres_selectionnes(indices_temporels.size()); for (std::size_t i_spectre = 0; i_spectre < spectres_selectionnes.size(); i_spectre++) { // On commence par ne garder que le bon nombre d'oscillateurs spectres_selectionnes[i_spectre].resize(nombre_oscillateurs); // Suivi des oscillateurs if (i_spectre > 0) { // Parcourt le spectre précédent for (std::size_t i_partiel = 0; i_partiel < nombre_oscillateurs; i_partiel++) { double min_ecart = 10000; std::size_t indice_min_ecart; // Trouve le partiel le plus proche dans le spectre actuel for (std::size_t ii_partiel = i_partiel; ii_partiel < nombre_oscillateurs; ii_partiel++) { double ecart = std::fabs(spectres_selectionnes[i_spectre][ii_partiel].second - spectres_selectionnes[i_spectre - 1][i_partiel].second); if (ecart < min_ecart) { min_ecart = ecart; indice_min_ecart = ii_partiel; } } // Modifier le spectre actuel pour replacer le partiel le plus proche sur la meme ligne que dans le spectre précédent // retirer le trouvé du vecteur à spectres_selectionnes[i_spectre][indice_min_ecart] // le rajouter à la position voulue spectres_selectionnes[i_spectre][i_partiel] } } } // Construction de la matrice d'interpolation de Vandermonde avec les indices temporels // Initialisation std::vector<std::vector<std::size_t>> matrice_interpolation(2 * nombre_spectres); for (std::size_t i_rang = 0; i_rang < 2 * nombre_spectres; i_rang++) matrice_interpolation[i_rang].resize(nombre_spectres); // Remplissage for (std::size_t i_rang = 0; i_rang < 2 * nombre_spectres; i_rang++) { for (std::size_t i_colonne = 0; i_colonne < nombre_spectres; i_colonne++) { // Augmentation de la matrice if (i_rang < nombre_spectres) { if (i_rang == i_colonne) matrice_interpolation[i_rang][i_colonne] = 1; else matrice_interpolation[i_rang][i_colonne] = 0; } // Matrice de Vandermonde else { matrice_interpolation[nombre_spectres + i_rang][i_colonne] = 0; } } } // Inversion de la matrice d'interpolation // Algorithme de gauss // Calcul pour chaque oscillateur des coefficients du polynôme d'interpolation for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++) { // Pour les amplitudes // A^-1 * a // Pour les fréquences // A^-1 * f } } #pragma endregion #pragma region Synthèse additive enum parmetres_synthese { parametre_frequence_echantillonnage, parametre_gain }; // Modifie un paramètre de la synthèse bool modifier_parametre_synthese(const std::size_t parametre, const double valeur) { switch (parametre) { case parametre_frequence_echantillonnage: frequence_echantillonnage = (int)valeur; case parametre_gain: gain = (double)valeur; } return true; } // Charge la collection depuis un fichier texte bool charger_collection_oscillateurs(const std::string &url_collection) { std::ifstream lecture_fichier; lecture_fichier.open(url_collection, std::ios::in); if (!lecture_fichier.is_open()) return false; // lire nombre oscillateurs // lire nombre coefficients std::size_t nombre_oscillateurs; std::size_t nombre_coefficients; // Resize de la collection d'oscillateurs collection_oscillateurs.resize(nombre_oscillateurs); for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++) { collection_oscillateurs[i_oscillateur].resize(nombre_coefficients); } for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++) { // verifier l'indice // Lecture des amplitudes for (std::size_t i_coefficient = 0; i_coefficient < nombre_coefficients; i_coefficient++) { lecture_fichier >> collection_oscillateurs[i_oscillateur][i_coefficient].first; } // // Lecture des fréquences for (std::size_t i_coefficient = 0; i_coefficient < nombre_coefficients; i_coefficient++) { lecture_fichier >> collection_oscillateurs[i_oscillateur][i_coefficient].second; } } lecture_fichier.close(); return true; } // Sauvegarde la collection vers un fichier texte bool sauvegarder_collection_oscillateurs(const std::string &url_collection) // faire les 3 autres comme celui-là { std::ofstream ecriture_fichier; ecriture_fichier.open(url_collection, std::ios::out); if (!ecriture_fichier.is_open()) return false; ecriture_fichier << "nom_preset =" << url_collection << std::endl; ecriture_fichier << "nombre_oscillateurs = " << collection_oscillateurs.size() << std::endl; ecriture_fichier << "nombre_coefficients = " << collection_oscillateurs[0].size() << std::endl; ecriture_fichier << std::endl; // Ecriture des oscillateurs for (std::size_t i_oscillateur = 0; i_oscillateur < collection_oscillateurs.size(); i_oscillateur++) { ecriture_fichier << "indice_oscillateur = " << i_oscillateur << std::endl; ecriture_fichier << std::endl; // Ecriture des amplitudes ecriture_fichier << "amplitudes = " << std::endl; for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs.size(); i_coefficient++) { ecriture_fichier << collection_oscillateurs[i_oscillateur][i_coefficient].first << std::endl; } ecriture_fichier << std::endl; // Ecriture des fréquences ecriture_fichier << "frequences = " << std::endl; for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs.size(); i_coefficient++) { ecriture_fichier << collection_oscillateurs[i_oscillateur][i_coefficient].second << std::endl; } ecriture_fichier << std::endl; } ecriture_fichier.close(); return true; } // Synthétise le son en temps réel depuis les polynômes d'interpolation double synthese(const std::size_t indice_echantillon, const double frequence, const double velocite) { if (collection_oscillateurs.size() == 0) return false; // Collection d'oscillateurs pas encore chargée double indice_temporel; // f de indice_echantillon, frequence_echantillonnage double indice_puissance; double oscillateur_amplitude; double oscillateur_frequence; double somme_oscillateurs = 0; for (std::size_t i_oscillateur = 0; i_oscillateur < collection_oscillateurs.size(); i_oscillateur++) { oscillateur_amplitude = 0; oscillateur_frequence = 0; for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs[i_oscillateur].size(); i_coefficient++) { indice_puissance = std::pow(indice_temporel, i_coefficient); oscillateur_amplitude += collection_oscillateurs[i_oscillateur][i_coefficient].first * velocite * indice_puissance; oscillateur_frequence += collection_oscillateurs[i_oscillateur][i_coefficient].second * frequence * indice_puissance; } somme_oscillateurs += oscillateur_amplitude * std::sin(2 * PI * oscillateur_frequence * indice_temporel); } if (std::abs(somme_oscillateurs) > 1) gain = 1 / std::abs(somme_oscillateurs); return somme_oscillateurs * gain; } #pragma endregion #pragma region Private scope namespace { // Spectres struct spectre { std::vector<std::pair<double, double>> partiels; // On utilise .first : amplitudes et .second : fréquences // Paramètres caractérisant le spectre double puissance; double dispersion; }; std::vector<spectre> collection_spectres; double diviser_amplitudes( const std::pair<double, double> &a, const double b) { return (a.first / b); } double diviser_frequences( const std::pair<double, double> &a, const double b) { return (a.second / b); } // Trier les partiels par ordre décroissant d'amplitude bool trier_partiels_amplitudes_descendant( const std::pair<double, double> &partiel_a, const std::pair<double, double> &partiel_b) { return (partiel_a.first > partiel_b.first); } // Oscillateurs [i_oscillateur][i_coefficient_lagrange].first / .second std::vector<std::vector<std::pair<double, double>>> collection_oscillateurs; // Paramètres de la synthèse std::size_t frequence_echantillonnage = 44100; double gain = 1; struct note { std::size_t midi_note; std::size_t midi_velocity; }; } #pragma endregion }
6dafb1709f149638caa18a42e0134cb622c96851
b5e8910a20789df489b4c2dff68f1a4f98c91d52
/SingleCoreLib/scl/UniqueId.h
336e4bd7d599ca9ec0ab82aa5e15ad488708c41a
[]
no_license
acoross/ComponentModel2
152fd27e3865ed833f7b99e660eb09f2a5a9d7c3
c8f182620dba3120b38c7d4af7de6beaac4a1a78
refs/heads/master
2021-01-23T00:53:18.470496
2017-06-16T16:41:23
2017-06-16T16:41:23
85,846,051
0
0
null
null
null
null
UTF-8
C++
false
false
180
h
#pragma once namespace scl { template <class T, class Siz = int> class UniqueId { public: static Siz Generate() { static Siz uid = 0; ++uid; return uid; } }; }
5b76d2b6dbb8cd9ce3d23aee21717d75aa134317
d5343dc299a6185326f9af2aab69987a95108633
/src/channel_access/server/cas/convert.hpp
d210e9998ad4ab23b0d2f66761bc0785012b78c4
[ "MIT" ]
permissive
delta-accelerator/channel_access.server
e90b4017954b47f4d57fe78e32de29742c81df74
d5f0456bc37bbe80b9d105e84f9dc43a6b438b78
refs/heads/master
2023-02-27T19:41:12.386811
2022-08-16T12:51:54
2022-08-16T12:51:54
189,587,814
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
hpp
#ifndef INCLUDE_GUARD_120C2201_BD9B_465C_B2BD_70FE4AA4A6BD #define INCLUDE_GUARD_120C2201_BD9B_465C_B2BD_70FE4AA4A6BD #include <Python.h> #include <casdef.h> namespace cas { /** Convert ExistsResponse enum value to pvExistsReturn value */ bool to_exist_return(PyObject* value, pvExistReturn& result); /** Convert AttachResponse to pvAttachReturn value */ bool to_attach_return(PyObject* value, pvAttachReturn& result); /** convert FieldType enum value to aitEnum value */ bool to_ait_enum(PyObject* value, aitEnum& result); /** convert python value to gdd value * use type as the value type. * convert any sequence to an array. */ bool to_gdd(PyObject* dict, aitEnum type, gdd &result); /** convert a gdd value to a python value * If compiled without numpy support, numpy is always false. * For array values: * if numpy is true create a numpy array otherwise create a tuple. */ PyObject* from_gdd(gdd const& value, bool numpy = false); /** convert python Trigger value to caEvent mask value */ bool to_event_mask(PyObject* value, casEventMask& mask, caServer const& server); } #endif
55d86ad99cc08478834634f2d5d598b3a1473b0a
04fee3ff94cde55400ee67352d16234bb5e62712
/7.20/source/Stu-27-爆零Starlight/massage.cpp
0da5cb840b091374ea29853f4b4f01a20428c598
[]
no_license
zsq001/oi-code
0bc09c839c9a27c7329c38e490c14bff0177b96e
56f4bfed78fb96ac5d4da50ccc2775489166e47a
refs/heads/master
2023-08-31T06:14:49.709105
2021-09-14T02:28:28
2021-09-14T02:28:28
218,049,685
1
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
#include<bits/stdc++.h> using namespace std; int a1[10010],a2[10010]; int main(){ freopen("massage.in","r",stdin); freopen("massage.out","w",stdout); int n,q; cin>>n>>q; for(int i=1;i<=n;++i){ cin>>a1[i]>>a2[i]; } if(n==3&&q==1) cout<<"20\n1033-1039-1049-1249-1279-5279-5179-8179\n20\n1373-3373-3343-3347-5347-5147-8147-8117-8017\n0\n1033"; else if(n==3&&q==0) cout<<"20\n20\n0"; return 0; }
26c3ae62bfd349461b5d69bce7d9f21cc5395ee6
a9736224708f049c901292a1afa508356fed4a35
/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_framework_legalize_to_llvm.cc
3f64642156953f1d442a5214af7bba66862cb4b6
[ "MIT", "Apache-2.0", "BSD-2-Clause" ]
permissive
rammya29/tensorflow
d2fae99544a87ef44ead761b3326bd6df12af46b
3795efc9294b52c123a266ebf14e60dad18f40a3
refs/heads/master
2023-06-22T21:09:23.465097
2021-07-14T06:53:27
2021-07-14T06:57:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,367
cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string> #include "llvm/Support/FormatVariadic.h" #include "mlir/Conversion/LLVMCommon/Pattern.h" // from @llvm-project #include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" namespace mlir { namespace kernel_gen { namespace tf_framework { namespace { using LLVM::LLVMFuncOp; static constexpr StringRef kCInterfaceAlloc = "_mlir_ciface_tf_alloc"; static constexpr StringRef kCInterfaceDealloc = "_mlir_ciface_tf_dealloc"; static constexpr StringRef kCInterfaceReportError = "_mlir_ciface_tf_report_error"; /// Base class for patterns converting TF Framework ops to function calls. template <typename OpTy> class ConvertToLLVMCallOpPattern : public ConvertOpToLLVMPattern<OpTy> { public: using ConvertOpToLLVMPattern<OpTy>::ConvertOpToLLVMPattern; // Attempts to find function symbol in the module, adds it if not found. FlatSymbolRefAttr getOrInsertTFFunction(PatternRewriter &rewriter, Operation *op) const { ModuleOp module = op->getParentOfType<ModuleOp>(); StringRef tf_func_name = GetFuncName(); auto tf_func = module.lookupSymbol<LLVMFuncOp>(tf_func_name); if (!tf_func) { OpBuilder::InsertionGuard guard(rewriter); rewriter.setInsertionPointToStart(module.getBody()); auto func_type = GetFuncType(); tf_func = rewriter.create<LLVMFuncOp>(rewriter.getUnknownLoc(), tf_func_name, func_type); } return SymbolRefAttr::get(rewriter.getContext(), tf_func_name); } protected: virtual StringRef GetFuncName() const = 0; virtual Type GetFuncType() const = 0; }; class TFAllocOpConverter : public ConvertToLLVMCallOpPattern<TFAllocOp> { public: using ConvertToLLVMCallOpPattern<TFAllocOp>::ConvertToLLVMCallOpPattern; LogicalResult matchAndRewrite( TFAllocOp tf_alloc_op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { mlir::Operation *op = tf_alloc_op.getOperation(); Location loc = op->getLoc(); TFAllocOp::Adaptor transformed(operands); MemRefType memref_type = tf_alloc_op.getType(); // Get memref descriptor sizes. SmallVector<Value, 4> sizes; SmallVector<Value, 4> strides; Value sizeBytes; getMemRefDescriptorSizes(loc, memref_type, llvm::to_vector<4>(transformed.dyn_sizes()), rewriter, sizes, strides, sizeBytes); // Get number of elements. Value num_elements = getNumElements(loc, sizes, rewriter); // Get element size. Value element_size = getSizeInBytes(loc, memref_type.getElementType(), rewriter); // Convert `output_index` or set it to -1 if the attribute is missing. Type llvmInt32Type = IntegerType::get(rewriter.getContext(), 32); Value output_index = rewriter.create<LLVM::ConstantOp>( loc, llvmInt32Type, rewriter.getI32IntegerAttr(tf_alloc_op.output_index().hasValue() ? tf_alloc_op.output_index().getValue() : -1)); // Convert `candidate_input_indices`. auto candidates_count_and_ptr = ConvertI32ArrayAttrToStackAllocatedArray( loc, tf_alloc_op.input_indices(), &rewriter); // Insert function call. FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op); Value allocated_byte_ptr = rewriter .create<LLVM::CallOp>( loc, getVoidPtrType(), tf_func_ref, llvm::makeArrayRef({transformed.ctx(), num_elements, element_size, output_index, candidates_count_and_ptr.first, candidates_count_and_ptr.second})) .getResult(0); MemRefDescriptor memRefDescriptor = CreateMemRefDescriptor( loc, rewriter, memref_type, allocated_byte_ptr, sizes); // Return the final value of the descriptor. rewriter.replaceOp(op, {memRefDescriptor}); return success(); } protected: StringRef GetFuncName() const override { return kCInterfaceAlloc; } Type GetFuncType() const override { Type llvm_i32_type = IntegerType::get(getDialect().getContext(), 32); Type llvm_i32_ptr_type = LLVM::LLVMPointerType::get(llvm_i32_type); Type llvm_void_ptr_type = getVoidPtrType(); return LLVM::LLVMFunctionType::get( llvm_void_ptr_type, llvm::makeArrayRef( {/*void* op_kernel_ctx*/ llvm_void_ptr_type, /*size_t num_elements*/ getIndexType(), /*size_t element_size*/ getIndexType(), /*int32_t output_index*/ llvm_i32_type, /*int32_t num_candidates*/ llvm_i32_type, /*int32_t* candidate_input_indices*/ llvm_i32_ptr_type})); } private: // TODO(pifon): Remove strides computation. MemRefDescriptor CreateMemRefDescriptor(Location loc, ConversionPatternRewriter &rewriter, MemRefType memref_type, Value allocated_byte_ptr, ArrayRef<Value> sizes) const { auto memref_desc = MemRefDescriptor::undef( rewriter, loc, typeConverter->convertType(memref_type)); // TF AllocateRaw returns aligned pointer => AllocatedPtr == AlignedPtr. Value allocated_type_ptr = rewriter.create<LLVM::BitcastOp>( loc, getElementPtrType(memref_type), allocated_byte_ptr); memref_desc.setAllocatedPtr(rewriter, loc, allocated_type_ptr); memref_desc.setAlignedPtr(rewriter, loc, allocated_type_ptr); memref_desc.setConstantOffset(rewriter, loc, 0); if (memref_type.getRank() == 0) { return memref_desc; } // Compute strides and populate descriptor `size` and `stride` fields. Value stride_carried = createIndexConstant(rewriter, loc, 1); for (int pos = sizes.size() - 1; pos >= 0; --pos) { Value size = sizes[pos]; memref_desc.setSize(rewriter, loc, pos, size); memref_desc.setStride(rewriter, loc, pos, stride_carried); // Update stride if (pos > 0) { stride_carried = rewriter.create<LLVM::MulOp>(loc, stride_carried, size); } } return memref_desc; } std::pair<Value, Value> ConvertI32ArrayAttrToStackAllocatedArray( Location loc, llvm::Optional<ArrayAttr> attr, ConversionPatternRewriter *rewriter) const { Type llvm_i32_type = IntegerType::get(getDialect().getContext(), 32); Type llvm_i32_ptr_type = LLVM::LLVMPointerType::get(llvm_i32_type); // If the attribute is missing or empty, set the element count to 0 and // return NULL. if (!attr.hasValue() || attr.getValue().empty()) { Value zero = rewriter->create<LLVM::ConstantOp>( loc, llvm_i32_type, rewriter->getI32IntegerAttr(0)); Value null_ptr = rewriter->create<LLVM::NullOp>(loc, llvm_i32_ptr_type); return std::make_pair(zero, null_ptr); } // Allocate array to store the elements. auto &array_attr = attr.getValue(); Value array_size = rewriter->create<LLVM::ConstantOp>( loc, llvm_i32_type, rewriter->getI32IntegerAttr(array_attr.size())); Value array_ptr = rewriter->create<LLVM::AllocaOp>( loc, llvm_i32_ptr_type, array_size, /*alignment=*/0); for (auto &dim : llvm::enumerate(array_attr)) { Value index = rewriter->create<LLVM::ConstantOp>( loc, llvm_i32_type, rewriter->getI32IntegerAttr(dim.index())); Value elem_ptr = rewriter->create<LLVM::GEPOp>(loc, llvm_i32_ptr_type, array_ptr, index); Value elem = rewriter->create<LLVM::ConstantOp>( loc, llvm_i32_type, rewriter->getI32IntegerAttr( dim.value().cast<IntegerAttr>().getInt())); rewriter->create<LLVM::StoreOp>(loc, elem, elem_ptr); } return std::make_pair(array_size, array_ptr); } }; class TFDeallocOpConverter : public ConvertToLLVMCallOpPattern<TFDeallocOp> { public: using ConvertToLLVMCallOpPattern<TFDeallocOp>::ConvertToLLVMCallOpPattern; LogicalResult matchAndRewrite( TFDeallocOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { TFDeallocOp::Adaptor transformed(operands); MemRefDescriptor memref(transformed.memref()); Value allocated_bytes_ptr = rewriter.create<LLVM::BitcastOp>( op.getLoc(), getVoidPtrType(), memref.allocatedPtr(rewriter, op.getLoc())); // Insert function call. FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op); rewriter.replaceOpWithNewOp<LLVM::CallOp>( op, llvm::None, tf_func_ref, llvm::makeArrayRef({transformed.ctx(), allocated_bytes_ptr})); return success(); } protected: StringRef GetFuncName() const override { return kCInterfaceDealloc; } Type GetFuncType() const override { return LLVM::LLVMFunctionType::get(getVoidType(), {getVoidPtrType(), getVoidPtrType()}); } }; class ReportErrorOpConverter : public ConvertToLLVMCallOpPattern<ReportErrorOp> { public: using ConvertToLLVMCallOpPattern<ReportErrorOp>::ConvertToLLVMCallOpPattern; LogicalResult matchAndRewrite( ReportErrorOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { ReportErrorOp::Adaptor transformed(operands, op.getOperation()->getAttrDictionary()); Location loc = op.getLoc(); auto module = op->getParentOfType<ModuleOp>(); Value message_constant = GenerateErrorMessageConstant( loc, module, transformed.msg().getValue(), rewriter); // Insert function call. FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op); Value error_code = rewriter.create<LLVM::ConstantOp>( loc, typeConverter->convertType(rewriter.getI32Type()), transformed.error_code()); rewriter.replaceOpWithNewOp<LLVM::CallOp>( op, llvm::None, tf_func_ref, llvm::makeArrayRef({transformed.ctx(), error_code, message_constant})); return success(); } protected: StringRef GetFuncName() const override { return kCInterfaceReportError; } Type GetFuncType() const override { MLIRContext *ctx = &getTypeConverter()->getContext(); auto i8_ptr_type = LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)); auto i32_type = IntegerType::get(ctx, 32); return LLVM::LLVMFunctionType::get( getVoidType(), {getVoidPtrType(), i32_type, i8_ptr_type}); } private: // Generates an LLVM IR dialect global that contains the name of the given // kernel function as a C string, and returns a pointer to its beginning. Value GenerateErrorMessageConstant(Location loc, Operation *module, StringRef message, OpBuilder &builder) const { std::string err_str; llvm::raw_string_ostream err_stream(err_str); err_stream << message; if (!loc.isa<UnknownLoc>()) { err_stream << " at "; loc.print(err_stream); } StringRef generated_error(err_stream.str()); std::string global_name = llvm::formatv("error_message_{0}", llvm::hash_value(generated_error)); Operation *global_constant = SymbolTable::lookupNearestSymbolFrom(module, global_name); if (global_constant) { Value globalPtr = builder.create<LLVM::AddressOfOp>( loc, cast<LLVM::GlobalOp>(global_constant)); MLIRContext *ctx = &getTypeConverter()->getContext(); Value c0 = builder.create<LLVM::ConstantOp>( loc, IntegerType::get(ctx, 64), builder.getIntegerAttr(builder.getIndexType(), 0)); return builder.create<LLVM::GEPOp>( loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr, ValueRange{c0, c0}); } return LLVM::createGlobalString(loc, builder, global_name, generated_error, LLVM::Linkage::Internal); } }; class NullContextOpConverter : public ConvertOpToLLVMPattern<NullContextOp> { public: using ConvertOpToLLVMPattern<NullContextOp>::ConvertOpToLLVMPattern; LogicalResult matchAndRewrite( NullContextOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { rewriter.replaceOpWithNewOp<LLVM::NullOp>(op, getVoidPtrType()); return success(); } }; class NullMemRefOpConverter : public ConvertOpToLLVMPattern<NullMemRefOp> { public: using ConvertOpToLLVMPattern<NullMemRefOp>::ConvertOpToLLVMPattern; LogicalResult matchAndRewrite( NullMemRefOp null_memref_op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { Location loc = null_memref_op->getLoc(); LLVMTypeConverter type_converter = *getTypeConverter(); mlir::Operation *op = null_memref_op.getOperation(); auto shaped_result_type = null_memref_op.getType().cast<BaseMemRefType>(); unsigned address_space = shaped_result_type.getMemorySpaceAsInt(); Type elem_type = shaped_result_type.getElementType(); Type llvm_elem_type = type_converter.convertType(elem_type); Value zero = createIndexConstant(rewriter, loc, 0); if (auto result_type = null_memref_op.getType().dyn_cast<MemRefType>()) { // Set all dynamic sizes to 1 and compute fake strides. SmallVector<Value, 4> dyn_sizes(result_type.getNumDynamicDims(), createIndexConstant(rewriter, loc, 1)); SmallVector<Value, 4> sizes, strides; Value sizeBytes; getMemRefDescriptorSizes(loc, result_type, dyn_sizes, rewriter, sizes, strides, sizeBytes); // Prepare packed args [allocatedPtr, alignedPtr, offset, sizes, strides] // to create a memref descriptor. Value null = rewriter.create<LLVM::NullOp>( loc, LLVM::LLVMPointerType::get(llvm_elem_type, address_space)); SmallVector<Value, 12> packed_values{null, null, zero}; packed_values.append(sizes); packed_values.append(strides); rewriter.replaceOp( op, MemRefDescriptor::pack(rewriter, loc, type_converter, result_type, packed_values)); return success(); } auto result_type = null_memref_op.getType().cast<UnrankedMemRefType>(); Type llvm_result_type = type_converter.convertType(result_type); auto desc = UnrankedMemRefDescriptor::undef(rewriter, loc, llvm_result_type); desc.setRank(rewriter, loc, zero); // Due to the current way of handling unranked memref results escaping, we // have to actually construct a ranked underlying descriptor instead of just // setting its pointer to NULL. SmallVector<Value, 4> sizes; UnrankedMemRefDescriptor::computeSizes(rewriter, loc, *getTypeConverter(), desc, sizes); Value underlying_desc_ptr = rewriter.create<LLVM::AllocaOp>( loc, getVoidPtrType(), sizes.front(), llvm::None); // Populate underlying ranked descriptor. Type elem_ptr_ptr_type = LLVM::LLVMPointerType::get( LLVM::LLVMPointerType::get(llvm_elem_type, address_space)); Value null = rewriter.create<LLVM::NullOp>( loc, LLVM::LLVMPointerType::get(llvm_elem_type, address_space)); UnrankedMemRefDescriptor::setAllocatedPtr( rewriter, loc, underlying_desc_ptr, elem_ptr_ptr_type, null); UnrankedMemRefDescriptor::setAlignedPtr(rewriter, loc, *getTypeConverter(), underlying_desc_ptr, elem_ptr_ptr_type, null); UnrankedMemRefDescriptor::setOffset(rewriter, loc, *getTypeConverter(), underlying_desc_ptr, elem_ptr_ptr_type, zero); desc.setMemRefDescPtr(rewriter, loc, underlying_desc_ptr); rewriter.replaceOp(op, {desc}); return success(); } }; class IsValidMemRefOpConverter : public ConvertOpToLLVMPattern<IsValidMemRefOp> { public: using ConvertOpToLLVMPattern<IsValidMemRefOp>::ConvertOpToLLVMPattern; LogicalResult matchAndRewrite( IsValidMemRefOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { Location loc = op.getLoc(); MemRefDescriptor desc(IsValidMemRefOp::Adaptor(operands).arg()); // Compare every size in the descriptor to 0 to check num_elements == 0. int64_t rank = op.arg().getType().cast<MemRefType>().getRank(); Value is_empty_shape = rewriter.create<LLVM::ConstantOp>( loc, rewriter.getI1Type(), rewriter.getBoolAttr(false)); Value zero = createIndexConstant(rewriter, loc, 0); for (int i = 0; i < rank; ++i) { Value size = desc.size(rewriter, loc, i); Value is_zero_size = rewriter.create<LLVM::ICmpOp>( loc, rewriter.getI1Type(), LLVM::ICmpPredicate::eq, size, zero); is_empty_shape = rewriter.create<LLVM::OrOp>(loc, is_empty_shape, is_zero_size); } Value ptr = rewriter.create<LLVM::BitcastOp>( loc, getVoidPtrType(), desc.allocatedPtr(rewriter, loc)); Value null = rewriter.create<LLVM::NullOp>(loc, getVoidPtrType()); Value is_not_nullptr = rewriter.create<LLVM::ICmpOp>( loc, rewriter.getI1Type(), LLVM::ICmpPredicate::ne, ptr, null); // Valid memref = ptr != NULL || num_elements == 0; rewriter.replaceOpWithNewOp<LLVM::OrOp>(op, is_not_nullptr, is_empty_shape); return success(); } }; } // namespace void PopulateTFFrameworkToLLVMConversionPatterns(LLVMTypeConverter *converter, RewritePatternSet *patterns) { // clang-format off patterns->insert< IsValidMemRefOpConverter, NullContextOpConverter, NullMemRefOpConverter, ReportErrorOpConverter, TFAllocOpConverter, TFDeallocOpConverter >(*converter); // clang-format on } } // namespace tf_framework } // namespace kernel_gen } // namespace mlir
ee7eb2819d9253d0a6a866e184c7760e97b58bf0
a4c4751cfc24db0824d2d9424b60261582b0b96c
/RU/Files/day2_6/mixer-snappyHexMesh/system/removeZones.topoSetDict
b8f8409059de7e283d99a5f2ac3cc44b6b9cd058
[]
no_license
shubham2941/TwoDaysMeshingCourse
02bbca556583e84d5e59a95ea8f98a2542945588
26fffa34a3721b952fbc9d38e5c9308d08201902
refs/heads/master
2020-06-13T02:20:20.923521
2016-01-05T16:31:48
2016-01-05T16:31:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
937
toposetdict
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object topoSetDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // actions ( { name ami; type cellZoneSet; action remove; } ); // ************************************************************************* //
dacc4d59b7a4da1b448c053aa83a016c632f9baa
1e987bd8b8be0dc1c139fa6bf92e8229eb51da27
/maker/arduino/interface/digital_value_hardware.cc
efd17cd26b4d3fbfa6a3ceda528374ff7aa1c58d
[]
no_license
tszdanger/phd
c97091b4f1d7712a836f0c8e3c6f819d53bd0dd5
aab7f16bd1f3546f81e349fc6e2325fb17beb851
refs/heads/master
2023-01-01T00:54:20.136122
2020-10-21T18:07:42
2020-10-21T18:09:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
267
cc
#include <Arduino.h> #include <Arduino_interface_digital_value.h> namespace arduino { /* static */ DigitalValue DigitalValue::High() { return DigitalValue(HIGH); } /* static */ DigitalValue DigitalValue::Low() { return DigitalValue(LOW); } } // namespace arduino
4b523e03fdc8b15eaa38ac658e5c8c693a1bf0ad
63fbcf1d489fad90573306b0bb73cae3c0182a98
/Common/Code/TypeVisualization.hpp
9707a3802a8ce6171a1548326d8fef992880f38e
[ "MIT" ]
permissive
jamiefang/internetmap
2b5515696329182ceeddf46058732b8c409ba77e
13bf01e8e1fde8db64ce8fd417a1c907783100ee
refs/heads/master
2020-09-12T15:40:53.628635
2019-03-01T23:31:31
2019-03-01T23:31:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
hpp
// // TypeVisualization.h // InternetMap // // Created by Nigel Brooke on 2013-01-30. // Copyright (c) 2013 Peer1. All rights reserved. // #ifndef __InternetMap__TypeVisualization__ #define __InternetMap__TypeVisualization__ #include "DefaultVisualization.hpp" class TypeVisualization : public DefaultVisualization { public: TypeVisualization(const std::string& name, int typeToHighlight); virtual Color nodeColor(NodePointer node); virtual std::string name(void) { return _name; } private: int _typeToHighlight; std::string _name; }; #endif /* defined(__InternetMap__TypeVisualization__) */
ab4e53cdf74faf9c7fdce9f69bfb261d7a987072
fea33fec45835f73155cba1b1ca8756115eafd50
/minicern/zebra/bknmparq.inc
095377719135b044e3b1b18094161049ce879b75
[]
no_license
vmc-project/geant3
f95a3e6451ec778d28962be8648af4d02a315f1e
0feb951e5504e2677e4d9919d50ed4497f3fcabf
refs/heads/master
2023-04-30T05:56:35.048796
2023-02-09T13:17:20
2023-02-09T13:17:20
84,311,188
8
11
null
2023-04-24T12:07:53
2017-03-08T11:03:56
Fortran
UTF-8
C++
false
false
497
inc
* * $Id$ * * $Log: bknmparq.inc,v $ * Revision 1.1.1.1 2002/06/16 15:18:49 hristov * Separate distribution of Geant3 * * Revision 1.1.1.1 1999/05/18 15:55:27 fca * AliRoot sources * * Revision 1.1.1.1 1996/03/06 10:46:56 mclareni * Zebra * * #ifndef CERNLIB_ZEBRA_BKNMPARQ_INC #define CERNLIB_ZEBRA_BKNMPARQ_INC * * BANK NAME PARAMETERS (MZLIFT) * * bknmparq.inc * PARAMETER(NNMBKQ=5,MNMIDQ=1,MNMNLQ=MNMIDQ+1) PARAMETER(MNMNSQ=MNMNLQ+1,MNMNDQ=MNMNSQ+1,MNMIOQ=MNMNDQ+1) #endif
cb17e88be81c3fe1c074988f3d824da59f56e6bf
0428c3b8086f12ebbc6de7967ee4437934e2146d
/misc/src/xml_parser.cpp
5ed1f917b536fe62ce6454a7b95e1644c15c5a0a
[]
no_license
cornway/stm32f4-dcmi-probe
e5cf112f83b09ea0d4af23660c12e78b101504e6
9cc677bdb092949d1212ec1fc831b7db3e485fbd
refs/heads/master
2020-04-28T03:16:52.112141
2019-03-11T05:23:51
2019-03-11T05:23:51
174,930,315
2
0
null
null
null
null
UTF-8
C++
false
false
101
cpp
#include "xml_parser.h" /* __weak void * operator new (uint32_t size) { return (void *)0; } */
4d22ffae5c234dbd322296cc038d7e8f8c33d79a
3179943d68996d3ca2d81961be0ac207300b7e4a
/c-upgrade/pta-dsstart-2.cpp
167f530b1d108514fa0517ede3f2b55648fe6d1e
[]
no_license
xucaimao/netlesson
8425a925fa671fb9fd372610c19b499b0d8a6fc2
088004a9b758387ae6860e2a44b587b54dbbd525
refs/heads/master
2021-06-07T06:24:35.276948
2020-05-30T07:04:02
2020-05-30T07:04:02
110,668,572
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
//中国大学MOOC-陈越、何钦铭-数据结构-起步能力自测题-2 素数对猜想 //write by xucaimao ;20171107-20:00 #include<cstdio> #include<cmath> const int maxn=100010; int prime[maxn]; int main(){ for(int i=2;i<maxn;i++) prime[i]=1; int sq=sqrt(maxn)+1; prime[0]=0; prime[1]=0; for(int i=2;i<sq;i++) for(int j=i*i;j<maxn;j+=i) prime[j]=0; //for(int i=2;i<maxn;i++) //if(prime[i]) printf("%d ",i); int N,tot=0,n=2,n1=3; scanf("%d",&N); while(n1<=N){ if( (n1-n) ==2 )tot++; n=n1; n1++;//指向下一个数字 while(!prime[n1])//指向下一个素数 n1++; //printf("%d ",n1); } printf("%d\n",tot); return 0; }
713acfd2fcafe2fb945ac8748f43d91238891e22
0cbdd9cd7c395cff651d4f895fa327d9e464ab38
/Src/KhaosMesh.cpp
45ca6c29502d8fe93d53cba611058e3bb929e366
[]
no_license
zengqh/khaos
128c332a7bf443761e03847da69c6eb9aa9c3b4e
929e60a8b72bf8e513200b9ce5837ec3e388bba4
refs/heads/master
2020-12-02T16:14:58.873539
2017-07-07T09:34:06
2017-07-07T09:34:06
96,522,956
0
0
null
null
null
null
GB18030
C++
false
false
18,203
cpp
#include "KhaosPreHeaders.h" #include "KhaosMesh.h" #include "KhaosRenderDevice.h" namespace Khaos { ////////////////////////////////////////////////////////////////////////// SubMesh::SubMesh() : m_primType(PT_TRIANGLELIST) { m_bvh = KHAOS_NEW AABBBVH; m_bvh->_init(this); } SubMesh::~SubMesh() { KHAOS_DELETE m_bvh; } int SubMesh::getPrimitiveCount() const { return m_ib->getIndexCount() / getPrimitiveTypeVertexCount(m_primType); } int SubMesh::getVertexCount() const { return m_vb->getVertexCount(); } VertexBuffer* SubMesh::createVertexBuffer() { if ( m_vb ) return m_vb.get(); m_vb.attach( g_renderDevice->createVertexBuffer() ); return m_vb.get(); } IndexBuffer* SubMesh::createIndexBuffer() { if ( m_ib ) return m_ib.get(); m_ib.attach( g_renderDevice->createIndexBuffer() ); return m_ib.get(); } void SubMesh::_expandVB( int maskAdd ) { khaosAssert( m_vb ); VertexDeclaration* vd = m_vb->getDeclaration(); int newID = vd->getID() | maskAdd; if ( vd->getID() == newID ) // 已经是了 return; // 创建并复制 VertexDeclaration* vdNew = g_vertexDeclarationManager->getDeclaration(newID); VertexBuffer* vbNew = g_renderDevice->createVertexBuffer(); vbNew->setDeclaration( vdNew ); vbNew->copyFrom( m_vb.get() ); // 设为新的 m_vb.reset( vbNew ); } void SubMesh::expandNormal() { _expandVB( VFM_NOR ); } void SubMesh::expandTangent() { _expandVB( VFM_TAN ); } void SubMesh::expandSH( int order ) { khaosAssert( order == 2 || order == 3 || order == 4 ); if ( order == 2 ) _expandVB( VFM_SH0 | VFM_SH1 ); else if ( order == 3 ) _expandVB( VFM_SH0 | VFM_SH1 | VFM_SH2 ); else if ( order == 4 ) _expandVB( VFM_SH0 | VFM_SH1 | VFM_SH2 | VFM_SH3 ); } void SubMesh::expandTex2() { _expandVB( VFM_TEX2 ); } void SubMesh::_getVertexAdjList( IntListList& adjList ) { // 获取每个点的邻接面列表 adjList.resize( getVertexCount() ); int primCount = getPrimitiveCount(); for ( int f = 0; f < primCount; ++f ) { int v0, v1, v2; m_ib->getCacheTriIndices( f, v0, v1, v2 ); adjList[v0].push_back(f); adjList[v1].push_back(f); adjList[v2].push_back(f); } } Vector3 SubMesh::_getFaceNormal( int face ) const { // 得到第f个面的法线 // 面的3个点 Vector3* v0; Vector3* v1; Vector3* v2; const_cast<SubMesh*>(this)->getTriVertices( face, v0, v1, v2 ); // 求法线,注意这里面是逆时针顺序 Vector3 va = *v1 - *v0; Vector3 vb = *v2 - *v1; Vector3 vc = va.crossProduct( vb ); return vc; //.normalisedCopy(); // 这里考虑面积因素不单位化 } void SubMesh::generateNormals( bool forceUpdate, bool refundImm ) { khaosAssert( m_vb ); // 是否已经有法线了 if ( m_vb->hasElement(VFM_NOR) && !forceUpdate ) return; // 确保法线 expandNormal(); // 确保缓存 cacheLocalData( true ); // 获取每个点的邻接面列表 IntListList adjList; _getVertexAdjList( adjList ); // 遍历每个点 int vtxCnt = getVertexCount(); for ( int i = 0; i < vtxCnt; ++i ) { // 计算该点的所有邻接面的法线和 Vector3 n(Vector3::ZERO); const IntList& adjs = adjList[i]; int adjCnt = (int)adjs.size(); for ( int j = 0; j < adjCnt; ++j ) { int faceIdx = adjs[j]; n += _getFaceNormal( faceIdx ); } *(m_vb->getCacheNormal(i)) = n.normalisedCopy(); } // 立即上传到gpu? if ( refundImm ) m_vb->refundLocalData(); } void SubMesh::generateTangents( bool forceUpdate, bool refundImm ) { khaosAssert( m_vb ); // 如果没有法线,我们先创建法线 generateNormals( false, false ); // 是否已经有切线了 if ( m_vb->hasElement(VFM_TAN) && !forceUpdate ) return; // 确保切线 expandTangent(); // 确保缓存 cacheLocalData( true ); // 开始计算切线~~~~~~~~~~~~~ // 计算每个面的切线 int primCount = getPrimitiveCount(); int vertexCount = getVertexCount(); vector<Vector3>::type faceTangents( primCount ); // 每个面的切线 vector<Vector3>::type faceBinormals( primCount ); // 每个面的次法线 IntListList vtxFaces( vertexCount ); // 每个顶点对应的邻接面列表 for ( int i = 0; i < primCount; ++i ) { // 该面3点索引 int i0, i1, i2; m_ib->getCacheTriIndices( i, i0, i1, i2 ); // 该面位置 const Vector3& v0 = *(m_vb->getCachePos(i0)); const Vector3& v1 = *(m_vb->getCachePos(i1)); const Vector3& v2 = *(m_vb->getCachePos(i2)); // 该面uv const Vector2& uv0 = *(m_vb->getCacheTex(i0)); // 在第一套uv const Vector2& uv1 = *(m_vb->getCacheTex(i1)); const Vector2& uv2 = *(m_vb->getCacheTex(i2)); // 第i个面的切线 Math::calcTangent( v0, v1, v2, uv0, uv1, uv2, faceTangents[i], faceBinormals[i] ); // 记录顶点使用的面 vtxFaces[i0].push_back( i ); vtxFaces[i1].push_back( i ); vtxFaces[i2].push_back( i ); } // 计算每个顶点的平均切线 for ( int i = 0; i < vertexCount; ++i ) { IntList& faces = vtxFaces[i]; // 该点邻接面 const Vector3& vnormal = *(m_vb->getCacheNormal(i)); // 该点法线 Vector3 tanget(Vector3::ZERO); Vector3 binormal(Vector3::ZERO); // 该点的所有邻接面的切线统计 for ( size_t j = 0; j < faces.size(); ++j ) { int fi = faces[j]; tanget += faceTangents[fi]; binormal += faceBinormals[fi]; } // 正交矫正 *(m_vb->getCacheTanget(i)) = Math::gramSchmidtOrthogonalize( tanget, binormal, vnormal ); } // 立即上传到gpu? if ( refundImm ) m_vb->refundLocalData(); } void SubMesh::updateAABB() { m_aabb.setNull(); if ( !m_vb ) return; if ( uint8* vb = (uint8*)m_vb->lock( HBA_READ ) ) { //int posOffset = m_vb->getDeclaration()->findElement(VFM_POS)->offset; Vector3* pos = (Vector3*)(vb /*+ posOffset*/); // always 0 m_aabb.merge( pos, m_vb->getVertexCount(), m_vb->getDeclaration()->getStride() ); m_vb->unlock(); } } void SubMesh::setAABB( const AxisAlignedBox& aabb ) { m_aabb = aabb; } void SubMesh::draw() { g_renderDevice->setVertexBuffer( getVertexBuffer() ); if ( IndexBuffer* ib = getIndexBuffer() ) { g_renderDevice->setIndexBuffer( ib ); g_renderDevice->drawIndexedPrimitive( getPrimitiveType(), 0, getPrimitiveCount() ); } else { g_renderDevice->drawPrimitive( getPrimitiveType(), 0, getPrimitiveCount() ); } } void SubMesh::cacheLocalData( bool forceUpdate ) { m_vb->cacheLocalData(forceUpdate); m_ib->cacheLocalData(forceUpdate); } void SubMesh::freeLocalData() { m_vb->freeLocalData(); m_ib->freeLocalData(); } void SubMesh::refundLocalData( bool vb, bool ib ) { if ( vb ) m_vb->refundLocalData(); if ( ib ) m_ib->refundLocalData(); } void SubMesh::getTriVertices( int face, Vector3*& v0, Vector3*& v1, Vector3*& v2 ) { int i0, i1, i2; m_ib->getCacheTriIndices( face, i0, i1, i2 ); v0 = m_vb->getCachePos(i0); v1 = m_vb->getCachePos(i1); v2 = m_vb->getCachePos(i2); } Vector2 SubMesh::getTriUV( int face, const Vector3& gravity ) const { int i0, i1, i2; m_ib->getCacheTriIndices( face, i0, i1, i2 ); const Vector2& uv0 = *(m_vb->getCacheTex(i0)); const Vector2& uv1 = *(m_vb->getCacheTex(i1)); const Vector2& uv2 = *(m_vb->getCacheTex(i2)); return uv0 * gravity.x + uv1 * gravity.y + uv2 * gravity.z; } Vector2 SubMesh::getTriUV2( int face, const Vector3& gravity ) const { int i0, i1, i2; m_ib->getCacheTriIndices( face, i0, i1, i2 ); const Vector2& uv0 = *(m_vb->getCacheTex2(i0)); const Vector2& uv1 = *(m_vb->getCacheTex2(i1)); const Vector2& uv2 = *(m_vb->getCacheTex2(i2)); return uv0 * gravity.x + uv1 * gravity.y + uv2 * gravity.z; } Vector3 SubMesh::getTriNormal( int face, const Vector3& gravity ) const { int i0, i1, i2; m_ib->getCacheTriIndices( face, i0, i1, i2 ); const Vector3& norm0 = *(m_vb->getCacheNormal(i0)); const Vector3& norm1 = *(m_vb->getCacheNormal(i1)); const Vector3& norm2 = *(m_vb->getCacheNormal(i2)); return norm0 * gravity.x + norm1 * gravity.y + norm2 * gravity.z; } void SubMesh::buildBVH( bool forceUpdate ) { cacheLocalData( false ); // 最低限度调用 m_bvh->build( forceUpdate ); } void SubMesh::clearBVH() { m_bvh->clear(); } AABBBVH::Result SubMesh::intersectDetail( const Ray& ray ) const { return m_bvh->intersect( ray ); } AABBBVH::Result SubMesh::intersectDetail( const LimitRay& ray ) const { return m_bvh->intersect( ray ); } void SubMesh::copyFrom( const SubMesh* rhs ) { this->m_primType = rhs->m_primType; // copy vb this->m_vb.release(); if ( rhs->m_vb ) { VertexBuffer* vb = this->createVertexBuffer(); vb->copyFrom( rhs->m_vb.get() ); } // copy ib this->m_ib.release(); if ( rhs->m_ib ) { IndexBuffer* ib = this->createIndexBuffer(); ib->copyFrom( rhs->m_ib.get() ); } // misc this->m_aabb = rhs->m_aabb; this->m_materialName = rhs->m_materialName; this->m_bvh->clear(); // 不复制,总清空 } ////////////////////////////////////////////////////////////////////////// Mesh::~Mesh() { _destructResImpl(); } SubMesh* Mesh::createSubMesh() { SubMesh* sm = KHAOS_NEW SubMesh; m_subMeshList.push_back( sm ); return sm; } void Mesh::setMaterialName( const String& mtrName ) { KHAOS_FOR_EACH( SubMeshList, m_subMeshList, it ) { (*it)->setMaterialName( mtrName ); } } void Mesh::updateAABB( bool forceAll ) { m_aabb.setNull(); for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; if ( forceAll ) sm->updateAABB(); m_aabb.merge( sm->getAABB() ); } } void Mesh::setAABB( const AxisAlignedBox& aabb ) { m_aabb = aabb; } void Mesh::expandSH( int order ) { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->expandSH( order ); } } void Mesh::expandTex2() { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->expandTex2(); } } void Mesh::generateNormals( bool forceUpdate, bool refundImm ) { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->generateNormals( forceUpdate, refundImm ); } } void Mesh::generateTangents( bool forceUpdate, bool refundImm ) { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->generateTangents( forceUpdate, refundImm ); } } void Mesh::cacheLocalData( bool forceUpdate ) { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->cacheLocalData( forceUpdate ); } } int Mesh::getVertexCount() const { int cnt = 0; for ( SubMeshList::const_iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { const SubMesh* sm = *it; cnt += sm->getVertexCount(); } return cnt; } void Mesh::freeLocalData() { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->freeLocalData(); } } void Mesh::buildBVH( bool forceUpdate ) { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->buildBVH( forceUpdate ); } } void Mesh::clearBVH() { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; sm->clearBVH(); } } template<class T> bool Mesh::_intersectBoundImpl( const T& ray, float* t ) const { std::pair<bool, float> ret = ray.intersects( m_aabb ); if ( t && ret.first ) *t = ret.second; return ret.first; } template<class T> bool Mesh::_intersectBoundMoreImpl( const T& ray, int* subIdx, float* t ) const { int cnt = (int)m_subMeshList.size(); if ( cnt == 1 ) // 只有1个情况,优化成intersectBound { bool ret = _intersectBoundImpl( ray, t ); if ( subIdx && ret ) *subIdx = 0; // 1个肯定是0啦 return ret; } if ( !ray.intersects(m_aabb).first ) return false; int sub = -1; float dist = Math::POS_INFINITY; for ( int i = 0; i < cnt; ++i ) { const SubMesh* sm = m_subMeshList[i]; std::pair<bool, float> curr = ray.intersects( sm->getAABB() ); if ( curr.first && curr.second < dist ) { sub = i; dist = curr.second; } } if ( sub == -1 ) return false; if ( subIdx ) *subIdx = sub; if ( t ) *t = dist; return true; } template<class T> bool Mesh::_intersectDetailImpl( const T& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const { if ( !ray.intersects(m_aabb).first ) return false; AABBBVH::Result ret; int sub = -1; int cnt = (int)m_subMeshList.size(); for ( int i = 0; i < cnt; ++i ) { const SubMesh* sm = m_subMeshList[i]; AABBBVH::Result curr = sm->intersectDetail( ray ); if ( curr.face != -1 && curr.distance < ret.distance ) { ret = curr; sub = i; } } if ( sub == -1 ) return false; if ( subIdx ) *subIdx = sub; if ( faceIdx ) *faceIdx = ret.face; if ( t ) *t = ret.distance; if ( gravity ) *gravity = ret.gravity; return true; } bool Mesh::intersectBound( const Ray& ray, float* t ) const { return _intersectBoundImpl( ray, t ); } bool Mesh::intersectBound( const LimitRay& ray, float* t ) const { return _intersectBoundImpl( ray, t ); } bool Mesh::intersectBoundMore( const Ray& ray, int* subIdx, float* t ) const { return _intersectBoundMoreImpl( ray, subIdx, t ); } bool Mesh::intersectBoundMore( const LimitRay& ray, int* subIdx, float* t ) const { return _intersectBoundMoreImpl( ray, subIdx, t ); } bool Mesh::intersectDetail( const Ray& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const { return _intersectDetailImpl( ray, subIdx, faceIdx, t, gravity ); } bool Mesh::intersectDetail( const LimitRay& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const { return _intersectDetailImpl( ray, subIdx, faceIdx, t, gravity ); } void Mesh::_clearSubMesh() { for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it ) { SubMesh* sm = *it; KHAOS_DELETE sm; } m_subMeshList.clear(); } void Mesh::copyFrom( const Resource* rhs ) { const Mesh* meshOth = static_cast<const Mesh*>(rhs); this->_clearSubMesh(); for ( int subIdx = 0; subIdx < meshOth->getSubMeshCount(); ++subIdx ) { SubMesh* sm = this->createSubMesh(); SubMesh* smOth = meshOth->getSubMesh( subIdx ); sm->copyFrom( smOth ); } m_aabb = meshOth->m_aabb; } void Mesh::_destructResImpl() { _clearSubMesh(); } void Mesh::drawSub( int i ) { getSubMesh(i)->draw(); } }
0061815e53c872c96ecc1a235d0a7f83e960b8b6
019c446b2c8f8e902226851db1b31eb1e3c850d5
/oneEngine/oneGame/source/after/terrain/system/MemoryManager.cpp
739b22f92097c2357c04bf86676e6300f90e5eba
[ "FTL", "BSD-3-Clause" ]
permissive
skarik/1Engine
cc9b6f7cf81903b75663353926a23224b81d1389
9f53b4cb19a6b8bb3bf2e3a4104c73614ffd4359
refs/heads/master
2023-09-04T23:12:50.706308
2023-08-29T05:28:21
2023-08-29T05:28:21
109,445,379
9
2
BSD-3-Clause
2021-08-30T06:48:27
2017-11-03T21:41:51
C++
UTF-8
C++
false
false
5,706
cpp
#include "MemoryManager.h" #include "core/settings/CGameSettings.h" #include "after/terrain/data/Node.h" #include <iostream> #include <memory> #include <thread> //===============================================================================================// // Manager settings //===============================================================================================// uint32_t Terrain::MemoryManager::MemorySize_Sidebuffer = sizeof(Terrain::terra_b) * 34*34*34; uint32_t Terrain::MemoryManager::MemorySize_Payload = sizeof(Terrain::terra_b) * BLOCK_COUNT; uint32_t Terrain::MemoryManager::MemorySize_Node = sizeof(Terrain::Node); //===============================================================================================// // Constructor and Destructor //===============================================================================================// Terrain::MemoryManager::MemoryManager ( void ) { if ( !Init() ) { printf( "Could not allocate enough memory for terrain. Currently at density %d.", CGameSettings::Active()->i_cl_ter_Range ); throw Core::OutOfMemoryException(); } } Terrain::MemoryManager::~MemoryManager( void ) { Free(); } //===============================================================================================// // System Start and End //===============================================================================================// bool Terrain::MemoryManager::Init ( void ) { //m_memoryMaxBlocks = (uint32_t)( 64 * 255 * pow(2,1+CGameSettings::Active()->i_cl_ter_Range) ); m_memoryMaxBlocks = (uint32_t)( 64 * pow(2,1+CGameSettings::Active()->i_cl_ter_Range) ); std::cout << " Block size: " << MemorySize_Payload << " with " << m_memoryMaxBlocks << " blocks." << std::endl; std::cout << " Estimated size: " << ((MemorySize_Payload+1) * m_memoryMaxBlocks)/(1024*1024) << " MB" << std::endl; try { // Terrain Memory Management uint32_t blocks = m_memoryMaxBlocks; // Attempt to allocate memory for the terrain m_memoryData = new char [ blocks * MemorySize_Payload ]; memset( m_memoryData, 0, blocks * MemorySize_Payload ); // Allocate memory for the terra mem flags m_memoryUsage = new char [ blocks ]; memset( m_memoryUsage, 0, blocks ); // Set the last eight blocks as used for ( int i = 1; i <= 8; ++i ) { m_memoryUsage[blocks-i] = 1; } } catch ( std::bad_alloc ) { return false; } return true; } void Terrain::MemoryManager::Free ( void ) { delete [] m_memoryData; m_memoryData = NULL; delete [] m_memoryUsage; m_memoryUsage = NULL; } //===============================================================================================// // Memory Requests //===============================================================================================// Terrain::terra_b* Terrain::MemoryManager::NewDataBlock ( void ) //void Terrain::MemoryManager::NewDataBlock ( Terrain::Payload** block ) { std::lock_guard<std::mutex> lock ( m_memoryLock ); uint32_t blocks = m_memoryMaxBlocks; uint32_t normalized_index = 0; // Find the first open index while ( m_memoryUsage[normalized_index] != 0 ) ++normalized_index; if ( normalized_index >= blocks ) { std::cout << "OH NO MY BOBA BALLS!" << std::endl; throw Core::OutOfMemoryException(); } // Get the new memory index uint32_t index = normalized_index * MemorySize_Payload; // Set the block to the new value //(*block) = (subblock16*)(pTerraData + index); //(*block) = (Terrain::Sector*)(&(m_memoryData[index])); // should be the same //(*block) = new(&(m_memoryData[index])) Terrain::Sector; //should still work terra_b* block = (terra_b*) &(m_memoryData[index]); // Turn on flag m_memoryUsage[normalized_index] = 1; // Return allocated area return block; } void Terrain::MemoryManager::FreeDataBlock ( terra_b* block ) { std::lock_guard<std::mutex> lock ( m_memoryLock ); uint32_t blocks = m_memoryMaxBlocks; uint32_t index = 0; // Figure out the index of block based on the memory address char* tblock = (char*)block; while ( tblock != m_memoryData + index ) index += MemorySize_Payload; // Get the index of the mem flag array uint32_t normalized_index = index / MemorySize_Payload; if ( normalized_index >= blocks ) exit(0); // Turn off flag m_memoryUsage[normalized_index] = 0; } //===============================================================================================// // System State Query //===============================================================================================// Real Terrain::MemoryManager::GetMemoryUsage ( void ) { std::lock_guard<std::mutex> lock ( m_memoryLock ); struct tBlockCounter { char* m_memoryUsage; uint32_t* count; uint32_t start; uint32_t end; void operator () ( void ) { for ( uint32_t i = start; i < end; ++i ) { if ( m_memoryUsage[i] ) { ++(*count); } } } }; // Create 4 counters uint32_t external_count[4]; tBlockCounter counters [4]; for ( uint i = 0; i < 4; ++i ) { external_count[i] = 0; counters[i].m_memoryUsage = m_memoryUsage; counters[i].count = &(external_count[i]); counters[i].start = i * (m_memoryMaxBlocks/4); counters[i].end = (i+1) * (m_memoryMaxBlocks/4); } // And run the four counters on four separate threads std::thread* threads[4]; for ( uint i = 0; i < 4; ++i ) { threads[i] = new std::thread( counters[i] ); } for ( uint i = 0; i < 4; ++i ) { threads[i]->join(); delete threads[i]; } // Count up the blocks the threads counted up uint32_t usedBlocks = 0; for ( uint i = 0; i < 4; ++i ) { usedBlocks += external_count[i]; } // Return the percentage of used blocks return usedBlocks/((Real)(m_memoryMaxBlocks)); }
d512741b750eb3a4091a2c1903db422fac1fd307
4b1ee3b6b7a23ab029e59e1744ec2f441c648863
/DEMCOMP/demcomp2/dem_comp2.cpp
7c29f550325fe5ccb2260d10861794dbbd2ba00a
[]
no_license
JimFawcett/CppBasicDemos
aa4d489befa7e4b5b5454c913ab889a5376658e7
77652c070e7ffa58b008a8afac9f32dd92e30a4f
refs/heads/master
2021-06-25T04:51:01.991278
2021-01-25T00:29:58
2021-01-25T00:29:58
195,317,448
2
0
null
null
null
null
UTF-8
C++
false
false
4,066
cpp
////////////////////////////////////////////////////////////////// // DEM_COMP2.CPP - demonstrates composition // // knows how to copy, assign, and destroy // // uses inefficient copy ctor design // ////////////////////////////////////////////////////////////////// #include <iostream> using namespace std; class composed { public: composed(void); composed(const composed& b); composed(int x); virtual ~composed(void); composed& operator= (const composed& b); friend ostream& operator<<(ostream& ostrm, const composed& b); private: int data; }; class composer { public: composer(void); composer(const composer &a); composer(int x1, int x2); virtual ~composer(void); composer& operator=(const composer& a); friend ostream& operator<<(ostream& ostrm, const composer& a); private: composed in1; composed in2; }; // //----< void constructor >------------------------------------- composed::composed(void) { cout << " composed void constructor called\n"; } //----< copy constructor >------------------------------------- composed::composed(const composed& b) : data(b.data) { cout << " composed copy constructor called\n"; } //----< promotion constructor >-------------------------------- composed::composed(int x) : data(x) { cout << " composed(int) constructor called\n"; cout << " set data = " << data << "\n"; } //----< destructor >------------------------------------------- composed::~composed(void) { cout << " composed destructor called\n"; } //----< assignment >------------------------------------------- composed& composed::operator= (const composed& b) { if(this==&b) return *this; cout << " composed operator= called\n"; data = b.data; return *this; } //----< insertion >-------------------------------------------- ostream& operator<<(ostream& ostrm, const composed& b) { ostrm << b.data; return ostrm; } // //----< void constructor >------------------------------------- composer::composer(void) { cout << " composer void constructor called\n"; } //----< copy constructor >------------------------------------- // this copy method is not efficient - see dem_ag2b composer::composer(const composer &a) { cout << " composer copy constructor called\n"; in1 = a.in1; in2 = a.in2; } //----< promotion constructor with initialization >------------ composer::composer(int size1, int size2) : in1(size1), in2(size2) { cout << " composer(int,int) constructor called\n"; cout << " set in1 = " << in1 << endl; cout << " set in2 = " << in2 << endl; } //----< destructor >------------------------------------------- composer::~composer(void) { cout << " composer destructor called\n"; } //----< assignment >------------------------------------------- composer& composer::operator=(const composer &a) { if(this==&a) return *this; cout << " composer operator= called\n"; in1 = a.in1; in2 = a.in2; return *this; } //----< annunciator >------------------------------------------ void message(char *s) { cout << endl << s << " executable statement of main\n"; } void main() { //---------------------------------------------- message("1st"); composed inner1; message("2nd"); composed inner2 = inner1; message("3rd"); inner1 = inner2; message("4th"); composer outer1; message("5th"); composer outer2(6,4); message("6th"); composer outer3 = outer1; message("7th"); outer3 = outer2; message("no more"); } // // now, composer has a copy ctor, assignment oper, and a dtor // - we see them being called in 6th statement, 7th // statement, and in the destruction sequence // one issue of note here: // if you compare composer source code for copy ctor and // annunciations you will see that when composer does a copy // construction it's elements are first constructed with // void ctor, then assigned with composed operator=() // there is a better way - see dem_comp2b
984f1dc9a30584bc111fbada107963e7afc54718
72f2992a3659ff746ba5ce65362acbe85a918df9
/apps-src/apps/external/zxing/qrcode/QRBitMatrixParser.h
f749c280c1cfdd8c0801a52ecefce0b14bd0a662
[ "BSD-2-Clause" ]
permissive
chongtianfeiyu/Rose
4742f06ee9ecd55f9717ac6378084ccf8bb02a15
412175b57265ba2cda1e33dd2047a5a989246747
refs/heads/main
2023-05-23T14:03:08.095087
2021-06-19T13:23:58
2021-06-19T14:00:25
391,238,554
0
1
BSD-2-Clause
2021-07-31T02:39:25
2021-07-31T02:39:24
null
UTF-8
C++
false
false
1,503
h
#pragma once /* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * 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. */ namespace ZXing { class BitMatrix; class ByteArray; namespace QRCode { class Version; class FormatInformation; /** * @author Sean Owen */ class BitMatrixParser { public: /** * @param bitMatrix {@link BitMatrix} to parse * return false if dimension is not >= 21 and 1 mod 4 */ static const Version* ReadVersion(const BitMatrix& bitMatrix, bool mirrored); static FormatInformation ReadFormatInformation(const BitMatrix& bitMatrix, bool mirrored); /** * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the * correct order in order to reconstruct the codewords bytes contained within the * QR Code.</p> * * @return bytes encoded within the QR Code * or empty array if the exact number of bytes expected is not read */ static ByteArray ReadCodewords(const BitMatrix& bitMatrix, const Version& version); }; } // QRCode } // ZXing
cde57931fb89c42727a50a05b1eaa5b252e47a02
4c0a47abd546571c37e279c283738e825e1a4ac5
/syncd/ServiceMethodTable.cpp
2f5f5183510a1cf220039d0dfcbd2adfd917d109
[ "Apache-2.0" ]
permissive
tonytitus/sonic-sairedis
054167fe3eb69f1d8ed0fcccee4573b4e6ffa205
2347db590f3b1799eacedef7e1e7c9990cc11ca9
refs/heads/master
2021-07-18T13:17:48.497968
2020-07-31T17:22:34
2020-07-31T17:22:34
198,504,530
0
1
NOASSERTION
2019-07-23T20:35:35
2019-07-23T20:35:35
null
UTF-8
C++
false
false
2,622
cpp
#include "ServiceMethodTable.h" #include "swss/logger.h" #include <utility> using namespace syncd; ServiceMethodTable::SlotBase::SlotBase( _In_ sai_service_method_table_t smt): m_handler(nullptr), m_smt(smt) { SWSS_LOG_ENTER(); // empty } ServiceMethodTable::SlotBase::~SlotBase() { SWSS_LOG_ENTER(); // empty } void ServiceMethodTable::SlotBase::setHandler( _In_ ServiceMethodTable* handler) { SWSS_LOG_ENTER(); m_handler = handler; } ServiceMethodTable* ServiceMethodTable::SlotBase::getHandler() const { SWSS_LOG_ENTER(); return m_handler; } const char* ServiceMethodTable::SlotBase::profileGetValue( _In_ int context, _In_ sai_switch_profile_id_t profile_id, _In_ const char* variable) { SWSS_LOG_ENTER(); return m_slots.at(context)->m_handler->profileGetValue(profile_id, variable); } int ServiceMethodTable::SlotBase::profileGetNextValue( _In_ int context, _In_ sai_switch_profile_id_t profile_id, _Out_ const char** variable, _Out_ const char** value) { return m_slots.at(context)->m_handler->profileGetNextValue(profile_id, variable, value); } const sai_service_method_table_t& ServiceMethodTable::SlotBase::getServiceMethodTable() const { SWSS_LOG_ENTER(); return m_smt; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winline" template<class B, template<size_t> class D, size_t... i> constexpr auto declare_static(std::index_sequence<i...>) { SWSS_LOG_ENTER(); return std::array<B*, sizeof...(i)>{{new D<i>()...}}; } template<class B, template<size_t> class D, size_t size> constexpr auto declare_static() { SWSS_LOG_ENTER(); auto arr = declare_static<B,D>(std::make_index_sequence<size>{}); return std::vector<B*>{arr.begin(), arr.end()}; } std::vector<ServiceMethodTable::SlotBase*> ServiceMethodTable::m_slots = declare_static<ServiceMethodTable::SlotBase, ServiceMethodTable::Slot, 10>(); #pragma GCC diagnostic pop ServiceMethodTable::ServiceMethodTable() { SWSS_LOG_ENTER(); for (auto& slot: m_slots) { if (slot->getHandler() == nullptr) { m_slot = slot; m_slot->setHandler(this); return; } } SWSS_LOG_THROW("no more available slots, max slots: %zu", m_slots.size()); } ServiceMethodTable::~ServiceMethodTable() { SWSS_LOG_ENTER(); m_slot->setHandler(nullptr); } const sai_service_method_table_t& ServiceMethodTable::getServiceMethodTable() const { SWSS_LOG_ENTER(); return m_slot->getServiceMethodTable(); }
31aa6d8ae6eceffaad0c5e93c4595c9496d02643
bb1bd534be66f23bc6a8f1d153e20c0690edac6c
/src/PipelineManager.cpp
acbf2fd475cdf6da9df61ea65be36c6cf33e5b6e
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
chenming5828/tiscamera
417e37d36dc7305b4dbd9c54060a35744594c1cf
f5bf8f02127946027edfe00bfdfd7fccc01e517e
refs/heads/master
2021-08-14T16:54:21.684854
2017-11-14T09:16:04
2017-11-14T09:16:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,888
cpp
/* * Copyright 2014 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PipelineManager.h" #include "internal.h" #include <ctime> #include <cstring> #include <algorithm> #include <utils.h> using namespace tcam; PipelineManager::PipelineManager () : status(TCAM_PIPELINE_UNDEFINED), current_ppl_buffer(0) {} PipelineManager::~PipelineManager () { if (status == TCAM_PIPELINE_PLAYING) { stop_playing(); } available_filter.clear(); filter_pipeline.clear(); filter_properties.clear(); } std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties () { return filter_properties; } std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const { return available_output_formats; } bool PipelineManager::setVideoFormat(const VideoFormat& f) { this->output_format = f; return true; } VideoFormat PipelineManager::getVideoFormat () const { return this->output_format; } bool PipelineManager::set_status (TCAM_PIPELINE_STATUS s) { if (status == s) return true; this->status = s; if (status == TCAM_PIPELINE_PLAYING) { if (create_pipeline()) { start_playing(); tcam_log(TCAM_LOG_INFO, "All pipeline elements set to PLAYING."); } else { status = TCAM_PIPELINE_ERROR; return false; } } else if (status == TCAM_PIPELINE_STOPPED) { stop_playing(); } return true; } TCAM_PIPELINE_STATUS PipelineManager::get_status () const { return status; } bool PipelineManager::destroyPipeline () { set_status(TCAM_PIPELINE_STOPPED); source = nullptr; sink = nullptr; return true; } bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } device_properties = device->getProperties(); available_input_formats = device->get_available_video_formats(); tcam_log(TCAM_LOG_DEBUG, "Received %zu formats.", available_input_formats.size()); distributeProperties(); this->source = std::make_shared<ImageSource>(); source->setSink(shared_from_this()); source->setDevice(device); for (const auto& f : available_filter) { auto p = f->getFilterProperties(); if (!p.empty()) { filter_properties.insert(filter_properties.end(), p.begin(), p.end()); } } available_output_formats = available_input_formats; if (available_output_formats.empty()) { tcam_log(TCAM_LOG_ERROR, "No output formats available."); return false; } return true; } std::shared_ptr<ImageSource> PipelineManager::getSource () { return source; } bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } this->sink = s; this->sink->set_source(shared_from_this()); return true; } std::shared_ptr<SinkInterface> PipelineManager::getSink () { return sink; } void PipelineManager::distributeProperties () { for (auto& f : available_filter) { f->setDeviceProperties(device_properties); } } static bool isFilterApplicable (uint32_t fourcc, const std::vector<uint32_t>& vec) { if (std::find(vec.begin(), vec.end(), fourcc) == vec.end()) { return false; } return true; } void PipelineManager::create_input_format (uint32_t fourcc) { input_format = output_format; input_format.set_fourcc(fourcc); } std::vector<uint32_t> PipelineManager::getDeviceFourcc () { // for easy usage we create a vector<fourcc> for avail. inputs std::vector<uint32_t> device_fourcc; for (const auto& v : available_input_formats) { tcam_log(TCAM_LOG_DEBUG, "Found device fourcc '%s' - %d", fourcc2description(v.get_fourcc()), v.get_fourcc()); device_fourcc.push_back(v.get_fourcc()); } return device_fourcc; } bool PipelineManager::set_source_status (TCAM_PIPELINE_STATUS status) { if (source == nullptr) { tcam_log(TCAM_LOG_ERROR, "Source is not defined"); return false; } if (!source->set_status(status)) { tcam_log(TCAM_LOG_ERROR, "Source did not accept status change"); return false; } return true; } bool PipelineManager::set_sink_status (TCAM_PIPELINE_STATUS status) { if (sink == nullptr) { tcam_log(TCAM_LOG_WARNING, "Sink is not defined."); return false; } if (!sink->set_status(status)) { tcam_log(TCAM_LOG_ERROR, "Sink spewed error"); return false; } return true; } bool PipelineManager::validate_pipeline () { // check if pipeline is valid if (source.get() == nullptr || sink.get() == nullptr) { return false; } // check source format auto in_format = source->getVideoFormat(); if (in_format != this->input_format) { tcam_log(TCAM_LOG_DEBUG, "Video format in source does not match pipeline: '%s' != '%s'", in_format.to_string().c_str(), input_format.to_string().c_str()); return false; } else { tcam_log(TCAM_LOG_DEBUG, "Starting pipeline with format: '%s'", in_format.to_string().c_str()); } VideoFormat in; VideoFormat out; for (auto f : filter_pipeline) { f->getVideoFormat(in, out); if (in != in_format) { tcam_log(TCAM_LOG_ERROR, "Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'", f->getDescription().name.c_str(), in_format.to_string().c_str(), in.to_string().c_str()); return false; } else { tcam_log(TCAM_LOG_DEBUG, "Filter %s connected to pipeline -- %s", f->getDescription().name.c_str(), out.to_string().c_str()); // save output for next comparison in_format = out; } } if (in_format != this->output_format) { tcam_log(TCAM_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'", in_format.to_string().c_str(), output_format.to_string().c_str()); return false; } return true; } bool PipelineManager::create_conversion_pipeline () { if (source.get() == nullptr || sink.get() == nullptr) { return false; } auto device_fourcc = getDeviceFourcc(); create_input_format(output_format.get_fourcc()); for (auto f : available_filter) { std::string s = f->getDescription().name; if (f->getDescription().type == FILTER_TYPE_CONVERSION) { if (isFilterApplicable(output_format.get_fourcc(), f->getDescription().output_fourcc)) { bool filter_valid = false; uint32_t fourcc_to_use = 0; for (const auto& cc : device_fourcc) { if (isFilterApplicable(cc, f->getDescription().input_fourcc)) { filter_valid = true; fourcc_to_use = cc; break; } } // set device format to use correct fourcc create_input_format(fourcc_to_use); if (filter_valid) { if (f->setVideoFormat(input_format, output_format)) { tcam_log(TCAM_LOG_DEBUG, "Added filter \"%s\" to pipeline", s.c_str()); filter_pipeline.push_back(f); } else { tcam_log(TCAM_LOG_DEBUG, "Filter %s did not accept format settings", s.c_str()); } } else { tcam_log(TCAM_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str()); } } else { tcam_log(TCAM_LOG_DEBUG, "Filter %s is not applicable", s.c_str()); } } } return true; } bool PipelineManager::add_interpretation_filter () { // if a valid pipeline can be created insert additional filter (e.g. autoexposure) // interpretations should be done as early as possible in the pipeline for (auto& f : available_filter) { if (f->getDescription().type == FILTER_TYPE_INTERPRET) { std::string s = f->getDescription().name; // applicable to sink bool all_formats = false; if (f->getDescription().input_fourcc.size() == 1) { if (f->getDescription().input_fourcc.at(0) == 0) { all_formats = true; } } if (all_formats ||isFilterApplicable(input_format.get_fourcc(), f->getDescription().input_fourcc)) { tcam_log(TCAM_LOG_DEBUG, "Adding filter '%s' after source", s.c_str()); f->setVideoFormat(input_format, input_format); filter_pipeline.insert(filter_pipeline.begin(), f); continue; } else { tcam_log(TCAM_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str()); } if (f->setVideoFormat(input_format, input_format)) { continue; } } } return true; } bool PipelineManager::allocate_conversion_buffer () { pipeline_buffer.clear(); for (int i = 0; i < 5; ++i) { tcam_image_buffer b = {}; b.pitch = output_format.get_size().width * img::get_bits_per_pixel(output_format.get_fourcc()) / 8; b.length = b.pitch * output_format.get_size().height; b.pData = (unsigned char*)malloc(b.length); b.format.fourcc = output_format.get_fourcc(); b.format.width = output_format.get_size().width; b.format.height = output_format.get_size().height; b.format.framerate = output_format.get_framerate(); this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b)); } current_ppl_buffer = 0; return true; } bool PipelineManager::create_pipeline () { if (source.get() == nullptr || sink.get() == nullptr) { return false; } // assure everything is in a defined state filter_pipeline.clear(); if (!create_conversion_pipeline()) { tcam_log(TCAM_LOG_ERROR, "Unable to determine conversion pipeline."); return false; } if (!source->setVideoFormat(input_format)) { tcam_log(TCAM_LOG_ERROR, "Unable to set video format in source."); return false; } if (!sink->setVideoFormat(output_format)) { tcam_log(TCAM_LOG_ERROR, "Unable to set video format in sink."); return false; } if (!source->set_buffer_collection(sink->get_buffer_collection())) { tcam_log(TCAM_LOG_ERROR, "Unable to set buffer collection."); return false; } tcam_log(TCAM_LOG_INFO, "Pipeline creation successful."); std::string ppl = "source -> "; for (const auto& f : filter_pipeline) { ppl += f->getDescription().name; ppl += " -> "; } ppl += " sink"; tcam_log(TCAM_LOG_INFO, "%s" , ppl.c_str()); return true; } bool PipelineManager::start_playing () { if (!set_sink_status(TCAM_PIPELINE_PLAYING)) { tcam_log(TCAM_LOG_ERROR, "Sink refused to change to state PLAYING"); goto error; } if (!set_source_status(TCAM_PIPELINE_PLAYING)) { tcam_log(TCAM_LOG_ERROR, "Source refused to change to state PLAYING"); goto error; } status = TCAM_PIPELINE_PLAYING; return true; error: stop_playing(); return false; } bool PipelineManager::stop_playing () { status = TCAM_PIPELINE_STOPPED; if (!set_source_status(TCAM_PIPELINE_STOPPED)) { tcam_log(TCAM_LOG_ERROR, "Source refused to change to state STOP"); return false; } for (auto& f : filter_pipeline) { if (!f->setStatus(TCAM_PIPELINE_STOPPED)) { tcam_log(TCAM_LOG_ERROR, "Filter %s refused to change to state STOP", f->getDescription().name.c_str()); return false; } } set_sink_status(TCAM_PIPELINE_STOPPED); //destroyPipeline(); return true; } void PipelineManager::push_image (std::shared_ptr<MemoryBuffer> buffer) { if (status == TCAM_PIPELINE_STOPPED) { return; } auto& current_buffer = buffer; for (auto& f : filter_pipeline) { if (f->getDescription().type == FILTER_TYPE_INTERPRET) { f->apply(current_buffer); } else if (f->getDescription().type == FILTER_TYPE_CONVERSION) { auto next_buffer = pipeline_buffer.at(current_ppl_buffer); next_buffer->set_statistics(current_buffer->get_statistics()); f->transform(*current_buffer, *next_buffer); current_buffer = next_buffer; current_ppl_buffer++; if (current_ppl_buffer == pipeline_buffer.size()) current_ppl_buffer = 0; } } if (sink != nullptr) { sink->push_image(current_buffer); } else { tcam_log(TCAM_LOG_ERROR, "Sink is NULL"); } } void PipelineManager::requeue_buffer (std::shared_ptr<MemoryBuffer> buffer) { if (source) { source->requeue_buffer(buffer); } } std::vector<std::shared_ptr<MemoryBuffer>> PipelineManager::get_buffer_collection () { return std::vector<std::shared_ptr<MemoryBuffer>>(); }
41c99b4639b18f91d9acd054ec4d88da845add52
651bb470cf728abc1161da7dbee6099bff082ea3
/chardefs.inc
b4081e271b453df628aaf1c29d85569081e68a74
[]
no_license
glockwork/phMeter
5678d5bb2478e39a5814eba6c63d65c4fce38637
d037635390b26cbc4c511368cce6e2decc12a6ab
refs/heads/master
2020-12-30T23:34:09.083709
2011-01-25T19:08:19
2011-01-25T19:08:19
37,402,549
0
1
null
2015-06-14T06:55:54
2015-06-14T06:55:54
null
UTF-8
C++
false
false
223
inc
; Character descriptor structure .EQU CharCode = 0 .EQU CharWidth = 1 .EQU CharEntry = 2 ; Character set descriptor structure .EQU CharTable = 0 .EQU CharHeight = 2 .EQU CharDefaultWidth =3
4514451a7e7de063b79e12fbabd843845df0e3d6
e51863bee27f813e2febfe313ca67f45ea9296ec
/spyder/widgets/sourcecode/codeeditor.cpp
29651e615d690769bcecdaeaad3ac697671c1bd9
[]
no_license
sk8boy/MySpyder
3d2ed6dfcf2d29e78be163e5d7e1433651edd852
4db4f1eebcbfb337b10b2ab1220922d0da090b4c
refs/heads/master
2022-09-27T02:55:39.748340
2020-06-07T12:09:34
2020-06-07T12:09:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
126,638
cpp
#include "codeeditor.h" GoToLineDialog::GoToLineDialog(CodeEditor* editor) : QDialog (editor, Qt::WindowTitleHint | Qt::WindowCloseButtonHint) { setAttribute(Qt::WA_DeleteOnClose); lineno = -1; this->editor = editor; setWindowTitle("Editor"); setModal(true); QLabel *label = new QLabel("Go to line:"); lineedit = new QLineEdit; QIntValidator* validator = new QIntValidator(lineedit); validator->setRange(1, editor->get_line_count()); lineedit->setValidator(validator); connect(lineedit,SIGNAL(textChanged(const QString &)), this,SLOT(text_has_changed(const QString &))); QLabel *cl_label = new QLabel("Current line:"); QLabel *cl_label_v = new QLabel(QString("<b>%1</b>").arg(editor->get_cursor_line_number())); QLabel *last_label = new QLabel("Line count:"); QLabel *last_label_v = new QLabel(QString("%1").arg(editor->get_line_count())); QGridLayout* glayout = new QGridLayout(); glayout->addWidget(label, 0, 0, Qt::AlignVCenter|Qt::AlignRight); glayout->addWidget(lineedit, 0, 1, Qt::AlignVCenter); glayout->addWidget(cl_label, 1, 0, Qt::AlignVCenter|Qt::AlignRight); glayout->addWidget(cl_label_v, 1, 1, Qt::AlignVCenter); glayout->addWidget(last_label, 2, 0, Qt::AlignVCenter|Qt::AlignRight); glayout->addWidget(last_label_v, 2, 1, Qt::AlignVCenter); QDialogButtonBox* bbox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Vertical, this); connect(bbox,SIGNAL(accepted()),this,SLOT(accept())); connect(bbox,SIGNAL(rejected()),this,SLOT(reject())); QVBoxLayout* btnlayout = new QVBoxLayout; btnlayout->addWidget(bbox); btnlayout->addStretch(1); QPushButton* ok_button = bbox->button(QDialogButtonBox::Ok); ok_button->setEnabled(false); connect(lineedit,&QLineEdit::textChanged, [=](const QString& text) { ok_button->setEnabled(text.size()>0); }); QHBoxLayout* layout = new QHBoxLayout; layout->addLayout(glayout); layout->addLayout(btnlayout); setLayout(layout); lineedit->setFocus(); } void GoToLineDialog::text_has_changed(const QString &text) { if (!text.isEmpty()) lineno = text.toInt(); else lineno = -1; } int GoToLineDialog::get_line_number() { return lineno; } //***********Viewport widgets LineNumberArea::LineNumberArea(CodeEditor* editor) : QWidget (editor) { code_editor = editor; setMouseTracking(true); } QSize LineNumberArea::sizeHint() const { return QSize(code_editor->compute_linenumberarea_width(), 0); } void LineNumberArea::paintEvent(QPaintEvent *event) { code_editor->linenumberarea_paint_event(event); } void LineNumberArea::mouseMoveEvent(QMouseEvent *event) { code_editor->linenumberarea_mousemove_event(event); } void LineNumberArea::mouseDoubleClickEvent(QMouseEvent *event) { code_editor->linenumberarea_mousedoubleclick_event(event); } void LineNumberArea::mousePressEvent(QMouseEvent *event) { code_editor->linenumberarea_mousepress_event(event); } void LineNumberArea::mouseReleaseEvent(QMouseEvent *event) { code_editor->linenumberarea_mouserelease_event(event); } void LineNumberArea::wheelEvent(QWheelEvent *event) { code_editor->wheelEvent(event); } int ScrollFlagArea::WIDTH = 12; int ScrollFlagArea::FLAGS_DX = 4; int ScrollFlagArea::FLAGS_DY = 2; ScrollFlagArea::ScrollFlagArea(CodeEditor* editor) : QWidget (editor) { setAttribute(Qt::WA_OpaquePaintEvent); code_editor = editor; connect(editor->verticalScrollBar(),&QAbstractSlider::valueChanged, [=](int) { this->repaint(); }); } QSize ScrollFlagArea::sizeHint() const { return QSize(WIDTH, 0); } void ScrollFlagArea::paintEvent(QPaintEvent *event) { code_editor->scrollflagarea_paint_event(event); } void ScrollFlagArea::mousePressEvent(QMouseEvent *event) { QScrollBar* vsb = code_editor->verticalScrollBar(); double value = this->position_to_value(event->pos().y()-1); vsb->setValue(static_cast<int>(value-.5*vsb->pageStep())); } double ScrollFlagArea::get_scale_factor(bool slider) const { int delta = slider ? 0 : 2; QScrollBar* vsb = code_editor->verticalScrollBar(); int position_height = vsb->height() - delta - 1; int value_height = vsb->maximum()-vsb->minimum()+vsb->pageStep(); return static_cast<double>(position_height) / value_height; } double ScrollFlagArea::value_to_position(int y, bool slider) const { int offset = slider ? 0 : 1; QScrollBar* vsb = code_editor->verticalScrollBar(); return (y-vsb->minimum())*this->get_scale_factor(slider)+offset; } double ScrollFlagArea::position_to_value(int y, bool slider) const { int offset = slider ? 0 : 1; QScrollBar* vsb = code_editor->verticalScrollBar(); return vsb->minimum()+qMax(0.0, (y-offset)/this->get_scale_factor(slider)); } QRect ScrollFlagArea::make_flag_qrect(int position) const { return QRect(FLAGS_DX/2, position-FLAGS_DY/2, WIDTH-FLAGS_DX, FLAGS_DY); } QRect ScrollFlagArea::make_slider_range(int value) const { QScrollBar* vsb = code_editor->verticalScrollBar(); double pos1 = value_to_position(value, true); double pos2 = value_to_position(value + vsb->pageStep(), true); return QRect(1, static_cast<int>(pos1), WIDTH-2, static_cast<int>(pos2-pos1+1)); } void ScrollFlagArea::wheelEvent(QWheelEvent *event) { code_editor->wheelEvent(event); } //============EdgeLine EdgeLine::EdgeLine(QWidget* editor) : QWidget (editor) { code_editor = editor; column = 79; setAttribute(Qt::WA_TransparentForMouseEvents); } void EdgeLine::paintEvent(QPaintEvent *event) { QPainter painter(this); QColor color(Qt::darkGray); color.setAlphaF(0.5); painter.fillRect(event->rect(), color); } //============BlockUserData BlockUserData::BlockUserData(CodeEditor* editor) : QTextBlockUserData () { this->editor = editor; this->breakpoint = false; this->breakpoint_condition = QString(); this->code_analysis = QList<QPair<QString,bool>>(); this->todo = ""; this->editor->blockuserdata_list.append(this); } bool BlockUserData::is_empty() { return (!breakpoint) && (code_analysis.isEmpty()) && (todo.isEmpty()); } void BlockUserData::del() { editor->blockuserdata_list.removeOne(this); delete this; } static void set_scrollflagarea_painter(QPainter* painter,const QString& light_color) { painter->setPen(QColor(light_color).darker(120)); painter->setBrush(QBrush(QColor(light_color))); } //提供该函数对QColor的重载是为了scrollflagarea_paint_event()函数 static void set_scrollflagarea_painter(QPainter* painter,const QColor& light_color) { painter->setPen(QColor(light_color).darker(120)); painter->setBrush(QBrush(QColor(light_color))); } QString get_file_language(const QString& filename,QString text) { QFileInfo info(filename); QString ext = info.suffix(); QString language = ext; if (ext.isEmpty()) { if (text.isEmpty()) { text = encoding::read(filename); } foreach (QString line, splitlines(text)) { if (line.trimmed().isEmpty()) continue; if (line.startsWith("#!")) { QString shebang = line.mid(2); if (shebang.contains("python")) language = "python"; } else break; } } return language; } /********** CodeEditor **********/ CodeEditor::CodeEditor(QWidget* parent) : TextEditBaseWidget (parent) { this->LANGUAGES = {{"Python", {"PythonSH", "#"}}, {"Cpp", {"CppSH", "//"}}, {"Markdown", {"MarkdownSH", "#"}}}; this->TAB_ALWAYS_INDENTS = QStringList({"py", "pyw", "python", "c", "cpp", "cl", "h"}); setFocusPolicy(Qt::StrongFocus); setCursorWidth(CONF_get("main", "cursor/width").toInt()); edge_line_enabled = true; edge_line = new EdgeLine(this); blanks_enabled = false; markers_margin = true; markers_margin_width = 15; error_pixmap = ima::icon("error").pixmap(QSize(14, 14)); warning_pixmap = ima::icon("warning").pixmap(QSize(14, 14)); todo_pixmap = ima::icon("todo").pixmap(QSize(14, 14)); bp_pixmap = ima::icon("breakpoint_big").pixmap(QSize(14, 14)); bpc_pixmap = ima::icon("breakpoint_cond_big").pixmap(QSize(14, 14)); linenumbers_margin = true; linenumberarea_enabled = false; linenumberarea = new LineNumberArea(this); connect(this,SIGNAL(blockCountChanged(int)), this,SLOT(update_linenumberarea_width(int))); connect(this,SIGNAL(updateRequest(QRect,int)), this,SLOT(update_linenumberarea(QRect,int))); linenumberarea_pressed = -1; linenumberarea_released = -1; occurrence_color = QColor(); ctrl_click_color = QColor(); sideareas_color = QColor(); matched_p_color = QColor(); unmatched_p_color = QColor(); normal_color = QColor(); comment_color = QColor(); linenumbers_color = QColor(Qt::darkGray); highlighter_class = "TextSH"; highlighter = nullptr; //QString ccs = "Spyder"; //if (!sh::COLOR_SCHEME_NAMES.contains(ccs)) // ccs = sh::COLOR_SCHEME_NAMES[0]; this->color_scheme = sh::get_color_scheme(); highlight_current_line_enabled = false; scrollflagarea_enabled = false; scrollflagarea = new ScrollFlagArea(this); scrollflagarea->hide(); warning_color = "#FFAD07"; error_color = "#EA2B0E"; todo_color = "#B4D4F3"; breakpoint_color = "#30E62E"; this->update_linenumberarea_width(); document_id = reinterpret_cast<size_t>(this); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(__cursor_position_changed())); __find_first_pos = -1; __find_flags = -1;//本代码并没有用到 supported_language = false; supported_cell_language = false; // classfunc_match = None comment_string = QString(); _kill_ring = new QtKillRing(this); blockuserdata_list = QList<BlockUserData*>(); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(update_breakpoints())); timer_syntax_highlight = new QTimer(this); timer_syntax_highlight->setSingleShot(true); timer_syntax_highlight->setInterval(300); connect(timer_syntax_highlight,SIGNAL(timeout()), this,SLOT(run_pygments_highlighter())); occurrence_highlighting = false; occurrence_timer = new QTimer(this); occurrence_timer->setSingleShot(true); occurrence_timer->setInterval(1500); connect(occurrence_timer,SIGNAL(timeout()), this,SLOT(__mark_occurrences())); occurrences = QList<int>(); occurrence_color = QColor(Qt::yellow).lighter(160); connect(this,SIGNAL(textChanged()),this,SLOT(__text_has_changed())); found_results = QList<int>(); found_results_color = QColor(Qt::magenta).lighter(180); gotodef_action = nullptr; this->setup_context_menu(); tab_indents = false; tab_mode = true; intelligent_backspace = true; go_to_definition_enabled = false; close_parentheses_enabled = true; close_quotes_enabled = false; add_colons_enabled = true; auto_unindent_enabled = true; this->setMouseTracking(true); __cursor_changed = false; ctrl_click_color = QColor(Qt::blue); this->breakpoints = this->get_breakpoints(); shortcuts = this->create_shortcuts(); __visible_blocks = QList<IntIntTextblock>(); connect(this,SIGNAL(painted(QPaintEvent*)),SLOT(_draw_editor_cell_divider())); connect(verticalScrollBar(),&QAbstractSlider::valueChanged, [=](int){ this->rehighlight_cells(); }); } void CodeEditor::cb_maker(int attr) { QTextCursor cursor = this->textCursor(); auto move_type = static_cast<QTextCursor::MoveOperation>(attr); cursor.movePosition(move_type); this->setTextCursor(cursor); } QList<ShortCutStrStr> CodeEditor::create_shortcuts() { QString keystr = "Ctrl+Space"; QShortcut* qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,&QShortcut::activated, [=](){ this->do_completion(false); }); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr codecomp(qsc,"Editor","Code Completion"); keystr = "Ctrl+Alt+Up"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(duplicate_line())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr duplicate_line(qsc,"Editor","Duplicate line"); keystr = "Ctrl+Alt+Down"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(copy_line())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr copyline(qsc,"Editor","Copy line"); keystr = "Ctrl+D"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(delete_line())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr deleteline(qsc,"Editor","Delete line"); keystr = "Alt+Up"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(move_line_up())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr movelineup(qsc,"Editor","Move line up"); keystr = "Alt+Down"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(move_line_down())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr movelinedown(qsc,"Editor","Move line down"); keystr = "Ctrl+Shift+Return"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(go_to_new_line())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr gotonewline(qsc,"Editor","Go to new line"); keystr = "Ctrl+G"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(do_go_to_definition())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr gotodef(qsc,"Editor","Go to definition"); keystr = "Ctrl+1"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(toggle_comment())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr toggle_comment(qsc,"Editor","Toggle comment"); keystr = "Ctrl+4"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(blockcomment())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr blockcomment(qsc,"Editor","Blockcomment"); keystr = "Ctrl+5"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(unblockcomment())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr unblockcomment(qsc,"Editor","Unblockcomment"); keystr = "Ctrl+Shift+U"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(transform_to_uppercase())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr transform_uppercase(qsc,"Editor","Transform to uppercase"); keystr = "Ctrl+U"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(transform_to_lowercase())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr transform_lowercase(qsc,"Editor","Transform to lowercase"); // lambda表达式 keystr = "Ctrl+]"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,&QShortcut::activated,[=]() { this->indent(true); }); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr indent(qsc,"Editor","Indent"); keystr = "Ctrl+["; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,&QShortcut::activated,[=]() { this->unindent(true); }); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr unindent(qsc,"Editor","Unindent"); QSignalMapper* signalMapper = new QSignalMapper(this); keystr = "Meta+A";// qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::StartOfLine));// qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr line_start(qsc,"Editor","Start of line");// keystr = "Meta+E"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::EndOfLine)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr line_end(qsc,"Editor","End of line"); keystr = "Meta+P"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Up)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr prev_line(qsc,"Editor","Previous line"); keystr = "Meta+N"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Down)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr next_line(qsc,"Editor","Next line"); keystr = "Meta+B"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Left)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr prev_char(qsc,"Editor","Previous char"); keystr = "Meta+F"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Right)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr next_char(qsc,"Editor","Next char"); keystr = "Meta+Left"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::PreviousWord)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr prev_word(qsc,"Editor","Previous word"); keystr = "Meta+Right"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::NextWord)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr next_word(qsc,"Editor","Next word"); keystr = "Meta+K"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_line_end())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr kill_line_end(qsc,"Editor","Kill to line end"); keystr = "Meta+U"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_line_start())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr kill_line_start(qsc,"Editor","Kill to line start"); keystr = "Meta+Y"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),_kill_ring,SLOT(yank())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr yank(qsc,"Editor","Yank"); keystr = "Shift+Meta+Y"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),_kill_ring,SLOT(rotate())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr kill_ring_rotate(qsc,"Editor","Rotate kill ring"); keystr = "Meta+Backspace"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_prev_word())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr kill_prev_word(qsc,"Editor","Kill previous word"); keystr = "Meta+D"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_next_word())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr kill_next_word(qsc,"Editor","Kill next word"); // keystr = "Ctrl+Home"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Start)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr start_doc(qsc,"Editor","Start of Document"); keystr = "Ctrl+End"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map())); signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::End)); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr end_doc(qsc,"Editor","End of Document"); // connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(cb_maker(int))); keystr = "Ctrl+Z"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(undo())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr undo(qsc,"Editor","undo"); keystr = "Ctrl+Shift+Z"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(redo())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr redo(qsc,"Editor","redo"); keystr = "Ctrl+X"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(cut())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr cut(qsc,"Editor","cut"); keystr = "Ctrl+C"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(copy())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr copy(qsc,"Editor","undo"); keystr = "Ctrl+V"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(paste())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr paste(qsc,"Editor","paste"); keystr = "Delete"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(_delete())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr _delete(qsc,"Editor","delete"); keystr = "Ctrl+A"; qsc = new QShortcut(QKeySequence(keystr), this, SLOT(selectAll())); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr select_all(qsc,"Editor","Select All"); // lambda表达式 keystr = "Ctrl+Alt+M"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,&QShortcut::activated,[=]() { this->enter_array_inline(); }); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr array_inline(qsc,"array_builder","enter array inline"); keystr = "Ctrl+M"; qsc = new QShortcut(QKeySequence(keystr), this); connect(qsc,&QShortcut::activated,[=]() { this->enter_array_table(); }); qsc->setContext(Qt::WidgetWithChildrenShortcut); ShortCutStrStr array_table(qsc,"array_builder","enter array table"); QList<ShortCutStrStr> res; res << codecomp<< duplicate_line<< copyline<< deleteline<< movelineup << movelinedown<< gotonewline<< gotodef<< toggle_comment<< blockcomment << unblockcomment<< transform_uppercase<< transform_lowercase << line_start<< line_end<< prev_line<< next_line << prev_char<< next_char<< prev_word<< next_word<< kill_line_end << kill_line_start<< yank<< kill_ring_rotate<< kill_prev_word << kill_next_word<< start_doc<< end_doc<< undo<< redo<< cut<< copy << paste<< _delete<< select_all<< array_inline<< array_table<< indent << unindent; return res; } QList<ShortCutStrStr> CodeEditor::get_shortcut_data() { return shortcuts; } void CodeEditor::closeEvent(QCloseEvent *event) { TextEditBaseWidget::closeEvent(event); } size_t CodeEditor::get_document_id() { return document_id; } void CodeEditor::set_as_clone(CodeEditor *editor) { // Set as clone editor this->setDocument(editor->document()); document_id = editor->get_document_id(); highlighter = editor->highlighter; eol_chars = editor->eol_chars; this->_apply_highlighter_color_scheme(); } //-----Widget setup and options void CodeEditor::toggle_wrap_mode(bool enable) { this->set_wrap_mode(enable ? "word" : QString()); } void CodeEditor::setup_editor(const QHash<QString, QVariant> &kwargs) { bool linenumbers = kwargs.value("linenumbers", true).toBool(); QString language = kwargs.value("language", QString()).toString(); bool markers = kwargs.value("markers", false).toBool(); // font QHash<QString, QVariant> dict = kwargs.value("color_scheme", QHash<QString, QVariant>()).toHash(); QHash<QString, ColorBoolBool> color_scheme; for (auto it=dict.begin();it!=dict.end();it++) { QString key = it.key(); ColorBoolBool val = it.value().value<ColorBoolBool>(); color_scheme[key] = val; } bool wrap = kwargs.value("wrap", false).toBool(); bool tab_mode = kwargs.value("tab_mode", true).toBool(); bool intelligent_backspace = kwargs.value("intelligent_backspace", true).toBool(); bool highlight_current_line = kwargs.value("highlight_current_line", true).toBool(); bool highlight_current_cell = kwargs.value("highlight_current_cell", true).toBool(); bool occurrence_highlighting= kwargs.value("occurrence_highlighting", true).toBool(); bool scrollflagarea = kwargs.value("scrollflagarea", true).toBool(); bool edge_line = kwargs.value("edge_line", true).toBool(); int edge_line_column = kwargs.value("edge_line_column", 79).toInt(); bool codecompletion_auto = kwargs.value("codecompletion_auto", false).toBool(); bool codecompletion_case = kwargs.value("codecompletion_case", true).toBool(); bool codecompletion_enter = kwargs.value("codecompletion_enter", false).toBool(); bool show_blanks = kwargs.value("show_blanks", false).toBool(); // calltips bool go_to_definition = kwargs.value("go_to_definition", false).toBool(); bool close_parentheses = kwargs.value("close_parentheses", true).toBool(); bool close_quotes = kwargs.value("close_quotes", false).toBool(); bool add_colons = kwargs.value("add_colons", true).toBool(); bool auto_unindent = kwargs.value("auto_unindent", true).toBool(); QString indent_chars = kwargs.value("indent_chars", QString(4,' ')).toString(); int tab_stop_width_spaces = kwargs.value("tab_stop_width_spaces", 4).toInt(); // cloned_from QString filename = kwargs.value("filename", QString()).toString(); int occurrence_timeout = kwargs.value("occurrence_timeout", 1500).toInt(); this->set_codecompletion_auto(codecompletion_auto); this->set_codecompletion_case(codecompletion_case); this->set_codecompletion_enter(codecompletion_enter); if (kwargs.contains("calltips")) this->set_calltips(kwargs.value("calltips").toBool()); this->set_go_to_definition_enabled(go_to_definition); this->set_close_parentheses_enabled(close_parentheses); this->set_close_quotes_enabled(close_quotes); this->set_add_colons_enabled(add_colons); this->set_auto_unindent_enabled(auto_unindent); this->set_indent_chars(indent_chars); this->set_scrollflagarea_enabled(scrollflagarea); this->set_edge_line_enabled(edge_line); this->set_edge_line_column(edge_line_column); this->set_blanks_enabled(show_blanks); if (kwargs.contains("cloned_from") && kwargs.contains("font")) this->setFont(kwargs.value("font").value<QFont>()); this->setup_margins(linenumbers, markers); this->set_language(language, filename); this->set_highlight_current_cell(highlight_current_cell); this->set_highlight_current_line(highlight_current_line); this->set_occurrence_highlighting(occurrence_highlighting); this->set_occurrence_timeout(occurrence_timeout); this->set_tab_mode(tab_mode); this->toggle_intelligent_backspace(intelligent_backspace); if (kwargs.contains("cloned_from")) { size_t id = kwargs.value("cloned_from").toULongLong(); CodeEditor* cloned_from = reinterpret_cast<CodeEditor*>(id); this->set_as_clone(cloned_from); this->update_linenumberarea_width(); } else if (kwargs.contains("font")) { QFont font = kwargs.value("font").value<QFont>(); this->set_font(font, color_scheme); } else if (!color_scheme.isEmpty()) this->set_color_scheme(color_scheme); this->set_tab_stop_width_spaces(tab_stop_width_spaces); this->toggle_wrap_mode(wrap); } void CodeEditor::setup_editor(bool linenumbers, const QString& language, bool markers, const QFont& font, const QHash<QString, ColorBoolBool> &color_scheme, bool wrap, bool tab_mode, bool intelligent_backspace, bool highlight_current_line, bool highlight_current_cell, bool occurrence_highlighting, bool scrollflagarea, bool edge_line, int edge_line_column, bool codecompletion_auto, bool codecompletion_case, bool codecompletion_enter, bool show_blanks, bool calltips, bool go_to_definition, bool close_parentheses, bool close_quotes, bool add_colons, bool auto_unindent, const QString& indent_chars, int tab_stop_width_spaces, CodeEditor* cloned_from, const QString& filename, int occurrence_timeout) { //# Code completion and calltips set_codecompletion_auto(codecompletion_auto); set_codecompletion_case(codecompletion_case); set_codecompletion_enter(codecompletion_enter); set_calltips(calltips); set_go_to_definition_enabled(go_to_definition); set_close_parentheses_enabled(close_parentheses); set_close_quotes_enabled(close_quotes); set_add_colons_enabled(add_colons); set_auto_unindent_enabled(auto_unindent); set_indent_chars(indent_chars); set_scrollflagarea_enabled(scrollflagarea); set_edge_line_enabled(edge_line); set_edge_line_column(edge_line_column); set_blanks_enabled(show_blanks); if (cloned_from) setFont(font); setup_margins(linenumbers, markers); set_language(language, filename); set_highlight_current_cell(highlight_current_cell); set_highlight_current_line(highlight_current_line); set_occurrence_highlighting(occurrence_highlighting); set_occurrence_timeout(occurrence_timeout); set_tab_mode(tab_mode); toggle_intelligent_backspace(intelligent_backspace); if (cloned_from) { set_as_clone(cloned_from); update_linenumberarea_width(); } else if (font != this->font()) set_font(font, color_scheme); else if (!color_scheme.isEmpty()) set_color_scheme(color_scheme); set_tab_stop_width_spaces(tab_stop_width_spaces); toggle_wrap_mode(wrap); } void CodeEditor::set_tab_mode(bool enable) { this->tab_mode = enable; } void CodeEditor::toggle_intelligent_backspace(bool state) { this->intelligent_backspace = state; } void CodeEditor::set_go_to_definition_enabled(bool enable) { this->go_to_definition_enabled = enable; } void CodeEditor::set_close_parentheses_enabled(bool enable) { this->close_parentheses_enabled = enable; } void CodeEditor::set_close_quotes_enabled(bool enable) { this->close_quotes_enabled = enable; } void CodeEditor::set_add_colons_enabled(bool enable) { this->add_colons_enabled = enable; } void CodeEditor::set_auto_unindent_enabled(bool enable) { this->auto_unindent_enabled = enable; } void CodeEditor::set_occurrence_highlighting(bool enable) { this->occurrence_highlighting = enable; if (!enable) this->__clear_occurrences(); } void CodeEditor::set_occurrence_timeout(int timeout) { this->occurrence_timer->setInterval(timeout); } void CodeEditor::set_highlight_current_line(bool enable) { this->highlight_current_line_enabled = enable; if (this->highlight_current_line_enabled) this->highlight_current_line(); else this->unhighlight_current_line(); } void CodeEditor::set_highlight_current_cell(bool enable) { bool hl_cell_enable = enable && this->supported_cell_language; this->highlight_current_cell_enabled = hl_cell_enable; if (this->highlight_current_cell_enabled) this->highlight_current_cell(); else this->unhighlight_current_cell(); } void CodeEditor::set_language(const QString &language, const QString &filename) { this->tab_indents = this->TAB_ALWAYS_INDENTS.contains(language); this->comment_string = ""; QString sh_class = "TextSH"; if (!language.isEmpty()) { //以后在这里添加别的语言,记得在构造函数更新LANGUAGES成员 QStringList list({"Python", "Cpp", "Markdown"}); foreach (QString key, list) { if (sourcecode::ALL_LANGUAGES[key].contains(language.toLower())) { this->supported_language = true; sh_class = LANGUAGES[key][0]; QString comment_string = LANGUAGES[key][1]; this->comment_string = comment_string; //key in CELL_LANGUAGES等价于key == "Python" if (key == "Python") { this->supported_cell_language = true; this->cell_separators = sourcecode::CELL_LANGUAGES[key]; } break; } } } this->_set_highlighter(sh_class); } void CodeEditor::_set_highlighter(const QString& sh_class) { this->highlighter_class = sh_class; if (this->highlighter) { this->highlighter->setParent(nullptr); this->highlighter->setDocument(nullptr); } if (highlighter_class == "PythonSH") { highlighter = new sh::PythonSH(this->document(), this->font(), this->color_scheme); } else if (highlighter_class == "CppSH") highlighter = new sh::CppSH(this->document(), this->font(), this->color_scheme); else if (highlighter_class == "MarkdownSH") highlighter = new sh::MarkdownSH(this->document(), this->font(), this->color_scheme); else if (highlighter_class == "TextSH") highlighter = new sh::TextSH(this->document(), this->font(), this->color_scheme); this->_apply_highlighter_color_scheme(); } bool CodeEditor::is_json() { //需要pygments第三方库 return false; } bool CodeEditor::is_python() { return this->highlighter_class == "PythonSH"; } bool CodeEditor::is_cpp() { return this->highlighter_class == "CppSH"; } bool CodeEditor::is_cython() { return this->highlighter_class == "CythonSH"; } bool CodeEditor::is_enmal() { return this->highlighter_class == "EnamlSH"; } bool CodeEditor::is_python_like() { return this->is_python() || this->is_cython() || this->is_enmal(); } void CodeEditor::intelligent_tab() { QString leading_text = this->get_text("sol","cursor"); if (leading_text.trimmed().isEmpty() || leading_text.endsWith('#')) this->indent_or_replace(); else if (this->in_comment_or_string() && !leading_text.endsWith(" ")) this->do_completion(); else if (leading_text.endsWith("import ") || leading_text.back()=='.') this->do_completion(); else if ((leading_text.split(QRegularExpression("\\s+"))[0]=="from" || leading_text.split(QRegularExpression("\\s+"))[0]=="import") && !leading_text.contains(';')) this->do_completion(); else if (leading_text.back()=='(' || leading_text.back()==',' || leading_text.endsWith(", ")) this->indent_or_replace(); else if (leading_text.endsWith(' ')) this->indent_or_replace(); // \W匹配非数字字母下划线;\Z匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串 else if (leading_text.indexOf(QRegularExpression("[^\\d\\W]\\w*\\Z", QRegularExpression::UseUnicodePropertiesOption)) > -1) this->do_completion(); else this->indent_or_replace(); } void CodeEditor::intelligent_backtab() { QString leading_text = this->get_text("sol","cursor"); if (leading_text.trimmed().isEmpty()) this->unindent(); else if (this->in_comment_or_string()) this->unindent(); else if (leading_text.back()=='(' || leading_text.back()==',' || leading_text.endsWith(", ")) { int position = this->get_position("cursor"); this->show_object_info(position); } else this->unindent(); } //****************************** void CodeEditor::rehighlight() { if (this->highlighter) this->highlighter->rehighlight(); if (this->highlight_current_cell_enabled) this->highlight_current_cell(); else this->unhighlight_current_cell(); if (this->highlight_current_line_enabled) this->highlight_current_line(); else this->unhighlight_current_line(); } void CodeEditor::rehighlight_cells() { if (this->highlight_current_cell_enabled) this->highlight_current_cell(); } void CodeEditor::setup_margins(bool linenumbers, bool markers) { this->linenumbers_margin = linenumbers; this->markers_margin = markers; this->set_linenumberarea_enabled(linenumbers || markers); } void CodeEditor::remove_trailing_spaces() { // 删除尾随空格 QTextCursor cursor = this->textCursor(); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::Start); while (true) { cursor.movePosition(QTextCursor::EndOfBlock); QString text = cursor.block().text(); int length = text.size() - rstrip(text).size(); if (length > 0) { cursor.movePosition(QTextCursor::Left,QTextCursor::KeepAnchor, length); cursor.removeSelectedText(); } if (cursor.atEnd()) break; cursor.movePosition(QTextCursor::NextBlock); } cursor.endEditBlock(); } void CodeEditor::fix_indentation() { QString text_before = this->toPlainText(); QString text_after = sourcecode::fix_indentation(text_before); if (text_before != text_after) { this->setPlainText(text_before); this->document()->setModified(true); } } QString CodeEditor::get_current_object() { QString source_code = this->toPlainText(); int offset = this->get_position("cursor"); return sourcecode::get_primary_at(source_code, offset); } //@Slot() void CodeEditor::_delete() { if (!this->has_selected_text()) { QTextCursor cursor = this->textCursor(); int position = cursor.position(); if (!cursor.atEnd()) cursor.setPosition(position+1, QTextCursor::KeepAnchor); this->setTextCursor(cursor); // 这里调用了setTextCursor更新可见光标 } this->remove_selected_text(); } //------Find occurrences QTextCursor CodeEditor::__find_first(const QString &text) { QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::Start); QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)), Qt::CaseSensitive); cursor = this->document()->find(regexp, cursor, flags); this->__find_first_pos = cursor.position(); return cursor; } QTextCursor CodeEditor::__find_next(const QString &text, QTextCursor cursor) { QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)), Qt::CaseSensitive); cursor = this->document()->find(regexp, cursor, flags); if (cursor.position() != this->__find_first_pos) return cursor; return QTextCursor(); } void CodeEditor::__cursor_position_changed() { auto pair = this->get_cursor_line_column(); int line = pair.first, column=pair.second; emit sig_cursor_position_changed(line,column); if (this->highlight_current_cell_enabled) this->highlight_current_cell(); else this->unhighlight_current_cell(); if (this->highlight_current_line_enabled) this->highlight_current_line(); else this->unhighlight_current_line(); if (this->occurrence_highlighting) { this->occurrence_timer->stop(); this->occurrence_timer->start(); } } void CodeEditor::__clear_occurrences() { occurrences.clear(); clear_extra_selections("occurrences"); scrollflagarea->update(); } void CodeEditor::__highlight_selection(const QString &key, const QTextCursor &cursor, const QColor &foreground_color, const QColor &background_color, const QColor &underline_color, QTextCharFormat::UnderlineStyle underline_style, bool update) { QList<QTextEdit::ExtraSelection> extra_selections = get_extra_selections(key); QTextEdit::ExtraSelection selection; if (foreground_color.isValid()) selection.format.setForeground(foreground_color); if (background_color.isValid()) selection.format.setBackground(background_color); if (underline_color.isValid()) { selection.format.setProperty(QTextFormat::TextUnderlineStyle, underline_style); selection.format.setProperty(QTextFormat::TextUnderlineColor, underline_color); } selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = cursor; extra_selections.append(selection); set_extra_selections(key,extra_selections); if (update) update_extra_selections(); } //@Slot() void CodeEditor::__mark_occurrences() { __clear_occurrences(); if (!supported_language) return; QString text = get_current_word(); if (text.isEmpty()) return; if (has_selected_text() && get_selected_text()!=text) return; if (is_python_like() && (sourcecode::is_keyword(text) || text == "self")) return; QTextCursor cursor = this->__find_first(text); occurrences.clear(); while (!cursor.isNull()) { occurrences.append(cursor.blockNumber()); __highlight_selection("occurrences",cursor, QColor(),occurrence_color); cursor = __find_next(text, cursor); } update_extra_selections(); if (occurrences.size() > 1 && occurrences.last()==0) occurrences.pop_back(); scrollflagarea->update(); } //-----highlight found results (find/replace widget) void CodeEditor::highlight_found_results(QString pattern, bool words, bool regexp) { if (pattern.isEmpty()) return; if (!regexp) pattern = QRegularExpression::escape(pattern); pattern = words ? QString("\\b%1\\b").arg(pattern) : pattern; QString text = this->toPlainText(); QRegularExpression regobj(pattern); if (!regobj.isValid()) return; QList<QTextEdit::ExtraSelection> extra_selections; found_results.clear(); QRegularExpressionMatchIterator iterator = regobj.globalMatch(text); while (iterator.hasNext()) { QRegularExpressionMatch match = iterator.next(); int pos1 = match.capturedStart(); int pos2 = match.capturedEnd(); QTextEdit::ExtraSelection selection; selection.format.setBackground(found_results_color); selection.cursor = this->textCursor(); selection.cursor.setPosition(pos1); found_results.append(selection.cursor.blockNumber()); selection.cursor.setPosition(pos2,QTextCursor::KeepAnchor); extra_selections.append(selection); } set_extra_selections("find", extra_selections); update_extra_selections(); } void CodeEditor::clear_found_results() { found_results.clear(); clear_extra_selections("find"); scrollflagarea->update(); } void CodeEditor::__text_has_changed() { if (!found_results.isEmpty()) clear_found_results(); } //-----markers int CodeEditor::get_markers_margin() { if (markers_margin) return markers_margin_width; else return 0; } //-----linenumberarea void CodeEditor::set_linenumberarea_enabled(bool state) { linenumberarea_enabled = state; linenumberarea->setVisible(state); update_linenumberarea_width(); } int CodeEditor::get_linenumberarea_width() { return linenumberarea->contentsRect().width(); } int CodeEditor::compute_linenumberarea_width() { if (!linenumberarea_enabled) return 0; int digits = 1; int maxb = qMax(1, blockCount()); while (maxb >= 10) { maxb /= 10; digits++; } int linenumbers_margin; if (this->linenumbers_margin) linenumbers_margin = 3+this->fontMetrics().width(QString(digits,'9')); else linenumbers_margin = 0; return linenumbers_margin + this->get_markers_margin(); } void CodeEditor::update_linenumberarea_width(int new_block_count) { Q_UNUSED(new_block_count); this->setViewportMargins(this->compute_linenumberarea_width(),0, this->get_scrollflagarea_width(),0); } void CodeEditor::update_linenumberarea(const QRect &qrect, int dy) { if (dy) this->linenumberarea->scroll(0, dy); else this->linenumberarea->update(0, qrect.y(), linenumberarea->width(), qrect.height()); if (qrect.contains(this->viewport()->rect())) this->update_linenumberarea_width(); } void CodeEditor::linenumberarea_paint_event(QPaintEvent *event) { QPainter painter(this->linenumberarea); painter.fillRect(event->rect(), this->sideareas_color); QFont font = this->font(); int font_height = this->fontMetrics().height(); QTextBlock active_block = this->textCursor().block(); int active_line_number = active_block.blockNumber()+1; auto draw_pixmap = [&](int ytop, const QPixmap &pixmap) { int pixmap_height; #if QT_VERSION < QT_VERSION_CHECK(5, 5, 0) pixmap_height = pixmap.height(); #else pixmap_height = static_cast<int>(pixmap.height() / pixmap.devicePixelRatio()); #endif painter.drawPixmap(0, ytop + (font_height-pixmap_height) / 2, pixmap); }; foreach (auto pair, this->__visible_blocks) { int top = pair.top; int line_number = pair.line_number; QTextBlock block = pair.block; if (this->linenumbers_margin) { if (line_number == active_line_number) { font.setWeight(font.Bold); painter.setFont(font); painter.setPen(this->normal_color); } else { font.setWeight(font.Normal); painter.setFont(font); painter.setPen(this->linenumbers_color); } painter.drawText(0, top, linenumberarea->width(), font_height, Qt::AlignRight | Qt::AlignBottom, QString::number(line_number)); } BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (this->markers_margin && data) { if (!data->code_analysis.isEmpty()) { bool error = false; foreach (auto pair, data->code_analysis) { error = pair.second; if (error) break; } if (error) draw_pixmap(top,error_pixmap); else draw_pixmap(top,warning_pixmap); } if (!data->todo.isEmpty()) draw_pixmap(top,todo_pixmap); if (data->breakpoint) { if (data->breakpoint_condition.isEmpty()) draw_pixmap(top,this->bp_pixmap); else draw_pixmap(top,this->bpc_pixmap); } } } } int CodeEditor::__get_linenumber_from_mouse_event(QMouseEvent *event) { QTextBlock block = firstVisibleBlock(); int line_number = block.blockNumber(); double top = blockBoundingGeometry(block). translated(this->contentOffset()).top(); double bottom = top + blockBoundingRect(block).height(); while (block.isValid() && top < event->pos().y()) { block = block.next(); top = bottom; bottom = top + blockBoundingRect(block).height(); line_number++; } return line_number; } void CodeEditor::linenumberarea_mousemove_event(QMouseEvent *event) { int line_number = __get_linenumber_from_mouse_event(event); QTextBlock block = document()->findBlockByNumber(line_number-1); BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); bool check = this->linenumberarea_released == -1; if (data && !data->code_analysis.isEmpty() && check) this->__show_code_analysis_results(line_number,data->code_analysis); if (event->buttons() == Qt::LeftButton) { this->linenumberarea_released = line_number; this->linenumberarea_select_lines(this->linenumberarea_pressed, this->linenumberarea_released); } } void CodeEditor::linenumberarea_mousedoubleclick_event(QMouseEvent *event) { int line_number = this->__get_linenumber_from_mouse_event(event); bool shift = event->modifiers() & Qt::ShiftModifier; this->add_remove_breakpoint(line_number,QString(),shift); } void CodeEditor::linenumberarea_mousepress_event(QMouseEvent *event) { int line_number = this->__get_linenumber_from_mouse_event(event); this->linenumberarea_pressed = line_number; this->linenumberarea_released = line_number; this->linenumberarea_select_lines(this->linenumberarea_pressed, this->linenumberarea_released); } void CodeEditor::linenumberarea_mouserelease_event(QMouseEvent *event) { Q_UNUSED(event); this->linenumberarea_pressed = -1; this->linenumberarea_released = -1; } void CodeEditor::linenumberarea_select_lines(int linenumber_pressed, int linenumber_released) { int move_n_blocks = linenumber_released - linenumber_pressed; int start_line = linenumber_pressed; QTextBlock start_block = this->document()->findBlockByLineNumber(start_line-1); QTextCursor cursor = this->textCursor(); cursor.setPosition(start_block.position()); if (move_n_blocks > 0) { for (int n = 0; n < qAbs(move_n_blocks)+1; ++n) cursor.movePosition(cursor.NextBlock, cursor.KeepAnchor); } else { cursor.movePosition(cursor.NextBlock); for (int n = 0; n < qAbs(move_n_blocks)+1; ++n) cursor.movePosition(cursor.PreviousBlock, cursor.KeepAnchor); } if (linenumber_released == this->blockCount()) cursor.movePosition(cursor.EndOfBlock,cursor.KeepAnchor); else cursor.movePosition(cursor.StartOfBlock,cursor.KeepAnchor); this->setTextCursor(cursor); } //------Breakpoints void CodeEditor::add_remove_breakpoint(int line_number, QString condition, bool edit_condition) { if (!this->is_python_like()) return; QTextBlock block; if (line_number == -1) block = this->textCursor().block(); else block = this->document()->findBlockByNumber(line_number-1); BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (data == nullptr) { data = new BlockUserData(this); data->breakpoint = true; } else if (!edit_condition) { data->breakpoint = !data->breakpoint; data->breakpoint_condition = QString(); } if (!condition.isEmpty()) { data->breakpoint_condition = condition; } if (edit_condition) { condition = data->breakpoint_condition; bool valid; condition = QInputDialog::getText(this, "Breakpoint", "Condition", QLineEdit::Normal,condition,&valid); if (valid == false) return; data->breakpoint = true; data->breakpoint_condition = (!condition.isEmpty()) ? condition : QString(); } if (data->breakpoint) { QString text = block.text().trimmed(); // 下一行设置注释以及双引号,单引号不能设置断点 if (text.size()==0 || startswith(text,QStringList({"#","\"","'"}))) data->breakpoint = false; } block.setUserData(data); // 在这里往QTextBlock上设置BlockUserData类型的数据 this->linenumberarea->update(); this->scrollflagarea->update(); emit this->breakpoints_changed(); } QList<QList<QVariant> > CodeEditor::get_breakpoints() { QList<QList<QVariant>> breakpoints; QTextBlock block = this->document()->firstBlock(); for (int line_number = 1; line_number < this->document()->blockCount()+1; ++line_number) { BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (data && data->breakpoint) { QList<QVariant> tmp; tmp.append(line_number); tmp.append(data->breakpoint_condition); breakpoints.append(tmp); } block = block.next(); } return breakpoints; } void CodeEditor::clear_breakpoints() { breakpoints.clear(); QList<BlockUserData*> tmp = this->blockuserdata_list; foreach (BlockUserData* data, tmp) { data->breakpoint = false; if (data->is_empty()) data->del(); } /*for (int i = 0; i < blockuserdata_list.size(); ++i) { blockuserdata_list[i]->breakpoint = false; if (blockuserdata_list[i]->is_empty()) { delete blockuserdata_list[i]; blockuserdata_list[i] = nullptr; } } blockuserdata_list.removeAll(nullptr);*/ } void CodeEditor::set_breakpoints(const QList<QVariant> &breakpoints) { this->clear_breakpoints(); foreach (auto breakpoint, breakpoints) { QList<QVariant> pair = breakpoint.toList(); int line_number = pair[0].toInt(); QString condition = pair[1].toString(); this->add_remove_breakpoint(line_number, condition); } } void CodeEditor::update_breakpoints() { emit this->breakpoints_changed(); } //-----Code introspection void CodeEditor::do_completion(bool automatic) { if (!this->is_completion_widget_visible()) emit this->get_completions(automatic); } void CodeEditor::do_go_to_definition() { if (!this->in_comment_or_string()) emit go_to_definition(this->textCursor().position()); } void CodeEditor::show_object_info(int position) { emit this->sig_show_object_info(position); } //-----edge line void CodeEditor::set_edge_line_enabled(bool state) { this->edge_line_enabled = state; this->edge_line->setVisible(state); } void CodeEditor::set_edge_line_column(int column) { this->edge_line->column = column; this->edge_line->update(); } //-----blank spaces void CodeEditor::set_blanks_enabled(bool state) { this->blanks_enabled = state; QTextOption option = this->document()->defaultTextOption(); option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators); if (this->blanks_enabled) option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces); else option.setFlags(option.flags() & ~QTextOption::ShowTabsAndSpaces); this->document()->setDefaultTextOption(option); this->rehighlight(); } //-----scrollflagarea void CodeEditor::set_scrollflagarea_enabled(bool state) { this->scrollflagarea_enabled = state; this->scrollflagarea->setVisible(state); this->update_linenumberarea_width(); } int CodeEditor::get_scrollflagarea_width() { if (this->scrollflagarea_enabled) return ScrollFlagArea::WIDTH; else return 0; } void CodeEditor::scrollflagarea_paint_event(QPaintEvent *event) { QPainter painter(this->scrollflagarea); painter.fillRect(event->rect(), this->sideareas_color); QTextBlock block = this->document()->firstBlock(); for (int line_number = 1; line_number < document()->blockCount()+1; ++line_number) { BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (data) { int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number)); if (!data->code_analysis.isEmpty()) { QString color = this->warning_color; foreach (auto pair, data->code_analysis) { bool error = pair.second; if (error) { color = this->error_color; break; } } set_scrollflagarea_painter(&painter,color); painter.drawRect(scrollflagarea->make_flag_qrect(position)); } if (!data->todo.isEmpty()) { set_scrollflagarea_painter(&painter, this->todo_color); painter.drawRect(scrollflagarea->make_flag_qrect(position)); } if (data->breakpoint) { set_scrollflagarea_painter(&painter,this->breakpoint_color); painter.drawRect(scrollflagarea->make_flag_qrect(position)); } } block = block.next(); } if (!this->occurrences.isEmpty()) { set_scrollflagarea_painter(&painter, this->occurrence_color); foreach (int line_number, this->occurrences) { int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number)); painter.drawRect(scrollflagarea->make_flag_qrect(position)); } } if (!this->found_results.isEmpty()) { set_scrollflagarea_painter(&painter,this->found_results_color); foreach (int line_number, this->found_results) { int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number)); painter.drawRect(scrollflagarea->make_flag_qrect(position)); } } QColor pen_color = QColor(Qt::white); pen_color.setAlphaF(0.8); painter.setPen(pen_color); QColor brush_color = QColor(Qt::white); brush_color.setAlphaF(0.5); painter.setBrush(QBrush(brush_color)); painter.drawRect(scrollflagarea->make_slider_range(firstVisibleBlock().blockNumber())); } void CodeEditor::resizeEvent(QResizeEvent *event) { TextEditBaseWidget::resizeEvent(event); QRect cr = this->contentsRect(); this->linenumberarea->setGeometry(QRect(cr.left(),cr.top(), compute_linenumberarea_width(), cr.height())); this->__set_scrollflagarea_geometry(cr); } void CodeEditor::__set_scrollflagarea_geometry(const QRect &contentrect) { QRect cr = contentrect; int vsbw; if (this->verticalScrollBar()->isVisible()) vsbw = this->verticalScrollBar()->contentsRect().width(); else vsbw = 0; int _left, _top, right, _bottom; this->getContentsMargins(&_left, &_top, &right, &_bottom); if (right > vsbw) vsbw = 0; this->scrollflagarea->setGeometry(QRect(cr.right()-ScrollFlagArea::WIDTH-vsbw, cr.top(), this->scrollflagarea->WIDTH,cr.height())); } //-----edgeline bool CodeEditor::viewportEvent(QEvent *event) { QPointF offset = this->contentOffset(); double x = this->blockBoundingGeometry(this->firstVisibleBlock()) .translated(offset.x(), offset.y()).left() \ +this->get_linenumberarea_width() \ +this->fontMetrics().width(QString(this->edge_line->column, '9'))+5; QRect cr = this->contentsRect(); this->edge_line->setGeometry(QRect(static_cast<int>(x), cr.top(), 1, cr.bottom())); this->__set_scrollflagarea_geometry(cr); return TextEditBaseWidget::viewportEvent(event); } void CodeEditor::_apply_highlighter_color_scheme() { sh::BaseSH* hl = highlighter; if (hl) { this->set_palette(hl->get_background_color(), hl->get_foreground_color()); currentline_color = hl->get_currentline_color(); currentcell_color = hl->get_currentcell_color(); occurrence_color = hl->get_occurrence_color(); ctrl_click_color = hl->get_ctrlclick_color(); sideareas_color = hl->get_sideareas_color(); comment_color = hl->get_comment_color(); normal_color = hl->get_foreground_color(); matched_p_color = hl->get_matched_p_color(); unmatched_p_color = hl->get_unmatched_p_color(); } } void CodeEditor::apply_highlighter_settings(const QHash<QString, ColorBoolBool> &color_scheme) { if (this->highlighter) { this->highlighter->setup_formats(this->font()); if (!color_scheme.isEmpty()) this->set_color_scheme(color_scheme); else this->highlighter->rehighlight(); } } QHash<int,sh::OutlineExplorerData> CodeEditor::get_outlineexplorer_data() { return highlighter->get_outlineexplorer_data(); } void CodeEditor::set_font(const QFont &font, const QHash<QString,ColorBoolBool> &color_scheme) { if (!color_scheme.isEmpty()) this->color_scheme = color_scheme; this->setFont(font); this->update_linenumberarea_width(); this->apply_highlighter_settings(color_scheme); } void CodeEditor::set_color_scheme(const QHash<QString,ColorBoolBool> &color_scheme) { this->color_scheme = color_scheme; if (this->highlighter) { this->highlighter->set_color_scheme(color_scheme); this->_apply_highlighter_color_scheme(); } if (this->highlight_current_cell_enabled) this->highlight_current_cell(); else this->unhighlight_current_cell(); if (this->highlight_current_line_enabled) this->highlight_current_line(); else this->unhighlight_current_line(); } void CodeEditor::set_text(const QString &text) { this->setPlainText(text); //禁用下面这行,不然会导致调用下面的函数,使未发生改变的文档状态变为isModified,文件名后出现星号 //this->set_eol_chars(text); } void CodeEditor::set_text_from_file(const QString &filename, QString language) { QString text = encoding::read(filename); if (language.isEmpty()) { language = get_file_language(filename, text); } this->set_language(language, filename); this->set_text(text); } void CodeEditor::append(const QString &text) { QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::End); cursor.insertText(text); } //@Slot() void CodeEditor::paste() { QClipboard* clipboard = QApplication::clipboard(); QString text = clipboard->text(); if (splitlines(text).size() > 1) { QString eol_chars = this->get_line_separator(); clipboard->setText((splitlines(text+eol_chars)).join(eol_chars)); } TextEditBaseWidget::paste(); } void CodeEditor::get_block_data(const QTextBlock &block) { // TODO highlighter.block_data是什么 } void CodeEditor::get_fold_level(int block_nb) { QTextBlock block = this->document()->findBlockByNumber(block_nb); //QTextBlockUserData* data = block.userData(); // TODO } //==============High-level editor features //@Slot() void CodeEditor::center_cursor_on_next_focus() { this->centerCursor(); disconnect(this,SIGNAL(focus_in()),this,SLOT(center_cursor_on_next_focus())); } void CodeEditor::go_to_line(int line, const QString &word) { line = qMin(line, this->get_line_count()); QTextBlock block = this->document()->findBlockByNumber(line-1); this->setTextCursor(QTextCursor(block)); if (this->isVisible()) this->centerCursor(); else connect(this,SIGNAL(focus_in()),this,SLOT(center_cursor_on_next_focus())); this->horizontalScrollBar()->setValue(0); if (!word.isEmpty() && block.text().contains(word)) this->find(word, QTextDocument::FindCaseSensitively); } void CodeEditor::exec_gotolinedialog() { GoToLineDialog* dlg = new GoToLineDialog(this); if (dlg->exec()) this->go_to_line(dlg->get_line_number()); } void CodeEditor::cleanup_code_analysis() { setUpdatesEnabled(false); clear_extra_selections("code_analysis"); QList<BlockUserData*> tmp = this->blockuserdata_list; foreach (BlockUserData* data, tmp) { data->code_analysis.clear(); if (data->is_empty()) data->del(); } this->setUpdatesEnabled(true); scrollflagarea->update(); linenumberarea->update(); } void CodeEditor::process_code_analysis(const QList<QList<QVariant> > &check_results) { cleanup_code_analysis(); if (check_results.isEmpty()) return; setUpdatesEnabled(false); QTextCursor cursor = textCursor(); QTextDocument* document = this->document(); QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords; foreach (auto pair, check_results) { QString message = pair[0].toString(); int line_number = pair[1].toInt(); bool error = message.contains("syntax"); QTextBlock block = this->document()->findBlockByNumber(line_number-1); BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (data == nullptr) data = new BlockUserData(this); data->code_analysis.append(qMakePair(message, error)); block.setUserData(data); QRegularExpression re("\\'[a-zA-Z0-9_]*\\'"); QRegularExpressionMatchIterator iterator = re.globalMatch(message); while (iterator.hasNext()) { QRegularExpressionMatch match = iterator.next(); QString text = match.captured().chopped(1); text = text.mid(1); auto is_line_splitted = [=](int line_no) { QString text = document->findBlockByNumber(line_no).text(); QString stripped = text.trimmed(); return stripped.endsWith("\\") || stripped.endsWith(',') || stripped.size() == 0; }; int line2 = line_number-1; while (line2<this->blockCount()-1 && is_line_splitted(line2)) line2++; cursor.setPosition(block.position()); cursor.movePosition(QTextCursor::StartOfBlock); QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)), Qt::CaseSensitive); QString color = error ? this->error_color : this->warning_color; cursor = document->find(regexp, cursor, flags); if (!cursor.isNull()) { while (!cursor.isNull() && cursor.blockNumber() <= line2 && cursor.blockNumber() >= line_number-1 && cursor.position() > 0) { this->__highlight_selection("code_analysis",cursor,QColor(), QColor(),QColor(color)); cursor = document->find(text, cursor, flags); } } } } update_extra_selections(); setUpdatesEnabled(true); linenumberarea->update(); } void CodeEditor::__show_code_analysis_results(int line_number, const QList<QPair<QString, bool> > &code_analysis) { QStringList msglist; foreach (auto pair, code_analysis) { msglist.append(pair.first); } this->show_calltip("Code analysis",msglist, false,"#129625",line_number); // 这里调用了show_calltip(text = QtringList) // show_calltip本代码总共两处调用,这里第一次 } int CodeEditor::go_to_next_warning() { QTextBlock block = this->textCursor().block(); int line_count = this->document()->blockCount(); BlockUserData* data; while (true) { if (block.blockNumber()+1 < line_count) block = block.next(); else block = this->document()->firstBlock(); data = dynamic_cast<BlockUserData*>(block.userData()); if (data && !data->code_analysis.isEmpty()) break; } int line_number = block.blockNumber()+1; this->go_to_line(line_number); this->__show_code_analysis_results(line_number, data->code_analysis); return this->get_position("cursor"); } int CodeEditor::go_to_previous_warning() { QTextBlock block = this->textCursor().block(); BlockUserData* data; while (true) { if (block.blockNumber() > 0) block = block.previous(); else block = this->document()->lastBlock(); data = dynamic_cast<BlockUserData*>(block.userData()); if (data && !data->code_analysis.isEmpty()) break; } int line_number = block.blockNumber()+1; this->go_to_line(line_number); this->__show_code_analysis_results(line_number, data->code_analysis); return this->get_position("cursor"); } //------Tasks management int CodeEditor::go_to_next_todo() { QTextBlock block = this->textCursor().block(); int line_count = this->document()->blockCount(); BlockUserData* data; while (true) { if (block.blockNumber()+1 < line_count) block = block.next(); else block = this->document()->firstBlock(); data = dynamic_cast<BlockUserData*>(block.userData()); if (data && !data->todo.isEmpty()) break; } int line_number = block.blockNumber()+1; this->go_to_line(line_number); this->show_calltip("To do",data->todo, false,"#3096FC",line_number); // 这里调用了show_calltip(text = Qtring) // show_calltip本代码总共两处调用,这里第二次 return this->get_position("cursor"); } void CodeEditor::process_todo(const QList<QList<QVariant> > &todo_results) { QList<BlockUserData*> tmp = this->blockuserdata_list; foreach (BlockUserData* data, tmp) { data->todo = ""; if (data->is_empty()) data->del(); } foreach (auto pair, todo_results) { QString message = pair[0].toString(); int line_number = pair[1].toInt(); QTextBlock block = this->document()->findBlockByNumber(line_number-1); BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData()); if (data == nullptr) data = new BlockUserData(this); data->todo = message; block.setUserData(data); } this->scrollflagarea->update(); } //------Comments/Indentation void CodeEditor::add_prefix(const QString& prefix) { QTextCursor cursor = this->textCursor(); if (this->has_selected_text()) { int start_pos=cursor.selectionStart(), end_pos=cursor.selectionEnd(); int first_pos = qMin(start_pos, end_pos); QTextCursor first_cursor = this->textCursor(); first_cursor.setPosition(first_pos); bool begins_at_block_start = first_cursor.atBlockStart(); cursor.beginEditBlock(); cursor.setPosition(end_pos); if (cursor.atBlockStart()) { cursor.movePosition(QTextCursor::PreviousBlock); if (cursor.position() <start_pos) cursor.setPosition(start_pos); } while (cursor.position() >= start_pos) { cursor.movePosition(QTextCursor::StartOfBlock); cursor.insertText(prefix); if (start_pos==0 && cursor.blockNumber()==0) break; cursor.movePosition(QTextCursor::PreviousBlock); cursor.movePosition(QTextCursor::EndOfBlock); } cursor.endEditBlock(); if (begins_at_block_start) { cursor = this->textCursor(); start_pos = cursor.selectionStart(); end_pos = cursor.selectionEnd(); if (start_pos < end_pos) start_pos -= prefix.size(); else end_pos -= prefix.size(); cursor.setPosition(start_pos, QTextCursor::MoveAnchor); cursor.setPosition(end_pos, QTextCursor::KeepAnchor); this->setTextCursor(cursor); } } else { cursor.beginEditBlock(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.insertText(prefix); cursor.endEditBlock(); } } void CodeEditor::__is_cursor_at_start_of_block(QTextCursor *cursor) { cursor->movePosition(QTextCursor::StartOfBlock); } void CodeEditor::remove_suffix(const QString &suffix) { QTextCursor cursor = this->textCursor(); cursor.setPosition(cursor.position()-suffix.size(), QTextCursor::KeepAnchor); if (cursor.selectedText() == suffix) cursor.removeSelectedText(); } void CodeEditor::remove_prefix(const QString &prefix) { QTextCursor cursor = this->textCursor(); if (this->has_selected_text()) { int start_pos = qMin(cursor.selectionStart(), cursor.selectionEnd()); int end_pos = qMax(cursor.selectionStart(), cursor.selectionEnd()); cursor.setPosition(start_pos); if (!cursor.atBlockStart()) { cursor.movePosition(QTextCursor::StartOfBlock); start_pos = cursor.position(); } cursor.beginEditBlock(); cursor.setPosition(end_pos); if (cursor.atBlockStart()) { cursor.movePosition(QTextCursor::PreviousBlock); if (cursor.position() <start_pos) cursor.setPosition(start_pos); } cursor.movePosition(QTextCursor::StartOfBlock); int old_pos = INT_MIN; while (cursor.position() >= start_pos) { int new_pos = cursor.position(); if (old_pos == new_pos) break; else old_pos = new_pos; QString line_text = cursor.block().text(); if ((!prefix.trimmed().isEmpty() && lstrip(line_text).startsWith(prefix)) || line_text.startsWith(prefix)) { cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, line_text.indexOf(prefix)); cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,prefix.size()); cursor.removeSelectedText(); } cursor.movePosition(QTextCursor::PreviousBlock); } cursor.endEditBlock(); } else { cursor.movePosition(QTextCursor::StartOfBlock); QString line_text = cursor.block().text(); if ((!prefix.trimmed().isEmpty() && lstrip(line_text).startsWith(prefix)) || line_text.startsWith(prefix)) { cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, line_text.indexOf(prefix)); cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor,prefix.size()); cursor.removeSelectedText(); } } } bool CodeEditor::fix_indent(bool forward, bool comment_or_string) { if (this->is_python_like()) return this->fix_indent_smart(forward, comment_or_string); else return this->simple_indentation(forward, comment_or_string); } bool CodeEditor::simple_indentation(bool forward, bool comment_or_string) { Q_UNUSED(comment_or_string); QTextCursor cursor = this->textCursor(); int block_nb = cursor.blockNumber(); QTextBlock prev_block = this->document()->findBlockByLineNumber(block_nb-1); QString prevline = prev_block.text(); QRegularExpression re("\\s*"); QRegularExpressionMatch match = re.match(prevline); QString indentation; if (match.capturedStart() == 0) indentation = match.captured(); if (!forward) indentation = indentation.mid(this->indent_chars.size()); cursor.insertText(indentation); return false; } bool CodeEditor::fix_indent_smart(bool forward, bool comment_or_string) { QTextCursor cursor = this->textCursor(); int block_nb = cursor.blockNumber(); int diff_paren = 0; int diff_brack = 0; int diff_curly = 0; bool add_indent = false; int prevline = 0; QString prevtext = ""; for (prevline = block_nb-1; prevline >= 0; --prevline) { cursor.movePosition(QTextCursor::PreviousBlock); prevtext = rstrip(cursor.block().text()); int inline_comment = prevtext.indexOf('#'); if (inline_comment != -1) prevtext = prevtext.left(inline_comment); if ((this->is_python_like() && !prevtext.trimmed().startsWith('#') && !prevtext.isEmpty()) || !prevtext.isEmpty()) { if (!prevtext.trimmed().split(QRegularExpression("\\s")).mid(0,1).contains("return") && (prevtext.trimmed().endsWith(')') || prevtext.trimmed().endsWith(']') || prevtext.trimmed().endsWith('}'))) comment_or_string = true; else if (prevtext.trimmed().endsWith(':') && this->is_python_like()) { add_indent = true; comment_or_string = true; } if (prevtext.count(')') > prevtext.count('(')) diff_paren = prevtext.count(')') - prevtext.count('('); else if (prevtext.count(']') > prevtext.count('[')) diff_brack = prevtext.count(']') - prevtext.count('['); else if (prevtext.count('}') > prevtext.count('{')) diff_curly = prevtext.count('}') - prevtext.count('{'); else if (diff_paren || diff_brack || diff_curly) { diff_paren += prevtext.count(')') - prevtext.count('('); diff_brack += prevtext.count(']') - prevtext.count('['); diff_curly += prevtext.count('}') - prevtext.count('{'); if (!(diff_paren || diff_brack || diff_curly)) break; } else break; } } int correct_indent; if (prevline) correct_indent = this->get_block_indentation(prevline); else correct_indent = 0; int indent = this->get_block_indentation(block_nb); if (add_indent) { if (this->indent_chars == "\t") correct_indent += this->tab_stop_width_spaces; else correct_indent += this->indent_chars.size(); } if (!comment_or_string) { if (prevtext.endsWith(':') && this->is_python_like()) { if (this->indent_chars == "\t") correct_indent += this->tab_stop_width_spaces; else correct_indent += this->indent_chars.size(); } else if(this->is_python_like() && (prevtext.endsWith("continue") || prevtext.endsWith("break") || prevtext.endsWith("pass") || (prevtext.trimmed().split(QRegularExpression("\\t")).mid(0,1).contains("return") && prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() == prevtext.split(QRegularExpression("\\)|\\}|\\]")).size()))) { if (this->indent_chars == "\t") correct_indent -= this->tab_stop_width_spaces; else correct_indent -= this->indent_chars.size(); } else if (prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() > 1) { // Dummy elemet to avoid index errors QStringList stack = {"dummy"}; QChar deactivate = QChar(0); foreach (QChar c, prevtext) { if (deactivate != QChar(0)) { if (c == deactivate) deactivate = QChar(0); } else if (c=='\'' || c=='\"') deactivate = c; else if (c=='(' || c=='[' || c=='{') stack.append(c); else if (c==')' && stack.last()=="(") stack.removeLast(); else if (c==']' && stack.last()=="[") stack.removeLast(); else if (c=='}' && stack.last()=="{") stack.removeLast(); } if (stack.size() == 1) { } else if (prevtext.indexOf(QRegularExpression("[\\(|\\{|\\[]\\s*$"))>-1 && ((this->indent_chars=="\t" && this->tab_stop_width_spaces*2 < prevtext.size()) || (this->indent_chars.startsWith(' ') && this->indent_chars.size()*2 < prevtext.size()))) { if (this->indent_chars == "\t") correct_indent += this->tab_stop_width_spaces * 2; else correct_indent += this->indent_chars.size() * 2; } else { QHash<QChar,QChar> rlmap = {{')','('}, {']','['}, {'}','{'}}; bool break_flag = true; for (auto it=rlmap.begin();it!=rlmap.end();it++) { QChar par = it.key(); int i_right = prevtext.lastIndexOf(par); if (i_right != -1) { prevtext = prevtext.left(i_right); for (int _i=0;_i<prevtext.split(par).size();_i++) { int i_left = prevtext.lastIndexOf(rlmap[par]); if (i_left != -1) prevtext = prevtext.left(i_left); else { break_flag = false; break; } } } } if (break_flag) { if (!prevtext.trimmed().isEmpty()) { if (prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() > 1) { QString prevexpr = prevtext.split(QRegularExpression("\\(|\\{|\\[")).last(); correct_indent = prevtext.size()-prevexpr.size(); } else correct_indent = prevtext.size(); } } } } } if (!(diff_paren || diff_brack || diff_curly) && !prevtext.endsWith(':') && prevline) { int cur_indent = this->get_block_indentation(block_nb-1); bool is_blank = this->get_text_line(block_nb-1).trimmed().isEmpty(); int prevline_indent = this->get_block_indentation(prevline); QString trailing_text = this->get_text_line(block_nb).trimmed(); if (cur_indent < prevline_indent && (!trailing_text.isEmpty() || is_blank)) { if (cur_indent % this->indent_chars.size() == 0) correct_indent = cur_indent; else correct_indent = cur_indent + (this->indent_chars.size() - cur_indent % this->indent_chars.size()); } } if ((forward && indent >= correct_indent) || (!forward && indent <= correct_indent)) return false; if (correct_indent >= 0) { QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::StartOfBlock); if (this->indent_chars == "\t") indent = indent / this->tab_stop_width_spaces; cursor.setPosition(cursor.position()+indent,QTextCursor::KeepAnchor); cursor.removeSelectedText(); QString indent_text; if (this->indent_chars == "\t") indent_text = QString(correct_indent / this->tab_stop_width_spaces,'\t') + QString(correct_indent % this->tab_stop_width_spaces,' '); else indent_text = QString(correct_indent,' '); cursor.insertText(indent_text); return true; } return false; } //@Slot() void CodeEditor::clear_all_output() { try { qDebug()<<"clear_all_output"<<__FILE__<<__LINE__; // TODO该函数依赖于第三方库nbformat } catch (const std::exception &e) { QMessageBox::critical(this,"Removal error", QString("It was not possible to remove outputs from this notebook. The error is:\n\n")+e.what()); return; } } //@Slot() void CodeEditor::convert_notebook() { try { qDebug()<<"convert_notebook"<<__FILE__<<__LINE__; // TODO该函数依赖于第三方库nbformat } catch (const std::exception &e) { QMessageBox::critical(this,"Conversion error", QString("It was not possible to convert this notebook. The error is:\n\n")+e.what()); return; } //TODO emit sig_new_file(); } void CodeEditor::indent(bool force) { QString leading_text = this->get_text("sol","cursor"); if (this->has_selected_text()) this->add_prefix(this->indent_chars); else if (force || leading_text.trimmed().isEmpty() || (this->tab_indents && this->tab_mode)) { if (this->is_python_like()) { if (!this->fix_indent(true)) this->add_prefix(this->indent_chars); } else this->add_prefix(this->indent_chars); } else { if (this->indent_chars.size() > 1) { int length = this->indent_chars.size(); this->insert_text(QString(length-(leading_text.size()%length),' ')); } else this->insert_text(this->indent_chars); } } void CodeEditor::indent_or_replace() { if ((this->tab_indents && this->tab_mode) || !this->has_selected_text()) this->indent(); else { QTextCursor cursor = this->textCursor(); if (this->get_selected_text() == cursor.block().text()) this->indent(); else { QTextCursor cursor1 = this->textCursor(); cursor1.setPosition(cursor.selectionStart()); QTextCursor cursor2 = this->textCursor(); cursor2.setPosition(cursor.selectionEnd()); if (cursor1.blockNumber() != cursor2.blockNumber()) this->indent(); else this->replace(this->indent_chars); } } } void CodeEditor::unindent(bool force) { if (this->has_selected_text()) this->remove_prefix(this->indent_chars); else { QString leading_text = this->get_text("sol","cursor"); if (force || leading_text.trimmed().isEmpty() || (this->tab_indents && this->tab_mode)) { if (this->is_python_like()) { if (!this->fix_indent(false)) this->remove_prefix(this->indent_chars); } else if (leading_text.endsWith("\t")) this->remove_prefix("\t"); else this->remove_prefix(this->indent_chars); } } } // @Slot() void CodeEditor::toggle_comment() { QTextCursor cursor = this->textCursor(); int start_pos = qMin(cursor.selectionStart(), cursor.selectionEnd()); int end_pos = qMax(cursor.selectionStart(), cursor.selectionEnd()); cursor.setPosition(end_pos); int last_line = cursor.block().blockNumber(); if (cursor.atBlockStart() && start_pos!=end_pos) last_line -= 1; cursor.setPosition(start_pos); int first_line = cursor.block().blockNumber(); bool is_comment_or_whitespace = true; bool at_least_one_comment = false; for (int _line_nb = first_line; _line_nb < last_line+1; ++_line_nb) { QString text = lstrip(cursor.block().text()); bool is_comment = text.startsWith(this->comment_string); bool is_whitespace = text == ""; is_comment_or_whitespace *= (is_comment || is_whitespace); if (is_comment) at_least_one_comment = true; cursor.movePosition(QTextCursor::NextBlock); } if (is_comment_or_whitespace && at_least_one_comment) this->uncomment(); else this->comment(); } void CodeEditor::comment() { this->add_prefix(this->comment_string); } void CodeEditor::uncomment() { this->remove_prefix(this->comment_string); } QString CodeEditor::__blockcomment_bar() { QString res = this->comment_string + " " + QString(78-this->comment_string.size(), '='); return res; } void CodeEditor::transform_to_uppercase() { QTextCursor cursor = this->textCursor(); int prev_pos = cursor.position(); QString selected_text = cursor.selectedText(); if (selected_text.size() == 0) { prev_pos = cursor.position(); cursor.select(QTextCursor::WordUnderCursor); selected_text = cursor.selectedText(); } QString s = selected_text.toUpper(); cursor.insertText(s); this->set_cursor_position(prev_pos); } void CodeEditor::transform_to_lowercase() { QTextCursor cursor = this->textCursor(); int prev_pos = cursor.position(); QString selected_text = cursor.selectedText(); if (selected_text.size() == 0) { prev_pos = cursor.position(); cursor.select(QTextCursor::WordUnderCursor); selected_text = cursor.selectedText(); } QString s = selected_text.toLower(); cursor.insertText(s); this->set_cursor_position(prev_pos); } void CodeEditor::blockcomment() { QString comline = this->__blockcomment_bar() + this->get_line_separator(); QTextCursor cursor = this->textCursor(); int start_pos, end_pos; if (this->has_selected_text()) { this->extend_selection_to_complete_lines(); start_pos = cursor.selectionStart(); end_pos = cursor.selectionEnd(); } else { start_pos = cursor.position(); end_pos = cursor.position(); } cursor.beginEditBlock(); cursor.setPosition(start_pos); cursor.movePosition(QTextCursor::StartOfBlock); while (cursor.position() <= end_pos) { cursor.insertText(this->comment_string + " "); cursor.movePosition(QTextCursor::EndOfBlock); if (cursor.atEnd()) break; cursor.movePosition(QTextCursor::NextBlock); end_pos += this->comment_string.size() + 1; } cursor.setPosition(end_pos); cursor.movePosition(QTextCursor::EndOfBlock); if (cursor.atEnd()) cursor.insertText(this->get_line_separator()); else cursor.movePosition(QTextCursor::NextBlock); cursor.insertText(comline); cursor.setPosition(start_pos); cursor.movePosition(QTextCursor::StartOfBlock); cursor.insertText(comline); cursor.endEditBlock(); } void CodeEditor::unblockcomment() { auto __is_comment_bar = [this](const QTextCursor &cursor) { return cursor.block().text().startsWith(this->__blockcomment_bar()); }; QTextCursor cursor1 = this->textCursor(); if (__is_comment_bar(cursor1)) return; while (!__is_comment_bar(cursor1)) { cursor1.movePosition(QTextCursor::PreviousBlock); if (cursor1.atStart()) break; } if (!__is_comment_bar(cursor1)) return; auto __in_block_comment = [this](const QTextCursor &cursor) { QString cs = this->comment_string; return cursor.block().text().startsWith(cs); }; QTextCursor cursor2 = QTextCursor(cursor1); cursor2.movePosition(QTextCursor::NextBlock); while (!__is_comment_bar(cursor2) && __in_block_comment(cursor2)) { cursor2.movePosition(QTextCursor::NextBlock); if (cursor2.block() == this->document()->lastBlock()) break; } if (!__is_comment_bar(cursor2)) return; QTextCursor cursor3 = this->textCursor(); cursor3.beginEditBlock(); cursor3.setPosition(cursor1.position()); cursor3.movePosition(QTextCursor::NextBlock); while (cursor3.position() < cursor2.position()) { cursor3.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); if (!cursor3.atBlockEnd()) cursor3.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); cursor3.removeSelectedText(); cursor3.movePosition(QTextCursor::NextBlock); } QList<QTextCursor> tmp; tmp << cursor2 << cursor1; foreach (QTextCursor cursor, tmp) { cursor3.setPosition(cursor.position()); cursor3.select(QTextCursor::BlockUnderCursor); cursor3.removeSelectedText(); } cursor3.endEditBlock(); } //------Kill ring handlers void CodeEditor::kill_line_end() { QTextCursor cursor = this->textCursor(); cursor.clearSelection(); cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); if (!cursor.hasSelection()) cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor); this->_kill_ring->kill_cursor(&cursor); this->setTextCursor(cursor); } void CodeEditor::kill_line_start() { QTextCursor cursor = this->textCursor(); cursor.clearSelection(); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); this->_kill_ring->kill_cursor(&cursor); this->setTextCursor(cursor); } QTextCursor CodeEditor::_get_word_start_cursor(int position) { QTextDocument* document = this->document(); position--; while (position && !document->characterAt(position).isLetterOrNumber()) position--; while (position && document->characterAt(position).isLetterOrNumber()) position--; QTextCursor cursor = this->textCursor(); cursor.setPosition(position+1); return cursor; } QTextCursor CodeEditor::_get_word_end_cursor(int position) { QTextDocument* document = this->document(); QTextCursor cursor = this->textCursor(); position = cursor.position(); cursor.movePosition(QTextCursor::End); int end = cursor.position(); while (position < end && !document->characterAt(position).isLetterOrNumber()) position++; while (position < end && document->characterAt(position).isLetterOrNumber()) position++; cursor.setPosition(position); return cursor; } void CodeEditor::kill_prev_word() { int position = this->textCursor().position(); QTextCursor cursor = this->_get_word_start_cursor(position); cursor.setPosition(position, QTextCursor::KeepAnchor); this->_kill_ring->kill_cursor(&cursor); this->setTextCursor(cursor); } void CodeEditor::kill_next_word() { int position = this->textCursor().position(); QTextCursor cursor = this->_get_word_end_cursor(position); cursor.setPosition(position, QTextCursor::KeepAnchor); this->_kill_ring->kill_cursor(&cursor); this->setTextCursor(cursor); } //------Autoinsertion of quotes/colons QString CodeEditor::__get_current_color(QTextCursor cursor) { if (cursor.isNull()) cursor = this->textCursor(); QTextBlock block = cursor.block(); int pos = cursor.position() - block.position(); QTextLayout* layout = block.layout(); QVector<QTextLayout::FormatRange> block_formats = layout->formats(); if (!block_formats.isEmpty()) { QTextCharFormat current_format; if (cursor.atBlockEnd()) current_format = block_formats.last().format; else { int flag = 1; foreach (auto fmt, block_formats) { if ((pos>=fmt.start) && (pos<fmt.start+fmt.length)) { current_format = fmt.format; flag = 0; } } if (flag) return QString(); } QString color = current_format.foreground().color().name(); return color; } else return QString(); } bool CodeEditor::in_comment_or_string(QTextCursor cursor) { if (this->highlighter) { QString current_color; if (cursor.isNull()) current_color = this->__get_current_color(); else current_color = this->__get_current_color(cursor); QString comment_color = this->highlighter->get_color_name("comment"); QString string_color = this->highlighter->get_color_name("string"); if ((current_color==comment_color) || (current_color==string_color)) return true; else return false; } else return false; } bool CodeEditor::__colon_keyword(QString text) { QStringList stmt_kws = {"def", "for", "if", "while", "with", "class", "elif", "except"}; QStringList whole_kws = {"else", "try", "except", "finally"}; text = lstrip(text); QStringList words = text.split(QRegularExpression("\\s+")); foreach (const QString& wk, whole_kws) { if (text == wk) return true; } if (words.size() < 2) return false; foreach (const QString& sk, stmt_kws) { if (words[0] == sk) return true; } return false; } bool CodeEditor::__forbidden_colon_end_char(QString text) { QList<QChar> end_chars = {':', '\\', '[', '{', '(', ','}; text = rstrip(text); foreach (const QChar& c, end_chars) { if (text.endsWith(c)) return true; } return false; } bool CodeEditor::__unmatched_braces_in_line(const QString &text,const QChar& closing_braces_type) { QList<QChar> opening_braces, closing_braces; if (closing_braces_type == QChar(0)) { opening_braces = {'(', '[', '{'}; closing_braces = {')', ']', '}'}; } else { closing_braces = {closing_braces_type}; QHash<QChar,QChar> dict = {{')','('}, {'}','{'}, {']','['}}; opening_braces = {dict[closing_braces_type]}; } QTextBlock block = this->textCursor().block(); int line_pos = block.position(); for (int pos = 0; pos < text.size(); ++pos) { QChar _char = text[pos]; if (opening_braces.contains(_char)) { int match = this->find_brace_match(line_pos+pos, _char, true); if ((match == -1) || (match > line_pos+text.size())) return true; } if (closing_braces.contains(_char)) { int match = this->find_brace_match(line_pos+pos, _char, false); if ((match == -1) || (match < line_pos)) return true; } } return false; } bool CodeEditor::__has_colon_not_in_brackets(const QString &text) { for (int pos = 0; pos < text.size(); ++pos) { QChar _char = text[pos]; if (_char == ':' && !this->__unmatched_braces_in_line(text.left(pos))) return true; } return false; } bool CodeEditor::autoinsert_colons() { QString line_text = this->get_text("sol","cursor"); if (!this->textCursor().atBlockEnd()) return false; else if (this->in_comment_or_string()) return false; else if (!this->__colon_keyword(line_text)) return false; else if (this->__forbidden_colon_end_char(line_text)) return false; else if (this->__unmatched_braces_in_line(line_text)) return false; else if (this->__has_colon_not_in_brackets(line_text)) return false; else return true; } QString CodeEditor::__unmatched_quotes_in_line(QString text) { text.replace("\\'",""); text.replace("\\\"",""); if (text.count("\"") % 2) return "\""; else if (text.count("'") % 2) return "'"; else return ""; } QString CodeEditor::__next_char() { QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); QString next_char = cursor.selectedText(); return next_char; } bool CodeEditor::__in_comment() { if (this->highlighter) { QString current_color = this->__get_current_color(); QString comment_color = this->highlighter->get_color_name("comment"); if (current_color == comment_color) return true; else return false; } else return false; } void CodeEditor::autoinsert_quotes(int key) { QHash<int,QChar> dict = {{Qt::Key_QuoteDbl, '"'}, {Qt::Key_Apostrophe, '\''}}; QChar _char = dict[key]; QString line_text = this->get_text("sol","eol"); QString line_to_cursor = this->get_text("sol","cursor"); QTextCursor cursor = this->textCursor(); QString last_three = this->get_text("sol","cursor").right(3); QString last_two = this->get_text("sol","cursor").right(2); QString trailing_text = this->get_text("cursor","eol").trimmed(); if (this->has_selected_text()) { QString text = _char + this->get_selected_text() + _char; this->insert_text(text); } else if (this->__in_comment()) this->insert_text(_char); else if (trailing_text.size() > 0 && !(this->__unmatched_quotes_in_line(line_to_cursor) == _char)) this->insert_text(_char); else if (!this->__unmatched_quotes_in_line(line_text).isEmpty() && !(last_three == QString(3,_char))) this->insert_text(_char); else if (this->__next_char() == _char) { cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 1); cursor.clearSelection(); this->setTextCursor(cursor); } else if (last_three == QString(3,_char)) { this->insert_text(QString(3,_char)); cursor = this->textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, 3); cursor.clearSelection(); this->setTextCursor(cursor); } else if (last_two == QString(2,_char)) { this->insert_text(_char); } else { this->insert_text(QString(2,_char)); cursor = this->textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter); this->setTextCursor(cursor); } } void CodeEditor::setup_context_menu() { undo_action = new QAction("Undo",this); connect(undo_action,SIGNAL(triggered(bool)),this,SLOT(undo())); undo_action->setIcon(ima::icon("undo")); undo_action->setShortcut(QKeySequence("Ctrl+Z")); undo_action->setShortcutContext(Qt::WindowShortcut); redo_action = new QAction("Redo",this); connect(redo_action,SIGNAL(triggered(bool)),this,SLOT(redo())); redo_action->setIcon(ima::icon("redo")); redo_action->setShortcut(QKeySequence("Ctrl+Shift+Z")); redo_action->setShortcutContext(Qt::WindowShortcut); cut_action = new QAction("Cut",this); connect(cut_action,SIGNAL(triggered(bool)),this,SLOT(cut())); cut_action->setIcon(ima::icon("editcut")); cut_action->setShortcut(QKeySequence("Ctrl+X")); cut_action->setShortcutContext(Qt::WindowShortcut); copy_action = new QAction("Copy",this); connect(copy_action,SIGNAL(triggered(bool)),this,SLOT(copy())); copy_action->setIcon(ima::icon("editcopy")); copy_action->setShortcut(QKeySequence("Ctrl+C")); copy_action->setShortcutContext(Qt::WindowShortcut); paste_action = new QAction("Paste",this); connect(paste_action,SIGNAL(triggered(bool)),this,SLOT(paste())); paste_action->setIcon(ima::icon("editpaste")); paste_action->setShortcut(QKeySequence("Ctrl+V")); paste_action->setShortcutContext(Qt::WindowShortcut); QAction* selectall_action = new QAction("Select All",this); connect(selectall_action,SIGNAL(triggered(bool)),this,SLOT(selectAll())); selectall_action->setIcon(ima::icon("selectall")); selectall_action->setShortcut(QKeySequence("Ctrl+A")); selectall_action->setShortcutContext(Qt::WindowShortcut); QAction* toggle_comment_action = new QAction("Comment/Uncomment",this); connect(toggle_comment_action,SIGNAL(triggered(bool)),this,SLOT(toggle_comment())); toggle_comment_action->setIcon(ima::icon("comment")); toggle_comment_action->setShortcut(QKeySequence("Ctrl+1")); toggle_comment_action->setShortcutContext(Qt::WindowShortcut); clear_all_output_action = new QAction("Clear all output",this); connect(clear_all_output_action,SIGNAL(triggered(bool)),this,SLOT(clear_all_output())); clear_all_output_action->setIcon(ima::icon("ipython_console")); clear_all_output_action->setShortcutContext(Qt::WindowShortcut); ipynb_convert_action = new QAction("Convert to Python script",this); connect(ipynb_convert_action,SIGNAL(triggered(bool)),this,SLOT(convert_notebook())); ipynb_convert_action->setIcon(ima::icon("python")); ipynb_convert_action->setShortcutContext(Qt::WindowShortcut); gotodef_action = new QAction("Go to definition",this); connect(gotodef_action,SIGNAL(triggered(bool)),this,SLOT(go_to_definition_from_cursor())); gotodef_action->setIcon(ima::icon("go to definition")); gotodef_action->setShortcut(QKeySequence("Ctrl+G")); gotodef_action->setShortcutContext(Qt::WindowShortcut); //# Run actions run_cell_action = new QAction("Run cell",this); connect(run_cell_action,SIGNAL(triggered(bool)),this,SIGNAL(run_cell())); run_cell_action->setIcon(ima::icon("run_cell")); run_cell_action->setShortcut(QKeySequence("Ctrl+Return")); run_cell_action->setShortcutContext(Qt::WindowShortcut); run_cell_and_advance_action = new QAction("Run cell and advance",this); connect(run_cell_and_advance_action,SIGNAL(triggered(bool)),this,SIGNAL(run_cell_and_advance())); run_cell_and_advance_action->setIcon(ima::icon("run_cell")); run_cell_and_advance_action->setShortcut(QKeySequence("Shift+Return")); run_cell_and_advance_action->setShortcutContext(Qt::WindowShortcut); re_run_last_cell_action = new QAction("Re-run last cell",this); connect(re_run_last_cell_action,SIGNAL(triggered(bool)),this,SIGNAL(re_run_last_cell())); re_run_last_cell_action->setIcon(ima::icon("run_cell")); re_run_last_cell_action->setShortcut(QKeySequence("Alt+Return")); re_run_last_cell_action->setShortcutContext(Qt::WindowShortcut); run_selection_action = new QAction("Run &selection or current line",this); connect(run_selection_action,SIGNAL(triggered(bool)),this,SIGNAL(run_selection())); run_selection_action->setIcon(ima::icon("run selection")); run_selection_action->setShortcut(QKeySequence("F9")); run_selection_action->setShortcutContext(Qt::WindowShortcut); //# Zoom actions QAction* zoom_in_action = new QAction("Zoom in",this); connect(zoom_in_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_in())); zoom_in_action->setIcon(ima::icon("zoom_in")); zoom_in_action->setShortcut(QKeySequence("ZoomIn")); zoom_in_action->setShortcutContext(Qt::WindowShortcut); QAction* zoom_out_action = new QAction("Zoom out",this); connect(zoom_out_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_out())); zoom_out_action->setIcon(ima::icon("zoom_out")); zoom_out_action->setShortcut(QKeySequence("ZoomOut")); zoom_out_action->setShortcutContext(Qt::WindowShortcut); QAction* zoom_reset_action = new QAction("Zoom reset",this); connect(zoom_reset_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_reset())); zoom_reset_action->setShortcut(QKeySequence("Ctrl+0")); zoom_reset_action->setShortcutContext(Qt::WindowShortcut); this->menu = new QMenu(this); QList<QAction*> actions_1 = { this->run_cell_action, this->run_cell_and_advance_action, this->re_run_last_cell_action, this->run_selection_action, this->gotodef_action, nullptr, this->undo_action, this->redo_action, nullptr, this->cut_action, this->copy_action, this->paste_action, selectall_action }; QList<QAction*> actions_2 = { nullptr, zoom_in_action, zoom_out_action, zoom_reset_action, nullptr, toggle_comment_action }; QList<QAction*> actions = actions_1 + actions_2; add_actions(this->menu, actions); this->readonly_menu = new QMenu(this); QList<QAction*> tmp = { this->copy_action, nullptr, selectall_action, this->gotodef_action }; add_actions(this->readonly_menu, tmp); } void CodeEditor::keyReleaseEvent(QKeyEvent *event) { this->timer_syntax_highlight->start(); TextEditBaseWidget::keyReleaseEvent(event); event->ignore(); } void CodeEditor::keyPressEvent(QKeyEvent *event) { int key = event->key(); bool ctrl= event->modifiers() & Qt::ControlModifier; bool shift = event->modifiers() & Qt::ShiftModifier; QString text = event->text(); bool has_selection = this->has_selected_text(); if (!text.isEmpty()) this->__clear_occurrences(); if (QToolTip::isVisible()) this->hide_tooltip_if_necessary(key); QList<QPair<QString,QString>> checks = {{qMakePair(QString("SelectAll"), QString("Select All"))}, {qMakePair(QString("Copy"), QString("Copy"))}, {qMakePair(QString("Cut"), QString("Cut"))}, {qMakePair(QString("Paste"), QString("Paste"))}}; //TODO for qname, name in checks: // seq = getattr(QKeySequence, qname) QStringList list_two = {"()", "[]", "{}", "\'\'", "\"\""}; QList<QChar> list_one = {',', ')', ']', '}'}; QHash<QString,QString> dict = {{"{", "{}"}, {"[", "[]"}}; if (key == Qt::Key_Enter || key == Qt::Key_Return) { if (!shift && !ctrl) { if (this->add_colons_enabled && this->is_python_like() && this->autoinsert_colons()) { this->textCursor().beginEditBlock(); this->insert_text(':' + this->get_line_separator()); this->fix_indent(); this->textCursor().endEditBlock(); } else if (this->is_completion_widget_visible() && this->codecompletion_enter) this->select_completion_list(); else { bool cmt_or_str_cursor = this->in_comment_or_string(); QTextCursor cursor = this->textCursor(); cursor.setPosition(cursor.block().position(), QTextCursor::KeepAnchor); bool cmt_or_str_line_begin = this->in_comment_or_string( cursor); bool cmt_or_str = cmt_or_str_cursor && cmt_or_str_line_begin; this->textCursor().beginEditBlock(); TextEditBaseWidget::keyPressEvent(event); this->fix_indent(cmt_or_str); this->textCursor().endEditBlock(); } } else if (shift) emit this->run_cell_and_advance(); else if (ctrl) emit this->run_cell(); } else if (shift && key == Qt::Key_Delete) { if (has_selection) this->cut(); else this->delete_line(); } else if (shift && key == Qt::Key_Insert) this->paste(); else if (key == Qt::Key_Insert && !shift && !ctrl) this->setOverwriteMode(!this->overwriteMode()); else if (key == Qt::Key_Backspace && !shift && !ctrl) { QString leading_text = this->get_text("sol", "cursor"); int leading_length = leading_text.size(); int trailing_spaces = leading_length - rstrip(leading_text).size(); if (has_selection || !this->intelligent_backspace) TextEditBaseWidget::keyPressEvent(event); else { QString trailing_text = this->get_text("cursor", "eol"); if (leading_text.trimmed().isEmpty() && leading_length > this->indent_chars.size()) { if (leading_length % this->indent_chars.size() == 0) this->unindent(); else TextEditBaseWidget::keyPressEvent(event); } else if (trailing_spaces and trailing_text.trimmed().isEmpty()) this->remove_suffix(leading_text.right(trailing_spaces)); else if (!leading_text.isEmpty() && !trailing_text.isEmpty() && list_two.contains(leading_text.right(1) + trailing_text.left(1))) { QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, 2); cursor.removeSelectedText(); } else { TextEditBaseWidget::keyPressEvent(event); if (this->is_completion_widget_visible()) this->completion_text.chop(1); } } } else if (key == Qt::Key_Period) { this->insert_text(text); if (this->is_python_like() && !this->in_comment_or_string() && this->codecompletion_auto) { QString last_obj = getobj(this->get_text("sol", "cursor")); if (!last_obj.isEmpty() && !isdigit(last_obj)) this->do_completion(true); } } else if (key == Qt::Key_Home) this->stdkey_home(shift, ctrl); else if (key == Qt::Key_End) this->stdkey_end(shift, ctrl); else if (text == "(" && !has_selection) { this->hide_completion_widget(); this->handle_parentheses(text); } else if ((text == "[" || text == "{") && !has_selection && this->close_parentheses_enabled) { QString s_trailing_text = this->get_text("cursor", "eol").trimmed(); if (s_trailing_text.size() == 0 || list_one.contains(s_trailing_text[0])) { this->insert_text(dict[text]); QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter); this->setTextCursor(cursor); } else TextEditBaseWidget::keyPressEvent(event); } else if ((key == Qt::Key_QuoteDbl || key == Qt::Key_Apostrophe) && this->close_quotes_enabled) this->autoinsert_quotes(key); else if ((key == Qt::Key_ParenRight || key == Qt::Key_BraceRight || key == Qt::Key_BracketRight) && !has_selection && this->close_parentheses_enabled && !this->textCursor().atBlockEnd()) { QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); QString text = cursor.selectedText(); QHash<int,QString> dict2 = {{Qt::Key_ParenRight, ")"}, {Qt::Key_BraceRight, "}"}, {Qt::Key_BracketRight, "]"}}; bool key_matches_next_char = text == dict2[key]; if (key_matches_next_char && !this->__unmatched_braces_in_line( cursor.block().text(), text[0])) { cursor.clearSelection(); this->setTextCursor(cursor); } else TextEditBaseWidget::keyPressEvent(event); } else if (key == Qt::Key_Colon && !has_selection && this->auto_unindent_enabled) { QString leading_text = this->get_text("sol", "cursor"); if (lstrip(leading_text)=="else" || lstrip(leading_text)=="finally") { auto ind = [](const QString& txt) ->int { return txt.size()-lstrip(txt).size(); }; QString prevtxt = this->textCursor().block().previous().text(); if (ind(leading_text) == ind(prevtxt)) this->unindent(true); } TextEditBaseWidget::keyPressEvent(event); } else if (key == Qt::Key_Space && !shift && !ctrl && !has_selection && this->auto_unindent_enabled) { QString leading_text = this->get_text("sol", "cursor"); if (lstrip(leading_text)=="elif" || lstrip(leading_text)=="except") { auto ind = [](const QString& txt) ->int { return txt.size()-lstrip(txt).size(); }; QString prevtxt = this->textCursor().block().previous().text(); if (ind(leading_text) == ind(prevtxt)) this->unindent(true); } TextEditBaseWidget::keyPressEvent(event); } else if (key == Qt::Key_Tab) { if (!has_selection && !this->tab_mode) this->intelligent_tab(); else this->indent_or_replace(); } else if (key == Qt::Key_Backtab) if (!has_selection && !this->tab_mode) this->intelligent_backtab(); else this->unindent(); else { TextEditBaseWidget::keyPressEvent(event); if (this->is_completion_widget_visible() && !text.isEmpty()) this->completion_text += text; } } // 该函数依赖于第三方库pygments语法高亮库,因此不去实现它 void CodeEditor::run_pygments_highlighter() {} void CodeEditor::handle_parentheses(const QString &text) { int position = this->get_position("cursor"); QString rest = rstrip(this->get_text("cursor","eol")); QList<QChar> list = {',', ')', ']', '}'}; bool valid = rest.isEmpty() || list.contains(rest[0]); if (this->close_parentheses_enabled && valid) { this->insert_text("()"); QTextCursor cursor = this->textCursor(); cursor.movePosition(QTextCursor::PreviousCharacter); this->setTextCursor(cursor); } else this->insert_text(text); if (this->is_python_like() && !this->get_text("sol","cursor").isEmpty() && this->calltips) emit this->sig_show_object_info(position); } void CodeEditor::mouseMoveEvent(QMouseEvent *event) { if (this->has_selected_text()) { TextEditBaseWidget::mouseMoveEvent(event); return; } if (this->go_to_definition_enabled && event->modifiers() & Qt::ControlModifier) { QString text = this->get_word_at(event->pos()); if (!text.isEmpty() && (this->is_python_like()) && !sourcecode::is_keyword(text)) { if (!this->__cursor_changed) { QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor)); this->__cursor_changed = true; } QTextCursor cursor = this->cursorForPosition(event->pos()); cursor.select(QTextCursor::WordUnderCursor); this->clear_extra_selections("ctrl_click"); this->__highlight_selection("ctrl_click", cursor, this->ctrl_click_color, QColor(), this->ctrl_click_color, QTextCharFormat::SingleUnderline, false); event->accept(); return; } } if (this->__cursor_changed) { QApplication::restoreOverrideCursor(); this->__cursor_changed = false; this->clear_extra_selections("ctrl_click"); } TextEditBaseWidget::mouseMoveEvent(event); } void CodeEditor::leaveEvent(QEvent *event) { if (this->__cursor_changed) { QApplication::restoreOverrideCursor(); this->__cursor_changed = false; this->clear_extra_selections("ctrl_click"); } TextEditBaseWidget::leaveEvent(event); } //@Slot() void CodeEditor::go_to_definition_from_cursor(QTextCursor cursor) { if (!this->go_to_definition_enabled) return; if (cursor.isNull()) cursor = this->textCursor(); if (this->in_comment_or_string()) return; int position = cursor.position(); QString text = cursor.selectedText(); if (text.size() == 0) { cursor.select(QTextCursor::WordUnderCursor); text = cursor.selectedText(); } if (!text.isEmpty()) emit this->go_to_definition(position); } void CodeEditor::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton && (event->modifiers() & Qt::ControlModifier)) { TextEditBaseWidget::mousePressEvent(event); QTextCursor cursor = this->cursorForPosition(event->pos()); this->go_to_definition_from_cursor(cursor); } else TextEditBaseWidget::mousePressEvent(event); } void CodeEditor::contextMenuEvent(QContextMenuEvent *event) { bool nonempty_selection = this->has_selected_text(); this->copy_action->setEnabled(nonempty_selection); this->cut_action->setEnabled(nonempty_selection); // TODO this->clear_all_output_action->setVisible(this->is_json() && false); this->ipynb_convert_action->setVisible(this->is_json() && false); this->run_cell_action->setVisible(this->is_python()); this->run_cell_and_advance_action->setVisible(this->is_python()); this->re_run_last_cell_action->setVisible(this->is_python()); this->gotodef_action->setVisible(this->go_to_definition_enabled && this->is_python_like()); QTextCursor cursor = this->textCursor(); QString text = cursor.selectedText(); if (text.size() == 0) { cursor.select(QTextCursor::WordUnderCursor); text = cursor.selectedText(); } this->undo_action->setEnabled(this->document()->isUndoAvailable()); this->redo_action->setEnabled(this->document()->isRedoAvailable()); QMenu* menu = this->menu; if (this->isReadOnly()) menu = this->readonly_menu; menu->popup(event->globalPos()); event->accept(); } void CodeEditor::dragEnterEvent(QDragEnterEvent *event) { if (!mimedata2url(event->mimeData()).isEmpty()) event->ignore(); else TextEditBaseWidget::dragEnterEvent(event); } void CodeEditor::dropEvent(QDropEvent *event) { if (!mimedata2url(event->mimeData()).isEmpty()) event->ignore(); else TextEditBaseWidget::dropEvent(event); } //------ Paint event void CodeEditor::paintEvent(QPaintEvent *event) { update_visible_blocks(event); TextEditBaseWidget::paintEvent(event); emit this->painted(event); } void CodeEditor::update_visible_blocks(QPaintEvent *event) { Q_UNUSED(event); this->__visible_blocks.clear(); QTextBlock block = this->firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = static_cast<int>(this->blockBoundingGeometry(block).translated( this->contentOffset()).top()); int bottom = top + static_cast<int>(this->blockBoundingRect(block).height()); int ebottom_bottom = this->height(); while (block.isValid()) { bool visible = bottom <= ebottom_bottom; if (visible == false) break; if (block.isVisible()) this->__visible_blocks.append(IntIntTextblock(top, blockNumber+1, block)); block = block.next(); top = bottom; bottom = top + static_cast<int>(this->blockBoundingRect(block).height()); blockNumber = block.blockNumber(); } } void CodeEditor::_draw_editor_cell_divider() { if (supported_cell_language) { QColor cell_line_color = this->comment_color; QPainter painter(this->viewport()); QPen pen = painter.pen(); pen.setStyle(Qt::SolidLine); pen.setBrush(cell_line_color); painter.setPen(pen); foreach (auto pair, this->__visible_blocks) { int top = pair.top; QTextBlock block = pair.block; // TODO源码是if self.is_cell_separator(block): if (this->is_cell_separator(QTextCursor(),block)) painter.drawLine(4,top,this->width(),top); } } } QList<IntIntTextblock> CodeEditor::visible_blocks() { return __visible_blocks; } bool CodeEditor::is_editor() { return true; } Printer::Printer(QPrinter::PrinterMode mode, const QFont& header_font) : QPrinter (mode) { this->setColorMode(QPrinter::Color); this->setPageOrder(QPrinter::FirstPageFirst); this->date = QDateTime::currentDateTime().toString(); if (header_font != QFont()) this->header_font = header_font; } TestWidget::TestWidget(QWidget *parent) : QSplitter (parent) { editor = new CodeEditor(this); QHash<QString, QVariant> kwargs; kwargs["linenumbers"] = true; kwargs["markers"] = true; kwargs["tab_mode"] = false; QFont font("Courier New", 10); kwargs["font"] = QVariant::fromValue(font); kwargs["show_blanks"] = true; QHash<QString,ColorBoolBool> color_scheme; color_scheme["background"] = ColorBoolBool("#3f3f3f"); color_scheme["currentline"] = ColorBoolBool("#333333"); color_scheme["currentcell"] = ColorBoolBool("#2c2c2c"); color_scheme["occurrence"] = ColorBoolBool("#7a738f"); color_scheme["ctrlclick"] = ColorBoolBool("#0000ff"); color_scheme["sideareas"] = ColorBoolBool("#3f3f3f"); color_scheme["matched_p"] = ColorBoolBool("#688060"); color_scheme["unmatched_p"] = ColorBoolBool("#bd6e76"); color_scheme["normal"] = ColorBoolBool("#dcdccc"); color_scheme["keyword"] = ColorBoolBool("#dfaf8f", true); color_scheme["builtin"] = ColorBoolBool("#efef8f"); color_scheme["definition"] = ColorBoolBool("#efef8f"); color_scheme["comment"] = ColorBoolBool("#7f9f7f", false, true); color_scheme["string"] = ColorBoolBool("#cc9393"); color_scheme["number"] = ColorBoolBool("#8cd0d3"); color_scheme["instance"] = ColorBoolBool("#dcdccc", false, true); QHash<QString, QVariant> dict; for (auto it=color_scheme.begin();it!=color_scheme.end();it++) { QString key = it.key(); QVariant val = QVariant::fromValue(it.value()); dict[key] = val; } kwargs["color_scheme"] = dict; editor->setup_editor(kwargs); addWidget(editor); classtree = new OutlineExplorerWidget(this); addWidget(classtree); connect(classtree,&OutlineExplorerWidget::edit_goto, [this](const QString&,int line,const QString& word){ editor->go_to_line(line,word); }); setStretchFactor(0, 4); setStretchFactor(1, 1); setWindowIcon(ima::icon("spyder")); } void TestWidget::load(const QString &filename) { editor->set_text_from_file(filename); QFileInfo info(filename); setWindowTitle(QString("%1 - %2 (%3)").arg("Editor"). arg(info.fileName()).arg(info.absolutePath())); classtree->set_current_editor(editor,filename,false,false); } static void test() { TestWidget* win = new TestWidget(nullptr); win->show(); win->load("F:/MyPython/spyder/widgets/sourcecode/codeeditor.py"); win->resize(900, 700); }
dae561d3cad1b72d65ecf485bb73d9a6e5b14c4b
cd4c589986e0cb69c025a50091a6cb083b1c5586
/QuantumEngine/Entities/GameObjectManager.h
bcb29117bbfd987c24ddb1bb2767a1306c2d1240
[]
no_license
DarriusWright/QuantumEngine
245e41afbf2d3eb4284afeb094a1b39b3423f739
aa1660fb6cb4c3645dcff215438b1b19a68dae06
refs/heads/master
2016-09-06T05:30:11.874136
2014-12-14T07:58:53
2014-12-14T07:58:53
27,872,722
1
0
null
null
null
null
UTF-8
C++
false
false
802
h
#pragma once #include <RTTI.h> #include <ExportHeader.h> #include <Manager.h> #include <vector> #include <map> #include "GameObject.h" #define GAMEOBJECT GameObjectManager::getInstance() class GameObjectManager : public Manager { RTTI_DECLARATIONS(GameObjectManager, RTTI); public: ENGINE_SHARED ~GameObjectManager(); ENGINE_SHARED GameObject * createGameObject(TransformComponent * transform = nullptr); ENGINE_SHARED void update()override; ENGINE_SHARED bool startUp()override; ENGINE_SHARED bool shutDown()override; static GameObjectManager * getInstance() { static GameObjectManager * gameObjectManager = new GameObjectManager(); return gameObjectManager; } protected: ENGINE_SHARED GameObjectManager(); std::map<int, GameObject*> gameObjects; static int numGameObjects; };
5385d4c596efe1410a4e9fe0853e710b39b0b0f4
ce5d5aa995e61c1df2c303e003ce1b882680d9a4
/vm.cpp
852feb02deca12c038f64d0669d447b86b71707e
[]
no_license
matiTechno/ic
770ccbe1855a915124f64a34086a209b27809320
0312a29eda1ebef6ef70c1a6e527c06afbe6528e
refs/heads/master
2020-09-08T17:59:22.247070
2020-02-03T15:28:59
2020-02-03T15:28:59
221,203,143
1
0
null
null
null
null
UTF-8
C++
false
false
15,667
cpp
#include "ic_impl.h" #define IC_STACK_SIZE (1024 * 1024) void ic_vm_init(ic_vm& vm) { vm.stack = (ic_data*)malloc(IC_STACK_SIZE * sizeof(ic_data)); } void ic_vm_free(ic_vm& vm) { free(vm.stack); } void ic_vm::push() { ++sp; assert(sp <= stack + IC_STACK_SIZE); } void ic_vm::push_many(int size) { sp += size; assert(sp <= stack + IC_STACK_SIZE); } ic_data ic_vm::pop() { --sp; return *sp; } void ic_vm::pop_many(int size) { sp -= size; } ic_data& ic_vm::top() { return *(sp - 1); } int ic_vm_run(ic_vm& _vm, ic_program& program) { ic_vm vm = _vm; // 20% perf gain in visual studio; but there is no gain if a parameter is passed by value, why? assert(bytes_to_data_size(program.global_data_byte_size) <= IC_STACK_SIZE); memcpy(vm.stack, program.bytecode, program.strings_byte_size); // set global non-string data to 0 memset(vm.stack + program.strings_byte_size, 0, program.global_data_byte_size - program.strings_byte_size); vm.sp = vm.stack + bytes_to_data_size(program.global_data_byte_size); vm.push_many(3); // main() return value, bp, ip vm.top().pointer = nullptr; // set a return address, see IC_OPC_RETURN for an explanation vm.bp = vm.sp; vm.ip = program.bytecode + program.strings_byte_size; for(;;) { ic_opcode opcode = (ic_opcode)*vm.ip; ++vm.ip; switch (opcode) { case IC_OPC_PUSH_S8: vm.push(); vm.top().s8 = *(char*)vm.ip; ++vm.ip; break; case IC_OPC_PUSH_S32: vm.push(); vm.top().s32 = read_int(&vm.ip); break; case IC_OPC_PUSH_F32: vm.push(); vm.top().f32 = read_float(&vm.ip); break; case IC_OPC_PUSH_F64: vm.push(); vm.top().f64 = read_double(&vm.ip); break; case IC_OPC_PUSH_NULLPTR: { vm.push(); vm.top().pointer = nullptr; break; } case IC_OPC_PUSH: { vm.push(); break; } case IC_OPC_PUSH_MANY: { vm.push_many(read_int(&vm.ip)); break; } case IC_OPC_POP: { vm.pop(); break; } case IC_OPC_POP_MANY: { int size = read_int(&vm.ip); vm.pop_many(size); break; } case IC_OPC_SWAP: { ic_data tmp = *(vm.sp - 2); *(vm.sp - 2) = vm.top(); vm.top() = tmp; break; } case IC_OPC_MEMMOVE: { void* dst = (char*)vm.sp - read_int(&vm.ip); void* src = (char*)vm.sp - read_int(&vm.ip); int byte_size = read_int(&vm.ip); memmove(dst, src, byte_size); break; } case IC_OPC_CLONE: { vm.push(); vm.top() = *(vm.sp - 2); break; } case IC_OPC_CALL: { int idx = read_int(&vm.ip); vm.push(); vm.top().pointer = vm.bp; vm.push(); vm.top().pointer = vm.ip; vm.bp = vm.sp; vm.ip = program.bytecode + idx; break; } case IC_OPC_CALL_HOST: { int idx = read_int(&vm.ip); ic_host_function& fun = program.host_functions[idx]; ic_data* argv = vm.sp - fun.param_size; ic_data* retv = argv - fun.return_size; fun.callback(argv, retv, fun.host_data); break; } case IC_OPC_RETURN: { vm.sp = vm.bp; vm.ip = (unsigned char*)vm.pop().pointer; vm.bp = (ic_data*)vm.pop().pointer; if (!vm.ip) return vm.top().s32; break; } case IC_OPC_JUMP_TRUE: { int idx = read_int(&vm.ip); if(vm.pop().s8) vm.ip = program.bytecode + idx; break; } case IC_OPC_JUMP_FALSE: { int idx = read_int(&vm.ip); if(!vm.pop().s8) vm.ip = program.bytecode + idx; break; } case IC_OPC_JUMP: { int idx = read_int(&vm.ip); vm.ip = program.bytecode + idx; break; } case IC_LOGICAL_NOT: { vm.top().s8 = !vm.top().s8; break; } case IC_OPC_ADDRESS: { int byte_offset = read_int(&vm.ip); vm.push(); vm.top().pointer = (char*)vm.bp + byte_offset; break; } case IC_OPC_ADDRESS_GLOBAL: { int byte_offset = read_int(&vm.ip); vm.push(); vm.top().pointer = (char*)vm.stack + byte_offset; break; } case IC_OPC_STORE_1: { void* ptr = vm.pop().pointer; *(char*)ptr = vm.top().s8; break; } case IC_OPC_STORE_4: { void* ptr = vm.pop().pointer; *(int*)ptr = vm.top().s32; break; } case IC_OPC_STORE_8: { void* ptr = vm.pop().pointer; *(double*)ptr = vm.top().f64; break; } case IC_OPC_STORE_STRUCT: { void* dst = vm.pop().pointer; int byte_size = read_int(&vm.ip); int data_size = bytes_to_data_size(byte_size); memcpy(dst, vm.sp - data_size, byte_size); break; } case IC_OPC_LOAD_1: { void* ptr = vm.top().pointer; vm.top().s8 = *(char*)ptr; break; } case IC_OPC_LOAD_4: { void* ptr = vm.top().pointer; vm.top().s32 = *(int*)ptr; break; } case IC_OPC_LOAD_8: { void* ptr = vm.top().pointer; vm.top().f64 = *(double*)ptr; break; } case IC_OPC_LOAD_STRUCT: { void* ptr = vm.pop().pointer; int byte_size = read_int(&vm.ip); int data_size = bytes_to_data_size(byte_size); vm.push_many(data_size); memcpy(vm.sp - data_size, ptr, byte_size); break; } case IC_OPC_COMPARE_E_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 == rhs; break; } case IC_OPC_COMPARE_NE_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 != rhs; break; } case IC_OPC_COMPARE_G_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 > rhs; break; } case IC_OPC_COMPARE_GE_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 >= rhs; break; } case IC_OPC_COMPARE_L_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 < rhs; break; } case IC_OPC_COMPARE_LE_S32: { int rhs = vm.pop().s32; vm.top().s8 = vm.top().s32 <= rhs; break; } case IC_OPC_NEGATE_S32: { vm.top().s32 = -vm.top().s32; break; } case IC_OPC_ADD_S32: { int rhs = vm.pop().s32; vm.top().s32 += rhs; break; } case IC_OPC_SUB_S32: { int rhs = vm.pop().s32; vm.top().s32 -= rhs; break; } case IC_OPC_MUL_S32: { int rhs = vm.pop().s32; vm.top().s32 *= rhs; break; } case IC_OPC_DIV_S32: { int rhs = vm.pop().s32; vm.top().s32 /= rhs; break; } case IC_OPC_MODULO_S32: { int rhs = vm.pop().s32; vm.top().s32 = vm.top().s32 % rhs; break; } case IC_OPC_COMPARE_E_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 == rhs; break; } case IC_OPC_COMPARE_NE_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 != rhs; break; } case IC_OPC_COMPARE_G_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 > rhs; break; } case IC_OPC_COMPARE_GE_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 >= rhs; break; } case IC_OPC_COMPARE_L_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 < rhs; break; } case IC_OPC_COMPARE_LE_F32: { float rhs = vm.pop().f32; vm.top().s8 = vm.top().f32 <= rhs; break; } case IC_OPC_NEGATE_F32: { vm.top().f32 = -vm.top().f32; break; } case IC_OPC_ADD_F32: { float rhs = vm.pop().f32; vm.top().f32 += rhs; break; } case IC_OPC_SUB_F32: { float rhs = vm.pop().f32; vm.top().f32 -= rhs; break; } case IC_OPC_MUL_F32: { float rhs = vm.pop().f32; vm.top().f32 *= rhs; break; } case IC_OPC_DIV_F32: { float rhs = vm.pop().f32; vm.top().f32 /= rhs; break; } case IC_OPC_COMPARE_E_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 == rhs; break; } case IC_OPC_COMPARE_NE_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 != rhs; break; } case IC_OPC_COMPARE_G_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 > rhs; break; } case IC_OPC_COMPARE_GE_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 >= rhs; break; } case IC_OPC_COMPARE_L_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 < rhs; break; } case IC_OPC_COMPARE_LE_F64: { double rhs = vm.pop().f64; vm.top().s8 = vm.top().f64 <= rhs; break; } case IC_OPC_NEGATE_F64: { vm.top().f64 = -vm.top().f64; break; } case IC_OPC_ADD_F64: { double rhs = vm.pop().f64; vm.top().f64 += rhs; break; } case IC_OPC_SUB_F64: { double rhs = vm.pop().f64; vm.top().f64 -= rhs; break; } case IC_OPC_MUL_F64: { double rhs = vm.pop().f64; vm.top().f64 *= rhs; break; } case IC_OPC_DIV_F64: { double rhs = vm.pop().f64; vm.top().f64 /= rhs; break; } case IC_OPC_COMPARE_E_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer == rhs; break; } case IC_OPC_COMPARE_NE_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer != rhs; break; } case IC_OPC_COMPARE_G_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer > rhs; break; } case IC_OPC_COMPARE_GE_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer >= rhs; break; } case IC_OPC_COMPARE_L_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer < rhs; break; } case IC_OPC_COMPARE_LE_PTR: { void* rhs = vm.pop().pointer; vm.top().s8 = vm.top().pointer <= rhs; break; } case IC_OPC_SUB_PTR_PTR: { int type_byte_size = read_int(&vm.ip); assert(type_byte_size); void* rhs = vm.pop().pointer; vm.top().s32 = ((char*)vm.top().pointer - (char*)rhs) / type_byte_size; break; } case IC_OPC_ADD_PTR_S32: { int type_byte_size = read_int(&vm.ip); assert(type_byte_size); int bytes = vm.pop().s32 * type_byte_size; vm.top().pointer = (char*)vm.top().pointer + bytes; break; } case IC_OPC_SUB_PTR_S32: { int type_byte_size = read_int(&vm.ip); assert(type_byte_size); int bytes = vm.pop().s32 * type_byte_size; vm.top().pointer = (char*)vm.top().pointer - bytes; break; } case IC_OPC_B_S8: vm.top().s8 = (bool)vm.top().s8; break; case IC_OPC_B_U8: vm.top().s8 = (bool)vm.top().u8; break; case IC_OPC_B_S32: vm.top().s8 = (bool)vm.top().s32; break; case IC_OPC_B_F32: vm.top().s8 = (bool)vm.top().f32; break; case IC_OPC_B_F64: vm.top().s8 = (bool)vm.top().f64; break; case IC_OPC_B_PTR: vm.top().s8 = (bool)vm.top().pointer; break; case IC_OPC_S8_U8: vm.top().s8 = vm.top().u8; break; case IC_OPC_S8_S32: vm.top().s8 = vm.top().s32; break; case IC_OPC_S8_F32: vm.top().s8 = vm.top().f32; break; case IC_OPC_S8_F64: vm.top().s8 = vm.top().f64; break; case IC_OPC_U8_S8: vm.top().u8 = vm.top().s8; break; case IC_OPC_U8_S32: vm.top().u8 = vm.top().s32; break; case IC_OPC_U8_F32: vm.top().u8 = vm.top().f32; break; case IC_OPC_U8_F64: vm.top().u8 = vm.top().f64; break; case IC_OPC_S32_S8: vm.top().s32 = vm.top().s8; break; case IC_OPC_S32_U8: vm.top().s32 = vm.top().u8; break; case IC_OPC_S32_F32: vm.top().s32 = vm.top().f32; break; case IC_OPC_S32_F64: vm.top().s32 = vm.top().f64; break; case IC_OPC_F32_S8: vm.top().f32 = vm.top().s8; break; case IC_OPC_F32_U8: vm.top().f32 = vm.top().u8; break; case IC_OPC_F32_S32: vm.top().f32 = vm.top().s32; break; case IC_OPC_F32_F64: vm.top().f32 = vm.top().f64; break; case IC_OPC_F64_S8: vm.top().f64 = vm.top().s8; break; case IC_OPC_F64_U8: vm.top().f64 = vm.top().u8; break; case IC_OPC_F64_S32: vm.top().f64 = vm.top().s32; break; case IC_OPC_F64_F32: vm.top().f64 = vm.top().f32; break; default: assert(false); } } // while }
b3d10a882fbde1ef7b87dd839bb7339f5be497db
5da7329111ede9432df039182275ad6ae0e4693d
/2012-arduino/TCL_lighting/audio_board/audio_board.ino
8b5c251801a7deeed2acd1cca1c93de29966eecb
[]
no_license
JamesHagerman/Sensatron
6bca70d378362978a285b49a7dbc14f14cc88c1c
9773c23481f83636fc7bc9c2938ea37f4bdc272e
refs/heads/master
2021-01-20T17:32:55.191392
2018-09-25T04:37:47
2018-09-25T04:37:47
61,709,147
2
3
null
2016-06-22T10:22:17
2016-06-22T10:07:22
null
UTF-8
C++
false
false
3,323
ino
// Spectrum analyzer shield pins int spectrumStrobe = 8; int spectrumReset = 9; int spectrumAnalog = 4; //4 for left channel, 5 for right. //This holds the 15 bit RGB values for each LED. //You'll need one for each LED, we're using 25 LEDs here. //Note you've only got limited memory, so you can only control //Several hundred LEDs on a normal arduino. Double that on a Duemilanove. int MyDisplay[25]; // Spectrum analyzer read values will be kept here. int Spectrum[7]; void setup() { byte Counter; // Turn on Serial port: Serial.begin(9600); Serial.println(""); Serial.println("Spectrum test written by James Hagerman"); //Setup pins to drive the spectrum analyzer. pinMode(spectrumReset, OUTPUT); pinMode(spectrumStrobe, OUTPUT); //Init spectrum analyzer digitalWrite(spectrumStrobe,LOW); delay(1); digitalWrite(spectrumReset,HIGH); delay(1); digitalWrite(spectrumStrobe,HIGH); delay(1); digitalWrite(spectrumStrobe,LOW); delay(1); digitalWrite(spectrumReset,LOW); delay(5); // Reading the analyzer now will read the lowest frequency. } void loop() { int Counter, Counter2, Counter3; showSpectrum(); delay(15); //We wait here for a little while until all the values to the LEDs are written out. //This is being done in the background by an interrupt. } // Read 7 band equalizer. void readSpectrum() { // Band 0 = Lowest Frequencies. byte Band; for(Band=0;Band <7; Band++) { Spectrum[Band] = (analogRead(spectrumAnalog) + analogRead(spectrumAnalog) ) >>1; //Read twice and take the average by dividing by 2 digitalWrite(spectrumStrobe,HIGH); digitalWrite(spectrumStrobe,LOW); } } void showSpectrum() { //Not I don;t use any floating point numbers - all integers to keep it zippy. readSpectrum(); byte Band, BarSize, MaxLevel; static unsigned int Divisor = 80, ChangeTimer=0; //, ReminderDivisor, unsigned int works, Remainder; MaxLevel = 0; for(Band=0;Band<5;Band++) {//We only graph the lowest 5 bands here, there is 2 more unused! //If value is 0, we don;t show anything on graph works = Spectrum[Band]/Divisor; //Bands are read in as 10 bit values. Scale them down to be 0 - 5 if(works > MaxLevel) { //Check if this value is the largest so far. MaxLevel = works; } Serial.print("band "); Serial.print(Band); Serial.print(" value: "); //Serial.print(works); Serial.print(Spectrum[Band]); Serial.print(" Divisor: "); Serial.println(Divisor); // for(BarSize=1;BarSize <=5; BarSize++) { // if( works > BarSize) { // LP.setLEDFast( LP.Translate(Band,BarSize-1),BarSize*6,31-(BarSize*5),0); // } else if ( works == BarSize) { // LP.setLEDFast( LP.Translate(Band,BarSize-1),BarSize*6,31-(BarSize*5),0); //Was remainder // } else { // LP.setLEDFast( LP.Translate(Band,BarSize-1),5,0,5); // } // } } // Adjust the Divisor if levels are too high/low. // If below 4 happens 20 times, then very slowly turn up. if (MaxLevel >= 5) { Divisor=Divisor+1; ChangeTimer=0; } else { if(MaxLevel < 4) { if(Divisor > 65) { if(ChangeTimer++ > 20) { Divisor--; ChangeTimer=0; } } } else { ChangeTimer=0; } } }
bacc0594b4b1bcdbb6e8ceffba3f142e561deb5c
5b0f0167080cc0684f507b0e50a872dca73d628f
/LeetCode/Check_Array_Formation_Through_Concatenation.cpp
47cf9631e9704603f2b25c2073c29d42b71dbd42
[]
no_license
donggan22/Algorithm
0918f522cfb0a7ddf67c8d888e242d655f4298cf
e8f988527c301fee1366180d197f3944caac7c76
refs/heads/main
2023-07-08T03:36:47.395275
2021-08-09T10:47:03
2021-08-09T10:47:03
323,762,785
0
0
null
null
null
null
UTF-8
C++
false
false
900
cpp
class Solution { public: bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) { if (arr.size() == 0) return false; unordered_map<int, int> m; for (int i = 0; i < arr.size(); i++) m.insert(make_pair(arr[i], i)); for (int i = 0; i < pieces.size(); i++) { int idx = 0; for (int j = 0; j < pieces[i].size(); j++) { if (j == 0) { if (m.end() == m.find(pieces[i][j])) return false; idx = m.find(pieces[i][j])->second + 1; } else { if (arr[idx] == pieces[i][j]) idx++; else return false; } } } return true; } };
61c4532608596185da6e48aa2555899f80f02257
d8371c58aa8ba6e31ecd40d97e0576bf9f366923
/include/general/allocation.h
29a7497200a81150c3f6fde5fc465f4fa541f100
[]
no_license
simmito/micmac-archeos
2499066b1652f9ba6a1e0391632f841333ffbcbf
9c66a1a656621b045173fa41874b39264ca39799
refs/heads/master
2021-01-15T21:35:26.952360
2013-07-17T15:36:36
2013-07-17T15:36:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,652
h
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #ifndef _ELISE_ALLOCATION_H #define _ELISE_ALLOCATION_H class Mcheck { public : void * operator new (size_t sz); void operator delete (void * ptr) ; private : // to avoid use void * operator new [] (size_t sz); void operator delete [] (void * ptr) ; }; template <const INT NBB> class ElListAlloc { public : void * get() { if (_l.empty()) _l.push_back(malloc(NBB)); void * res = _l.front(); _l.pop_front(); return res; } void put(void * v) { _l.push_front(v); } void purge() { while (! _l.empty()) { free(_l.front()); _l.pop_front(); } } private : ElSTDNS list<void *> _l; }; /*******************************************************************/ /* */ /* Classes for garbage collection */ /* */ /*******************************************************************/ /* Class RC_Object : References Counting Object */ class RC_Object : public Mcheck { friend void decr_ref(class Object_cptref * oc); friend class PRC0; protected : RC_Object(); virtual ~RC_Object(); //---- data ---- union { int cpt_ref; RC_Object * next; } _d; private : // declared as static so that they can be called with 0 static void decr_ref(RC_Object *); public : static void incr_ref(RC_Object *); }; /* Class PRC0 : Pointer to References Counting Object */ class PRC0 { public : // big three : PRC0 (const PRC0&); ~PRC0(void) ; void operator=(const PRC0 p2); void * ptr(){return _ptr;} PRC0 (RC_Object *) ; protected : inline PRC0(){_ptr=0;}; //-------- data ---------- RC_Object * _ptr; private : static void decr_ref(RC_Object * oc); // just to avoid use : // PRC0 * operator &(); }; #endif // ! _ELISE_ALLOCATION_H /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
9f64f557bd36653ac5fc3079221d23f24052773f
06f035b37775178a407866e8791b484b781bc114
/MyEngine/BumpMapShaderClass.cpp
9e9e22fa656cdb1193b53a57132749f5b2c3af8f
[]
no_license
yohan7979/ShaderSample
0cea2904a1a66cb3a1ff1b004b4a8330dd1d1787
0a5e5b8dd97e5d06386760eda03db9cf75278fd5
refs/heads/master
2022-04-18T10:50:16.854497
2020-04-17T14:47:12
2020-04-17T14:47:12
256,537,389
0
0
null
null
null
null
UHC
C++
false
false
9,026
cpp
#include "BumpMapShaderClass.h" BumpMapShaderClass::BumpMapShaderClass() : m_matrixBuffer(nullptr) , m_LightBuffer(nullptr) , m_sampleState(nullptr) { } BumpMapShaderClass::BumpMapShaderClass(const BumpMapShaderClass& other) { } BumpMapShaderClass::~BumpMapShaderClass() { } bool BumpMapShaderClass::Initialize(ID3D11Device* device, HWND hwnd) { bool result; // Initialize the vertex and pixel shaders. result = InitializeShader(device, hwnd, L"../MyEngine/Shader/bumpmap.vs", L"../MyEngine/Shader/bumpmap.ps", "BumpMapVertexShader", "BumpMapPixelShader"); if (!result) { return false; } return true; } void BumpMapShaderClass::Shutdown() { ShutdownShader(); } bool BumpMapShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename, const char* vsName, const char* psName) { Super::InitializeShader(device, hwnd, vsFilename, psFilename, vsName, psName); D3D11_INPUT_ELEMENT_DESC polygonLayout[6]; polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "NORMAL"; polygonLayout[2].SemanticIndex = 0; polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[2].InputSlot = 0; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[2].InstanceDataStepRate = 0; polygonLayout[3].SemanticName = "TANGENT"; polygonLayout[3].SemanticIndex = 0; polygonLayout[3].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[3].InputSlot = 0; polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[3].InstanceDataStepRate = 0; polygonLayout[4].SemanticName = "BINORMAL"; polygonLayout[4].SemanticIndex = 0; polygonLayout[4].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[4].InputSlot = 0; polygonLayout[4].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[4].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[4].InstanceDataStepRate = 0; polygonLayout[5].SemanticName = "TEXCOORD"; polygonLayout[5].SemanticIndex = 1; polygonLayout[5].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[5].InputSlot = 1; polygonLayout[5].AlignedByteOffset = 0; polygonLayout[5].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[5].InstanceDataStepRate = 1; UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // 정점 입력 레이아웃 생성 if (FAILED(device->CreateInputLayout(polygonLayout, numElements, m_vertexShaderBuffer->GetBufferPointer(), m_vertexShaderBuffer->GetBufferSize(), &m_layout))) { return false; } if (m_vertexShaderBuffer) { m_vertexShaderBuffer->Release(); m_vertexShaderBuffer = nullptr; } if (m_pixelShaderBuffer) { m_pixelShaderBuffer->Release(); m_pixelShaderBuffer = nullptr; } // 상수 버퍼 생성 D3D11_BUFFER_DESC matrixBufferDesc; matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC; matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType); matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; matrixBufferDesc.MiscFlags = 0; matrixBufferDesc.StructureByteStride = 0; if (FAILED(device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer))) { return false; } // 샘플러 생성 D3D11_SAMPLER_DESC samplerDesc; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.MipLODBias = 0.f; samplerDesc.MaxAnisotropy = 1; samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; samplerDesc.BorderColor[0] = 0; samplerDesc.BorderColor[1] = 0; samplerDesc.BorderColor[2] = 0; samplerDesc.BorderColor[3] = 0; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; if (FAILED(device->CreateSamplerState(&samplerDesc, &m_sampleState))) { return false; } // 광원 상수 버퍼 생성 D3D11_BUFFER_DESC lightBufferDesc; lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC; lightBufferDesc.ByteWidth = sizeof(LightBufferType); lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; lightBufferDesc.MiscFlags = 0; lightBufferDesc.StructureByteStride = 0; if (FAILED(device->CreateBuffer(&lightBufferDesc, NULL, &m_LightBuffer))) { return false; } return true; } void BumpMapShaderClass::ShutdownShader() { Super::ShutdownShader(); if (m_matrixBuffer) { m_matrixBuffer->Release(); m_matrixBuffer = nullptr; } if (m_LightBuffer) { m_LightBuffer->Release(); m_LightBuffer = nullptr; } if (m_sampleState) { m_sampleState->Release(); m_sampleState = nullptr; } } bool BumpMapShaderClass::Render(ID3D11DeviceContext* deviceContext, int vertexCount, int indexCount, int instanceCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView** textures, int textureCount, D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor) { bool result; // Set the shader parameters that it will use for rendering. result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, textures, textureCount, lightDirection, diffuseColor); if (!result) { return false; } // Now render the prepared buffers with the shader. if (instanceCount > 0) { RenderShaderInstanced(deviceContext, vertexCount, instanceCount); } else { RenderShader(deviceContext, indexCount); } return true; } bool BumpMapShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView** textures, int textureCount, D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor) { // 쉐이더에서 쓸 수 있게 행렬 전치 D3DXMatrixTranspose(&worldMatrix, &worldMatrix); D3DXMatrixTranspose(&viewMatrix, &viewMatrix); D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix); // 상수 버퍼에 쓸 수 있게 잠금 D3D11_MAPPED_SUBRESOURCE mappedResource; if (FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))) { return false; } // 서브리소스를 통해 데이터 쓰기 MatrixBufferType* dataPtr = static_cast<MatrixBufferType*>(mappedResource.pData); dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // 잠금 해제 deviceContext->Unmap(m_matrixBuffer, 0); // 정점 쉐이더에 상수 버퍼 갱신 deviceContext->VSSetConstantBuffers(0, 1, &m_matrixBuffer); // 픽셀 쉐이더에 텍스쳐 배열 세팅 (ShaderResourceView) deviceContext->PSSetShaderResources(0, textureCount, textures); // 광원 상수 버퍼 잠금 if (FAILED(deviceContext->Map(m_LightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource))) { return false; } LightBufferType* dataPtr2 = static_cast<LightBufferType*>(mappedResource.pData); dataPtr2->diffuseColor = diffuseColor; dataPtr2->lightDirection = lightDirection; // 픽셀 쉐이더에 상수 버퍼 갱신 deviceContext->Unmap(m_LightBuffer, 0); deviceContext->PSSetConstantBuffers(0, 1, &m_LightBuffer); return true; } void BumpMapShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount) { // Set the vertex input layout. deviceContext->IASetInputLayout(m_layout); // Set the vertex and pixel shaders that will be used to render this triangle. deviceContext->VSSetShader(m_vertexShader, NULL, 0); deviceContext->PSSetShader(m_pixelShader, NULL, 0); // Set the sampler states in the pixel shader. deviceContext->PSSetSamplers(0, 1, &m_sampleState); // Render the triangle. deviceContext->DrawIndexed(indexCount, 0, 0); } void BumpMapShaderClass::RenderShaderInstanced(ID3D11DeviceContext* deviceContext, int vertexCount, int instanceCount) { // Set the vertex input layout. deviceContext->IASetInputLayout(m_layout); // Set the vertex and pixel shaders that will be used to render this triangle. deviceContext->VSSetShader(m_vertexShader, NULL, 0); deviceContext->PSSetShader(m_pixelShader, NULL, 0); // Set the sampler states in the pixel shader. deviceContext->PSSetSamplers(0, 1, &m_sampleState); // Render the triangle. deviceContext->DrawInstanced(vertexCount, instanceCount, 0, 0); }
b797394de6d94fc0af6a9dcca68e55e4ecad1b9c
12a12837e4de40befdce2cae31f245298f1b34e7
/MyProject/Plugins/FirebaseFeatures/Source/ThirdParty/firebase_cpp_sdk/include/firebase/firestore/field_value.h
73e940ac1c0f79ceff49c7a568b9400c371fa8b5
[ "Apache-2.0" ]
permissive
Sergujest/softwareteam-unreal
fddb5f8016d464d4c07efa557e7d72c202725d94
f2aeec5544ef39312428bf7b911139ab368120cd
refs/heads/master
2023-06-13T02:03:32.030948
2021-07-09T14:09:17
2021-07-09T14:09:17
384,178,077
0
0
null
null
null
null
UTF-8
C++
false
false
12,377
h
/* * Copyright 2018 Google * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_ #include <cstdint> #include <iosfwd> #include <limits> #include <string> #include <vector> #include "firebase/internal/type_traits.h" #include "firebase/firestore/map_field_value.h" namespace firebase { class Timestamp; namespace firestore { class DocumentReference; class FieldValueInternal; class GeoPoint; /** * @brief A field value represents variant datatypes as stored by Firestore. * * FieldValue can be used when reading a particular field with * DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When * writing document fields with DocumentReference::Set() or * DocumentReference::Update(), it can also represent sentinel values in * addition to real data values. * * For a non-sentinel instance, you can check whether it is of a particular type * with is_foo() and get the value with foo_value(), where foo can be one of * null, boolean, integer, double, timestamp, string, blob, reference, * geo_point, array or map. If the instance is not of type foo, the call to * foo_value() will fail (and cause a crash). */ class FieldValue final { // Helper aliases for `Increment` member functions. // Qualifying `is_integer` is to prevent ambiguity with the // `FieldValue::is_integer` member function. // Note: normally, `enable_if::type` would be included in the alias, but such // a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within // an alias template). template <typename T> using EnableIfIntegral = enable_if<::firebase::is_integer<T>::value, int>; template <typename T> using EnableIfFloatingPoint = enable_if<is_floating_point<T>::value, int>; public: /** * The enumeration of all valid runtime types of FieldValue. */ enum class Type { kNull, kBoolean, kInteger, kDouble, kTimestamp, kString, kBlob, kReference, kGeoPoint, kArray, kMap, // Below are sentinel types. Sentinel types can be passed to Firestore // methods as arguments, but are never returned from Firestore. kDelete, kServerTimestamp, kArrayUnion, kArrayRemove, kIncrementInteger, kIncrementDouble, }; /** * @brief Creates an invalid FieldValue that has to be reassigned before it * can be used. * * Calling any member function on an invalid FieldValue will be a no-op. If * the function returns a value, it will return a zero, empty, or invalid * value, depending on the type of the value. */ FieldValue(); /** * @brief Copy constructor. * * `FieldValue` is immutable and can be efficiently copied (no deep copy is * performed). * * @param[in] other `FieldValue` to copy from. */ FieldValue(const FieldValue& other); /** * @brief Move constructor. * * Moving is more efficient than copying for a `FieldValue`. After being moved * from, a `FieldValue` is equivalent to its default-constructed state. * * @param[in] other `FieldValue` to move data from. */ FieldValue(FieldValue&& other) noexcept; ~FieldValue(); /** * @brief Copy assignment operator. * * `FieldValue` is immutable and can be efficiently copied (no deep copy is * performed). * * @param[in] other `FieldValue` to copy from. * * @return Reference to the destination `FieldValue`. */ FieldValue& operator=(const FieldValue& other); /** * @brief Move assignment operator. * * Moving is more efficient than copying for a `FieldValue`. After being moved * from, a `FieldValue` is equivalent to its default-constructed state. * * @param[in] other `FieldValue` to move data from. * * @return Reference to the destination `FieldValue`. */ FieldValue& operator=(FieldValue&& other) noexcept; /** * @brief Constructs a FieldValue containing the given boolean value. */ static FieldValue Boolean(bool value); /** * @brief Constructs a FieldValue containing the given 64-bit integer value. */ static FieldValue Integer(int64_t value); /** * @brief Constructs a FieldValue containing the given double-precision * floating point value. */ static FieldValue Double(double value); /** * @brief Constructs a FieldValue containing the given Timestamp value. */ static FieldValue Timestamp(Timestamp value); /** * @brief Constructs a FieldValue containing the given std::string value. */ static FieldValue String(std::string value); /** * @brief Constructs a FieldValue containing the given blob value of given * size. `value` is copied into the returned FieldValue. */ static FieldValue Blob(const uint8_t* value, size_t size); /** * @brief Constructs a FieldValue containing the given reference value. */ static FieldValue Reference(DocumentReference value); /** * @brief Constructs a FieldValue containing the given GeoPoint value. */ static FieldValue GeoPoint(GeoPoint value); /** * @brief Constructs a FieldValue containing the given FieldValue vector * value. */ static FieldValue Array(std::vector<FieldValue> value); /** * @brief Constructs a FieldValue containing the given FieldValue map value. */ static FieldValue Map(MapFieldValue value); /** @brief Gets the current type contained in this FieldValue. */ Type type() const; /** @brief Gets whether this FieldValue is currently null. */ bool is_null() const { return type() == Type::kNull; } /** @brief Gets whether this FieldValue contains a boolean value. */ bool is_boolean() const { return type() == Type::kBoolean; } /** @brief Gets whether this FieldValue contains an integer value. */ bool is_integer() const { return type() == Type::kInteger; } /** @brief Gets whether this FieldValue contains a double value. */ bool is_double() const { return type() == Type::kDouble; } /** @brief Gets whether this FieldValue contains a timestamp. */ bool is_timestamp() const { return type() == Type::kTimestamp; } /** @brief Gets whether this FieldValue contains a string. */ bool is_string() const { return type() == Type::kString; } /** @brief Gets whether this FieldValue contains a blob. */ bool is_blob() const { return type() == Type::kBlob; } /** * @brief Gets whether this FieldValue contains a reference to a document in * the same Firestore. */ bool is_reference() const { return type() == Type::kReference; } /** @brief Gets whether this FieldValue contains a GeoPoint. */ bool is_geo_point() const { return type() == Type::kGeoPoint; } /** @brief Gets whether this FieldValue contains an array of FieldValues. */ bool is_array() const { return type() == Type::kArray; } /** @brief Gets whether this FieldValue contains a map of std::string to * FieldValue. */ bool is_map() const { return type() == Type::kMap; } /** @brief Gets the boolean value contained in this FieldValue. */ bool boolean_value() const; /** @brief Gets the integer value contained in this FieldValue. */ int64_t integer_value() const; /** @brief Gets the double value contained in this FieldValue. */ double double_value() const; /** @brief Gets the timestamp value contained in this FieldValue. */ class Timestamp timestamp_value() const; /** @brief Gets the string value contained in this FieldValue. */ std::string string_value() const; /** @brief Gets the blob value contained in this FieldValue. */ const uint8_t* blob_value() const; /** @brief Gets the blob size contained in this FieldValue. */ size_t blob_size() const; /** @brief Gets the DocumentReference contained in this FieldValue. */ DocumentReference reference_value() const; /** @brief Gets the GeoPoint value contained in this FieldValue. */ class GeoPoint geo_point_value() const; /** @brief Gets the vector of FieldValues contained in this FieldValue. */ std::vector<FieldValue> array_value() const; /** * @brief Gets the map of string to FieldValue contained in this FieldValue. */ MapFieldValue map_value() const; /** * @brief Returns `true` if this `FieldValue` is valid, `false` if it is not * valid. An invalid `FieldValue` could be the result of: * - Creating a `FieldValue` using the default constructor. * - Calling `DocumentSnapshot::Get(field)` for a field that does not exist * in the document. * * @return `true` if this `FieldValue` is valid, `false` if this `FieldValue` * is invalid. */ bool is_valid() const { return internal_ != nullptr; } /** @brief Constructs a null. */ static FieldValue Null(); /** * @brief Returns a sentinel for use with Update() to mark a field for * deletion. */ static FieldValue Delete(); /** * Returns a sentinel that can be used with Set() or Update() to include * a server-generated timestamp in the written data. */ static FieldValue ServerTimestamp(); /** * Returns a special value that can be used with Set() or Update() that tells * the server to union the given elements with any array value that already * exists on the server. Each specified element that doesn't already exist in * the array will be added to the end. If the field being modified is not * already an array, it will be overwritten with an array containing exactly * the specified elements. * * @param elements The elements to union into the array. * @return The FieldValue sentinel for use in a call to Set() or Update(). */ static FieldValue ArrayUnion(std::vector<FieldValue> elements); /** * Returns a special value that can be used with Set() or Update() that tells * the server to remove the given elements from any array value that already * exists on the server. All instances of each element specified will be * removed from the array. If the field being modified is not already an * array, it will be overwritten with an empty array. * * @param elements The elements to remove from the array. * @return The FieldValue sentinel for use in a call to Set() or Update(). */ static FieldValue ArrayRemove(std::vector<FieldValue> elements); /** * Returns a string representation of this `FieldValue` for logging/debugging * purposes. * * @note the exact string representation is unspecified and subject to * change; don't rely on the format of the string. */ std::string ToString() const; /** * Outputs the string representation of this `FieldValue` to the given stream. * * @see `ToString()` for comments on the representation format. */ friend std::ostream& operator<<(std::ostream& out, const FieldValue& value); private: friend class DocumentReferenceInternal; friend class DocumentSnapshotInternal; friend class FieldValueInternal; friend class FirestoreInternal; friend class QueryInternal; friend class TransactionInternal; friend class Wrapper; friend class WriteBatchInternal; friend struct ConverterImpl; friend bool operator==(const FieldValue& lhs, const FieldValue& rhs); explicit FieldValue(FieldValueInternal* internal); static FieldValue IntegerIncrement(int64_t by_value); static FieldValue DoubleIncrement(double by_value); FieldValueInternal* internal_ = nullptr; }; /** Checks `lhs` and `rhs` for equality. */ bool operator==(const FieldValue& lhs, const FieldValue& rhs); /** Checks `lhs` and `rhs` for inequality. */ inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) { return !(lhs == rhs); } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_
a4a8494ad4213938c1ae44891e71a54dde3be884
3a77e7ffa78b51e1be18576f0c3e99048be8734f
/be/src/io/cache/block/block_file_segment.h
b462259931c831b1ce9b72f5bbdae01ca30e8a74
[ "OpenSSL", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-facebook-patent-rights-2", "PSF-2.0", "dtoa", "MIT", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
yiguolei/incubator-doris
e73e2c44c7e3a3869d379555a29abfe48f97de6c
ada01b7ba6eac5d442b7701b78cea44235ed5017
refs/heads/master
2023-08-18T23:28:09.915740
2023-08-05T05:18:18
2023-08-05T05:18:44
160,305,067
1
1
Apache-2.0
2023-07-07T08:05:16
2018-12-04T05:43:20
Java
UTF-8
C++
false
false
6,264
h
// 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. // This file is copied from // https://github.com/ClickHouse/ClickHouse/blob/master/src/Interpreters/Cache/FileSegment.h // and modified by Doris #pragma once #include <fmt/format.h> #include <stddef.h> #include <atomic> #include <condition_variable> #include <list> #include <memory> #include <mutex> #include <string> #include <utility> #include "common/status.h" #include "io/cache/block/block_file_cache.h" #include "io/fs/file_writer.h" #include "util/slice.h" namespace doris { namespace io { class FileBlock; class FileReader; using FileBlockSPtr = std::shared_ptr<FileBlock>; using FileBlocks = std::list<FileBlockSPtr>; class FileBlock { friend class LRUFileCache; friend struct FileBlocksHolder; public: using Key = IFileCache::Key; using LocalWriterPtr = std::unique_ptr<FileWriter>; using LocalReaderPtr = std::weak_ptr<FileReader>; enum class State { DOWNLOADED, /** * When file segment is first created and returned to user, it has state EMPTY. * EMPTY state can become DOWNLOADING when getOrSetDownaloder is called successfully * by any owner of EMPTY state file segment. */ EMPTY, /** * A newly created file segment never has DOWNLOADING state until call to getOrSetDownloader * because each cache user might acquire multiple file segments and reads them one by one, * so only user which actually needs to read this segment earlier than others - becomes a downloader. */ DOWNLOADING, SKIP_CACHE, }; FileBlock(size_t offset, size_t size, const Key& key, IFileCache* cache, State download_state, CacheType cache_type); ~FileBlock(); State state() const; static std::string state_to_string(FileBlock::State state); /// Represents an interval [left, right] including both boundaries. struct Range { size_t left; size_t right; Range(size_t left, size_t right) : left(left), right(right) {} bool operator==(const Range& other) const { return left == other.left && right == other.right; } size_t size() const { return right - left + 1; } std::string to_string() const { return fmt::format("[{}, {}]", std::to_string(left), std::to_string(right)); } }; const Range& range() const { return _segment_range; } const Key& key() const { return _file_key; } size_t offset() const { return range().left; } State wait(); // append data to cache file Status append(Slice data); // read data from cache file Status read_at(Slice buffer, size_t read_offset); // finish write, release the file writer Status finalize_write(); // set downloader if state == EMPTY std::string get_or_set_downloader(); std::string get_downloader() const; void reset_downloader(std::lock_guard<std::mutex>& segment_lock); bool is_downloader() const; bool is_downloaded() const { return _is_downloaded.load(); } CacheType cache_type() const { return _cache_type; } static std::string get_caller_id(); size_t get_download_offset() const; size_t get_downloaded_size() const; std::string get_info_for_log() const; std::string get_path_in_local_cache() const; State state_unlock(std::lock_guard<std::mutex>&) const; FileBlock& operator=(const FileBlock&) = delete; FileBlock(const FileBlock&) = delete; private: size_t get_downloaded_size(std::lock_guard<std::mutex>& segment_lock) const; std::string get_info_for_log_impl(std::lock_guard<std::mutex>& segment_lock) const; bool has_finalized_state() const; Status set_downloaded(std::lock_guard<std::mutex>& segment_lock); bool is_downloader_impl(std::lock_guard<std::mutex>& segment_lock) const; void complete_unlocked(std::lock_guard<std::mutex>& segment_lock); void reset_downloader_impl(std::lock_guard<std::mutex>& segment_lock); const Range _segment_range; State _download_state; std::string _downloader_id; LocalWriterPtr _cache_writer; LocalReaderPtr _cache_reader; size_t _downloaded_size = 0; /// global locking order rule: /// 1. cache lock /// 2. segment lock mutable std::mutex _mutex; std::condition_variable _cv; /// Protects downloaded_size access with actual write into fs. /// downloaded_size is not protected by download_mutex in methods which /// can never be run in parallel to FileBlock::write() method /// as downloaded_size is updated only in FileBlock::write() method. /// Such methods are identified by isDownloader() check at their start, /// e.g. they are executed strictly by the same thread, sequentially. mutable std::mutex _download_mutex; Key _file_key; IFileCache* _cache; std::atomic<bool> _is_downloaded {false}; CacheType _cache_type; }; struct FileBlocksHolder { explicit FileBlocksHolder(FileBlocks&& file_segments_) : file_segments(std::move(file_segments_)) {} FileBlocksHolder(FileBlocksHolder&& other) noexcept : file_segments(std::move(other.file_segments)) {} FileBlocksHolder& operator=(const FileBlocksHolder&) = delete; FileBlocksHolder(const FileBlocksHolder&) = delete; ~FileBlocksHolder(); FileBlocks file_segments {}; std::string to_string(); }; } // namespace io } // namespace doris
d8d1ad6f9cb5c5b3f1056d2a770fa81d4a84ad45
cf4605896cec9cea2c868d131e4a095c05a4fd1e
/C++/Ch4-C++/Ch4-14-swap-def.cpp
e6ab3d148fa0aa67150ca23f85fd840cdd494aa3
[]
no_license
alice2100chen/ourProgramming
1e5a57a3acecb005f63802471d76dfb581f70c86
a94818371ef86cf1eafaca22cf6cb451b0c50556
refs/heads/master
2020-04-20T00:31:50.823679
2020-01-06T14:26:49
2020-01-06T14:26:49
168,523,623
1
0
null
null
null
null
UTF-8
C++
false
false
491
cpp
#include <iostream> using namespace std; void swap(int a[], int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } void print_array(int arr[], int arr_len){ for(int i = 0; i < arr_len; i++){ cout << arr[i] << " "; } cout << endl; } int main(){ int num_visitors[7] = {70, 10, 14, 7, 25, 30, 50}; // 索引0~6代表星期日到六 print_array(num_visitors, 7); swap(num_visitors, 0, 6); print_array(num_visitors, 7); return 0; }
d559e0f9b3d79dd66a2e1ff9648e3974ad4d1abd
ef03edfaaf3437b24d3492ac3865968fcfda7909
/src/DesignPatterns/src/C++/002-GOFPatterns/003-BehavioralPatterns/004-Strategy/TemplateOperationStrategy/sample.cpp
c7d322e5d149b5c319de31c6844bc5d3937cf8c5
[]
no_license
durmazmehmet/CSD-UML-Design-Patterns
c60a6a008ec1b2de0cf5bdce74bc1336c4ceeb63
ae25ec31452016025ff0407e6c6728322624b082
refs/heads/main
2023-07-25T23:02:24.703632
2021-08-31T23:18:19
2021-08-31T23:18:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include <iostream> #include "IntOperationContext.h" #include "IntAddOperationStrategy.h" #include "IntAddWithValueOperationStrategy .h" using namespace std; #if 1 int main() { IntAddOperationStrategy as; IntAddWithValueOperationStrategy aws{ 3 }; IntOperationContext context{10, 20, as }; cout << context.execute() << endl; context.SetStrategy(aws); cout << context.execute() << endl; return 0; } #endif
81658eee6db9dad6c4db552577d67cbc6ca3b9cb
9dcf91bc705c1e7907afac96cfe8b07d86d1f637
/include/wm_navigation/WmGlobalNavigation.h
cb32eeffe6244728f83464592a208b965bc6d5f7
[ "BSD-3-Clause" ]
permissive
fmrico/WaterMellon
7dd47beca113d95836311e48827fef2beb778985
5d61914d9597118735e933e6d61a7e7872d83f5a
refs/heads/master
2021-01-10T11:42:55.551205
2015-10-27T22:08:42
2015-10-27T22:08:42
43,119,298
1
0
null
null
null
null
UTF-8
C++
false
false
4,021
h
/* * mapper.h * * Created on: 22/08/2015 * Author: paco */ #ifndef WMGLOBALNAVIGATION_H_ #define WMGLOBALNAVIGATION_H_ #include "ros/ros.h" #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <tf/transform_listener.h> #include <tf/message_filter.h> #include <message_filters/subscriber.h> #include <pcl/point_types.h> #include <pcl/conversions.h> #include <pcl_ros/transforms.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/voxel_grid.h> #include <pcl_conversions/pcl_conversions.h> #include "pcl/point_types_conversion.h" //#include <pcl/kdtree/kdtree_flann.h> #include <pcl/octree/octree_search.h> #include <pcl/octree/octree.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/OccupancyGrid.h> #include <ros/console.h> #include <float.h> #include <boost/math/distributions.hpp> #include <boost/math/distributions/normal.hpp> #include <stdlib.h> #include <time.h> #include <algorithm> #include <time.h> //#include <random> #include <wm_navigation/Particle.h> #include <costmap_2d/costmap_2d_ros.h> #include <costmap_2d/costmap_2d_publisher.h> #include <geometry_msgs/PoseStamped.h> #include <wm_navigation/Utilities.h> #include <watermellon/GNavGoalStamped.h> namespace wm_navigation { class WmGlobalNavigation { public: WmGlobalNavigation(ros::NodeHandle private_nh_ = ros::NodeHandle("~")); virtual ~WmGlobalNavigation(); virtual void mapCallback(const sensor_msgs::PointCloud2::ConstPtr& map_in); virtual void goalCallback(const geometry_msgs::PoseStamped::ConstPtr& goal_in); virtual void poseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& goal_in); virtual void perceptionCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_in); virtual void step(); void setGoalPose(const geometry_msgs::PoseStamped& goal_in); geometry_msgs::Pose getStartingPose(); geometry_msgs::Pose getEndPose(); geometry_msgs::Pose getCurrentPose(); private: void publish_all(); void publish_static_map(); void publish_dynamic_map(); void publish_gradient(); void publish_goal(); void updateStaticCostmap(); void updateDynamicCostmap(); void updatePath(); inline bool isPath(int i, int j, int cost); void updateGradient(int i, int j, int cost); float getLocalizationQuality(const geometry_msgs::PoseWithCovarianceStamped& pos_info); ros::NodeHandle nh_; tf::TransformListener tfListener_; tf::MessageFilter<sensor_msgs::PointCloud2>* tfMapSub_; tf::MessageFilter<sensor_msgs::PointCloud2>* tfPerceptSub_; message_filters::Subscriber<sensor_msgs::PointCloud2>* mapSub_; message_filters::Subscriber<sensor_msgs::PointCloud2>* perceptSub_; ros::Subscriber goal_sub_; ros::Subscriber pose_sub_; std::string worldFrameId_; std::string baseFrameId_; double res_; double pointcloudMinZ_; double pointcloudMaxZ_; double dynamic_cost_dec_; double dynamic_cost_inc_; double robot_radious_; static const int MAX_COST=255; geometry_msgs::PoseWithCovarianceStamped pose_; pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr map_; pcl::PointCloud<pcl::PointXYZRGB>::Ptr last_perception_; float map_max_x_, map_min_x_, map_max_y_, map_min_y_; ros::WallTime last_dynamic_map_update_; costmap_2d::Costmap2D static_costmap_; costmap_2d::Costmap2D dynamic_costmap_; costmap_2d::Costmap2D goal_gradient_; costmap_2d::Costmap2DPublisher static_costmap_pub_; costmap_2d::Costmap2DPublisher dynamic_costmap_pub_; costmap_2d::Costmap2DPublisher goal_gradient_pub_; std::vector<geometry_msgs::PoseStamped> plan_; geometry_msgs::PoseStamped::Ptr goal_; geometry_msgs::Pose::Ptr start_; watermellon::GNavGoalStamped::Ptr goal_vector_; ros::Publisher goal_vector_pub_; bool has_goal_; bool recalcule_path_; }; } #endif /* WMGLOBALNAVIGATION_H_ */
d0ddf6b1193ac6714ed78f721bc24d3fa6c54c05
1210df674a4a6ec547f8a6f1e8b2ea0b72bfabf7
/C7/7_4/StdAfx.cpp
ffe25f652d79b2e74eef4f86dcd416944064498c
[]
no_license
20191864229/G29
05e911e6185afd4ba6a85c4864a16d1e638885bb
144902d98bc2329a5c28a81ae7a8a7457c47fdc2
refs/heads/master
2020-08-16T19:59:42.203215
2019-12-16T14:15:33
2019-12-16T14:15:33
215,545,241
0
0
null
2019-11-02T01:11:42
2019-10-16T12:40:58
C++
UTF-8
C++
false
false
282
cpp
// stdafx.cpp : source file that includes just the standard includes // 7_4.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
87fd18dc7a0c813bc9fcd283f5591cde2e240716
a4a072ec59436e148121e87889714a68859da9da
/Src/Engine/3_Modules/Render/Assets/Material.h
f94ca71cf04edc08ae31612f0754a1641173e0ea
[]
no_license
morcosan/CYRED
3615441445bcfdfada3cd55533b3af4c1d14fac6
a65c7645148c522b2f14a5e447e1fe01ed3455bc
refs/heads/master
2021-03-23T07:25:30.131090
2016-05-10T20:49:47
2016-05-10T20:49:47
247,435,142
0
0
null
null
null
null
UTF-8
C++
false
false
1,805
h
// Copyright (c) 2015 Morco (www.morco.ro) // MIT License #pragma once #include "../../../1_Required/Required.h" #include "../../../2_BuildingBlocks/String/String.h" #include "../../../2_BuildingBlocks/Data/DataUnion.h" #include "../../../2_BuildingBlocks/Data/DataArray.h" #include "../../../2_BuildingBlocks/Asset.h" namespace CYRED { class Shader; class Texture; } namespace CYRED { namespace Enum_FaceCulling { enum Enum { CULL_BACK , CULL_FRONT , CULL_NONE }; } typedef Enum_FaceCulling::Enum FaceCulling; } namespace CYRED { class DLL Material : public Asset { public: Material(); virtual ~Material() {} public: void LoadUniqueID () override; void LoadFullFile () override; void ClearAsset () override; public: Shader* GetShader () const; bool IsWireframe () const; float GetLineWidth () const; FaceCulling GetFaceCulling () const; void SetShader ( Shader* shader ); void SetWireframe ( bool value ); void SetLineWidth ( float value ); void SetFaceCulling ( FaceCulling value ); void SetProperty ( const Char* name, Int value ); void SetProperty ( const Char* name, Float value ); void SetProperty ( const Char* name, const Vector2& value ); void SetProperty ( const Char* name, const Vector3& value ); void SetProperty ( const Char* name, const Vector4& value ); void SetProperty ( const Char* name, Texture* value ); UInt GetPropertiesCount (); DataUnion& GetPropertyDataAt ( UInt index ); const Char* GetPropertyNameAt ( UInt index ); void ClearProperties (); protected: struct _Property { String name; DataUnion data; }; Shader* _shader; bool _isWireframe; float _lineWidth; FaceCulling _faceCulling; DataArray<_Property> _properties; }; }
d01eb570ad6b1b5b8a0837cddb323339ba623c2d
d4a7a5a7e2868f5b3563b69d6e457e53d9f1c18e
/我的第一个c++程序.cpp
f57c616415469cd65299223817d62d1197d5d872
[]
no_license
cli851/noi
630328d2e08785caf2bc559618fa1c415a39f647
3245e8ea84486553ef24d05ab50aa81837d36657
refs/heads/master
2023-04-19T16:04:52.275245
2021-05-08T14:38:50
2021-05-08T14:38:50
null
0
0
null
null
null
null
GB18030
C++
false
false
237
cpp
#include<iostream> using namespace std; int main() { cout<<"春晓"<<endl; cout<<"春眠不觉晓,"<<endl; cout<<"处处蚊子咬,"<<endl; cout<<"夜来嗡嗡声,"<<endl; cout<<"脓包知多少。"<<endl; return 0; }
e969085e55e814f28f4940ff3dd0ea6949fcee78
1a9462cf8bf332d5171afe1913fba9a0fec262f8
/externals/boost/boost/functional/detail/hash_float.hpp
07d19c3040636a130a93c0957d3d7e7a03b234d7
[ "BSD-2-Clause" ]
permissive
ugozapad/g-ray-engine
4184fd96cd06572eb7e847cc48fbed1d0ab5767a
6a28c26541a6f4d50b0ca666375ab45f815c9299
refs/heads/main
2023-06-24T06:45:37.003158
2021-07-23T01:16:34
2021-07-23T01:16:34
377,952,802
4
0
null
null
null
null
UTF-8
C++
false
false
3,663
hpp
// Copyright Daniel James 2005-2006. Use, modification, and distribution are // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Based on Peter Dimov's proposal // http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf // issue 6.18. #if !defined(BOOST_FUNCTIONAL_DETAIL_HASH_FLOAT_HEADER) #define BOOST_FUNCTIONAL_DETAIL_HASH_FLOAT_HEADER #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/functional/detail/float_functions.hpp> #include <boost/limits.hpp> #include <boost/assert.hpp> #include <errno.h> // Don't use fpclassify or _fpclass for stlport. #if !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION) # if defined(__GLIBCPP__) || defined(__GLIBCXX__) // GNU libstdc++ 3 # if (defined(__USE_ISOC99) || defined(_GLIBCXX_USE_C99_MATH)) && \ !(defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)) # define BOOST_HASH_USE_FPCLASSIFY # endif # elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER) // Dinkumware Library, on Visual C++ # if defined(BOOST_MSVC) # define BOOST_HASH_USE_FPCLASS # endif # endif #endif namespace boost { namespace hash_detail { inline void hash_float_combine(std::size_t& seed, std::size_t value) { seed ^= value + (seed<<6) + (seed>>2); } template <class T> inline std::size_t float_hash_impl(T v) { int exp = 0; errno = 0; v = boost::hash_detail::call_frexp(v, &exp); if(errno) return 0; std::size_t seed = 0; std::size_t const length = (std::numeric_limits<T>::digits + std::numeric_limits<int>::digits - 1) / std::numeric_limits<int>::digits; for(std::size_t i = 0; i < length; ++i) { v = boost::hash_detail::call_ldexp(v, std::numeric_limits<int>::digits); int const part = static_cast<int>(v); v -= part; hash_float_combine(seed, part); } hash_float_combine(seed, exp); return seed; } template <class T> inline std::size_t float_hash_value(T v) { #if defined(BOOST_HASH_USE_FPCLASSIFY) using namespace std; switch (fpclassify(v)) { case FP_ZERO: return 0; case FP_INFINITE: return (std::size_t)(v > 0 ? -1 : -2); case FP_NAN: return (std::size_t)(-3); case FP_NORMAL: case FP_SUBNORMAL: return float_hash_impl(v); default: BOOST_ASSERT(0); return 0; } #elif defined(BOOST_HASH_USE_FPCLASS) switch(_fpclass(v)) { case _FPCLASS_NZ: case _FPCLASS_PZ: return 0; case _FPCLASS_PINF: return (std::size_t)(-1); case _FPCLASS_NINF: return (std::size_t)(-2); case _FPCLASS_SNAN: case _FPCLASS_QNAN: return (std::size_t)(-3); case _FPCLASS_NN: case _FPCLASS_ND: return float_hash_impl(v); case _FPCLASS_PD: case _FPCLASS_PN: return float_hash_impl(v); default: BOOST_ASSERT(0); return 0; } #else return float_hash_impl(v); #endif } } } #endif
e70b8d53ee7e3e340b0a10ccd797f320adcd245c
882238b7118ba2f7c2f8eb36212508203d0466a4
/generator/enum.h
3c972a63ac7203745dad060ac9781e33a75dad11
[ "MIT" ]
permissive
alisharifi01/hottentot
32c0184c9aa2248047eb03ca13d68dc8557b962b
e578a2185c473301076ece5634113ab663996a3e
refs/heads/master
2020-03-27T10:19:17.074850
2016-11-13T07:58:08
2016-11-13T07:58:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,458
h
/* The MIT License (MIT) * * Copyright (c) 2015 LabCrypto Org. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef _ORG_LABCRYPTO_HOTTENTOT_GENERATOR__ENUM_H_ #define _ORG_LABCRYPTO_HOTTENTOT_GENERATOR__ENUM_H_ #include <map> #include "declaration.h" namespace org { namespace labcrypto { namespace hottentot { namespace generator { namespace java { class JavaGenerator; }; namespace cc { class CCGenerator; }; class Module; class Enum { friend class Hot; friend class ::org::labcrypto::hottentot::generator::cc::CCGenerator; friend class ::org::labcrypto::hottentot::generator::java::JavaGenerator; public: public: Enum(Module *module) : module_(module) { } virtual ~Enum() {} public: inline virtual void AddItem(std::string name, uint16_t value) { items_[name] = value; revItems_[value] = name; } inline virtual std::string GetName() const { return name_; } inline virtual void SetName(std::string name) { name_ = name; } inline virtual std::string GetItemName(uint16_t itemValue) { return revItems_[itemValue]; } inline virtual uint16_t GetItemValue(std::string itemName) { return items_[itemName]; } private: std::string name_; std::map<std::string, uint16_t> items_; std::map<uint16_t, std::string> revItems_; Module *module_; }; } } } } #endif
b79e65fc586ca15bb23d36f567410e165cdd1cb9
eaae3bc291b9b8455e3f56650271655089fff997
/EFE Engine/include/scene/TileLayer.h
5c14b33a538b06f56d33354c1d8f1c99c4113467
[]
no_license
mifozski/EFE-Engine
59b6274830b68fa2e7f21b5d91de9d222297cbcb
32521a8f534e3ff863617bfb42360f8f568bacd0
refs/heads/master
2021-05-28T07:35:55.934515
2015-01-02T20:08:55
2015-01-02T20:08:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
945
h
#ifndef EFE_TILELAYER_H #define EFE_TILELAYER_H #include <vector> #include "scene/Tile.h" #include "math/MathTypes.h" #include "system/SystemTypes.h" namespace efe { enum eTileLayerType { eTileLayerType_Normal, eTileLayerType_LastEnum }; typedef std::vector<cTile*> tTileVec; typedef tTileVec::iterator tTileVecIt; class cTileLayer { friend class cTileMapRectIt; friend class cTileMapLineIt; public: cTileLayer(unsigned int a_lW, unsigned int a_lH, bool a_bCollision, bool a_bLit, eTileLayerType a_Type, float a_fZ = 0); ~cTileLayer(); bool SetTile(unsigned int a_lX, unsigned int a_lY, cTile *a_Val); cTile *GetAt(int a_lX, int a_lY); cTile *GetAt(int a_lNum); void SetZ(float a_fZ){m_fZ = a_fZ;} float GetZ(){return m_fZ;} bool HasCollsion(){return m_bCollision;} private: tTileVec m_vTile; cVector2l m_vSize; bool m_bCollision; bool m_bLit; float m_fZ; eTileLayerType m_Type; }; }; #endif
8296d686fa7a1716a2d20c01b4352e7a2d1eafe1
cf64d8d2d02661f0635b6e44c4d0903965eebe2e
/Round 630 (Div. 2)/A.cpp
293a7b2bc506c778c47d66c1247586ef0726fc7b
[]
no_license
LavishGulati/Codeforces
469b741855ce863877e0f6eb725bbe63bef0b91b
59756c87e37f903a0e8c84060478207d09b1bad2
refs/heads/master
2023-08-30T22:46:23.533386
2023-08-21T11:26:18
2023-08-21T11:26:18
145,226,865
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<long long, long long> pll; typedef pair<int, int> pii; typedef pair<int, bool> pib; #define pb push_back #define umap unordered_map #define uset unordered_set #define f first #define s second #define mp make_pair #define all(x) x.begin(), x.end() #define pq priority_queue #define MOD 1000000007 int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--){ int a, b, c, d; cin >> a >> b >> c >> d; int x, y, x1, y1, x2, y2; cin >> x >> y >> x1 >> y1 >> x2 >> y2; if(x-a+b >= x1 && x-a+b <= x2 && y-c+d >= y1 && y-c+d <= y2){ if(a > b && x1 > x-1){ cout << "No" << endl; } else if(a < b && x2 < x+1){ cout << "No" << endl; } else if(a == b && a > 0 && x1 > x-1 && x2 < x+1){ cout << "No" << endl; } else if(c > d && y1 > y-1){ cout << "No" << endl; } else if(c < d && y2 < y+1){ cout << "No" << endl; } else if(c == d && c > 0 && y1 > y-1 && y2 < y+1){ cout << "No" << endl; } else{ cout << "Yes" << endl; } } else{ cout << "No" << endl; } } }
756b6850ae09a618934e035517f99fb911046c65
de7e771699065ec21a340ada1060a3cf0bec3091
/spatial3d/src/java/org/apache/lucene/spatial3d/geom/GeoBaseCompositeMembershipShape.h
a18fe0bbfcd731a8f89393638bdeeb95cf7f4d81
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
3,234
h
#pragma once #include "stringhelper.h" #include <limits> #include <memory> #include <type_traits> #include <typeinfo> /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/gpl-3.0.en.html * * 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. */ namespace org::apache::lucene::spatial3d::geom { /** * Base class to create a composite of GeoMembershipShapes * * @param <T> is the type of GeoMembershipShapes of the composite. * @lucene.internal */ template <typename T> class GeoBaseCompositeMembershipShape : public GeoBaseCompositeShape<T>, public GeoMembershipShape { GET_CLASS_NAME(GeoBaseCompositeMembershipShape) static_assert(std::is_base_of<GeoMembershipShape, T>::value, L"T must inherit from GeoMembershipShape"); /** * Constructor. */ public: GeoBaseCompositeMembershipShape(std::shared_ptr<PlanetModel> planetModel) : GeoBaseCompositeShape<T>(planetModel) { } /** * Constructor for deserialization. * @param planetModel is the planet model. * @param inputStream is the input stream. * @param clazz is the class of the generic. */ GeoBaseCompositeMembershipShape(std::shared_ptr<PlanetModel> planetModel, std::shared_ptr<InputStream> inputStream, std::type_info<T> &clazz) : GeoBaseCompositeShape<T>(planetModel, inputStream, clazz) { } double computeOutsideDistance(std::shared_ptr<DistanceStyle> distanceStyle, std::shared_ptr<GeoPoint> point) override { return computeOutsideDistance(distanceStyle, point->x, point->y, point->z); } double computeOutsideDistance(std::shared_ptr<DistanceStyle> distanceStyle, double const x, double const y, double const z) override { if (isWithin(x, y, z)) { return 0.0; } double distance = std::numeric_limits<double>::infinity(); for (std::shared_ptr<GeoMembershipShape> shape : shapes) { constexpr double normalDistance = shape->computeOutsideDistance(distanceStyle, x, y, z); if (normalDistance < distance) { distance = normalDistance; } } return distance; } protected: std::shared_ptr<GeoBaseCompositeMembershipShape> shared_from_this() { return std::static_pointer_cast<GeoBaseCompositeMembershipShape>( GeoBaseCompositeShape<T>::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/spatial3d/geom/
10e7a3db1782418e81456090bc58081689c9a968
7d71fa3604d4b0538f19ed284bc5c7d8b52515d2
/Clients/AG/AgOutlookAddIn/Outlook.cpp
f6f72b7ad318b2fd34ab6407bc330a8d74619614
[]
no_license
lineCode/ArchiveGit
18e5ddca06330018e4be8ab28c252af3220efdad
f9cf965cb7946faa91b64e95fbcf8ad47f438e8b
refs/heads/master
2020-12-02T09:59:37.220257
2016-01-20T23:55:26
2016-01-20T23:55:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,804
cpp
#include "stdafx.h" #include "resource.h" #include "Outlook.h" #include "MapiAdmin.h" // Note: Namespace class member has changed to _Namespace in Outlook 2000 and 2002 // #include "msoutl8.h" // Outlook 97 // #include "msoutl85.h" // Outlook 98 // #include "msoutl9.h" // Outlook 2000 // #include "msoutl.h" // Outlook 2002 // #include "msoe.h" // Outlook Express ///////////////////////////////////////////////////////////////////////////// COutlook::COutlook(IDispatch* pApplication) { m_pApplication = pApplication; } ///////////////////////////////////////////////////////////////////////////// void COutlook::MapiSendmail() { CMapiAdmin mapi; // MAPI_NEW_SESSION|MAPI_TIMEOUT_SHORT //j HWND hWndParent = AfxGetMainWnd()->GetSafeHwnd(); if (!mapi.Logon(NULL/*hWndParent*/, NULL/*lpszProfileName*/, NULL/*lpszPassword*/, 0/*flFlags*/)) return; LPCTSTR ppRecipients[1] = {"[email protected]"}; mapi.CreateMessage(1, ppRecipients, "About our meeting", "Here is a test message", true); if (mapi.SendMessage()) MessageBox(NULL, "Message sent successfully", "Sent", MB_OK); } ///////////////////////////////////////////////////////////////////////////// void COutlook::AddContact() { Outlook::_ApplicationPtr pOutlook(m_pApplication); // Logon. Doesn't hurt if you are already running and logged on _NameSpacePtr pOutlookNamespace; pOutlook->GetNamespace(CComBSTR("MAPI"), &pOutlookNamespace); CComVariant varOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); pOutlookNamespace->Logon(varOptional, varOptional, varOptional, varOptional); // Create a new contact IDispatchPtr pCreateDispatch; pOutlook->CreateItem(Outlook::olContactItem, &pCreateDispatch); Outlook::_ContactItemPtr pContact(pCreateDispatch); // Setup Contact information pContact->put_FullName(CComBSTR("James Smith")); //j pContact->put_Birthday(CComDateTime(1975,9,15/*nYear,nMonth,nDay*/, 0,0,0/*nHour,nMin,nSec*/)); pContact->put_CompanyName(CComBSTR("Microsoft")); pContact->put_HomeTelephoneNumber(CComBSTR("704-555-8888")); pContact->put_Email1Address(CComBSTR("[email protected]")); pContact->put_JobTitle(CComBSTR("Developer")); pContact->put_HomeAddress(CComBSTR("111 Main St.\nCharlotte, NC 28226")); // Save Contact //j pContact->Save(); // Display pContact->Display(CComVariant((long)false/*bModal*/)); pOutlookNamespace->Logoff(); } ///////////////////////////////////////////////////////////////////////////// void COutlook::AddAppointment() { Outlook::_ApplicationPtr pOutlook(m_pApplication); // Logon. Doesn't hurt if you are already running and logged on _NameSpacePtr pOutlookNamespace; pOutlook->GetNamespace(CComBSTR("MAPI"), &pOutlookNamespace); CComVariant varOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); pOutlookNamespace->Logon(varOptional, varOptional, varOptional, varOptional); // Create a new appointment IDispatchPtr pCreateDispatch; pOutlook->CreateItem(Outlook::olAppointmentItem, &pCreateDispatch); Outlook::_AppointmentItemPtr pAppointment(pCreateDispatch); // Schedule it for two minutes from now COleDateTime apptDate = COleDateTime::GetCurrentTime(); pAppointment->put_Start((DATE)apptDate + DATE(2.0/(24.0*60.0))); // Set other appointment info pAppointment->put_Duration(60); pAppointment->put_Subject(CComBSTR("Meeting to discuss plans")); pAppointment->put_Body(CComBSTR("Meeting with James to discuss plans.")); pAppointment->put_Location(CComBSTR("Home Office")); pAppointment->put_ReminderMinutesBeforeStart(1); pAppointment->put_ReminderSet(TRUE); // Save the appointment //j pAppointment->Save(); // Display pAppointment->Display(CComVariant((long)false/*bModal*/)); pOutlookNamespace->Logoff(); }
cf37d9c6a12e2cadbc48bfa80a224ea9409c1cd5
36437a87c8110c0a0dd33fd28b312a6bbf1ef716
/others/pinhole_test.cpp
11782f16316abdb52c7da03bcabe8c9c91c83450
[]
no_license
hanebarla/RayTracing_Practice
17d5b0a03ad42af2cf7efa6fffe4a04c877eb13b
d05079ea02372e47abb3017692299464014d7a8d
refs/heads/master
2022-12-26T19:54:23.328483
2020-10-12T13:41:41
2020-10-12T13:41:41
298,297,250
0
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
#include "libs\vec3.h" #include "libs\ray.h" #include "libs\image.h" #include "libs\camera.h" int main(){ Image img(512, 512); PinholeCamera cam(Vec3(0, 0, 0), Vec3(0, 0, -1), 1); for(int i=0; i<img.width; i++){ for(int j=0; j<img.height; j++){ double u = (2.0*i - img.width)/img.width; double v = (2.0*j - img.height)/img.height; Ray ray = cam.getRay(-u, -v); Vec3 col = (ray.direction + 1.0)/2.0; img.setPixel(i, j, col); } } img.ppm_output("images\\pinholw_test.ppm"); return 0; }
ff0ef350ed9bee28b7b87248c81d45636e86a859
ada0e80868447865811b0098381db0d43dd63852
/ProgrammingPractice/Code/C++ Learning/Functors/Example3.cpp
ab6bd1d56bcba9ad178c4d345fca8ab830d77cd0
[]
no_license
phantom7knight/ProgrammingPracticeSamples
a4bc2fd9fbfc94dbb36ab3e1bfff88c3405df7ab
a13db3ca2bc8ac7af2b87703908455a3d97b2dfe
refs/heads/master
2023-08-01T01:40:57.933518
2021-09-17T04:38:59
2021-09-17T04:38:59
250,716,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
#include "../../../Helper Functions/Helper.hpp" //================================================================================================= //Lambda function example //================================================================================================= int main() { int m = 0; int n = 0; int Tcase = 4; switch (Tcase) { case 0: { [&, n](int a) mutable { m = ++n + a; }(15); //notes //[&,n] we send m by reference //(int a) -> this is the arg list which we want to send in the Lambda fn. //(15) is the value of arg 'a'. std::cout << m << std::endl << n << std::endl; } break; case 1: { [=](int a) mutable {m = ++n + a; }(10); std::cout << m << std::endl << n << std::endl; } break; { int aa = 5; auto Increment = [&] { ++aa; }; STDPRINTLINE("The value of a which was 5 is inserted into Increment Lambda expr"); STDPRINTLINE("new value of a is"); Increment(); STDPRINTLINE(aa); } break; case 3: { auto checkGreater = [](int a, int b) { //std::swap(a, b); if (a > b) { STDPRINTLINE("A is bigger"); } else { STDPRINTLINE("B is bigger"); } }; checkGreater(5, 15); } break; case 4: { std::vector<int> vec_here; //Push data into the vector for (int i = 0; i < 12; ++i) { vec_here.push_back(i); } //Lambda expr to find data which is even std::for_each(vec_here.begin(), vec_here.end(), [=](int num) { if (num % 2 == 0) { STDPRINTLINE(num); } }); } break; } return 0; }
91150c232fd4047e36d70be6baef956f8bbb5aad
e8ed22a5cbdf2f00236612d9244f0b7c296ebe0f
/Source/Toon_Tanks/GameModes/TankGameModeBase.cpp
47aa1c7e0bf36435bf6572efa0d19e3191f51e0e
[]
no_license
MujibBasha/Tanks-War-Game
16903439f19d491e51b3651d5e91fa218500a876
2d0694a4e8ae44c7c216c00900d18abc6b44b29e
refs/heads/main
2023-01-23T19:30:20.020722
2020-11-30T07:53:27
2020-11-30T07:53:27
317,148,976
0
0
null
null
null
null
UTF-8
C++
false
false
1,838
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TankGameModeBase.h" #include "Toon_Tanks/Pawns/PawnTank.h" #include "Toon_Tanks/Pawns/PawnTurret.h" #include "Kismet/GamePlayStatics.h" #include "Toon_Tanks/PlayerControllers/PlayerControllerBase.h" #include "TimerManager.h" void ATankGameModeBase::BeginPlay() { TargetTurrets = GetTargetTurretCount(); PlayerTank = Cast<APawnTank>(UGameplayStatics::GetPlayerPawn(this, 0)); PlayerControllerRef = Cast<APlayerControllerBase>(UGameplayStatics::GetPlayerController(this, 0)); HandleGameStart(); Super::BeginPlay(); } int32 ATankGameModeBase::GetTargetTurretCount() { TSubclassOf<APawnTurret> ClassToFind; ClassToFind = APawnTurret::StaticClass(); TArray<AActor*> TurretActors; UGameplayStatics::GetAllActorsOfClass(GetWorld(), ClassToFind, TurretActors); return TurretActors.Num();; } void ATankGameModeBase::ActorDied(AActor* DeadActor) { if (DeadActor == PlayerTank) { if (PlayerControllerRef) { PlayerControllerRef->setPlayerEnableState(false); } PlayerTank->PawnDestroyed(); HandleGameOver(false); } else if (APawnTurret* DestroyTurret = Cast<APawnTurret>(DeadActor)) { DestroyTurret->PawnDestroyed(); TargetTurrets--; if (TargetTurrets == 0) { HandleGameOver(true); } } } void ATankGameModeBase::HandleGameStart() { GameStart(); if (PlayerControllerRef) { PlayerControllerRef->setPlayerEnableState(false); FTimerHandle PlayerEnableHandle; FTimerDelegate PlayerEnableDelegate = FTimerDelegate::CreateUObject(PlayerControllerRef, &APlayerControllerBase::setPlayerEnableState,true); GetWorldTimerManager().SetTimer(PlayerEnableHandle,PlayerEnableDelegate,StartDelay,false); } } void ATankGameModeBase::HandleGameOver(bool PlayerWon) { GameOver(PlayerWon); }
f8311ccca6742349d7a47425b23a71a23ca5a89e
aac8888a3258a2dc310fcc9de20e9b12ca3c1469
/main.cpp
e9344b6768c151f89e1ba7991e43dd0a63750b63
[]
no_license
data1213/temp_repository
b182189e696ca3f53c7ff6acb03a2a83b3dbc7d1
cd0eda3393c4febec93da01cc3fc3705c306a700
refs/heads/master
2020-05-19T07:31:46.051803
2019-05-04T14:42:26
2019-05-04T14:42:26
184,900,143
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); // 主窗口对象 MainWindow w; //显式主窗口 w.show(); //进入阻塞模式 return a.exec(); }
976215d6f5cb4801c9cdb59f07191b08392905fc
ea1f01ce32671a1214dd7e0995bc131307e58476
/A4/GeometryNode.hpp
75cddb9cd187ccbaf16b135a1f687839c6a8e18c
[]
no_license
mismayil/cs488
65a729adfe9757a7c52d0609b381888d64b1f12b
d8938779bc0b1b1fd9ca5a5dd29d25f6e843a721
refs/heads/master
2021-01-10T06:45:50.215212
2015-12-31T19:27:13
2015-12-31T19:27:13
48,860,054
1
0
null
null
null
null
UTF-8
C++
false
false
319
hpp
#pragma once #include "SceneNode.hpp" #include "Primitive.hpp" #include "Material.hpp" class GeometryNode : public SceneNode { public: GeometryNode( const std::string & name, Primitive *prim, Material *mat = nullptr ); void setMaterial( Material *material ); Material *m_material; Primitive *m_primitive; };
1d628ac5b13c83e1a1a44d4f7139ad542e14030b
dcb75b10a352d9cfc0ae31f28679a2d56b10b875
/Source/Mordhau/StrikeMotion.h
2ac8703d57f6bf9becd4cbc5c8580695cc7a6e4a
[]
no_license
Net-Slayer/Mordhau_uSDK
df5a096c21eb43e910c9b90c69ece495384608e0
c4ff76b5d7462fc6ccad176bd8f1db2efdd2c910
refs/heads/master
2023-04-28T02:48:14.072100
2021-12-15T16:35:08
2021-12-15T16:35:08
301,417,546
3
1
null
2021-08-23T13:23:29
2020-10-05T13:26:39
C++
UTF-8
C++
false
false
2,454
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Mordhau.h" #include "AttackMotion.h" #include "StrikeMotion.generated.h" /** * */ UCLASS() class MORDHAU_API UStrikeMotion : public UAttackMotion { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, EditAnywhere) struct FRotator AnimAngleCueAmount; //(Edit, BlueprintVisible, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) class UCurveFloat* AnimAngleCurve; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float ExtraEarlyReleaseForLookUpOverheads; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float ExtraEarlyReleaseForLookUpNonUndercuts; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float CounterCompensateOverheadFixupTerm; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float CounterCompensateOverheadFixupTiltTerm; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float CounterCompensateWeight; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float MaxTurnCompensation; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float CounterCompensateLookTime; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) struct FVector2D AngleToReleasePortionGlanceIn; //(Edit, BlueprintVisible, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) struct FVector2D AngleToReleasePortionGlanceOut; //(Edit, BlueprintVisible, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float GlanceMinimumTurnAmount; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float GlanceOppositeMinimumTurnAmount; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float GlanceBlockedMinimumTurnAmount; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) UPROPERTY(BlueprintReadWrite, EditAnywhere) float GlanceBlockedOppositeMinimumTurnAmount; //(Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) };
b2fe9dac32915bd258854533afaa16319181e9f8
8aaca4789239bd08f6422ec95de4782243fbb55e
/FCX/Plugins/Effekseer/Intermediate/Build/Win64/UE4Editor/Inc/EffekseerEd/EffekseerModelFactory.generated.h
53335dd81091e6b0aa373a2705b981ba3d89bc61
[]
no_license
mikemikeMyuta/Future-Creation-Exhibition
0e8572f20a5eff241a0241da5029399e83443714
d76795f26ad18e09d4bc2836784587476a8c47f1
refs/heads/master
2020-08-02T02:24:39.957952
2019-10-18T06:44:33
2019-10-18T06:44:33
211,202,171
0
0
null
null
null
null
UTF-8
C++
false
false
5,231
h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef EFFEKSEERED_EffekseerModelFactory_generated_h #error "EffekseerModelFactory.generated.h already included, missing '#pragma once' in EffekseerModelFactory.h" #endif #define EFFEKSEERED_EffekseerModelFactory_generated_h #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS_NO_PURE_DECLS #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUEffekseerModelFactory(); \ friend struct Z_Construct_UClass_UEffekseerModelFactory_Statics; \ public: \ DECLARE_CLASS(UEffekseerModelFactory, UFactory, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/EffekseerEd"), NO_API) \ DECLARE_SERIALIZER(UEffekseerModelFactory) #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS \ private: \ static void StaticRegisterNativesUEffekseerModelFactory(); \ friend struct Z_Construct_UClass_UEffekseerModelFactory_Statics; \ public: \ DECLARE_CLASS(UEffekseerModelFactory, UFactory, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/EffekseerEd"), NO_API) \ DECLARE_SERIALIZER(UEffekseerModelFactory) #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UEffekseerModelFactory(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UEffekseerModelFactory) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UEffekseerModelFactory); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UEffekseerModelFactory); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UEffekseerModelFactory(UEffekseerModelFactory&&); \ NO_API UEffekseerModelFactory(const UEffekseerModelFactory&); \ public: #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_ENHANCED_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UEffekseerModelFactory(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UEffekseerModelFactory(UEffekseerModelFactory&&); \ NO_API UEffekseerModelFactory(const UEffekseerModelFactory&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UEffekseerModelFactory); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UEffekseerModelFactory); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UEffekseerModelFactory) #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_13_PROLOG #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS_NO_PURE_DECLS \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS_NO_PURE_DECLS \ FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_ENHANCED_CONSTRUCTORS \ static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class EffekseerModelFactory."); \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> EFFEKSEERED_API UClass* StaticClass<class UEffekseerModelFactory>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
bf7794328260e51b312970306958109ce4ca68e8
48d5dbf4475448f5df6955f418d7c42468d2a165
/SDK/SoT_BP_Harpoon_classes.hpp
431547d1a77d80f7cee054584c02cb560d1595f5
[]
no_license
Outshynd/SoT-SDK-1
80140ba84fe9f2cdfd9a402b868099df4e8b8619
8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4
refs/heads/master
2022-11-21T04:35:29.362290
2020-07-10T14:50:55
2020-07-10T14:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
hpp
#pragma once // Sea of Thieves (1.4.16) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_Harpoon_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Harpoon.BP_Harpoon_C // 0x0018 (0x0428 - 0x0410) class ABP_Harpoon_C : public AActor { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0410(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UStaticMeshComponent* shp_rope_coil_02_a; // 0x0418(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class USceneComponent* DefaultSceneRoot; // 0x0420(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_Harpoon.BP_Harpoon_C")); return ptr; } void UserConstructionScript(); void ReceiveBeginPlay(); void ExecuteUbergraph_BP_Harpoon(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
074d9afdbca931dab2d0776ab45a5aca41c4ec67
0fb70d4dc8e3fbbd9233a26094976947c56f1f34
/HackerRank Problems/Solve_Me_First.cpp
532a357a8b488fdc92a12a6446673260f017b582
[]
no_license
ahmedemad9/CPP
86831b5554cfc922576e922b2e8eab92a8cb87ab
2791f05684d9c43c5ddd4f43ff72b4883ee056fc
refs/heads/main
2023-03-05T01:42:44.465075
2021-02-15T19:54:57
2021-02-15T19:54:57
339,190,356
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int solveMeFirst(int a,int b); int solveMeFirst(int a, int b) { return(a+b); } int main() { int num1, num2; int sum; cin>>num1>>num2; sum = solveMeFirst(num1,num2); cout<<sum; return 0; }
d6bb8d4c4ce15fb7d5fd9774ce73bbe419ab9455
da00f367cf627944bf2e70fde1ac740c9cd50f42
/windows_ce_4_2_081231/WINCE420/PRIVATE/SERVERS/UPNP/UPNPCAPI/upnpcapi.cpp
9f862334dc8f5d3db80c2f528c854c7c60b7803e
[]
no_license
xiaoqgao/windows_ce_4_2_081231
9a5c427aa00f93ca8994cf80ec1777a309544a5d
2e397f2929a998e72034e3a350fc57d8dc10eaa9
refs/heads/master
2022-12-21T20:19:38.308851
2020-09-28T19:59:38
2020-09-28T19:59:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,096
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // This source code is licensed under Microsoft Shared Source License // Version 1.0 for Windows CE. // For a copy of the license visit http://go.microsoft.com/fwlink/?LinkId=3223. // #include <windows.h> #include <ssdppch.h> #include <upnpdevapi.h> #include <ssdpapi.h> #include <ssdpioctl.h> #include <service.h> #include "ssdpfuncc.h" #include "string.hxx" #define celems(_x) (sizeof(_x) / sizeof(_x[0])) BOOL InitCallbackTarget(PCWSTR pszName, PUPNPCALLBACK pfCallback, PVOID pvContext, DWORD *phCallback); BOOL StopCallbackTarget(PCWSTR pszName); //LONG cInitialized = 0; HANDLE g_hUPNPSVC = INVALID_HANDLE_VALUE; // handle to SSDP service CRITICAL_SECTION g_csUPNPAPI; static DWORD cbBytesReturned; // not used int ClientStop(); int ClientStart() { EnterCriticalSection(&g_csUPNPAPI); DBGCHK(L"UPNPAPI", g_hUPNPSVC == INVALID_HANDLE_VALUE); if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { // Try to open the SSDP service g_hUPNPSVC = CreateFile(TEXT("UPP1:"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); DWORD dwBytesReturned; DeviceIoControl(g_hUPNPSVC, IOCTL_SERVICE_START, NULL, 0, NULL, 0, &dwBytesReturned, NULL); } LeaveCriticalSection(&g_csUPNPAPI); return (g_hUPNPSVC != INVALID_HANDLE_VALUE); } int ClientStop() { EnterCriticalSection(&g_csUPNPAPI); if (g_hUPNPSVC != INVALID_HANDLE_VALUE) { CloseHandle(g_hUPNPSVC); g_hUPNPSVC = INVALID_HANDLE_VALUE; } LeaveCriticalSection(&g_csUPNPAPI); return TRUE; } /* Device creation */ BOOL WINAPI UpnpAddDevice(IN UPNPDEVICEINFO *pDev) { BOOL fRet = FALSE; struct AddDeviceParams parms = {pDev}; DWORD dwCallbackHandle; if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } fRet = InitCallbackTarget(pDev->pszDeviceName, pDev->pfCallback, pDev->pvUserDevContext, &dwCallbackHandle); if (fRet) { PVOID pvTemp = pDev->pvUserDevContext; pDev->pvUserDevContext = (PVOID)dwCallbackHandle; fRet = DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_ADD_DEVICE, &parms, sizeof(parms), NULL, 0, &cbBytesReturned, NULL); // restore the changed parameters pDev->pvUserDevContext = pvTemp; if (!fRet) { StopCallbackTarget(pDev->pszDeviceName); } } return fRet; } BOOL WINAPI UpnpRemoveDevice( PCWSTR pszDeviceName) { BOOL fRet; if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } fRet = DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_REMOVE_DEVICE, (PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR), NULL, 0, &cbBytesReturned, NULL); StopCallbackTarget(pszDeviceName); // this may fail if the target has already been removed return fRet; } /* Publication control */ BOOL WINAPI UpnpPublishDevice( PCWSTR pszDeviceName) { if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } return DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_PUBLISH_DEVICE, (PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR), NULL, 0, &cbBytesReturned, NULL); } BOOL WINAPI UpnpUnpublishDevice( PCWSTR pszDeviceName) { if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } return DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_UNPUBLISH_DEVICE, (PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR), NULL, 0, &cbBytesReturned, NULL); } /* Description info */ BOOL WINAPI UpnpGetUDN( IN PCWSTR pszDeviceName, // [in] local device name IN PCWSTR pszTemplateUDN, // [in, optional] the UDN element in the original device description OUT PWSTR pszUDNBuf, // [in] buffer to hold the assigned UDN IN OUT PDWORD pchBuf) // [in,out] size of buffer/ length filled (in WCHARs) { struct GetUDNParams parms = {pszDeviceName, pszTemplateUDN, pszUDNBuf, pchBuf}; if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } return DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_GET_UDN, &parms, sizeof(parms), NULL, 0, &cbBytesReturned, NULL); } BOOL WINAPI UpnpGetSCPDPath( IN PCWSTR pszDeviceName, // [in] local device name IN PCWSTR pszUDN, IN PCWSTR pszServiceId, // [in] serviceId (from device description) OUT PWSTR pszSCPDPath, // [out] file path to SCPD IN DWORD cchFilePath) // [in] size of pszSCPDFilePath in WCHARs { struct GetSCPDPathParams parms= {pszDeviceName, pszUDN, pszServiceId, pszSCPDPath, cchFilePath}; if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } return DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_GET_SCPD_PATH, &parms, sizeof(parms), NULL, 0, &cbBytesReturned, NULL); } /* Eventing */ BOOL WINAPI UpnpSubmitPropertyEvent( PCWSTR pszDeviceName, PCWSTR pszUDN, PCWSTR pszServiceName, DWORD nArgs, UPNPPARAM *rgArgs) { struct SubmitPropertyEventParams parms = {pszDeviceName, pszUDN, pszServiceName, nArgs, rgArgs}; if (g_hUPNPSVC == INVALID_HANDLE_VALUE) { ClientStart(); } return DeviceIoControl( g_hUPNPSVC, UPNP_IOCTL_SUBMIT_PROPERTY_EVENT, &parms, sizeof(parms), NULL, 0, &cbBytesReturned, NULL); } bool EncodeForXML(LPCWSTR pwsz, ce::wstring* pstr) { wchar_t aCharacters[] = {L'<', L'>', L'\'', L'"', L'&'}; wchar_t* aEntityReferences[] = {L"&lt;", L"&gt;", L"&apos;", L"&quot;", L"&amp;"}; bool bReplaced; pstr->reserve(static_cast<ce::wstring::size_type>(1.1 * wcslen(pwsz))); pstr->resize(0); for(const wchar_t* pwch = pwsz; *pwch; ++pwch) { bReplaced = false; for(int i = 0; i < sizeof(aCharacters)/sizeof(*aCharacters); ++i) if(*pwch == aCharacters[i]) { pstr->append(aEntityReferences[i]); bReplaced = true; break; } if(!bReplaced) pstr->append(pwch, 1); } return true; } /* <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:actionNameResponse xmlns:u="urn:schemas-upnp-org:service:serviceType:v"> <argumentName>out arg value</argumentName> other out args and their values go here, if any </u:actionNameResponse> </s:Body> </s:Envelope> */ const WCHAR c_szSOAPResp1[] = L"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" \r\n" L"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" L" <s:Body>\r\n" L" <u:%sResponse xmlns:u=\"%s\">\r\n"; const WCHAR c_szSOAPResp2[] = L" </u:%sResponse>\r\n" L" </s:Body>\r\n" L"</s:Envelope>\r\n"; const WCHAR c_szSOAPArg[] = L"<%s>%s</%s>\r\n"; static bool _UpnpSetControlResponse( UPNPSERVICECONTROL *pUPNPAction, DWORD cOutArgs, UPNPPARAM *aOutArg, PWSTR* ppszRawResp) { int cch = celems(c_szSOAPResp1) + celems(c_szSOAPResp2), cch2; ce::wstring str; DWORD i; // force out argument for QueryStateVariable to be "return" if (wcscmp(pUPNPAction->pszAction, L"QueryStateVariable") == 0 && cOutArgs == 1) aOutArg[0].pszName = L"return"; cch += 2*wcslen(pUPNPAction->pszAction) + wcslen(pUPNPAction->pszServiceType); for (i=0; i < cOutArgs; i++) { EncodeForXML(aOutArg[i].pszValue, &str); cch += wcslen(c_szSOAPArg) + 2*wcslen(aOutArg[i].pszName) + str.length(); } *ppszRawResp = new WCHAR [cch]; if (!*ppszRawResp) return false; cch2 = wsprintfW(*ppszRawResp,c_szSOAPResp1,pUPNPAction->pszAction, pUPNPAction->pszServiceType); for (i=0; i < cOutArgs; i++) { EncodeForXML(aOutArg[i].pszValue, &str); cch2+=wsprintfW(*ppszRawResp + cch2, c_szSOAPArg, aOutArg[i].pszName, static_cast<LPCWSTR>(str), aOutArg[i].pszName); } cch2 += wsprintfW(*ppszRawResp + cch2, c_szSOAPResp2, pUPNPAction->pszAction); DBGCHK(L"UPNPAPI", cch2 < cch); return true; } BOOL WINAPI UpnpSetControlResponse( UPNPSERVICECONTROL *pUPNPAction, DWORD cOutArgs, UPNPPARAM *aOutArg) { BOOL fRet = FALSE; PWSTR pszRawResp = NULL; __try { fRet = _UpnpSetControlResponse(pUPNPAction, cOutArgs, aOutArg, &pszRawResp); } __except (EXCEPTION_EXECUTE_HANDLER) { SetLastError(ERROR_INVALID_PARAMETER); fRet = FALSE; } if (fRet) fRet = UpnpSetRawControlResponse(pUPNPAction,HTTP_STATUS_OK, pszRawResp); if (pszRawResp) delete[] pszRawResp; return fRet; } const WCHAR c_szSOAPFault[]= L"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n" L" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" L" <s:Body>\r\n" L" <s:Fault>\r\n" L" <faultcode>s:Client</faultcode>\r\n" L" <faultstring>UPnPError</faultstring>\r\n" L" <detail>\r\n" L" <UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">\r\n" L" <errorCode>%d</errorCode>\r\n" L" <errorDescription>%s</errorDescription>\r\n" L" </UPnPError>\r\n" L" </detail>\r\n" L" </s:Fault>\r\n" L" </s:Body>\r\n" L" </s:Envelope>\r\n"; static bool _UpnpSetErrorResponse( UPNPSERVICECONTROL *pUPNPAction, DWORD dwErrorCode, PCWSTR pszErrorDescription, // error code and description PWSTR* ppszRawResp) { int cch; ce::wstring strErrorDescription; EncodeForXML(pszErrorDescription, &strErrorDescription); cch = strErrorDescription.length() + 10 + celems(c_szSOAPFault); *ppszRawResp = new WCHAR [cch]; if (!*ppszRawResp) return false; cch -= wsprintfW(*ppszRawResp, c_szSOAPFault, dwErrorCode, static_cast<LPCWSTR>(strErrorDescription)); DBGCHK(L"UPNPAPI",cch > 0); return true; } BOOL WINAPI UpnpSetErrorResponse( UPNPSERVICECONTROL *pUPNPAction, DWORD dwErrorCode, PCWSTR pszErrorDescription // error code and description ) { BOOL fRet = FALSE; PWSTR pszRawResp = NULL; __try { fRet = _UpnpSetErrorResponse(pUPNPAction, dwErrorCode, pszErrorDescription, &pszRawResp); } __except(EXCEPTION_EXECUTE_HANDLER) { SetLastError(ERROR_INVALID_PARAMETER); fRet = FALSE; } if (fRet) fRet = UpnpSetRawControlResponse(pUPNPAction, HTTP_STATUS_SERVER_ERROR, pszRawResp); if (pszRawResp) delete[] pszRawResp; return fRet; } #ifdef DEBUG DBGPARAM dpCurSettings = { TEXT("UPNPCAPI"), { TEXT("Misc"), TEXT("Init"), TEXT("Announce"), TEXT("Events"), TEXT("Socket"),TEXT("Search"), TEXT("Parser"),TEXT("Timer"), TEXT("Cache"),TEXT("Control"),TEXT("Cache"),TEXT(""), TEXT(""),TEXT(""),TEXT("Trace"),TEXT("Error") }, 0x0000806f }; #endif //extern CRITICAL_SECTION g_csSSDPAPI; extern "C" BOOL WINAPI DllMain(IN PVOID DllHandle, IN ULONG Reason, IN PVOID Context OPTIONAL) { switch (Reason) { case DLL_PROCESS_ATTACH: DEBUGREGISTER((HMODULE)DllHandle); InitializeCriticalSection(&g_csUPNPAPI); SocketInit(); // We don't need to receive thread attach and detach // notifications, so disable them to help application // performance. DisableThreadLibraryCalls((HMODULE)DllHandle); svsutil_Initialize(); break; case DLL_PROCESS_DETACH: SocketFinish(); ClientStop(); svsutil_DeInitialize(); DeleteCriticalSection(&g_csUPNPAPI); break; } return TRUE; }
adfd7a6a14b17d4470936ff80f2f6c6d7d59f1af
3884f4a95c1398d65e7a5ea41a40d586ed22e0f2
/tests/ocltst/log/oclTestLog.cpp
519833fd982e5d97c416c102b71dd4ea10c1cee9
[ "MIT" ]
permissive
mcdmaster/ROCm-OpenCL-Runtime
e06acfd8f978618653a9508a5c1a5df48798fa43
5deb874c013445b9e39e29607ff956af6d64f92c
refs/heads/main
2023-02-08T00:33:42.800012
2020-12-27T07:04:26
2020-12-27T07:04:26
324,706,912
0
0
MIT
2020-12-27T07:07:46
2020-12-27T07:07:45
null
UTF-8
C++
false
false
3,148
cpp
/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "oclTestLog.h" #include <cassert> #include <cstring> #include "OCLLog.h" oclLog::oclLog() : m_stdout_fp(stdout), m_filename(""), m_writeToFileIsEnabled(false) {} oclLog::~oclLog() { disable_write_to_file(); } void oclLog::enable_write_to_file(std::string filename) { m_writeToFileIsEnabled = true; m_filename = filename; FILE* fp = fopen(m_filename.c_str(), "w"); if (fp == NULL) { oclTestLog(OCLTEST_LOG_ALWAYS, "ERROR: Cannot open file %s. Disabling logging to file.\n", filename.c_str()); m_writeToFileIsEnabled = false; } else { fclose(fp); } } void oclLog::disable_write_to_file() { m_writeToFileIsEnabled = false; } void oclLog::vprint(char const* fmt, va_list args) { // hack for fixing the lnx64bit segfault and // garbage printing in file. XXX 2048 a magic number char buffer[4096]; memset(buffer, 0, sizeof(buffer)); int rc = vsnprintf(buffer, sizeof(buffer), fmt, args); assert(rc >= 0 && rc != sizeof(buffer)); fputs(buffer, m_stdout_fp); if (m_writeToFileIsEnabled) { FILE* fp = fopen(m_filename.c_str(), "a"); if (fp == NULL) { oclTestLog(OCLTEST_LOG_ALWAYS, "ERROR: Cannot open file %s. Disabling logging to file.\n", m_filename.c_str()); m_writeToFileIsEnabled = false; } fputs(buffer, fp); fclose(fp); } } void oclLog::flush() { fflush(m_stdout_fp); } static oclLog& theLog() { static oclLog Log; return Log; } static oclLoggingLevel currentLevel = OCLTEST_LOG_ALWAYS; static float logcount = 0.0f; void oclTestLog(oclLoggingLevel logLevel, const char* fmt, ...) { logcount += 1.0f; if (logLevel <= currentLevel) { va_list args; va_start(args, fmt); theLog().vprint(fmt, args); theLog().flush(); va_end(args); } } void oclTestEnableLogToFile(const char* filename) { theLog().enable_write_to_file(filename); } void oclTestSetLogLevel(int level) { if (level >= 0) { currentLevel = static_cast<oclLoggingLevel>(level); } }
e9e8ad5e90ede19d07fbf8bfbaf849f410ec2fa0
c464b71b7936f4e0ddf9246992134a864dd02d64
/workWithClint/TestCase/processor1/1.1/U
8c8ad7f0cab31d7b9163507381dc71947fa9d5b8
[]
no_license
simuBT/foamyLatte
c11e69cb2e890e32e43e506934ccc31b40c4dc20
8f5263edb1b2ae92656ffb38437cc032eb8e4a53
refs/heads/master
2021-01-18T05:28:49.236551
2013-10-11T04:38:23
2013-10-11T04:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,548
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM Extend Project: Open source CFD | | \\ / O peration | Version: 1.6-ext | | \\ / A nd | Web: www.extend-project.de | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "1.1"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 70 ( (0.230977 0.029319 0) (0.519873 0.0332098 0) (0.579292 0.0403418 0) (0.553305 0.0237814 0) (0.502069 0.0085463 0) (0.406123 -0.00239878 0) (0.194628 -0.00373003 0) (0.269571 -0.0795232 0) (0.308729 -0.163548 0) (0.322409 -0.216063 0) (0.314826 -0.224191 0) (0.300404 -0.199572 0) (0.286694 -0.16141 0) (0.275736 -0.122838 0) (0.268592 -0.0895595 0) (0.26285 -0.0594691 0) (0.511142 -0.0667148 0) (0.493097 -0.148946 0) (0.454929 -0.191822 0) (0.409008 -0.193405 0) (0.368148 -0.16974 0) (0.336527 -0.137504 0) (0.313341 -0.105897 0) (0.298035 -0.0787053 0) (0.285447 -0.053261 0) (0.573621 -0.0450473 0) (0.544129 -0.111801 0) (0.496544 -0.143818 0) (0.445153 -0.145118 0) (0.400229 -0.128822 0) (0.364614 -0.10615 0) (0.337333 -0.0832353 0) (0.318285 -0.0631021 0) (0.301485 -0.0436433 0) (0.555875 -0.0350377 0) (0.533385 -0.0795014 0) (0.494124 -0.100454 0) (0.449604 -0.101048 0) (0.408293 -0.0898973 0) (0.373661 -0.074441 0) (0.345857 -0.0588181 0) (0.32559 -0.0451323 0) (0.306842 -0.0319826 0) (0.505983 -0.026427 0) (0.488391 -0.0518243 0) (0.456502 -0.0628716 0) (0.419235 -0.0618245 0) (0.383427 -0.054075 0) (0.352483 -0.0442206 0) (0.327094 -0.0347522 0) (0.308117 -0.0267449 0) (0.290187 -0.0196649 0) (0.404383 -0.0182305 0) (0.386595 -0.0280681 0) (0.35876 -0.0305476 0) (0.327979 -0.0277218 0) (0.299349 -0.0226538 0) (0.275165 -0.0175369 0) (0.255713 -0.013328 0) (0.241085 -0.0101974 0) (0.227385 -0.00833405 0) (0.187184 -0.00684241 0) (0.172133 -0.00787391 0) (0.15403 -0.00707114 0) (0.136839 -0.00540512 0) (0.122604 -0.00374972 0) (0.111643 -0.00251432 0) (0.103413 -0.00176107 0) (0.0971947 -0.00141924 0) (0.0911278 -0.00164715 0) ) ; boundaryField { inlet { type fixedValue; value nonuniform 0(); } outlet { type zeroGradient; } fixedWalls { type fixedValue; value uniform (0 0 0); } frontAndBack { type empty; } procBoundary1to2 { type processor; value nonuniform List<vector> 7((0.378544 0.155145 0) (0.546982 0.139291 0) (0.558935 0.121562 0) (0.522469 0.0793744 0) (0.475495 0.0419434 0) (0.390555 0.0138164 0) (0.191856 0.000415838 0)); } procBoundary1to0 { type processor; value nonuniform List<vector> 9((0.0551523 -0.00785684 0) (0.101212 -0.110629 0) (0.1587 -0.189204 0) (0.190755 -0.214193 0) (0.209318 -0.198235 0) (0.221192 -0.163193 0) (0.228388 -0.124986 0) (0.232979 -0.0907942 0) (0.235995 -0.0600538 0)); } } // ************************************************************************* //
[ "clint@clint-Parallels-Virtual-Platform.(none)" ]
clint@clint-Parallels-Virtual-Platform.(none)
0962c90609a2041754ed0bc8073e06e11da3991f
cce5e3f708b383ec64ba2f6b5367fd928a061e28
/LogReg.cpp
abae7c48e319cf1fccc7b8669d8249ea557e9912
[]
no_license
15831944/CPP_Machine_Learning
a5752a2987f9deb5678445fa574a9b56662833c5
d6c6cbb0ae38455d3b3198d909359e927284a5a6
refs/heads/master
2023-03-20T19:09:37.402013
2019-11-06T05:08:23
2019-11-06T05:08:23
null
0
0
null
null
null
null
GB18030
C++
false
false
3,902
cpp
#include "MatrixOpe.h" /** 梯度下降算法,主要是确定负梯度方向,步长,采用迭代的思想迭代n至收敛, 当目标函数是凸规划问题,那么局部最小值就是全局最小值 **/ int gradAscent_Log(Matrix x,Matrix y) { if(y.col!=1) { cout<<"logReg is two class"<<endl; return -1; } Matrix weights(x.col,y.col,0.1,"T"); Matrix xT = x.transposeMatrix(); float alpha=0.01;///迭代步长 float error=0;///记录错误率 int iter=0; int i,j; Matrix z(y.row,y.col,0,"T");//最好确定矩阵的大小 Matrix grad(x.col,y.col,0,"T"); for(iter=0; iter<5000; iter++) { z = x * weights; for(i=0; i<z.row; i++) { z.data[i][0]=sigmoid(z.data[i][0]); } z = y - z; error=0; for(i=0; i<x.row; i++)///统计错误率 error+=z.data[i][0]; //cout<<"error="<<error<<endl; //if(error<x.row/100 && error>x.row/100)///设置错误率小于一定值时退出迭代 // break; grad = xT * z;///计算负梯度方向 //grad = (1.0/x.row) * grad; for(i=0; i<grad.row; i++) grad.data[i][0]*= alpha;///负梯度方向与步长的乘积确定迭代值 weights = weights + grad;///往负梯度方向走一个步长 } /** 验证算法的正确性 **/ int er1=0,er2=0; Matrix train=x * weights; cout<<"test"<<endl; for(i=0; i<y.row; i++) { if(train.data[i][0]>0) { cout<<1-y.data[i][0]<<endl; er1+=(1-y.data[i][0]); } else { cout<<0-y.data[i][0]<<endl; er2-=(0-y.data[i][0]); } } //cout<<"er1="<<er1<<endl; //cout<<"er2="<<er2<<endl; } /** 随机梯度下降与梯度下降法不同的是在负梯度方向的确定,梯度下降是根据所有的样本来确定负梯度方向, 而随机梯度下降每次只看一个样本点来确定负梯度方向,虽然不完全可信,但随着迭代次数增加,同样收敛 **/ int stoGradAscent_Log(Matrix x,Matrix y)//随机梯度下降每一次选择m个样本进行求梯度下降方向,该代码中只选择一个样本进行求解梯度下降方向与数值 { Matrix xOneRow(1,x.col,0,"T"); Matrix xOneRowT(x.col,1,0,"T"); Matrix weights(x.col,y.col,0.1,"T"); Matrix z(1,y.col,0,"T");//最好确定矩阵的大小 Matrix grad(x.col,y.col,0,"T"); double alpha=0.001;///步长 double error; int i,j,c; for(c=0; c<1000; c++) { for(i=0; i<x.row; i++) { xOneRow=x.getOneRow(i);///随机选择一个样本点,这里没有作随机选择,而是按序选择 z = xOneRow * weights; z.data[0][0]=sigmoid(z.data[0][0]); z.data[0][0]=y.data[i][0]-z.data[0][0]; xOneRowT = xOneRow.transposeMatrix(); grad = xOneRowT * z;///根据一样样本的预测误差来确定负梯度方向 for(j=0; j<grad.row; j++) grad.data[j][0]*=alpha; weights = weights + grad; ///迭代 } } //验证算法的正确性 cout<<"test"<<endl; Matrix test = x * weights; for(i=0; i<y.row; i++) { if(test.data[i][0]>0) { cout<<1-y.data[i][0]<<endl; } else { cout<<0-y.data[i][0]<<endl; } } } int LogReg() { const char *file="data\\LogReg.txt"; const string model="gradAscent"; const double alpha=0.01; Matrix x; cout<<"loadData"<<endl; cout<<"----------------------"<<endl; x.LoadData(file); Matrix y; y=x.getOneCol(x.col-1); x.deleteOneCol(x.col-1); if(model=="gradAscent") gradAscent_Log(x,y); if(model=="stoGradAscent") stoGradAscent_Log(x,y); return 0; }
7eeef307b65116777a3ff74da3d2ca630f1b7046
530208803dd07020362230c413cb77be548db263
/src/rpcrawtransaction.cpp
0959377d1e54572564a57ac441aad36caa2d13f5
[ "MIT" ]
permissive
cryptoghass/bitcoinpositive
d93dbb2ad85f9e02e2efa0f34301de0ab6af7ef4
3a1f0e29e49efa821f330996d127be2d3883ab6d
refs/heads/master
2020-04-04T12:34:00.610291
2018-01-12T11:14:32
2018-01-12T11:14:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,984
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; // // Utilities: convert hex-encoded Values // (throws error if not hex). // uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BitcoinPositive address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; assert(pwalletMain != NULL); pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64 nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<const CScriptID&>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(const Value& input, inputs) { const Object& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(txid, nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BitcoinPositive address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); vector<unsigned char> txData(ParseHexV(params[0], "argument")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.GetCoins(prevHash, coins); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); CCoins coins; if (view.GetCoins(txid, coins)) { if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } // what todo if txid is known, but the actual output isn't? } if ((unsigned int)nOut >= coins.vout.size()) coins.vout.resize(nOut+1); coins.vout[nOut].scriptPubKey = scriptPubKey; coins.vout[nOut].nValue = 0; // we don't know the actual output value view.SetCoins(txid, coins); // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type)); Value v = find_value(prevOut, "redeemScript"); if (!(v == Value::null)) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; CCoins coins; if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n)) { fComplete = false; continue; } const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "sendrawtransaction <hex string> [allowhighfees=false]\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); // parse hex string from parameter vector<unsigned char> txData(ParseHexV(params[0], "parameter")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; bool fOverrideFees = false; if (params.size() > 1) fOverrideFees = params[1].get_bool(); // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); bool fHave = false; CCoinsViewCache &view = *pcoinsTip; CCoins existingCoins; { fHave = view.GetCoins(hashTx, existingCoins); if (!fHave) { // push to local node CValidationState state; if (!tx.AcceptToMemoryPool(state, true, false, NULL, !fOverrideFees)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state } } if (fHave) { if (existingCoins.nHeight < 1000000000) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain"); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { SyncWithWallets(hashTx, tx, NULL, true); } RelayTransaction(tx, hashTx); return hashTx.GetHex(); } Value getnormalizedtxid(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getnormalizedtxid <hex string>\n" "Return the normalized transaction ID."); // parse hex string from parameter vector<unsigned char> txData(ParseHexV(params[0], "parameter")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashNormalized = tx.GetNormalizedHash(); return hashNormalized.GetHex(); }
13057dd1dd941d7691a0060306fd0ef213fcf9b0
b5106297fd9fe8e77cd6466ce6402fcf5d452c08
/useranalysis/online5_sync/src/myanalysis.cc
6aa8d1c0a8f052b71c97c307de351797e56b9a0a
[]
no_license
vihophong/brikenmacros-1
c8b1b7907987d93f0b79c8bb93f301c4e82bb82f
1162c1814668586bc3c0b94e2aaa6072c7717c22
refs/heads/main
2023-06-15T13:30:40.185037
2021-04-29T10:33:30
2021-04-29T10:33:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,828
cc
/* ************************ DO NOT REMOVE ****************************** */ #include <iostream> #include <pmonitor/pmonitor.h> #include "myanalysis.h" #include <time.h> #include <libDataStruct.h> #include <bitset> #include <stdint.h> #include <vector> #include <map> #include <TSystem.h> #include <TROOT.h> #include <TH1.h> #include <TH2.h> #include <TFile.h> #include <TTree.h> #include <TRandom.h> #include <TString.h> #include <TCanvas.h> #include <iostream> #include <fstream> #include <correlation.h> #include "TThread.h" //#define SLOW_ONLINE 100000 #define RATE_CAL_REFESH_SECONDS 10 #define MAX_N_BOARD 20 #define V1730_MAX_N_CH 16 #define V1740_N_MAX_CH 64 //! parameters for V1740 #define NSBL 8 #define N_MAX_WF_LENGTH 90 UShort_t trig_pos = N_MAX_WF_LENGTH*30/100;//unit of sample UShort_t sampling_interval = 16*8;//unit of ns TFile* file0 = 0; TTree* tree = 0; NIGIRI* data; int nevt = 0; int nevtb[MAX_N_BOARD]; void Init(){ for (Int_t i=0;i<MAX_N_BOARD;i++){ nevtb[i]=0; } } void ProcessEvent(NIGIRI* data_now){ //if (data_now->b<11){ if (data_now->b==4||data_now->b==5||data_now->b==-1){ cout<<data_now->b<<"\t"<<data_now->ts<<endl; nevtb[data_now->b]++; } } void DoUpdate(){ } void OpenFile(const char* filename){ file0 = new TFile(filename,"recreate"); tree = new TTree("tree","tree"); } void CloseMe(){ if (file0) { if (tree) tree->Write(); file0->Close(); } } //!************************************************** //! Data decoding //! ************************************************* //! parameters for decoding V1740 zerosuppression #define V1740_HDR 6 //! packet map typedef enum{ NONE = 0, LUPO = 1, V1740ZSP = 2, V1740RAW = 3, V1730DPPPHA = 4, }pmap_decode; //! full map //#define N_PACKETMAP 16 //const int packetmap[]={49,50,51,52,53,54,55,56,57,58,59,60,100,101,102,103}; //const pmap_decode packetdecode[]={LUPO,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1730DPPPHA,V1730DPPPHA,V1730DPPPHA,V1730DPPPHA}; #define N_PACKETMAP 16 const int packetmap[]={49,50,51,52,53,54,55,56,57,58,59,60,100,101,102,103}; const pmap_decode packetdecode[]={LUPO,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1740ZSP,V1730DPPPHA,V1730DPPPHA,V1730DPPPHA,V1730DPPPHA}; UShort_t ledthr[MAX_N_BOARD][V1740_N_MAX_CH]; NIGIRI* data_prev[MAX_N_BOARD]; int init_done = 0; struct refesh_thread_argument { unsigned int refreshinterval; }; static TThread *refesh_thread = 0; void rateupdate(void * ptr){ refesh_thread_argument* ta = (refesh_thread_argument *) ptr; unsigned int my_refreshinterval = ta->refreshinterval; time_t last_time = time(0); //force an update on start //cout<<"refesh thread initialized, current time since January 1, 1970"<<last_time<<endl; while (1) { time_t x = time(0); if ( x - last_time > my_refreshinterval) { last_time = x; DoUpdate(); } } } int pinit() { if (init_done) return 1; init_done = 1; #ifdef RATE_CAL_REFESH_SECONDS refesh_thread_argument* ta = new refesh_thread_argument; ta->refreshinterval = RATE_CAL_REFESH_SECONDS; refesh_thread = new TThread(rateupdate,ta); refesh_thread->Run(); #endif gROOT->ProcessLine(".L libDataStruct.so"); data=new NIGIRI; for (Int_t i=0;i<MAX_N_BOARD;i++){ data_prev[i]=new NIGIRI; for (Int_t j=0;j<V1740_N_MAX_CH;j++){ ledthr[i][j]=850; } } Init(); return 0; } void decodeV1740raw(Packet* p1740raw){ //!************************************************** //! v1740Raw data packet //! ************************************************* int* tmp; int* words; words=(int*) p1740raw->getIntArray(tmp); int nevt=p1740raw->getPadding(); int ipos=0; for (int evt=0;evt<nevt;evt++){ //NIGIRI* data=new NIGIRI; data->Clear(); data->DecodeHeaderRaw(words,ipos,p1740raw->getHitFormat()); ipos+=data->event_size; ProcessEvent(data); }//end of event loop } #define TSCORR 6 double thr_abs = 150; void decodeV1740zsp(Packet* p1740zsp){ //!************************************************** //! v1740 with zerosuppresion data packet //! ************************************************* int* temp; int* gg; gg=(int*) p1740zsp->getIntArray(temp); //! header //NIGIRI* data=new NIGIRI; int nEvents = p1740zsp->getPadding(); //cout<<"\n********** "<<nEvents<<" ***********\n"<<endl; int k=0; for (Int_t i=0;i<nEvents;i++){ data->Clear(); int headaddr = k; data->DecodeHeaderZsp(&gg[k],p1740zsp->getHitFormat()); ProcessEvent(data); // k+=V1740_HDR+V1740_N_MAX_CH; // //! get number of channels from channel mask // double min_finets = 99999; // int ich_min_finets = -1; // for (int i=0;i<V1740_N_MAX_CH;i++){ // int chgrp = i/8; // if (((data->channel_mask>>chgrp)&0x1)==0) continue; // //! header // NIGIRIHit* chdata=new NIGIRIHit; // chdata->ch = i;//for sorter // int nsample = gg[headaddr+V1740_HDR+i]; // if (nsample>NSBL&&nsample<N_MAX_WF_LENGTH){ // data->board_fail_flag = 1; // } // chdata->nsample = nsample; // UShort_t WaveLine[nsample]; // int ispl = 0; // for (int j=0;j<nsample/2+nsample%2;j++){ // if (ispl<nsample) { // WaveLine[ispl]=gg[k]&0xFFFF; // chdata->pulse.push_back(gg[k]&0xFFFF); // } // ispl++; // if (ispl<nsample) { // WaveLine[ispl]=(gg[k]>>16)&0xFFFF; // chdata->pulse.push_back((gg[k]>>16)&0xFFFF); // } // ispl++; // k++; // } // //!-------------------- // if (nsample>NSBL){ // chdata->processPulseV1740(data->ts,NSBL,ledthr[data->b][chdata->ch],trig_pos,sampling_interval); // } // if (chdata->finets<min_finets&&chdata->finets>=0){ // min_finets =chdata->finets; // ich_min_finets = i; // } // data->AddHit(chdata); // }//loop all channels // data->trig_ch = ich_min_finets; // if (data->board_fail_flag==1){ // data_prev[data->b]->MergePulse(data,data_prev[data->b]->ts,NSBL,ledthr[data->b],trig_pos,sampling_interval,N_MAX_WF_LENGTH); // } // //ProcessEvent(data); // //! process data // if (data_prev[data->b]->b>=0){ // if (data_prev[data->b]->board_fail_flag!=1) // ProcessEvent(data_prev[data->b]); // data_prev[data->b]->Clear(); // } // data->Copy(*data_prev[data->b]); // //data_prev[data->b] = (NIGIRI*) data->Clone(); } } void decodeV1730dpppha(Packet* p1730dpppha){ //!************************************************** //! v1730DPPPHA packet //! ************************************************* int* tmp; int* words; words=(int*) p1730dpppha->getIntArray(tmp); int totalsize = p1730dpppha->getPadding(); int pos=0; boardaggr_t boardaggr; while (pos<totalsize){ //! board aggr //! check if we have valid datum if ((words[pos]&0xF0000000)!=0xA0000000) cout<<"Error decoding V1730DPPPHA!"<<endl; boardaggr.size = (words[pos]&0xFFFFFFF); boardaggr.board_id = (words[pos+1]&0xF8000000)>>27; boardaggr.board_fail_flag = (bool)((words[pos+1]&0x4000000)>>26); boardaggr.pattern = (words[pos+1]&0x7FFF00)>>8; boardaggr.dual_ch_mask = (words[pos+1]&0xFF); boardaggr.counter = (words[pos+2]&0x7FFFFF); boardaggr.timetag = words[pos+3]; //boardaggr.print(); pos+=4; for (int i=0;i<V1730_MAX_N_CH/2;i++){ if (((boardaggr.dual_ch_mask>>i)&0x1)==0) continue; //! read channel aggr channelaggr_t channelaggr; channelaggr.groupid=i; channelaggr.formatinfo=(words[pos]&0x80000000)>>31; channelaggr.size=words[pos]&0x7FFFFFFF; channelaggr.dual_trace_flag=(words[pos+1]&0x80000000)>>31; channelaggr.energy_enable_flag=(words[pos+1]&0x40000000)>>30; channelaggr.trigger_time_stamp_enable_flag=(words[pos+1]&0x20000000)>>29; channelaggr.extra2_enable_flag=(words[pos+1]&0x10000000)>>28; channelaggr.waveformsample_enable_flag=(words[pos+1]&0x8000000)>>27; channelaggr.extra_option_enable_flag=(words[pos+1]&0x7000000)>>24; channelaggr.analogprobe1_selection=(words[pos+1]&0xC00000)>>22; channelaggr.analogprobe2_selection=(words[pos+1]&0x300000)>>20; channelaggr.digitalprobe_selection=(words[pos+1]&0xF0000)>>16; int nsampleto8=(words[pos+1]&0xFFFF); channelaggr.n_samples=nsampleto8*8; //channelaggr.print(); pos+=2; //! read dual channel data //! check if this has two channel data int nword_samples=channelaggr.n_samples/2+channelaggr.n_samples%2; int nevents=(channelaggr.size-2)/(nword_samples+3); for (int i=0;i<nevents;i++){ channel_t channeldata; // read header int odd_even_flag=(words[pos]&0x80000000)>>31; if (odd_even_flag==0) channeldata.ch=channelaggr.groupid*2;//even else channeldata.ch=channelaggr.groupid*2+1; channeldata.trigger_time_tag=(words[pos]&0x7FFFFFFF); channeldata.n_samples=channelaggr.n_samples; pos++; // read data samples for (int n=0;n<channeldata.n_samples/2+channeldata.n_samples%2;n++){ //! read channel samples int ap1= (words[pos]&0x3FFF); int ap2= (words[pos]&0x3FFF0000)>>16; if (channelaggr.dual_trace_flag==1){//dual trace channeldata.ap1_sample.push_back(ap1);//even sample of ap1 channeldata.ap2_sample.push_back(ap2);//even sample of ap2 }else{//single trace channeldata.ap1_sample.push_back(ap1);//even sample of ap1 channeldata.ap1_sample.push_back(ap2);//odd sample of ap1 //cout<<"single trace"<<endl; } channeldata.dp_sample.push_back((words[pos]&0x4000)>>14);//even sample channeldata.dp_sample.push_back((words[pos]&0x40000000)>>30);//odd sample channeldata.trg_sample.push_back((words[pos]&0x8000)>>15);//even sample channeldata.trg_sample.push_back((words[pos]&0x80000000)>>31);//odd sample pos++; } // read extras channeldata.extras2 = words[pos]; channeldata.extras = (words[pos+1]&0x1F0000)>>16; channeldata.pileup_rollover_flag = (words[pos+1]&0x8000)>>15; channeldata.energy = (words[pos+1]&0x7FFF); pos+=2; //channeldata.print(); //! process channel data //NIGIRI* data=new NIGIRI; data->Clear(); data->b = p1730dpppha->getHitFormat(); data->evt = boardaggr.counter; data->event_size = channelaggr.size; UInt_t tslsb = (UInt_t) (channeldata.trigger_time_tag&0x7FFFFFFF); UInt_t tsmsb = (UInt_t) ((channeldata.extras2>>16)&0xFFFF); Double_t tpz_baseline = ((Double_t)(channeldata.extras2&0xFFFF))/4.; data->ts = (((ULong64_t)tsmsb<<31)&0x7FFF80000000)|(ULong64_t)tslsb; data->ts = data->ts*V1730_DGTZ_CLK_RES; //cout<<channelaggr.extra2_enable_flag<<"\t"<<channelaggr.extra_option_enable_flag<<"\t"<<data->ts<<endl; NIGIRIHit* hit = new NIGIRIHit; hit->ch = channeldata.ch; hit->clong = channeldata.energy; hit->baseline = tpz_baseline; //! assign analog and digital probe hit->pulse_ap1 =channeldata.ap1_sample; hit->pulse_ap2 =channeldata.ap1_sample; hit->pulse_dp1 =channeldata.dp_sample;; hit->pulse_dp2 =channeldata.trg_sample; data->AddHit(hit); ProcessEvent(data); }//loop on channel data //pos+=channelaggr.size; }//loop through all dual channels data }//end loop on all words //std::cout<<"---"<<std::endl; } void decodelupo(Packet* pLUPO){ int* tmp; int* gg; gg=(int*) pLUPO->getIntArray(tmp); //NIGIRI* data=new NIGIRI; data->Clear(); data->b = pLUPO->getHitFormat(); UInt_t tslsb = (UInt_t)gg[3]; UInt_t tsmsb = (UInt_t)gg[2]; data->ts = (((ULong64_t)tsmsb<<32)&0xFFFF00000000)|(ULong64_t)tslsb;//resolution is 10 ns! data->ts = data->ts*LUPO_CLK_RES; data->pattern= gg[1];//daq counter data->evt = gg[0]; ProcessEvent(data); } int process_event (Event * e) { nevt++; // time_t tevt =e->getTime(); // cout<<"***************** Eventpacket number = "<<e->getEvtSequence()<<" / record date time"<<asctime(gmtime(&tevt))<<"***************\n"<<endl; Packet *pmap[N_PACKETMAP]; for (Int_t i=0;i<N_PACKETMAP;i++){ pmap[i]=e->getPacket(packetmap[i]); if (pmap[i]){ if (packetdecode[i]==LUPO){ decodelupo(pmap[i]); }else if (packetdecode[i]==V1740ZSP){ decodeV1740zsp(pmap[i]); }else if (packetdecode[i]==V1740RAW){ decodeV1740raw(pmap[i]); }else if (packetdecode[i]==V1730DPPPHA){ decodeV1730dpppha(pmap[i]); }else{ //cout<<"out of definition!"<<endl; } delete pmap[i]; #ifdef SLOW_ONLINE usleep(SLOW_ONLINE); #endif } } return 0; } int pclose(){ cout<<"Closing"<<endl; CloseMe(); return 0; } int phsave (const char *filename){ OpenFile(filename); return 0; } int main (int argc, char* argv[]) { if (argc!=3&&argc!=4){ cout<<"Usage. ./offline input output"<<endl; cout<<"Usage. ./offline input_list_file output anything"<<endl; return 0; } if (argc==3) pfileopen(argv[1]); else plistopen(argv[1]); phsave(argv[2]); prun(); return 0; }
0aa869b2e8623b7b9fd11b3ca11511394a3f66d7
5470644b5f0834b9646649da365c96101a2f9b2a
/Sources/Elastos/Frameworks/Droid/Base/Core/inc/webkit/CCookieManager.h
b4a898ca02bae9fc32f579d5a1c754a4e5a70a81
[]
no_license
dothithuy/ElastosRDK5_0
42372da3c749170581b5ee9b3884f4a27ae81608
2cf231e9f09f8b3b8bcacb11080b4a87d047833f
refs/heads/master
2021-05-13T15:02:22.363934
2015-05-25T01:54:38
2015-05-25T01:54:38
116,755,452
1
0
null
2018-01-09T02:33:06
2018-01-09T02:33:06
null
UTF-8
C++
false
false
1,225
h
#ifndef __CCOOKIEMANAGER_H__ #define __CCOOKIEMANAGER_H__ #include "_CCookieManager.h" #include "webkit/CookieManager.h" using Elastos::Droid::Net::IWebAddress; namespace Elastos { namespace Droid { namespace Webkit { CarClass(CCookieManager), public CookieManager { public: CARAPI SetAcceptCookie( /* [in] */ Boolean accept); CARAPI AcceptCookie( /* [out] */ Boolean* result); CARAPI SetCookie( /* [in] */ const String& url, /* [in] */ const String& value); CARAPI GetCookie( /* [in] */ const String& url, /* [out] */ String* cookie); CARAPI GetCookieEx( /* [in] */ const String& url, /* [in] */ Boolean privateBrowsing, /* [out] */ String* cookie); CARAPI GetCookieEx2( /* [in] */ IWebAddress* uri, /* [out] */ String* cookie); CARAPI RemoveSessionCookie(); CARAPI RemoveAllCookie(); CARAPI HasCookies( /* [out] */ Boolean* result); CARAPI HasCookiesEx( /* [in] */ Boolean privateBrowsing, /* [out] */ Boolean* result); CARAPI RemoveExpiredCookie(); }; } // namespace Webkit } // namespace Droid } // namespace Elastos #endif // __CCOOKIEMANAGER_H__
21fc0388467caf112af742f3eeae53e66e56911c
32f71433eabc363fca0ea76f342c318ad3d2d8b3
/hdu/12411.cpp
a6efe1bbabaf1fa6a62e47d6c24476e86c6274f5
[ "WTFPL" ]
permissive
qxzg/My-acm
b7c01b06d4dbe0b9a4119f0fe553a929c6fa3ef8
9797fa5b8dd26ccacb35b17676a53ecd8ebf3d81
refs/heads/master
2023-07-10T15:36:58.422674
2023-07-04T07:13:14
2023-07-04T07:13:14
132,225,475
0
0
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
////////////////////System Comment//////////////////// ////Welcome to Hangzhou Dianzi University Online Judge ////http://acm.hdu.edu.cn ////////////////////////////////////////////////////// ////Username: nicainicai ////Nickname: 你猜 ////Run ID: ////Submit time: 2016-02-28 18:42:27 ////Compiler: GUN C++ ////////////////////////////////////////////////////// ////Problem ID: 1241 ////Problem Title: ////Run result: Accept ////Run time:62MS ////Run memory:2040KB //////////////////System Comment End////////////////// #include <cstdlib> #include <iostream> using namespace std; char a[105][105] = {}; int k = 0; void oil(int i,int j) { if(a[i][j] == '*') return ; a[i][j] = '*'; oil(i+1,j); oil(i-1,j); oil(i,j+1); oil(i,j-1); oil(i+1,j+1); oil(i-1,j-1); oil(i+1,j-1); oil(i-1,j+1); } int main(int argc, char *argv[]) { int n, m, i, j; while(cin>>n>>m) { k=0; if(n == 0 && m == 0) break; for(i=0;i<=n+1;i++) { for(j=0;j<=m+1;j++) { a[i][j] = '*'; } } for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { cin>>a[i][j]; } } for(i=1;i<=n;i++) for(j=1;j<=m;j++) if(a[i][j] == '@') { k++; oil(i,j); } cout<<k<<endl; } system("PAUSE"); return EXIT_SUCCESS; }
99c70f998479ca640799ec4eafde3120a5b82cc3
7939ba0be25a0819f1ab9bbd2510f4c865d3cc31
/src/inventoryController.cpp
27da9ec01ebbc4db22ce71fb1d642d72cf90f4af
[]
no_license
CaptainGobelin/BGS-dev
05697f34b4685a5b3c798d12c3ef86fc75cd2537
5dd7a0a17602943204035945effff3775df97e92
refs/heads/master
2021-01-01T05:47:48.736326
2014-09-23T12:52:10
2014-09-23T12:52:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include "headers/inventoryController.h" InventoryController::InventoryController() {} int InventoryController::launch(Character &character) { //Juste display the inventory until you press I, Escape or Close inventoryScreen.display(character); GameInput input = this->inventoryScreen.recupInput(); while (input.getValue() != I_INPUT) { if (input.getValue() == ESCAPE_INPUT) return I_INPUT; if (input.getValue() == CLOSE_INPUT) return input.getValue(); input = this->inventoryScreen.recupInput(); } return input.getValue(); }
9bb6fa1699511a3f6a1fbd69ed41ddb9e22c6dbc
013506d4dca645b54173ef269c2fa023f3ea1066
/P5/Scene.h
f6aca48c214399f2def30fc752dbbcae06a1a48e
[]
no_license
hjx201/cs3113-projectos
2d78e50978b88feb68bc0038cb2ad674069c00f6
cfbf9a3a3fe8f6939fd2754f673cfb1df54fbf00
refs/heads/master
2023-06-18T07:50:38.588123
2021-07-20T06:48:58
2021-07-20T06:48:58
267,763,850
0
1
null
null
null
null
UTF-8
C++
false
false
691
h
#pragma once #define GL_SILENCE_DEPRECATION #ifdef _WINDOWS #include <GL/glew.h> #endif #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_opengl.h> #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "ShaderProgram.h" #include "Util.h" #include "Entity.h" #include "Map.h" struct GameState { Map* map; Entity* player; Entity* enemies; int nextScene; }; class Scene { public: bool isWon = false; GameState state; virtual void Initialize() = 0; virtual void ProcessInput(SDL_Event event) = 0; virtual glm::mat4 Update(float deltaTime, glm::mat4 viewMatrix) = 0; virtual void Render(ShaderProgram* program) = 0; };
fa553ced77c3012a434c2b75161539c964bfce36
6092f9f051f28837ef1631fca45c50b95b1beaf8
/FirmwareManager/src/FlashTask.h
207573c64560a20925ea255b7251f31710f4879e
[ "MIT" ]
permissive
Pandoriaantje/DreamcastHDMI
f558e7b6338cbe2d6d7579ed56da99844e0be201
2ff00679cdb4bc8eb54dda1cfc626bd195fee567
refs/heads/master
2020-03-28T17:56:19.172777
2018-09-02T20:31:39
2018-09-02T20:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,376
h
#ifndef FLASH_TASK_H #define FLASH_TASK_H #include <global.h> #include <Task.h> #include <fastlz.h> extern MD5Builder md5; extern File flashFile; extern SPIFlash flash; extern int totalLength; extern int readLength; extern int last_error; void reverseBitOrder(uint8_t *buffer); void _writeFile(const char *filename, const char *towrite, unsigned int len); void _readFile(const char *filename, char *target, unsigned int len); extern TaskManager taskManager; class FlashTask : public Task { public: FlashTask(uint8_t v) : Task(1), dummy(v), progressCallback(NULL) { }; void SetProgressCallback(ProgressCallback callback) { progressCallback = callback; } void ClearProgressCallback() { progressCallback = NULL; } private: uint8_t dummy; ProgressCallback progressCallback; uint8_t *buffer = NULL; uint8_t *result = NULL; uint8_t *result_start = NULL; uint8_t header[16]; size_t bytes_in_result = 0; size_t block_size = 1536; int chunk_size = 0; unsigned int page; int prevPercentComplete; virtual bool OnStart() { page = 0; totalLength = -1; readLength = 0; prevPercentComplete = -1; last_error = NO_ERROR; // local chunk_size = 0; bytes_in_result = 0; md5.begin(); flashFile = SPIFFS.open(FIRMWARE_FILE, "r"); if (flashFile) { flashFile.readBytes((char *) header, 16); // check "magic" if (header[0] != 'D' || header[1] != 'C' || header[2] != 0x07 || header[3] != 0x04) { last_error = ERROR_WRONG_MAGIC; // TODO: report header bytes via DEBUG InvokeCallback(false); return false; } // check version if (header[4] != 0x01 || header[5] != 0x00) { last_error = ERROR_WRONG_VERSION; InvokeCallback(false); return false; } // read block size block_size = header[6] + (header[7] << 8); // read file size and convert it to flash pages by dividing by 256 totalLength = (header[8] + (header[9] << 8) + (header[10] << 16) + (header[11] << 24)) / 256; md5.add(header, 16); buffer = (uint8_t *) malloc(block_size); result = (uint8_t *) malloc(block_size); result_start = result; // initialze complete buffer with flash "default" initBuffer(result, block_size); // erase chip flash.enable(); flash.chip_erase_async(); return true; } else { last_error = ERROR_FILE; InvokeCallback(false); return false; } } virtual void OnUpdate(uint32_t deltaTime) { if (!flash.is_busy_async()) { if (page >= PAGES || doFlash() == -1) { taskManager.StopTask(this); } } readLength = page; int percentComplete = (totalLength <= 0 ? 0 : (int)(readLength * 100 / totalLength)); if (prevPercentComplete != percentComplete) { prevPercentComplete = percentComplete; InvokeCallback(false); } } void InvokeCallback(bool done) { if (progressCallback != NULL) { progressCallback(readLength, totalLength, done, last_error); } } void initBuffer(uint8_t *buffer, int len) { for (int i = 0 ; i < len ; i++) { // flash default (unwritten) is 0xff buffer[i] = 0xff; } } int doFlash() { int bytes_write = 0; if (chunk_size > 0) { // step 3: decompress bytes_in_result = fastlz_decompress(buffer, chunk_size, result, block_size); chunk_size = 0; return 0; /* no bytes written yet */ } if (bytes_in_result == 0) { // reset the result buffer pointer result = result_start; // step 1: read chunk header if (flashFile.readBytes((char *) buffer, 2) == 0) { // no more chunks return -1; } md5.add(buffer, 2); chunk_size = buffer[0] + (buffer[1] << 8); // step 2: read chunk length from file flashFile.readBytes((char *) buffer, chunk_size); md5.add(buffer, chunk_size); return 0; /* no bytes written yet */ } // step 4: write data to flash, in 256 byte long pages bytes_write = bytes_in_result > 256 ? 256 : bytes_in_result; /* even it's called async, it actually writes 256 bytes over SPI bus, it's just not calling the blocking "busy wait" */ flash.page_write_async(page, result); /* cleanup last 256 byte area afterwards, as spi flash memory is always written in chunks of 256 byte */ initBuffer(result, 256); bytes_in_result -= bytes_write; result += bytes_write; /* advance the char* by written bytes */ page++; return bytes_write; /* 256 bytes written */ } virtual void OnStop() { flash.disable(); flashFile.close(); md5.calculate(); String md5sum = md5.toString(); _writeFile("/etc/last_flash_md5", md5sum.c_str(), md5sum.length()); if (buffer != NULL) free(buffer); // make sure pointer is reset to original start result = result_start; if (result != NULL) free(result); buffer = NULL; result = NULL; result_start = NULL; InvokeCallback(true); } }; #endif
eb6ef4b6beb868077c35436bc064caf9617af2f8
12d28b5b3fa8b856f8604ca1307746d678affa69
/策略模式/strategy.h
56bcd5c564d1d4a5ede2fe06b4f4f80776ec91bf
[]
no_license
wangzhengyang/DesignPattern
d92c9c8f7aa0cae29f9ab0552af248f75550bdfd
cab3796603d942c22daff4e2fe9e11ab35c00110
refs/heads/master
2022-08-18T14:22:50.361881
2020-05-17T15:16:49
2020-05-17T15:16:49
255,211,328
0
0
null
null
null
null
UTF-8
C++
false
false
161
h
#ifndef _STRATEGY_H #define _STRATEGY_H class Strategy{ private: //... public: Strategy(){} virtual ~Strategy(){} virtual void Algorithm() = 0; }; #endif
a17b5b925e73f424ab56804ce8a95c648e53aa2a
0193ae6eb6578df5fb302cbbb18da3863affbb3c
/src/Native/libmultihash/exports.cpp
3afceaca5b7ea4ac53a18b79207268c995e6a1de
[ "MIT" ]
permissive
wiico/miningcore
573ac9d71f26131e3cf426fddb1f9b35d2e369ff
607c5ade16a29c7bf4991b2acc87a2dccf21b406
refs/heads/master
2020-04-03T06:28:04.905605
2018-09-17T20:59:53
2018-09-17T20:59:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,098
cpp
/* Copyright 2017 Coin Foundry (coinfoundry.org) Authors: Oliver Weichhold ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "bcrypt.h" #include "keccak.h" #include "quark.h" #include "scryptjane.h" #include "scryptn.h" #include "neoscrypt.h" #include "skein.h" #include "x11.h" #include "groestl.h" #include "blake.h" #include "blake2s.h" #include "fugue.h" #include "qubit.h" #include "s3.h" #include "hefty1.h" #include "shavite3.h" #include "x13.h" #include "x14.h" #include "nist5.h" #include "x15.h" #include "x17.h" #include "fresh.h" #include "dcrypt.h" #include "jh.h" #include "c11.h" #include "Lyra2RE.h" #include "Lyra2.h" #include "x16r.h" #include "x16s.h" #include "equi/equihashverify.h" #include "libethash/sha3.h" #include "libethash/internal.h" #include "libethash/ethash.h" extern "C" bool ethash_get_default_dirname(char* strbuf, size_t buffsize); #ifdef _WIN32 #define MODULE_API __declspec(dllexport) #else #define MODULE_API #endif extern "C" MODULE_API void scrypt_export(const char* input, char* output, uint32_t N, uint32_t R, uint32_t input_len) { scrypt_N_R_1_256(input, output, N, R, input_len); } extern "C" MODULE_API void quark_export(const char* input, char* output, uint32_t input_len) { quark_hash(input, output, input_len); } extern "C" MODULE_API void x11_export(const char* input, char* output, uint32_t input_len) { x11_hash(input, output, input_len); } extern "C" MODULE_API void x17_export(const char* input, char* output, uint32_t input_len) { x17_hash(input, output, input_len); } extern "C" MODULE_API void x15_export(const char* input, char* output, uint32_t input_len) { x15_hash(input, output, input_len); } extern "C" MODULE_API void neoscrypt_export(const unsigned char* input, unsigned char* output, uint32_t profile) { neoscrypt(input, output, profile); } extern "C" MODULE_API void scryptn_export(const char* input, char* output, uint32_t nFactor, uint32_t input_len) { unsigned int N = 1 << nFactor; scrypt_N_R_1_256(input, output, N, 1, input_len); //hardcode for now to R=1 for now } extern "C" MODULE_API void kezzak_export(const char* input, char* output, uint32_t input_len) { keccak_hash(input, output, input_len); } extern "C" MODULE_API void bcrypt_export(const char* input, char* output, uint32_t input_len) { bcrypt_hash(input, output); } extern "C" MODULE_API void skein_export(const char* input, char* output, uint32_t input_len) { skein_hash(input, output, input_len); } extern "C" MODULE_API void groestl_export(const char* input, char* output, uint32_t input_len) { groestl_hash(input, output, input_len); } extern "C" MODULE_API void groestl_myriad_export(const char* input, char* output, uint32_t input_len) { groestlmyriad_hash(input, output, input_len); } extern "C" MODULE_API void blake_export(const char* input, char* output, uint32_t input_len) { blake_hash(input, output, input_len); } extern "C" MODULE_API void blake2s_export(const char* input, char* output, uint32_t input_len) { blake2s_hash(input, output, input_len); } extern "C" MODULE_API void dcrypt_export(const char* input, char* output, uint32_t input_len) { dcrypt_hash(input, output, input_len); } extern "C" MODULE_API void fugue_export(const char* input, char* output, uint32_t input_len) { fugue_hash(input, output, input_len); } extern "C" MODULE_API void qubit_export(const char* input, char* output, uint32_t input_len) { qubit_hash(input, output, input_len); } extern "C" MODULE_API void s3_export(const char* input, char* output, uint32_t input_len) { s3_hash(input, output, input_len); } extern "C" MODULE_API void hefty1_export(const char* input, char* output, uint32_t input_len) { hefty1_hash(input, output, input_len); } extern "C" MODULE_API void shavite3_export(const char* input, char* output, uint32_t input_len) { shavite3_hash(input, output, input_len); } extern "C" MODULE_API void nist5_export(const char* input, char* output, uint32_t input_len) { nist5_hash(input, output, input_len); } extern "C" MODULE_API void fresh_export(const char* input, char* output, uint32_t input_len) { fresh_hash(input, output, input_len); } extern "C" MODULE_API void jh_export(const char* input, char* output, uint32_t input_len) { jh_hash(input, output, input_len); } extern "C" MODULE_API void c11_export(const char* input, char* output) { c11_hash(input, output); } extern "C" MODULE_API void lyra2re_export(const char* input, char* output) { lyra2re_hash(input, output); } extern "C" MODULE_API void lyra2rev2_export(const char* input, char* output) { lyra2re2_hash(input, output); } extern "C" MODULE_API void x16r_export(const char* input, char* output, uint32_t input_len) { x16r_hash(input, output, input_len); } extern "C" MODULE_API void x16s_export(const char* input, char* output, uint32_t input_len) { x16s_hash(input, output, input_len); } extern "C" MODULE_API bool equihash_verify_export(const char* header, int header_length, const char* solution, int solution_length) { if (header_length != 140) { return false; } std::vector<unsigned char> vecSolution(solution, solution + solution_length); return verifyEH_200_9(header, vecSolution, NULL); } extern "C" MODULE_API bool equihash_verify_btg_export(const char* header, int header_length, const char* solution, int solution_length) { if (header_length != 140) { return false; } std::vector<unsigned char> vecSolution(solution, solution + solution_length); return verifyEH_144_5(header, vecSolution, "BgoldPoW"); } extern "C" MODULE_API void sha3_256_export(const char* input, char* output, uint32_t input_len) { SHA3_256((ethash_h256 const*) output, (uint8_t const*) input, input_len); } extern "C" MODULE_API void sha3_512_export(const char* input, char* output, uint32_t input_len) { SHA3_512((uint8_t*) output, (uint8_t const*)input, input_len); } extern "C" MODULE_API uint64_t ethash_get_datasize_export(uint64_t const block_number) { return ethash_get_datasize(block_number); } extern "C" MODULE_API uint64_t ethash_get_cachesize_export(uint64_t const block_number) { return ethash_get_cachesize(block_number); } extern "C" MODULE_API ethash_light_t ethash_light_new_export(uint64_t block_number) { return ethash_light_new(block_number); } extern "C" MODULE_API void ethash_light_delete_export(ethash_light_t light) { ethash_light_delete(light); } extern "C" MODULE_API void ethash_light_compute_export( ethash_light_t light, ethash_h256_t const *header_hash, uint64_t nonce, ethash_return_value_t *result) { *result = ethash_light_compute(light, *header_hash, nonce); } extern "C" MODULE_API ethash_full_t ethash_full_new_export(const char *dirname, ethash_light_t light, ethash_callback_t callback) { uint64_t full_size = ethash_get_datasize(light->block_number); ethash_h256_t seedhash = ethash_get_seedhash(light->block_number); return ethash_full_new_internal(dirname, seedhash, full_size, light, callback); } extern "C" MODULE_API void ethash_full_delete_export(ethash_full_t full) { ethash_full_delete(full); } extern "C" MODULE_API void ethash_full_compute_export( ethash_full_t full, ethash_h256_t const *header_hash, uint64_t nonce, ethash_return_value_t *result) { *result = ethash_full_compute(full, *header_hash, nonce); } extern "C" MODULE_API void const* ethash_full_dag_export(ethash_full_t full) { return ethash_full_dag(full); } extern "C" MODULE_API uint64_t ethash_full_dag_size_export(ethash_full_t full) { return ethash_full_dag_size(full); } extern "C" MODULE_API ethash_h256_t ethash_get_seedhash_export(uint64_t block_number) { return ethash_get_seedhash(block_number); } extern "C" MODULE_API bool ethash_get_default_dirname_export(char *buf, size_t buf_size) { return ethash_get_default_dirname(buf, buf_size); }
144a0a47a7a06505447ce9c42f2ae5284acd39dd
d4654d2c7fa785794e3a56ee354d216d80374420
/quickfix/C++/fix44/CollateralRequest.h
23e57f343f3e4cf2ac559dfe3ce7b2487fa35b9e
[ "MIT" ]
permissive
SoftFx/TTFixClient
de702cf25d10167aaaf023dc18921eaf8fc117b7
c7ce42f1c9fc6fbd1f3158bc5d126a5659d09296
refs/heads/master
2023-02-09T07:00:12.233839
2023-02-06T13:20:34
2023-02-06T13:20:34
34,795,054
10
10
null
2015-07-29T14:31:56
2015-04-29T13:23:00
C++
UTF-8
C++
false
false
12,782
h
#ifndef FIX44_COLLATERALREQUEST_H #define FIX44_COLLATERALREQUEST_H #include "Message.h" namespace FIX44 { class CollateralRequest : public Message { public: CollateralRequest() : Message(MsgType()) {} CollateralRequest(const FIX::Message& m) : Message(m) {} CollateralRequest(const Message& m) : Message(m) {} CollateralRequest(const CollateralRequest& m) : Message(m) {} static FIX::MsgType MsgType() { return FIX::MsgType("AX"); } CollateralRequest( const FIX::CollReqID& aCollReqID, const FIX::CollAsgnReason& aCollAsgnReason, const FIX::TransactTime& aTransactTime ) : Message(MsgType()) { set(aCollReqID); set(aCollAsgnReason); set(aTransactTime); } FIELD_SET(*this, FIX::CollReqID); FIELD_SET(*this, FIX::CollAsgnReason); FIELD_SET(*this, FIX::TransactTime); FIELD_SET(*this, FIX::ExpireTime); FIELD_SET(*this, FIX::NoPartyIDs); class NoPartyIDs: public FIX::Group { public: NoPartyIDs() : FIX::Group(453,448,FIX::message_order(448,447,452,802,0)) {} FIELD_SET(*this, FIX::PartyID); FIELD_SET(*this, FIX::PartyIDSource); FIELD_SET(*this, FIX::PartyRole); FIELD_SET(*this, FIX::NoPartySubIDs); class NoPartySubIDs: public FIX::Group { public: NoPartySubIDs() : FIX::Group(802,523,FIX::message_order(523,803,0)) {} FIELD_SET(*this, FIX::PartySubID); FIELD_SET(*this, FIX::PartySubIDType); }; }; FIELD_SET(*this, FIX::Account); FIELD_SET(*this, FIX::AccountType); FIELD_SET(*this, FIX::ClOrdID); FIELD_SET(*this, FIX::OrderID); FIELD_SET(*this, FIX::SecondaryOrderID); FIELD_SET(*this, FIX::SecondaryClOrdID); FIELD_SET(*this, FIX::Symbol); FIELD_SET(*this, FIX::SymbolSfx); FIELD_SET(*this, FIX::SecurityID); FIELD_SET(*this, FIX::SecurityIDSource); FIELD_SET(*this, FIX::Product); FIELD_SET(*this, FIX::CFICode); FIELD_SET(*this, FIX::SecurityType); FIELD_SET(*this, FIX::SecuritySubType); FIELD_SET(*this, FIX::MaturityMonthYear); FIELD_SET(*this, FIX::MaturityDate); FIELD_SET(*this, FIX::CouponPaymentDate); FIELD_SET(*this, FIX::IssueDate); FIELD_SET(*this, FIX::RepoCollateralSecurityType); FIELD_SET(*this, FIX::RepurchaseTerm); FIELD_SET(*this, FIX::RepurchaseRate); FIELD_SET(*this, FIX::Factor); FIELD_SET(*this, FIX::CreditRating); FIELD_SET(*this, FIX::InstrRegistry); FIELD_SET(*this, FIX::CountryOfIssue); FIELD_SET(*this, FIX::StateOrProvinceOfIssue); FIELD_SET(*this, FIX::LocaleOfIssue); FIELD_SET(*this, FIX::RedemptionDate); FIELD_SET(*this, FIX::StrikePrice); FIELD_SET(*this, FIX::StrikeCurrency); FIELD_SET(*this, FIX::OptAttribute); FIELD_SET(*this, FIX::ContractMultiplier); FIELD_SET(*this, FIX::CouponRate); FIELD_SET(*this, FIX::SecurityExchange); FIELD_SET(*this, FIX::Issuer); FIELD_SET(*this, FIX::EncodedIssuerLen); FIELD_SET(*this, FIX::EncodedIssuer); FIELD_SET(*this, FIX::SecurityDesc); FIELD_SET(*this, FIX::EncodedSecurityDescLen); FIELD_SET(*this, FIX::EncodedSecurityDesc); FIELD_SET(*this, FIX::Pool); FIELD_SET(*this, FIX::ContractSettlMonth); FIELD_SET(*this, FIX::CPProgram); FIELD_SET(*this, FIX::CPRegType); FIELD_SET(*this, FIX::DatedDate); FIELD_SET(*this, FIX::InterestAccrualDate); FIELD_SET(*this, FIX::NoSecurityAltID); class NoSecurityAltID: public FIX::Group { public: NoSecurityAltID() : FIX::Group(454,455,FIX::message_order(455,456,0)) {} FIELD_SET(*this, FIX::SecurityAltID); FIELD_SET(*this, FIX::SecurityAltIDSource); }; FIELD_SET(*this, FIX::NoEvents); class NoEvents: public FIX::Group { public: NoEvents() : FIX::Group(864,865,FIX::message_order(865,866,867,868,0)) {} FIELD_SET(*this, FIX::EventType); FIELD_SET(*this, FIX::EventDate); FIELD_SET(*this, FIX::EventPx); FIELD_SET(*this, FIX::EventText); }; FIELD_SET(*this, FIX::AgreementDesc); FIELD_SET(*this, FIX::AgreementID); FIELD_SET(*this, FIX::AgreementDate); FIELD_SET(*this, FIX::AgreementCurrency); FIELD_SET(*this, FIX::TerminationType); FIELD_SET(*this, FIX::StartDate); FIELD_SET(*this, FIX::EndDate); FIELD_SET(*this, FIX::DeliveryType); FIELD_SET(*this, FIX::MarginRatio); FIELD_SET(*this, FIX::SettlDate); FIELD_SET(*this, FIX::Quantity); FIELD_SET(*this, FIX::QtyType); FIELD_SET(*this, FIX::Currency); FIELD_SET(*this, FIX::MarginExcess); FIELD_SET(*this, FIX::TotalNetValue); FIELD_SET(*this, FIX::CashOutstanding); FIELD_SET(*this, FIX::NoTrdRegTimestamps); class NoTrdRegTimestamps: public FIX::Group { public: NoTrdRegTimestamps() : FIX::Group(768,769,FIX::message_order(769,770,771,0)) {} FIELD_SET(*this, FIX::TrdRegTimestamp); FIELD_SET(*this, FIX::TrdRegTimestampType); FIELD_SET(*this, FIX::TrdRegTimestampOrigin); }; FIELD_SET(*this, FIX::Side); FIELD_SET(*this, FIX::Price); FIELD_SET(*this, FIX::PriceType); FIELD_SET(*this, FIX::AccruedInterestAmt); FIELD_SET(*this, FIX::EndAccruedInterestAmt); FIELD_SET(*this, FIX::StartCash); FIELD_SET(*this, FIX::EndCash); FIELD_SET(*this, FIX::Spread); FIELD_SET(*this, FIX::BenchmarkCurveCurrency); FIELD_SET(*this, FIX::BenchmarkCurveName); FIELD_SET(*this, FIX::BenchmarkCurvePoint); FIELD_SET(*this, FIX::BenchmarkPrice); FIELD_SET(*this, FIX::BenchmarkPriceType); FIELD_SET(*this, FIX::BenchmarkSecurityID); FIELD_SET(*this, FIX::BenchmarkSecurityIDSource); FIELD_SET(*this, FIX::NoStipulations); class NoStipulations: public FIX::Group { public: NoStipulations() : FIX::Group(232,233,FIX::message_order(233,234,0)) {} FIELD_SET(*this, FIX::StipulationType); FIELD_SET(*this, FIX::StipulationValue); }; FIELD_SET(*this, FIX::TradingSessionID); FIELD_SET(*this, FIX::TradingSessionSubID); FIELD_SET(*this, FIX::SettlSessID); FIELD_SET(*this, FIX::SettlSessSubID); FIELD_SET(*this, FIX::ClearingBusinessDate); FIELD_SET(*this, FIX::Text); FIELD_SET(*this, FIX::EncodedTextLen); FIELD_SET(*this, FIX::EncodedText); FIELD_SET(*this, FIX::NoExecs); class NoExecs: public FIX::Group { public: NoExecs() : FIX::Group(124,17,FIX::message_order(17,0)) {} FIELD_SET(*this, FIX::ExecID); }; FIELD_SET(*this, FIX::NoTrades); class NoTrades: public FIX::Group { public: NoTrades() : FIX::Group(897,571,FIX::message_order(571,818,0)) {} FIELD_SET(*this, FIX::TradeReportID); FIELD_SET(*this, FIX::SecondaryTradeReportID); }; FIELD_SET(*this, FIX::NoLegs); class NoLegs: public FIX::Group { public: NoLegs() : FIX::Group(555,600,FIX::message_order(600,601,602,603,604,607,608,609,764,610,611,248,249,250,251,252,253,257,599,596,597,598,254,612,942,613,614,615,616,617,618,619,620,621,622,623,624,556,740,739,955,956,0)) {} FIELD_SET(*this, FIX::LegSymbol); FIELD_SET(*this, FIX::LegSymbolSfx); FIELD_SET(*this, FIX::LegSecurityID); FIELD_SET(*this, FIX::LegSecurityIDSource); FIELD_SET(*this, FIX::LegProduct); FIELD_SET(*this, FIX::LegCFICode); FIELD_SET(*this, FIX::LegSecurityType); FIELD_SET(*this, FIX::LegSecuritySubType); FIELD_SET(*this, FIX::LegMaturityMonthYear); FIELD_SET(*this, FIX::LegMaturityDate); FIELD_SET(*this, FIX::LegCouponPaymentDate); FIELD_SET(*this, FIX::LegIssueDate); FIELD_SET(*this, FIX::LegRepoCollateralSecurityType); FIELD_SET(*this, FIX::LegRepurchaseTerm); FIELD_SET(*this, FIX::LegRepurchaseRate); FIELD_SET(*this, FIX::LegFactor); FIELD_SET(*this, FIX::LegCreditRating); FIELD_SET(*this, FIX::LegInstrRegistry); FIELD_SET(*this, FIX::LegCountryOfIssue); FIELD_SET(*this, FIX::LegStateOrProvinceOfIssue); FIELD_SET(*this, FIX::LegLocaleOfIssue); FIELD_SET(*this, FIX::LegRedemptionDate); FIELD_SET(*this, FIX::LegStrikePrice); FIELD_SET(*this, FIX::LegStrikeCurrency); FIELD_SET(*this, FIX::LegOptAttribute); FIELD_SET(*this, FIX::LegContractMultiplier); FIELD_SET(*this, FIX::LegCouponRate); FIELD_SET(*this, FIX::LegSecurityExchange); FIELD_SET(*this, FIX::LegIssuer); FIELD_SET(*this, FIX::EncodedLegIssuerLen); FIELD_SET(*this, FIX::EncodedLegIssuer); FIELD_SET(*this, FIX::LegSecurityDesc); FIELD_SET(*this, FIX::EncodedLegSecurityDescLen); FIELD_SET(*this, FIX::EncodedLegSecurityDesc); FIELD_SET(*this, FIX::LegRatioQty); FIELD_SET(*this, FIX::LegSide); FIELD_SET(*this, FIX::LegCurrency); FIELD_SET(*this, FIX::LegPool); FIELD_SET(*this, FIX::LegDatedDate); FIELD_SET(*this, FIX::LegContractSettlMonth); FIELD_SET(*this, FIX::LegInterestAccrualDate); FIELD_SET(*this, FIX::NoLegSecurityAltID); class NoLegSecurityAltID: public FIX::Group { public: NoLegSecurityAltID() : FIX::Group(604,605,FIX::message_order(605,606,0)) {} FIELD_SET(*this, FIX::LegSecurityAltID); FIELD_SET(*this, FIX::LegSecurityAltIDSource); }; }; FIELD_SET(*this, FIX::NoUnderlyings); class NoUnderlyings: public FIX::Group { public: NoUnderlyings() : FIX::Group(711,311,FIX::message_order(311,312,309,305,457,462,463,310,763,313,542,241,242,243,244,245,246,256,595,592,593,594,247,316,941,317,436,435,308,306,362,363,307,364,365,877,878,318,879,810,882,883,884,885,886,944,0)) {} FIELD_SET(*this, FIX::UnderlyingSymbol); FIELD_SET(*this, FIX::UnderlyingSymbolSfx); FIELD_SET(*this, FIX::UnderlyingSecurityID); FIELD_SET(*this, FIX::UnderlyingSecurityIDSource); FIELD_SET(*this, FIX::UnderlyingProduct); FIELD_SET(*this, FIX::UnderlyingCFICode); FIELD_SET(*this, FIX::UnderlyingSecurityType); FIELD_SET(*this, FIX::UnderlyingSecuritySubType); FIELD_SET(*this, FIX::UnderlyingMaturityMonthYear); FIELD_SET(*this, FIX::UnderlyingMaturityDate); FIELD_SET(*this, FIX::UnderlyingCouponPaymentDate); FIELD_SET(*this, FIX::UnderlyingIssueDate); FIELD_SET(*this, FIX::UnderlyingRepoCollateralSecurityType); FIELD_SET(*this, FIX::UnderlyingRepurchaseTerm); FIELD_SET(*this, FIX::UnderlyingRepurchaseRate); FIELD_SET(*this, FIX::UnderlyingFactor); FIELD_SET(*this, FIX::UnderlyingCreditRating); FIELD_SET(*this, FIX::UnderlyingInstrRegistry); FIELD_SET(*this, FIX::UnderlyingCountryOfIssue); FIELD_SET(*this, FIX::UnderlyingStateOrProvinceOfIssue); FIELD_SET(*this, FIX::UnderlyingLocaleOfIssue); FIELD_SET(*this, FIX::UnderlyingRedemptionDate); FIELD_SET(*this, FIX::UnderlyingStrikePrice); FIELD_SET(*this, FIX::UnderlyingStrikeCurrency); FIELD_SET(*this, FIX::UnderlyingOptAttribute); FIELD_SET(*this, FIX::UnderlyingContractMultiplier); FIELD_SET(*this, FIX::UnderlyingCouponRate); FIELD_SET(*this, FIX::UnderlyingSecurityExchange); FIELD_SET(*this, FIX::UnderlyingIssuer); FIELD_SET(*this, FIX::EncodedUnderlyingIssuerLen); FIELD_SET(*this, FIX::EncodedUnderlyingIssuer); FIELD_SET(*this, FIX::UnderlyingSecurityDesc); FIELD_SET(*this, FIX::EncodedUnderlyingSecurityDescLen); FIELD_SET(*this, FIX::EncodedUnderlyingSecurityDesc); FIELD_SET(*this, FIX::UnderlyingCPProgram); FIELD_SET(*this, FIX::UnderlyingCPRegType); FIELD_SET(*this, FIX::UnderlyingCurrency); FIELD_SET(*this, FIX::UnderlyingQty); FIELD_SET(*this, FIX::UnderlyingPx); FIELD_SET(*this, FIX::UnderlyingDirtyPrice); FIELD_SET(*this, FIX::UnderlyingEndPrice); FIELD_SET(*this, FIX::UnderlyingStartValue); FIELD_SET(*this, FIX::UnderlyingCurrentValue); FIELD_SET(*this, FIX::UnderlyingEndValue); FIELD_SET(*this, FIX::NoUnderlyingSecurityAltID); class NoUnderlyingSecurityAltID: public FIX::Group { public: NoUnderlyingSecurityAltID() : FIX::Group(457,458,FIX::message_order(458,459,0)) {} FIELD_SET(*this, FIX::UnderlyingSecurityAltID); FIELD_SET(*this, FIX::UnderlyingSecurityAltIDSource); }; FIELD_SET(*this, FIX::CollAction); }; FIELD_SET(*this, FIX::NoMiscFees); class NoMiscFees: public FIX::Group { public: NoMiscFees() : FIX::Group(136,137,FIX::message_order(137,138,139,891,0)) {} FIELD_SET(*this, FIX::MiscFeeAmt); FIELD_SET(*this, FIX::MiscFeeCurr); FIELD_SET(*this, FIX::MiscFeeType); FIELD_SET(*this, FIX::MiscFeeBasis); }; }; } #endif