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
41411ede81a3f14d5f5efda3aad396093d6910f8
16337b0d88df96767281cbc0024ed4e5e0dc2309
/Tic-Tac-bigToe.cpp
ccd6f979a725f324386a94cc966771516cbbf2ac
[]
no_license
Xephoney/Tic-Tac-bigToe
8c3c5d93a5f49799d90034a428a61d509b672883
3ea53e4f72486c476eb673a8f1736b24f3f5442c
refs/heads/master
2022-12-24T15:47:03.404000
2020-09-27T19:22:51
2020-09-27T19:22:51
298,370,665
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,368
cpp
#include <iostream> #include <string> #include <vector> //This is included for the use of vectors #include <time.h> //This is for random number generation //Here we declare the functions that i will define further down. //these functions are tied to the gameplay loop void DisplayGrid(); void InputAndExec(); void PlayerSwitch(); int WinConditionCheck(); void CalculateComputerMove(char); //These are the main functions between games. void GamePvP(); void GamePvE(); void MainMenu(); //The reason i went with global variables was to limit the amount of calls, and passing variables to functions and getting... //the right return variables. Only the important variables are global. std::vector<char> grid { '1','2','3','4','5','6','7','8','9' }; char players[2] { 'X', 'O' }; int playerIndex = 1; int main() { srand(time(NULL)); //Greeting when first running the application std::cout << "Welcome to Tic-Tac-(Big)Toe \n"; MainMenu(); return 0; } void MainMenu() { int answer = NULL; std::cout << "What would you like to play? \n"; std::cout << " 1 : Player VS Player \n" << " 2 : Player VS CPU \n \n" << " 8 : Exit Game \n"; std::cout << "Select a gamemode : "; std::cin >> answer; //here we do the corresponding code execution based on what the user typed in. // I wanted to avoid using a while loop here, because of the thought that it would be a loop, in a loop, in a loop... for ever. // So instead i just kept to Functions executions. // I don't know for sure whether this is the best solution or not, but it works! :D //Here i get then input from the player and execute the right code that was selected from the player. switch (answer) { case 0: //I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever. system("CLS"); std::cin.clear(); std::cin.ignore(10000, '\n'); MainMenu(); break; case 1: system("CLS"); GamePvP(); break; case 2: system("CLS"); GamePvE(); break; case 8: std::cout << "Closing Game"; return; default: //I have to include cin.clear and cin.ignore before calling MainMenu() again, to stop it from looping forever. system("CLS"); std::cin.clear(); std::cin.ignore(10000, '\n'); MainMenu(); break; } } int moves = 0; void GamePvP() { playerIndex = 0; bool GameOver = false; moves = 0; //The reason why i fill out the grid here, is because everytime the game restarts... //I need to make sure its a new grid. so it clears the board from the last game. grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; do { //as the functions says it displays the grid. DisplayGrid(); //This is for getting input, aswell as InputAndExec(); //Here i run the Win Condition function and store the result of that test in my X variable. //Then we proceed to check weather that the winner was either X or O. int x = WinConditionCheck(); if (x == 0 || x == 1) { //The reason for Display Grid is just to update the display so you could see where the //Where the winning connections were! DisplayGrid(); std::cout << "\nPlayer " << players[x] << " wins! Congrats! \n"; GameOver = true; system("pause"); } //I keep a count of the total amount of moves. and if the total number of moves is 9, and wincheck returns false. then it has to be a tie. else if (moves == 9) { //Tie DisplayGrid(); std::cout << "\n [- TIE -] \n"; GameOver = true; system("pause"); } } while (!GameOver); //Clears screen and returns to Main Menu system("CLS"); MainMenu(); } void GamePvE() { playerIndex = 0; bool GameOver = false; moves = 0; grid = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; char answer = 'æ'; int computer = -1; int player = -1; std::cout << "Do you want to be X or O? \n "; std::cout << "X / O : "; std::cin >> answer; answer = toupper(answer); //This is just to make sure that the input is a Char value. //Initial game setup. The player selects their desigered and the cpu gets if (answer == players[0]) { computer = 1; player = 0; std::cout << "Okay, You = X CPU = O \n When you are ready "; } else if (answer == players[1]) { computer = 0; player = 1; std::cout << "Okay, CPU = X You = O \n When you are ready "; } else //This is just to remove the possibility of a rogue exec without the right variables. { std::cin.clear(); std::cin.ignore(10000, '\n'); GamePvE(); return; } system("pause"); //This do-while loop goes aslong as GameOver is false. do { DisplayGrid(); if (playerIndex == computer) { //this just ends up passing through what character the computer has. //So it can do the right placement in the grid. CalculateComputerMove(players[computer]); } else { InputAndExec(); } //This is the section of the gameloop that checks for wins or if the game is a tie. int x = WinConditionCheck(); if (x == computer) { //The reason for Display Grid is just to update the display so you could see where the //Where the winning connections were! DisplayGrid(); std::cout << "\n [- CPU WON -] "; GameOver = true; system("pause"); } else if (x == player) { DisplayGrid(); std::cout << "\n [- YOU WON -] "; GameOver = true; system("pause"); } else if (moves == 9) { DisplayGrid(); std::cout << "\n [- TIE -] \n"; GameOver = true; system("pause"); } } while (!GameOver); system("CLS"); MainMenu(); } //Game Loop functions void DisplayGrid() { system("CLS"); for (auto x = 0; x < grid.size(); x++) { std::cout << "| " << grid.at(x) << " "; if (x == 2 || x == 5 || x == 8) { std::cout << "|" << std::endl; } } } void InputAndExec() { //The reason for this being a long long int, is because i kept getting build errors because i was doing a arithmetic overflow warning //So i then "upgraded" to this to remove that error. long long int playerInput = 0; std::cout << "[" << players[playerIndex] << "] turn : "; //Gets input from console and store the answer in the playerInput variable std::cin >> playerInput; if (playerInput-1 <= 8 && playerInput-1 >= 0) { if (grid.at(playerInput-1) == 'X' || grid.at(playerInput-1) == 'O') { std::cout << "Invalid selection, you cannot select a place that has already been taken! \n"; InputAndExec(); return; } else { grid[playerInput-1] = players[playerIndex]; moves++; PlayerSwitch(); return; } } else // This else is to catch any input that isn't an integer. then repeat. { std::cin.clear(); std::cin.ignore(10000, '\n'); std::cout << "Invalid input! Choose a number from the grid above! \n"; } } int WinConditionCheck() { //Here im just creating a variable that checks for winner, and then returns the player index number... //which corresponds with a char in players[]. char winner = 'Ø'; char a, b, c; //Horizontal for (long int i = 1; i <= 7; i+=3) { // These variables are temp just for storing values so the if statement further down stays relativly clean and easy to debug. a = grid.at(i); b = grid.at(i-1); c = grid.at(i+1); //What these variables check store is what is in the grid at the spesific point. They only hold that info based on the current iteration. //This if statement then checks weather or not they are all the same, it doesn't matter if its X or O. Aslong as all of them are the same... //it then continues to the next check if (a == b && b == c) { //Here we grab the character value of the winning row, then we do a check as to who won. then return a int value. //This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1. winner = grid.at(i); if (winner == 'X') { return 0; } else { return 1; } } } //Vertical win check for (long int i = 0; i < 3; i++) { //Here i grab a the current iterator and add the required grid locations to make a check. //im just using a, b and c because it really doesn't require to be that spesific. These are temp variables that... //have a single purpose, which is to check weather or not they are the same. a = grid.at(i); b = grid.at(i + 3); c = grid.at(i + 6); //This if statement just checks that all the temp variables are the same, and by that we can determine that we have a winner. //Since the temp varibles are set to check the one beneath another, this then checks the colum for a win condition. if (a == b && b == c) { //Here we grab the character value of the winning row, then we do a check as to who won. then return a int value. //This int value that is returned, corresponds with the index of the players[], where X = 0, and O = 1. winner = grid.at(i); if (winner == 'X') { return 0; } else { return 1; } } } //For the diagonal checks, all i have to do, since there are only two options. i will hardcode those checks. //The reason for that is because of time, i could most likly come up with a clever solution, however it would end up taking way longer.. //Than simply writing it out. This is only Tic-Tac-Toe. #pragma region DiagonalChecks //Diagonal Check 1 a = grid.at(2); b = grid.at(4); c = grid.at(6); std::cout << a << b << c; if (a == b && b == c) { //Same as before, we grab the variable at a this time, and return the correct index in players[]. winner = b; if (winner == 'X') { return 0; } else { return 1; } } //Diagonal Check 2 a = grid.at(0); b = grid.at(4); c = grid.at(8); if (a == b && b == c) { //Same as before, we grab the variable at a this time, and return the correct index in players[]. winner = b; if (winner == 'X') { return 0; } else { return 1; } } #pragma endregion return 2; } void PlayerSwitch() { //This function just inverts the player index. I think there is a better and prettier way to do this, however this will do for now. //Its not pretty, but i added an easter-egg incase something went horribly wrong! switch (playerIndex) { case 0 : playerIndex = 1; break; case 1 : playerIndex = 0; break; default: std::cout << "WTF just happened, im just gonna try something\n"; playerIndex = 0; break; } } void CalculateComputerMove(char CPUchar) { //Just initializing a seed(time) for my random number generator. int selected = (rand() % 8 + 1)-1; if (grid.at(selected) == 'X' || grid.at(selected) == 'O') { CalculateComputerMove(CPUchar); return; } else { grid.at(selected) = CPUchar; moves++; PlayerSwitch(); return; } }
[ "hans_olahoftun@hotmail.com" ]
hans_olahoftun@hotmail.com
7ade5627a226f91a37d1e00ba158ba1f1eace614
6a56f4e8bfa2da98cfc51a883b7cae01736c3046
/ovaldi-code-r1804-trunk/src/probes/unix/PasswordProbe.h
03062e89f9d72a9942bd7a1aac071a565a9a4ae6
[]
no_license
tmcclain-taptech/Ovaldi-Win10
6b11e495c8d37fd73aae6c0281287cadbc491e59
7214d742c66f3df808d70e880ba9dad69cea403d
refs/heads/master
2021-07-07T09:36:30.776000
2019-03-28T19:11:29
2019-03-28T19:11:29
164,451,763
2
1
null
null
null
null
UTF-8
C++
false
false
2,857
h
// // //****************************************************************************************// // Copyright (c) 2002-2014, The MITRE Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // * Neither the name of The MITRE Corporation nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //****************************************************************************************// #ifndef PASSWORDPROBE_H #define PASSWORDPROBE_H #include "AbsProbe.h" #include "Item.h" #include "Object.h" #include <pwd.h> #include <string> /** This class is responsible for collecting information about unix password_objects. */ class PasswordProbe : public AbsProbe { public: virtual ~PasswordProbe(); /** Get all the files on the system that match the pattern and collect their attributes. */ virtual ItemVector* CollectItems(Object* object); /** Return a new Item created for storing file information */ virtual Item* CreateItem(); /** Ensure that the PasswordProbe is a singleton. */ static AbsProbe* Instance(); private: PasswordProbe(); /** Creates an item from a passwd struct */ Item *CreateItemFromPasswd(struct passwd const *pwInfo); /** Finds a single item by name. */ Item *GetSingleItem(const std::string& username); /** Finds multiple items according to the given object entity. */ ItemVector *GetMultipleItems(Object *passwordObject); /** Singleton instance */ static PasswordProbe* instance; }; #endif
[ "tmcclain@tapestrytech.com" ]
tmcclain@tapestrytech.com
8bfe178d65efb2f52470e306b87737b39f700ce6
f80d267d410b784458e61e4c4603605de368de9b
/TESTONE/exampleios/usr/local/include/fit_developer_field_description.hpp
a5af5c51d16055664f81433af69b821385dd83c5
[]
no_license
bleeckerj/Xcode-FIT-TEST
84bdb9e1969a93a6380a9c64dce0a0e715d81fe8
37490e3b1e913dc3dfabdae39b48bddea24f1023
refs/heads/master
2021-01-20T14:39:53.249000
2017-02-22T05:59:28
2017-02-22T05:59:28
82,766,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
hpp
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.24Release // Tag = production/akw/20.24.01-0-g5fa480b //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_DEVELOPER_FIELD_DESCRIPTION_HPP) #define FIT_DEVELOPER_FIELD_DESCRIPTION_HPP #include "fit_field_description_mesg.hpp" #include "fit_developer_data_id_mesg.hpp" #include <vector> namespace fit { class DeveloperFieldDescription { public: DeveloperFieldDescription() = delete; DeveloperFieldDescription(const DeveloperFieldDescription& other); DeveloperFieldDescription(const FieldDescriptionMesg& desc, const DeveloperDataIdMesg& developer); virtual ~DeveloperFieldDescription(); FIT_UINT32 GetApplicationVersion() const; FIT_UINT8 GetFieldDefinitionNumber() const; std::vector<FIT_UINT8> GetApplicationId() const; private: FieldDescriptionMesg* description; DeveloperDataIdMesg* developer; }; } // namespace fit #endif // defined(FIT_FIELD_DEFINITION_HPP)
[ "julian@omata.com" ]
julian@omata.com
06c1ab5ff8ab138987ba9ad1ed0f423d945bafe7
6817617489ef291d4d53ac844ba7a2b14cc17ae2
/11942.cpp
dcc6c32bd3395a76801df96fb6b8693215e020ec
[]
no_license
Asad51/UVA-Problem-Solving
1932f2cd73261cd702f58d4f189a4a134dbd6286
af28ae36a2074d4e2a67670dbbbd507438c56c3e
refs/heads/master
2020-03-23T14:52:49.420000
2019-10-24T17:03:37
2019-10-24T17:03:37
120,592,261
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int t; cin>>t; cout<<"Lumberjacks:\n"; while(t--){ bool in = true; bool dec = true; int p; for(int i=0; i<10; i++){ int n; cin>>n; if(!i){ p = n; continue; } if(n<p || !in) in = false; if(n>p || !dec) dec = false; p = n; } if(!in && !dec) cout<<"Unordered\n"; else cout<<"Ordered\n"; } return 0; }
[ "asad.cse.ru.15@gmail.com" ]
asad.cse.ru.15@gmail.com
77e95d74adb0d91068d318a9f567bd723eb4bd30
8a970882a0be9f3d85edbf6ecec0050b762e8d80
/GazEngine/gazengine/Entity.h
ded187d2149547f453fc7c141f5bfa9b3cc59aa9
[]
no_license
simplegsb/gazengine
472d1de8d300c8406ffec148844911fd21d5c1e0
b0a7300aa535b14494789fb88c16d6dda1c4e622
refs/heads/master
2016-09-05T21:02:49.531000
2013-04-29T08:33:16
2013-04-29T08:33:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
h
#ifndef ENTITY_H_ #define ENTITY_H_ #include <memory> #include <string> #include <vector> class Component; class Entity { public: static const unsigned short UNCATEGORIZED = 0; Entity(unsigned short category = UNCATEGORIZED, const std::string& name = std::string()); virtual ~Entity(); /** * <p> * Adds a component. * </p> * * @param component The component to add. */ void addComponent(Component* component); unsigned short getCategory() const; /** * <p> * Retrieves the components. * </p> * * @return The components. */ template<typename ComponentType> std::vector<ComponentType*> getComponents() const; unsigned int getId() const; /** * <p> * Retrieves the name of this <code>Entity</code>. * </p> * * @return The name of this <code>Entity</code>. */ const std::string& getName() const; /** * <p> * Retrieves a single component. * </p> * * @return The single component. */ template<typename ComponentType> ComponentType* getSingleComponent() const; /** * <p> * Removes a component. * </p> * * @param component The component to remove. */ void removeComponent(const Component& component); private: unsigned short category; /** * <p> * The components. * </p> */ std::vector<Component*> components; unsigned int id; /** * <p> * The name of this <code>Entity</code>. * </p> */ std::string name; static unsigned int nextId; }; #include "Entity.tpp" #endif /* ENTITY_H_ */
[ "simplegsb@gmail.com" ]
simplegsb@gmail.com
f974d4af50705dd6f63c51d6d7a1ee1c85bf7cd3
414c6adb394c3c7ef4b80ab9b62cfc238ff726e2
/tutorial/spinny/main.cc
39f9f8736922a4b8a41c9e0c1c9d1bf851f0a4b6
[]
no_license
akeley98/vkme
68ca6db6c246fe8b4a25a3fb0982ff2552d8ef9b
1b8e7df2a8290a0cc7bd97bf82c88a6eeff40be1
refs/heads/master
2022-12-23T19:53:47.583000
2020-09-29T05:34:32
2020-09-29T05:34:32
291,925,536
0
0
null
null
null
null
UTF-8
C++
false
false
11,670
cc
#include "window.hh" #include "render.hh" #include "util.hh" using namespace myricube; // Absolute path of the executable, minus the -bin or .exe, plus -data/ // This is where shaders and stuff are stored. std::string data_directory; std::string expand_filename(const std::string& in) { if (data_directory.size() == 0) { throw std::logic_error("Cannot call expand_filename before main"); } return in[0] == '/' ? in : data_directory + in; } bool ends_with_bin_or_exe(const std::string& in) { auto sz = in.size(); if (sz < 4) return false; const char* suffix = &in[sz - 4]; return strcmp(suffix, "-bin") == 0 or strcmp(suffix, ".exe") == 0; } bool paused = false; int target_fragments = 0; void add_key_targets(Window& window, Camera& camera) { static float speed = 8.0f; static float sprint_mod = 1.0f; struct Position { glm::dvec3 eye = glm::dvec3(0); float theta = 1.5707f; float phi = 1.5707f; }; static Position old_positions_ring_buffer[256]; static Position future_positions_ring_buffer[256]; static uint8_t old_idx = 0; static uint8_t future_idx = 0; static auto get_camera_position = [&camera] () -> Position { Position p; p.eye = camera.get_eye(); p.theta = camera.get_theta(); p.phi = camera.get_phi(); return p; }; static auto push_camera_position = [&] { old_positions_ring_buffer[--old_idx] = get_camera_position(); }; static auto push_camera_position_callback = [&] (KeyArg arg) { if (arg.repeat) return false; push_camera_position(); return true; }; KeyTarget pop_old_camera, pop_future_camera; pop_old_camera.down = [&] (KeyArg) -> bool { future_positions_ring_buffer[--future_idx] = get_camera_position(); Position p = old_positions_ring_buffer[old_idx++]; camera.set_eye(p.eye); camera.set_theta(p.theta); camera.set_phi(p.phi); return true; }; pop_future_camera.down = [&] (KeyArg) -> bool { old_positions_ring_buffer[--old_idx] = get_camera_position(); Position p = future_positions_ring_buffer[future_idx++]; camera.set_eye(p.eye); camera.set_theta(p.theta); camera.set_phi(p.phi); return true; }; window.add_key_target("pop_old_camera", pop_old_camera); window.add_key_target("pop_future_camera", pop_future_camera); KeyTarget forward, backward, leftward, rightward, upward, downward; forward.down = push_camera_position_callback; forward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, 0, +arg.dt * speed * sprint_mod); return true; }; backward.down = push_camera_position_callback; backward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, 0, -arg.dt * speed * sprint_mod); return true; }; leftward.down = push_camera_position_callback; leftward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(-arg.dt * speed * sprint_mod, 0, 0); return true; }; rightward.down = push_camera_position_callback; rightward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(+arg.dt * speed * sprint_mod, 0, 0); return true; }; upward.down = push_camera_position_callback; upward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, +arg.dt * speed * sprint_mod, 0); return true; }; downward.down = push_camera_position_callback; downward.per_frame = [&] (KeyArg arg) -> bool { camera.frenet_move(0, -arg.dt * speed * sprint_mod, 0); return true; }; window.add_key_target("forward", forward); window.add_key_target("backward", backward); window.add_key_target("leftward", leftward); window.add_key_target("rightward", rightward); window.add_key_target("upward", upward); window.add_key_target("downward", downward); KeyTarget sprint, speed_up, slow_down; sprint.down = [&] (KeyArg) -> bool { sprint_mod = 7.0f; return true; }; sprint.up = [&] (KeyArg) -> bool { sprint_mod = 1.0f; return true; }; speed_up.down = [&] (KeyArg arg) -> bool { if (!arg.repeat) speed *= 2.0f; return !arg.repeat; }; slow_down.down = [&] (KeyArg arg) -> bool { if (!arg.repeat) speed *= 0.5f; return !arg.repeat; }; window.add_key_target("sprint", sprint); window.add_key_target("speed_up", speed_up); window.add_key_target("slow_down", slow_down); KeyTarget vertical_scroll, horizontal_scroll, look_around; look_around.down = push_camera_position_callback; look_around.per_frame = [&] (KeyArg arg) -> bool { camera.inc_theta(arg.mouse_rel_x * arg.dt * 0.01f); camera.inc_phi(arg.mouse_rel_y * arg.dt * 0.01f); return true; }; vertical_scroll.down = [&] (KeyArg arg) -> bool { camera.inc_phi(arg.amount * -0.05f); return true; }; horizontal_scroll.down = [&] (KeyArg arg) -> bool { camera.inc_theta(arg.amount * -0.05f); return true; }; window.add_key_target("look_around", look_around); window.add_key_target("vertical_scroll", vertical_scroll); window.add_key_target("horizontal_scroll", horizontal_scroll); } // Given the full path of a key binds file, parse it for key bindings // and add it to the window's database of key bindings (physical // key/mouse button to KeyTarget name associations). // // Syntax: the file should consist of lines of pairs of key names and // KeyTarget names. Blank (all whitespace) lines are allowed as well // as comments, which go from a # character to the end of the line. // // Returns true iff successful (check errno on false). bool add_key_binds_from_file(Window& window, std::string filename) noexcept { FILE* file = fopen(filename.c_str(), "r"); if (file == nullptr) { fprintf(stderr, "Could not open %s\n", filename.c_str()); return false; } int line_number = 0; auto skip_whitespace = [file] { int c; while (1) { c = fgetc(file); if (c == EOF) return; if (c == '\n' or !isspace(c)) { ungetc(c, file); return; } } }; errno = 0; bool eof = false; while (!eof) { std::string key_name; std::string target_name; ++line_number; int c; skip_whitespace(); // Parse key name (not case sensitive -- converted to lower case) while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') goto end_line; if (isspace(c)) break; if (c == '#') goto comment; key_name.push_back(c); } skip_whitespace(); // Parse target name (case sensitive) while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') goto end_line; if (isspace(c)) break; if (c == '#') goto comment; target_name.push_back(c); } skip_whitespace(); // Check for unexpected cruft at end of line. c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } else if (c == '#') { goto comment; } else if (c == '\n') { goto end_line; } else { fprintf(stderr, "%s:%i unexpected third token" " starting with '%c'\n", filename.c_str(), line_number, c); errno = EINVAL; goto bad_eof; } // Skip over comment characters from # to \n comment: while (1) { c = fgetc(file); if (c == EOF) { if (errno != 0 and errno != EAGAIN) goto bad_eof; eof = true; goto end_line; } if (c == '\n') { break; } } end_line: // skip blank lines silently. if (key_name.size() == 0) continue; // Complain if only one token is provided on a line. if (target_name.size() == 0) { fprintf(stderr, "%s:%i key name without target name.\n", filename.c_str(), line_number); errno = EINVAL; goto bad_eof; } auto keycode = keycode_from_name(key_name); if (keycode == 0) { fprintf(stderr, "%s:%i unknown key name %s.\n", filename.c_str(), line_number, key_name.c_str()); errno = EINVAL; goto bad_eof; } fprintf(stderr, "Binding %s (%i) to %s\n", key_name.c_str(), keycode, target_name.c_str()); window.bind_keycode(keycode, target_name); } if (fclose(file) != 0) { fprintf(stderr, "Error closing %s\n", filename.c_str()); return false; } return true; bad_eof: fprintf(stderr, "Warning: unexpected end of parsing.\n"); int eof_errno = errno; fclose(file); errno = eof_errno; return true; // I'm getting bogus EOF fails all the time so fake success :/ } void bind_keys(Window& window) { auto default_file = expand_filename("default-keybinds.txt"); auto user_file = expand_filename("keybinds.txt"); bool default_okay = add_key_binds_from_file(window, default_file); if (!default_okay) { fprintf(stderr, "Failed to parse %s\n", default_file.c_str()); fprintf(stderr, "%s (%i)\n", strerror(errno), errno); exit(2); } bool user_okay = add_key_binds_from_file(window, user_file); if (!user_okay) { if (errno == ENOENT) { fprintf(stderr, "Custom keybinds file %s not found.\n", user_file.c_str()); } else { fprintf(stderr, "Failed to parse %s\n", user_file.c_str()); fprintf(stderr, "%s (%i)\n", strerror(errno), errno); exit(2); } } } int main(int argc, char** argv) { // Data directory (where shaders are stored) is the path of this // executable, with the -bin or .exe file extension replaced with // -data. Construct that directory name here. data_directory = argv[0]; if (!ends_with_bin_or_exe(data_directory)) { fprintf(stderr, "%s should end with '-bin' or '.exe'\n", data_directory.c_str()); return 1; } for (int i = 0; i < 4; ++i) data_directory.pop_back(); data_directory += "-data/"; // Instantiate the camera. Camera camera; // Create a window; callback ensures these window dimensions stay accurate. int screen_x = 0, screen_y = 0; auto on_window_resize = [&camera, &screen_x, &screen_y] (int x, int y) { camera.set_window_size(x, y); screen_x = x; screen_y = y; }; Window window(on_window_resize); Renderer* renderer = new_renderer(window); add_key_targets(window, camera); bind_keys(window); while (window.frame_update()) draw_frame(renderer, camera); delete_renderer(renderer); }
[ "dza724@gmail.com" ]
dza724@gmail.com
95534aae2f06adbc3b44e859658780f8bf0cf800
3f9081b23333e414fb82ccb970e15b8e74072c54
/bs2k/behaviors/skills/oneortwo_step_kick_bms.h
e7f968c14d8092e86a4e41ed23b6e7ac3a2558ab
[]
no_license
rc2dcc/Brainstormers05PublicRelease
5c8da63ac4dd3b84985bdf791a4e5580bbf0ba59
2141093960fad33bf2b3186d6364c08197e9fe8e
refs/heads/master
2020-03-22T07:32:36.757000
2018-07-04T18:28:32
2018-07-04T18:28:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,945
h
/* Brainstormers 2D (Soccer Simulation League 2D) PUBLIC SOURCE CODE RELEASE 2005 Copyright (C) 1998-2005 Neuroinformatics Group, University of Osnabrueck, Germany This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _ONEORTWO_STEP_KICK_BMS_H_ #define _ONEORTWO_STEP_KICK_BMS_H_ /* This behavior is a port of Move_1or2_Step_Kick into the behavior framework. get_cmd will try to kick in one step and otherwise return a cmd that will start a two-step kick. There are some functions that return information about the reachable velocities and the needed steps, so that you can prepare in your code for what this behavior will do. This behavior usually takes the current player position as reference point, but you can override this by calling set_state() prior to any other function. This makes it possible to "fake" the player's position during the current cycle. Use reset_state to re-read the WS information, or wait until the next cycle. Note that kick_to_pos_with_final_vel() is rather unprecise concerning the final velocity of the ball. I don't know how to calculate the needed starting vel precisely, so I have taken the formula from the original Neuro_Kick2 move (which was even more unprecise...) and tweaked it a bit, but it is still not perfect. Note also that this behavior, as opposed to the original move, has a working collision check - the original move ignored the player's vel... (w) 2002 Manuel Nickschas */ #include "../base_bm.h" #include "one_step_kick_bms.h" #include "angle.h" #include "Vector.h" #include "tools.h" #include "cmd.h" #include "n++.h" #include "macro_msg.h" #include "valueparser.h" #include "options.h" #include "ws_info.h" #include "log_macros.h" #include "mystate.h" #include "../../policy/abstract_mdp.h" class OneOrTwoStepKickItrActions { static const Value kick_pwr_min = 20; static const Value kick_pwr_inc = 10; static const Value kick_pwr_max = 100; static const Value kick_ang_min = 0; static const Value kick_ang_inc = 2*PI/8.; // static const Value kick_ang_inc = 2*PI/36.; // ridi: I think it should be as much! too much static const Value kick_ang_max = 2*PI-kick_ang_inc; static const Value dash_pwr_min = 20; static const Value dash_pwr_inc = 20; static const Value dash_pwr_max = 100; static const Value turn_ang_min = 0; static const Value turn_ang_inc = 2*PI/18.; // static const Value turn_ang_max = 2*PI-turn_ang_inc; static const Value turn_ang_max = 0; // ridi: do not allow turns static const Value kick_pwr_steps = (kick_pwr_max-kick_pwr_min)/kick_pwr_inc + 1; static const Value dash_pwr_steps = (dash_pwr_max-dash_pwr_min)/dash_pwr_inc + 1; static const Value turn_ang_steps = (turn_ang_max-turn_ang_min)/turn_ang_inc + 1; static const Value kick_ang_steps = (kick_ang_max-kick_ang_min)/kick_ang_inc + 1; Cmd_Main action; Value kick_pwr,dash_pwr; ANGLE kick_ang,turn_ang; int kick_pwr_done,kick_ang_done,dash_pwr_done,turn_ang_done; public: void reset() { kick_pwr_done=0;kick_ang_done=0;dash_pwr_done=0;turn_ang_done=0; kick_pwr=kick_pwr_min;kick_ang= ANGLE(kick_ang_min);dash_pwr=dash_pwr_min; turn_ang=ANGLE(turn_ang_min); } Cmd_Main *next() { if(kick_pwr_done<kick_pwr_steps && kick_ang_done<kick_ang_steps) { action.unset_lock(); action.unset_cmd(); action.set_kick(kick_pwr,kick_ang.get_value_mPI_pPI()); kick_ang+= ANGLE(kick_ang_inc); if(++kick_ang_done>=kick_ang_steps) { kick_ang=ANGLE(kick_ang_min); kick_ang_done=0; kick_pwr+=kick_pwr_inc; kick_pwr_done++; } return &action; } if(dash_pwr_done<dash_pwr_steps) { action.unset_lock(); action.unset_cmd(); action.set_dash(dash_pwr); dash_pwr+=dash_pwr_inc; dash_pwr_done++; return &action; } if(turn_ang_done<turn_ang_steps) { action.unset_lock(); action.unset_cmd(); action.set_turn(turn_ang); turn_ang+= ANGLE(turn_ang_inc); turn_ang_done++; return &action; } return NULL; } }; class OneOrTwoStepKick: public BaseBehavior { static bool initialized; #if 0 struct MyState { Vector my_vel; Vector my_pos; ANGLE my_angle; Vector ball_pos; Vector ball_vel; Vector op_pos; ANGLE op_bodydir; }; #endif OneStepKick *onestepkick; OneOrTwoStepKickItrActions itr_actions; Cmd_Main result_cmd1,result_cmd2; Value result_vel1,result_vel2; bool result_status; bool need_2_steps; long set_in_cycle; Vector target_pos; ANGLE target_dir; Value target_vel; bool kick_to_pos; bool calc_done; MyState fake_state; long fake_state_time; void get_ws_state(MyState &state); MyState get_cur_state(); bool calculate(const MyState &state,Value vel,const ANGLE &dir,const Vector &pos,bool to_pos, Cmd_Main &res_cmd1,Value &res_vel1,Cmd_Main &res_cmd2,Value &res_vel2, bool &need_2steps); bool do_calc(); public: /** This makes it possible to "fake" WS information. This must be called _BEFORE_ any of the kick functions, and is valid for the current cycle only. */ void set_state(const Vector &mypos,const Vector &myvel,const ANGLE &myang, const Vector &ballpos,const Vector &ballvel, const Vector &op_pos = Vector(1000,1000), const ANGLE &op_bodydir = ANGLE(0), const int op_bodydir_age = 1000); void set_state( const AState & state ); /** Resets the current state to that found in WS. This must be called _BEFORE_ any of the kick functions. */ void reset_state(); void kick_in_dir_with_initial_vel(Value vel,const ANGLE &dir); void kick_in_dir_with_max_vel(const ANGLE &dir); void kick_to_pos_with_initial_vel(Value vel,const Vector &point); void kick_to_pos_with_final_vel(Value vel,const Vector &point); void kick_to_pos_with_max_vel(const Vector &point); /** false is returned if we do not reach our desired vel within two cycles. Note that velocities are set to zero if the resulting pos is not ok, meaning that even if a cmd would reach the desired vel, we will ignore it if the resulting pos is not ok. */ bool get_vel(Value &vel_1step,Value &vel_2step); bool get_cmd(Cmd &cmd_1step,Cmd &cmd_2step); bool get_vel(Value &best_vel); // get best possible vel (1 or 2 step) bool get_cmd(Cmd &best_cmd); // get best possible cmd (1 or 2 step) // returns 0 if kick is not possible, 1 if kick in 1 step is possible, 2 if in 2 steps. probably modifies vel int is_kick_possible(Value &speed,const ANGLE &dir); bool need_two_steps(); bool can_keep_ball_in_kickrange(); static bool init(char const * conf_file, int argc, char const* const* argv) { if(initialized) return true; initialized = true; if(OneStepKick::init(conf_file,argc,argv)) { cout << "\nOneOrTwoStepKick behavior initialized."; } else { ERROR_OUT << "\nCould not initialize OneStepKick behavior - stop loading."; exit(1); } return true; } OneOrTwoStepKick() { set_in_cycle = -1; onestepkick = new OneStepKick(); onestepkick->set_log(false); // we don't want OneStepKick-Info in our logs! } virtual ~OneOrTwoStepKick() { delete onestepkick; } }; #endif
[ "cookie.yz@qq.com" ]
cookie.yz@qq.com
6bb71dcc34b99d77ceb1ceff65cfbc759d142cb5
fb72a82827496e66e04ecb29abbca788a1ea0525
/src/wallet/wallet.h
5c79de2b263b987cf010ed0c6314bf311d8d6581
[ "MIT" ]
permissive
exiliumcore/exilium
92631c2e7abeeae6a80debbb699441d6b56e2fee
6aa88fe0c40fe72850e5bdb265741a375b2ab766
refs/heads/master
2020-03-14T05:50:41.214000
2018-05-13T01:00:24
2018-05-13T01:00:24
131,472,364
0
1
null
null
null
null
UTF-8
C++
false
false
37,762
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2018 The Exilium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_WALLET_H #define BITCOIN_WALLET_WALLET_H #include "amount.h" #include "base58.h" #include "streams.h" #include "tinyformat.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "wallet/crypter.h" #include "wallet/wallet_ismine.h" #include "wallet/walletdb.h" #include "privatesend.h" #include <algorithm> #include <map> #include <set> #include <stdexcept> #include <stdint.h> #include <string> #include <utility> #include <vector> #include <boost/shared_ptr.hpp> /** * Settings */ extern CFeeRate payTxFee; extern CAmount maxTxFee; extern unsigned int nTxConfirmTarget; extern bool bSpendZeroConfChange; extern bool fSendFreeTransactions; static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000; //! -paytxfee default static const CAmount DEFAULT_TRANSACTION_FEE = 0; //! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB static const CAmount nHighTransactionFeeWarning = 0.01 * COIN; //! -fallbackfee default static const CAmount DEFAULT_FALLBACK_FEE = 1000; //! -mintxfee default static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000; //! -maxtxfee default static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.2 * COIN; // "smallest denom" + X * "denom tails" //! minimum change amount static const CAmount MIN_CHANGE = CENT; //! Default for -spendzeroconfchange static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true; //! Default for -sendfreetransactions static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false; //! -txconfirmtarget default static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2; //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis) static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning; //! Largest (in bytes) free transaction we're willing to create static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000; static const bool DEFAULT_WALLETBROADCAST = true; //! if set, all keys will be derived by using BIP39/BIP44 static const bool DEFAULT_USE_HD_WALLET = false; class CBlockIndex; class CCoinControl; class COutput; class CReserveKey; class CScript; class CTxMemPool; class CWalletTx; /** (client) version numbers for particular wallet features */ enum WalletFeature { FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output) FEATURE_WALLETCRYPT = 40000, // wallet encryption FEATURE_COMPRPUBKEY = 60000, // compressed public keys FEATURE_HD = 120200, // Hierarchical key derivation after BIP32 (HD Wallet), BIP44 (multi-coin), BIP39 (mnemonic) // which uses on-the-fly private key derivation FEATURE_LATEST = 61000 }; enum AvailableCoinsType { ALL_COINS, ONLY_DENOMINATED, ONLY_NONDENOMINATED, ONLY_1000, // find masternode outputs including locked ones (use with caution) ONLY_PRIVATESEND_COLLATERAL }; struct CompactTallyItem { CTxDestination txdest; CAmount nAmount; std::vector<CTxIn> vecTxIn; CompactTallyItem() { nAmount = 0; } }; /** A key pool entry */ class CKeyPool { public: int64_t nTime; CPubKey vchPubKey; bool fInternal; // for change outputs CKeyPool(); CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(nTime); READWRITE(vchPubKey); if (ser_action.ForRead()) { try { READWRITE(fInternal); } catch (std::ios_base::failure&) { /* flag as external address if we can't read the internal boolean (this will be the case for any wallet before the HD chain split version) */ fInternal = false; } } else { READWRITE(fInternal); } } }; /** Address book data */ class CAddressBookData { public: std::string name; std::string purpose; CAddressBookData() { purpose = "unknown"; } typedef std::map<std::string, std::string> StringMap; StringMap destdata; }; struct CRecipient { CScript scriptPubKey; CAmount nAmount; bool fSubtractFeeFromAmount; }; typedef std::map<std::string, std::string> mapValue_t; static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue) { if (!mapValue.count("n")) { nOrderPos = -1; // TODO: calculate elsewhere return; } nOrderPos = atoi64(mapValue["n"].c_str()); } static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue) { if (nOrderPos == -1) return; mapValue["n"] = i64tostr(nOrderPos); } struct COutputEntry { CTxDestination destination; CAmount amount; int vout; }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: /** Constant used in hashBlock to indicate tx has been abandoned */ static const uint256 ABANDON_HASH; public: uint256 hashBlock; /* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest * block in the chain we know this or any in-wallet dependency conflicts * with. Older clients interpret nIndex == -1 as unconfirmed for backward * compatibility. */ int nIndex; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = uint256(); nIndex = -1; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { std::vector<uint256> vMerkleBranch; // For compatibility with older versions. READWRITE(*(CTransaction*)this); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); } int SetMerkleBranch(const CBlock& block); /** * Return depth of transaction in blockchain: * <0 : conflicts with a transaction this deep in the blockchain * 0 : in memory pool, waiting to be included in a block * >=1 : this many blocks deep in the main chain */ int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const; int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); } bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true); bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); } bool isAbandoned() const { return (hashBlock == ABANDON_HASH); } void setAbandoned() { hashBlock = ABANDON_HASH; } }; /** * A transaction with a bunch of additional info that only the owner cares about. * It includes any unrecorded transactions needed to link it back to the block chain. */ class CWalletTx : public CMerkleTx { private: const CWallet* pwallet; public: mapValue_t mapValue; std::vector<std::pair<std::string, std::string> > vOrderForm; unsigned int fTimeReceivedIsTxTime; unsigned int nTimeReceived; //! time received by this node unsigned int nTimeSmart; char fFromMe; std::string strFromAccount; int64_t nOrderPos; //! position in ordered transaction list // memory only mutable bool fDebitCached; mutable bool fCreditCached; mutable bool fImmatureCreditCached; mutable bool fAvailableCreditCached; mutable bool fAnonymizedCreditCached; mutable bool fDenomUnconfCreditCached; mutable bool fDenomConfCreditCached; mutable bool fWatchDebitCached; mutable bool fWatchCreditCached; mutable bool fImmatureWatchCreditCached; mutable bool fAvailableWatchCreditCached; mutable bool fChangeCached; mutable CAmount nDebitCached; mutable CAmount nCreditCached; mutable CAmount nImmatureCreditCached; mutable CAmount nAvailableCreditCached; mutable CAmount nAnonymizedCreditCached; mutable CAmount nDenomUnconfCreditCached; mutable CAmount nDenomConfCreditCached; mutable CAmount nWatchDebitCached; mutable CAmount nWatchCreditCached; mutable CAmount nImmatureWatchCreditCached; mutable CAmount nAvailableWatchCreditCached; mutable CAmount nChangeCached; CWalletTx() { Init(NULL); } CWalletTx(const CWallet* pwalletIn) { Init(pwalletIn); } CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn) { Init(pwalletIn); } CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn) { Init(pwalletIn); } void Init(const CWallet* pwalletIn) { pwallet = pwalletIn; mapValue.clear(); vOrderForm.clear(); fTimeReceivedIsTxTime = false; nTimeReceived = 0; nTimeSmart = 0; fFromMe = false; strFromAccount.clear(); fDebitCached = false; fCreditCached = false; fImmatureCreditCached = false; fAvailableCreditCached = false; fAnonymizedCreditCached = false; fDenomUnconfCreditCached = false; fDenomConfCreditCached = false; fWatchDebitCached = false; fWatchCreditCached = false; fImmatureWatchCreditCached = false; fAvailableWatchCreditCached = false; fChangeCached = false; nDebitCached = 0; nCreditCached = 0; nImmatureCreditCached = 0; nAvailableCreditCached = 0; nAnonymizedCreditCached = 0; nDenomUnconfCreditCached = 0; nDenomConfCreditCached = 0; nWatchDebitCached = 0; nWatchCreditCached = 0; nAvailableWatchCreditCached = 0; nImmatureWatchCreditCached = 0; nChangeCached = 0; nOrderPos = -1; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (ser_action.ForRead()) Init(NULL); char fSpent = false; if (!ser_action.ForRead()) { mapValue["fromaccount"] = strFromAccount; WriteOrderPos(nOrderPos, mapValue); if (nTimeSmart) mapValue["timesmart"] = strprintf("%u", nTimeSmart); } READWRITE(*(CMerkleTx*)this); std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev READWRITE(vUnused); READWRITE(mapValue); READWRITE(vOrderForm); READWRITE(fTimeReceivedIsTxTime); READWRITE(nTimeReceived); READWRITE(fFromMe); READWRITE(fSpent); if (ser_action.ForRead()) { strFromAccount = mapValue["fromaccount"]; ReadOrderPos(nOrderPos, mapValue); nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0; } mapValue.erase("fromaccount"); mapValue.erase("version"); mapValue.erase("spent"); mapValue.erase("n"); mapValue.erase("timesmart"); } //! make sure balances are recalculated void MarkDirty() { fCreditCached = false; fAvailableCreditCached = false; fImmatureCreditCached = false; fAnonymizedCreditCached = false; fDenomUnconfCreditCached = false; fDenomConfCreditCached = false; fWatchDebitCached = false; fWatchCreditCached = false; fAvailableWatchCreditCached = false; fImmatureWatchCreditCached = false; fDebitCached = false; fChangeCached = false; } void BindWallet(CWallet *pwalletIn) { pwallet = pwalletIn; MarkDirty(); } //! filter decides which addresses will count towards the debit CAmount GetDebit(const isminefilter& filter) const; CAmount GetCredit(const isminefilter& filter) const; CAmount GetImmatureCredit(bool fUseCache=true) const; CAmount GetAvailableCredit(bool fUseCache=true) const; CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const; CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const; CAmount GetChange() const; CAmount GetAnonymizedCredit(bool fUseCache=true) const; CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const; void GetAmounts(std::list<COutputEntry>& listReceived, std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const; void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const; bool IsFromMe(const isminefilter& filter) const { return (GetDebit(filter) > 0); } // True if only scriptSigs are different bool IsEquivalentTo(const CWalletTx& tx) const; bool InMempool() const; bool IsTrusted() const; bool WriteToDisk(CWalletDB *pwalletdb); int64_t GetTxTime() const; int GetRequestCount() const; bool RelayWalletTransaction(CConnman* connman, std::string strCommand="tx"); std::set<uint256> GetConflicts() const; }; class COutput { public: const CWalletTx *tx; int i; int nDepth; bool fSpendable; bool fSolvable; COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn) { tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn; } //Used with Darksend. Will return largest nondenom, then denominations, then very small inputs int Priority() const; std::string ToString() const; }; /** Private key that includes an expiration date in case it never gets used. */ class CWalletKey { public: CPrivKey vchPrivKey; int64_t nTimeCreated; int64_t nTimeExpires; std::string strComment; //! todo: add something to note what created it (user, getnewaddress, change) //! maybe should have a map<string, string> property map CWalletKey(int64_t nExpires=0); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vchPrivKey); READWRITE(nTimeCreated); READWRITE(nTimeExpires); READWRITE(LIMITED_STRING(strComment, 65536)); } }; /** * Internal transfers. * Database key is acentry<account><counter>. */ class CAccountingEntry { public: std::string strAccount; CAmount nCreditDebit; int64_t nTime; std::string strOtherAccount; std::string strComment; mapValue_t mapValue; int64_t nOrderPos; //! position in ordered transaction list uint64_t nEntryNo; CAccountingEntry() { SetNull(); } void SetNull() { nCreditDebit = 0; nTime = 0; strAccount.clear(); strOtherAccount.clear(); strComment.clear(); nOrderPos = -1; nEntryNo = 0; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); //! Note: strAccount is serialized as part of the key, not here. READWRITE(nCreditDebit); READWRITE(nTime); READWRITE(LIMITED_STRING(strOtherAccount, 65536)); if (!ser_action.ForRead()) { WriteOrderPos(nOrderPos, mapValue); if (!(mapValue.empty() && _ssExtra.empty())) { CDataStream ss(nType, nVersion); ss.insert(ss.begin(), '\0'); ss << mapValue; ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end()); strComment.append(ss.str()); } } READWRITE(LIMITED_STRING(strComment, 65536)); size_t nSepPos = strComment.find("\0", 0, 1); if (ser_action.ForRead()) { mapValue.clear(); if (std::string::npos != nSepPos) { CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion); ss >> mapValue; _ssExtra = std::vector<char>(ss.begin(), ss.end()); } ReadOrderPos(nOrderPos, mapValue); } if (std::string::npos != nSepPos) strComment.erase(nSepPos); mapValue.erase("n"); } private: std::vector<char> _ssExtra; }; /** * A CWallet is an extension of a keystore, which also maintains a set of transactions and balances, * and provides the ability to create new transactions. */ class CWallet : public CCryptoKeyStore, public CValidationInterface { private: /** * Select a set of coins such that nValueRet >= nTargetValue and at least * all coins from coinControl are selected; Never select unconfirmed coins * if they are not ours */ bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = true) const; CWalletDB *pwalletdbEncryption; //! the current wallet version: clients below this version are not able to load the wallet int nWalletVersion; //! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded int nWalletMaxVersion; int64_t nNextResend; int64_t nLastResend; bool fBroadcastTransactions; mutable bool fAnonymizableTallyCached; mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached; mutable bool fAnonymizableTallyCachedNonDenom; mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom; /** * Used to keep track of spent outpoints, and * detect and report conflicts (double-spends or * mutated transactions where the mutant gets mined). */ typedef std::multimap<COutPoint, uint256> TxSpends; TxSpends mapTxSpends; void AddToSpends(const COutPoint& outpoint, const uint256& wtxid); void AddToSpends(const uint256& wtxid); std::set<COutPoint> setWalletUTXO; /* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */ void MarkConflicted(const uint256& hashBlock, const uint256& hashTx); void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>); /* HD derive new child key (on internal or external chain) */ void DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/); public: /* * Main wallet lock. * This lock protects all the fields added by CWallet * except for: * fFileBacked (immutable after instantiation) * strWalletFile (immutable after instantiation) */ mutable CCriticalSection cs_wallet; bool fFileBacked; const std::string strWalletFile; void LoadKeyPool(int nIndex, const CKeyPool &keypool) { if (keypool.fInternal) { setInternalKeyPool.insert(nIndex); } else { setExternalKeyPool.insert(nIndex); } // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (mapKeyMetadata.count(keyid) == 0) mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } std::set<int64_t> setInternalKeyPool; std::set<int64_t> setExternalKeyPool; std::map<CKeyID, CKeyMetadata> mapKeyMetadata; typedef std::map<unsigned int, CMasterKey> MasterKeyMap; MasterKeyMap mapMasterKeys; unsigned int nMasterKeyMaxID; CWallet() { SetNull(); } CWallet(const std::string& strWalletFileIn) : strWalletFile(strWalletFileIn) { SetNull(); fFileBacked = true; } ~CWallet() { delete pwalletdbEncryption; pwalletdbEncryption = NULL; } void SetNull() { nWalletVersion = FEATURE_BASE; nWalletMaxVersion = FEATURE_BASE; fFileBacked = false; nMasterKeyMaxID = 0; pwalletdbEncryption = NULL; nOrderPosNext = 0; nNextResend = 0; nLastResend = 0; nTimeFirstKey = 0; fBroadcastTransactions = false; fAnonymizableTallyCached = false; fAnonymizableTallyCachedNonDenom = false; vecAnonymizableTallyCached.clear(); vecAnonymizableTallyCachedNonDenom.clear(); } std::map<uint256, CWalletTx> mapWallet; std::list<CAccountingEntry> laccentries; typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair; typedef std::multimap<int64_t, TxPair > TxItems; TxItems wtxOrdered; int64_t nOrderPosNext; std::map<uint256, int> mapRequestCount; std::map<CTxDestination, CAddressBookData> mapAddressBook; CPubKey vchDefaultKey; std::set<COutPoint> setLockedCoins; int64_t nTimeFirstKey; int64_t nKeysLeftSinceAutoBackup; std::map<CKeyID, CHDPubKey> mapHdPubKeys; //<! memory map of HD extended pubkeys const CWalletTx* GetWalletTx(const uint256& hash) const; //! check whether we are allowed to upgrade (or already support) to the named feature bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; } /** * populate vCoins with vector of available COutputs. */ void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = false) const; /** * Shuffle and select coins until nTargetValue is reached while avoiding * small change; This method is stochastic for some inputs and upon * completion the coin set and corresponding actual target value is * assembled */ bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend = false) const; // Coin selection bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax); bool GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const; bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const; bool SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true) const; /// Get 1000exilium output and keys which can be used for the Masternode bool GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash = "", std::string strOutputIndex = ""); /// Extract txin information and keys from output bool GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet); bool HasCollateralInputs(bool fOnlyConfirmed = true) const; int CountInputsWithAmount(CAmount nInputAmount); // get the PrivateSend chain depth for a given input int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const; // respect current settings int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const; bool IsDenominated(const COutPoint& outpoint) const; bool IsSpent(const uint256& hash, unsigned int n) const; bool IsLockedCoin(uint256 hash, unsigned int n) const; void LockCoin(COutPoint& output); void UnlockCoin(COutPoint& output); void UnlockAllCoins(); void ListLockedCoins(std::vector<COutPoint>& vOutpts); /** * keystore implementation * Generate a new key */ CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal /*= false*/); //! HaveKey implementation that also checks the mapHdPubKeys bool HaveKey(const CKeyID &address) const; //! GetPubKey implementation that also checks the mapHdPubKeys bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; //! GetKey implementation that can derive a HD private key on the fly bool GetKey(const CKeyID &address, CKey& keyOut) const; //! Adds a HDPubKey into the wallet(database) bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal); //! loads a HDPubKey into the wallets memory bool LoadHDPubKey(const CHDPubKey &hdPubKey); //! Adds a key to the store, and saves it to disk. bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); //! Adds a key to the store, without saving it to disk (used by LoadWallet) bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); } //! Load metadata (used by LoadWallet) bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata); bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; } //! Adds an encrypted key to the store, and saves it to disk. bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); bool AddCScript(const CScript& redeemScript); bool LoadCScript(const CScript& redeemScript); //! Adds a destination data tuple to the store, and saves it to disk bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value); //! Erases a destination data tuple in the store and on disk bool EraseDestData(const CTxDestination &dest, const std::string &key); //! Adds a destination data tuple to the store, without saving it to disk bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value); //! Look up a destination data tuple in the store, return true if found false otherwise bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const; //! Adds a watch-only address to the store, and saves it to disk. bool AddWatchOnly(const CScript &dest); bool RemoveWatchOnly(const CScript &dest); //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) bool LoadWatchOnly(const CScript &dest); bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false); bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase); bool EncryptWallet(const SecureString& strWalletPassphrase); void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const; /** * Increment the next transaction order id * @return next transaction order id */ int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL); void MarkDirty(); bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb); void SyncTransaction(const CTransaction& tx, const CBlock* pblock); bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate); int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false); void ReacceptWalletTransactions(); void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman); std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman); CAmount GetBalance() const; CAmount GetUnconfirmedBalance() const; CAmount GetImmatureBalance() const; CAmount GetWatchOnlyBalance() const; CAmount GetUnconfirmedWatchOnlyBalance() const; CAmount GetImmatureWatchOnlyBalance() const; CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const; CAmount GetAnonymizedBalance() const; float GetAverageAnonymizedRounds() const; CAmount GetNormalizedAnonymizedBalance() const; CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance = 0) const; CAmount GetDenominatedBalance(bool unconfirmed=false) const; bool GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend); bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend); /** * Insert additional inputs into the transaction by * calling CreateTransaction(); */ bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching); /** * Create a new transaction paying the recipients with a set of coins * selected by SelectCoins(); Also create the change output, when needed */ bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false); bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, std::string strCommand="tx"); bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason); bool ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts); bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb); static CFeeRate minTxFee; static CFeeRate fallbackFee; /** * Estimate the minimum fee considering user set parameters * and the required fee */ static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool); /** * Return the minimum required fee taking into account the * floating relay fee and user set minimum transaction fee */ static CAmount GetRequiredFee(unsigned int nTxBytes); bool NewKeyPool(); size_t KeypoolCountExternalKeys(); size_t KeypoolCountInternalKeys(); bool TopUpKeyPool(unsigned int kpSize = 0); void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal); void KeepKey(int64_t nIndex); void ReturnKey(int64_t nIndex, bool fInternal); bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/); int64_t GetOldestKeyPoolTime(); void GetAllReserveKeys(std::set<CKeyID>& setAddress) const; std::set< std::set<CTxDestination> > GetAddressGroupings(); std::map<CTxDestination, CAmount> GetAddressBalances(); std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const; isminetype IsMine(const CTxIn& txin) const; CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const; isminetype IsMine(const CTxOut& txout) const; CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const; bool IsChange(const CTxOut& txout) const; CAmount GetChange(const CTxOut& txout) const; bool IsMine(const CTransaction& tx) const; /** should probably be renamed to IsRelevantToMe */ bool IsFromMe(const CTransaction& tx) const; CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const; CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const; CAmount GetChange(const CTransaction& tx) const; void SetBestChain(const CBlockLocator& loc); DBErrors LoadWallet(bool& fFirstRunRet); DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx); bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose); bool DelAddressBook(const CTxDestination& address); bool UpdatedTransaction(const uint256 &hashTx); void Inventory(const uint256 &hash) { { LOCK(cs_wallet); std::map<uint256, int>::iterator mi = mapRequestCount.find(hash); if (mi != mapRequestCount.end()) (*mi).second++; } } void GetScriptForMining(boost::shared_ptr<CReserveScript> &script); void ResetRequestCount(const uint256 &hash) { LOCK(cs_wallet); mapRequestCount[hash] = 0; }; unsigned int GetKeyPoolSize() { AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool return setInternalKeyPool.size() + setExternalKeyPool.size(); } bool SetDefaultKey(const CPubKey &vchPubKey); //! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false); //! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format) bool SetMaxVersion(int nVersion); //! get the current wallet format (the oldest client version guaranteed to understand this wallet) int GetVersion() { LOCK(cs_wallet); return nWalletVersion; } //! Get wallet transactions that conflict with given transaction (spend same outputs) std::set<uint256> GetConflicts(const uint256& txid) const; //! Flush wallet (bitdb flush) void Flush(bool shutdown=false); //! Verify the wallet database and perform salvage if required static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString); /** * Address book entry changed. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged; /** * Wallet transaction added, removed or updated. * @note called with lock cs_wallet held. */ boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged; /** Show progress e.g. for rescan */ boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress; /** Watch-only address added */ boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged; /** Inquire whether this wallet broadcasts transactions. */ bool GetBroadcastTransactions() const { return fBroadcastTransactions; } /** Set whether this wallet broadcasts transactions. */ void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; } /* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */ bool AbandonTransaction(const uint256& hashTx); /** * HD Wallet Functions */ /* Returns true if HD is enabled */ bool IsHDEnabled(); /* Generates a new HD chain */ void GenerateNewHDChain(); /* Set the HD chain model (chain child index counters) */ bool SetHDChain(const CHDChain& chain, bool memonly); bool SetCryptedHDChain(const CHDChain& chain, bool memonly); bool GetDecryptedHDChain(CHDChain& hdChainRet); }; /** A key allocated from the key pool. */ class CReserveKey : public CReserveScript { protected: CWallet* pwallet; int64_t nIndex; CPubKey vchPubKey; bool fInternal; public: CReserveKey(CWallet* pwalletIn) { nIndex = -1; pwallet = pwalletIn; fInternal = false; } ~CReserveKey() { ReturnKey(); } void ReturnKey(); bool GetReservedKey(CPubKey &pubkey, bool fInternalIn /*= false*/); void KeepKey(); void KeepScript() { KeepKey(); } }; /** * Account information. * Stored in wallet with key "acc"+string account name. */ class CAccount { public: CPubKey vchPubKey; CAccount() { SetNull(); } void SetNull() { vchPubKey = CPubKey(); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vchPubKey); } }; #endif // BITCOIN_WALLET_WALLET_H
[ "devexilium@gmail.com" ]
devexilium@gmail.com
2700f3690854eaf5a2187d2d57c0ce1df9fa0f9f
29288023bde7829066f810540963a7b35573fa31
/BstUsingSet.cpp
4f984176f775caa7499cc3e20cab43944733c536
[]
no_license
Sohail-khan786/Competitve-Programming
6e56bdd8fb7b3660edec50c72f680b6ed2c41a0f
e90dcf557778a4c0310e03539e4f3c1c939bb3a1
refs/heads/master
2022-10-08T06:55:46.637000
2020-06-07T18:39:20
2020-06-07T18:39:20
254,899,456
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include<bits/stdc++.h> using namespace std; int main() { int flag=1; set<int> s; set<int>::iterator it; int x; while(flag!=3) { cout<<"1.Insert 2.Delete 3.Exit"<<endl; cin>>flag; cout<<"value\t"; cin>>x; if(flag==1) { s.insert(x); } else if(flag==2) { s.erase(x); } cout<<"Extracting max n min from a set"<<cout<<endl; //s.end has iterator to last element of the set which is the size of the set and hence decrement it by one to get the maximum element present in the set; it = s.end(); it--; cout<<"maxx = "<<*(it)<<" minn ="<<*s.begin(); cout<<endl; } return 0; }
[ "Khansohail0540@gmail.com" ]
Khansohail0540@gmail.com
40bc68efa1d237aacc7f1b2a5010046f0e4cf13c
4b1289b0eb41c045a24b4626857097571c988e9b
/Least_Loose_Number_In_The_Array.cpp
01dac7320be1eee1ec1af9b49c0962158327697f
[]
no_license
Arvy1998/Calculus-and-Play-with-New-Syntax
136d942c1be8dc59d3b6d764881d7a9aea5a68cd
b442156a850dad2ed7c53ce86d3435fb35d78fe9
refs/heads/master
2021-07-11T02:05:09.180000
2019-03-12T22:00:42
2019-03-12T22:00:42
129,288,984
1
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { long long n, seka[101], MIN_TEIG = 0, count; vector <long long> izulus_teig_sk; cin >> n; for (auto x = 0; x < n; x++) { cin >> seka[x]; } for (auto i = 0; i < n; i++) { if (i == 0) { if (seka[i] > seka[i + 1]) { izulus_teig_sk.push_back(seka[i]); } } if (i > 0 && i < n - 1) { if (seka[i] > seka[i - 1] && seka[i] > seka[i + 1]) { izulus_teig_sk.push_back(seka[i]); } } if (i == n - 1) { if (seka[i] > seka[i - 1]) { izulus_teig_sk.push_back(seka[i]); } } } if (izulus_teig_sk.size() == 0 || n <= 1) { cout << "NO"; exit(0); } else { sort(izulus_teig_sk.begin(), izulus_teig_sk.end()); for (size_t j = 0; j < izulus_teig_sk.size(); j++) { if (izulus_teig_sk[j] > 0) { MIN_TEIG = izulus_teig_sk[j]; cout << MIN_TEIG; break; } } } if (MIN_TEIG == 0) { cout << "NO"; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
819eb928fa03acd974c3e18443532022f13c2f05
711b11d08abdb3a7df2574b0b4c86af21c5c6750
/dest.h
e06af74e0264187915ab70b86b0e67aa85d2a79f
[]
no_license
nflath/MSP430Emulator
4aee9e093113cc41d9041a1728eedd742fd786b2
a97a1b97b895b3533597bcdb69bec8b75db395df
refs/heads/master
2021-01-13T01:54:55.258000
2015-08-25T05:10:04
2015-08-25T05:10:04
41,343,926
0
0
null
null
null
null
UTF-8
C++
false
false
2,382
h
#include <assert.h> #ifndef DEST_H #define DEST_H #include "error.h" // Classes representing 'Destinations' types in MSP430 - See the section // 'MSP430 addressing modes' in https://en.wikipedia.org/wiki/TI_MSP430#MSP430_CPU class State; class Dest { // Virtual base clase. public: virtual void set(short value) { notimplemented(); } // Sets the value of this destination virtual void setByte(unsigned char value) { notimplemented(); } // Sets the value of this destination (byte addressing mode) virtual short value() { notimplemented(); return 0;} // Returns the value of this destination virtual unsigned char valueByte() { notimplemented(); return 0;} // Returns the value of this destination(byte addressing mode) virtual std::string toString() = 0; // Returns a string representation of this destination virtual bool usedExtensionWord() { return false; } // Whether an extension word was used to represent this destination virtual unsigned char size() { return usedExtensionWord() ? 2 : 0; } // How many extra bytes this destination took up in the assembly }; class RegisterDest : public Dest { // Destination representing a register (r14) public: virtual std::string toString(); virtual void set(short value); virtual void setByte(unsigned char value); virtual short value(); virtual unsigned char valueByte(); RegisterDest(unsigned short reg_) : reg(reg_) {} unsigned short reg; }; class RegisterOffsetDest : public RegisterDest { // Destination representing the memory address at a register plus an offset (0x40(r14)) public: virtual std::string toString(); virtual bool usedExtensionWord() { return true; } virtual void set(short value); virtual void setByte(unsigned char value); virtual short value(); virtual unsigned char valueByte(); RegisterOffsetDest(unsigned short reg_, short offset_) : RegisterDest(reg_), offset(offset_) { } short offset; }; class AbsoluteDest : public Dest { // Destination that is just a memory address (&0x4400) public: virtual std::string toString(); virtual bool usedExtensionWord() { return true; } virtual void set(short value); virtual void setByte(unsigned char value); virtual unsigned char valueByte(); AbsoluteDest(unsigned short address_) : address(address_) { } unsigned short address; }; extern State* s; #endif
[ "flat0103@gmail.com" ]
flat0103@gmail.com
19203a417004197a3b51e22fe5a3dc21d6bcd8c4
57f87cd5fb9448bc6cdbf10769365393efae3a00
/firmware_v5/telelogger/teleclient.h
a6433b87bd84452fb52cfd90b903677e97fb909f
[]
no_license
NatroNx/Freematics
6a366805aef406d6f4deae050414f9611bbe710e
011ae3212f57fdee7648eb34171e141c55a413ed
refs/heads/master
2020-03-25T02:15:51.919000
2018-07-31T13:14:23
2018-07-31T13:14:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,569
h
class TeleClient { public: virtual void reset() { txCount = 0; txBytes = 0; rxBytes = 0; } virtual bool notify(byte event, const char* serverKey, const char* payload = 0) { return true; } virtual bool connect() { return true; } virtual bool transmit(const char* packetBuffer, unsigned int packetSize) { return true; } virtual void inbound() {} virtual bool begin() { return true; } virtual void end() {} uint32_t txCount = 0; uint32_t txBytes = 0; uint32_t rxBytes = 0; uint32_t lastSyncTime = 0; uint32_t lastSentTime = 0; uint16_t feedid = 0; }; class TeleClientUDP : public TeleClient { public: bool notify(byte event, const char* serverKey, const char* payload = 0); bool connect(); bool transmit(const char* packetBuffer, unsigned int packetSize); void inbound(); bool verifyChecksum(char* data); #if NET_DEVICE == NET_WIFI UDPClientWIFI net; #elif NET_DEVICE == NET_SIM800 UDPClientSIM800 net; #elif NET_DEVICE == NET_SIM5360 UDPClientSIM5360 net; #elif NET_DEVICE == NET_SIM7600 UDPClientSIM7600 net; #else NullClient net; #endif }; class TeleClientHTTP : public TeleClient { public: bool connect(); bool transmit(const char* packetBuffer, unsigned int packetSize); #if NET_DEVICE == NET_WIFI HTTPClientWIFI net; #elif NET_DEVICE == NET_SIM800 HTTPClientSIM800 net; #elif NET_DEVICE == NET_SIM5360 HTTPClientSIM5360 net; #elif NET_DEVICE == NET_SIM7600 HTTPClientSIM7600 net; #else NullClient net; #endif };
[ "stanleyhuangyc@gmail.com" ]
stanleyhuangyc@gmail.com
376f659de9de4170c19135d4e5e6f4fa7d95e938
bc33abf80f11c4df023d6b1f0882bff1e30617cf
/CPP/other/李泉彰/hhh.cpp
0e114bad33f893d5b9c3e166e74c22c9172ffe76
[]
no_license
pkuzhd/ALL
0fad250c710b4804dfd6f701d8f45381ee1a5d11
c18525decdfa70346ec32ca2f47683951f4c39e0
refs/heads/master
2022-07-11T18:20:26.435000
2019-11-20T13:25:24
2019-11-20T13:25:24
119,031,607
0
0
null
2022-06-21T21:10:42
2018-01-26T09:19:23
C++
UTF-8
C++
false
false
6,060
cpp
#include <stdio.h> #include <iostream> using namespace std; int qipan[15][15] = { 0 }; int times = 0; int print(); bool is_win(int x, int y, int flag); bool is_near(int x, int y); bool AI_set(int flag); int calc_value(int x, int y, int flag, int depth, int _max_value); int qixing(int x, int y); int main(int argc, char **argv) { int flag = 1; while (true) { ++times; print(); int x, y; if (flag == 1) { while (true) { cin >> x >> y; if (!qipan[x][y] || x < 0 || x >= 15 || y < 0 || y >= 15) break; } qipan[x][y] = flag; if (is_win(x, y, flag)) break; } else { if (AI_set(flag)) break; } flag *= -1; } if (flag == 1) { printf("black\n"); } else { printf("white\n"); } system("pause"); return 0; } int print() { for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) cout << (qipan[i][j] ? (qipan[i][j] == 1 ? "*" : "#") : "0"); cout << endl; } cout << endl; return 0; } bool is_win(int x, int y, int flag) { int number = 1; for (int i = x + 1; i < 15; ++i) { if (qipan[i][y] == flag) ++number; else break; } for (int i = x - 1; i >= 0; --i) { if (qipan[i][y] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int i = y + 1; i < 15; ++i) { if (qipan[x][i] == flag) ++number; else break; } for (int i = y - 1; i >= 0; --i) { if (qipan[x][i] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int j = 1; x + j < 15 && y + j < 15; ++j) { if (qipan[x + j][y + j] == flag) ++number; else break; } for (int j = 1; x - j >= 0 && y - j >= 0; ++j) { if (qipan[x - j][y - j] == flag) ++number; else break; } if (number >= 5) return true; number = 1; for (int j = 1; x + j < 15 && y - j >= 0; ++j) { if (qipan[x + j][y - j] == flag) ++number; else break; } for (int j = 1; x - j >= 0 && y + j < 15; ++j) { if (qipan[x - j][y + j] == flag) ++number; else break; } if (number >= 5) return true; return false; } bool is_near(int x, int y) { // cout << x << " " << y << endl; int _near = 2; for (int i = (x - _near >= 0 ? x - _near : 0); i <= (x + _near < 15 ? x + _near : 14); ++i) { for (int j = (y - _near >= 0 ? y - _near : 0); j <= (y + _near < 15 ? y + _near : 14); ++j) { if (qipan[i][j]) return true; } } return false; } bool AI_set(int flag) { int max_value = -10000000; int x = 7, y = 7; for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (qipan[i][j]) continue; if (!is_near(i, j)) continue; int t_value = calc_value(i, j, flag, 0, max_value); if (is_win(i, j, flag)) { qipan[i][j] = flag; return true; } if (t_value > max_value) { max_value = t_value; x = i; y = j; } } } qipan[x][y] = flag; cout << x << " " << y << " " << flag << " " << is_win(x, y, flag)<< endl; return false; } int calc_value(int x, int y, int flag, int depth, int _max_value) { int _value = 0; qipan[x][y] = flag; if (depth < 4) { int max_value = -10000000; for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (qipan[i][j] || !is_near(i, j)) continue; int t_value = calc_value(i, j, -flag, depth + 1, max_value); if (t_value > -_max_value) { qipan[x][y] = 0; return t_value; } if (is_win(i, j, -flag)) { qipan[x][y] = 0; return -10000000; } if (t_value > max_value) { max_value = t_value; } } } _value -= max_value; } else _value += qixing(x, y); qipan[x][y] = 0; return _value; } int qixing(int x, int y) { int flag = qipan[x][y]; bool dead = false; int number = 1; int _value = 0; int sz_qixing[2][6] = { 0 }; // x 方向 number = 1; dead = false; for (int i = x + 1; ; ++i) { if (i < 15 && qipan[i][y] == flag) ++number; else { if (i >= 15 || qipan[i][y]) dead = true; break; } } for (int i = x - 1; i >= 0; --i) { if (i >= 0 && qipan[i][y] == flag) ++number; else { if ((i < 0 || qipan[i][y]) && dead) break; else { if (dead || qipan[i][y]) dead = true; ++sz_qixing[dead][number]; } } } // y方向 number = 1; dead = false; for (int i = y + 1; ; ++i) { if (i < 15 && qipan[x][i] == flag) ++number; else { if (i >= 15 || qipan[x][i]) dead = true; break; } } for (int i = y - 1; i >= 0; --i) { if (i >= 0 && qipan[x][i] == flag) ++number; else { if ((i < 0 || qipan[x][i]) && dead) break; else { if (dead || qipan[x][i]) dead = true; ++sz_qixing[dead][number]; } } } // x y 方向 number = 1; dead = false; for (int i = 1; ; ++i) { if (x + i < 15 && y + i < 15 && qipan[x + i][y + i] == flag) ++number; else { if (x + i >= 15 || y + i >= 15 || qipan[x + i][y + i]) dead = true; break; } } for (int i = 1; ; ++i) { if (x - i >= 0 && y - i >= 0 && qipan[x - i][y - i] == flag) ++number; else { if ((x - i < 0 || y - i < 0 || qipan[x - i][y - i]) && dead) break; else { if (dead || qipan[x - i][y - i]) dead = true; ++sz_qixing[dead][number]; } } } // x -y 方向 number = 1; dead = false; for (int i = 1; ; ++i) { if (x + i < 15 && y - i >= 0 && qipan[x + i][y - i] == flag) ++number; else { if (x + i >= 15 || y - i < 0 || qipan[x + i][y - i]) dead = true; break; } } for (int i = 1; ; ++i) { if (x - i >= 0 && y + i < 15 && qipan[x - i][y + i] == flag) ++number; else { if ((x - i < 0 || y + i >= 15 || qipan[x - i][y + i]) && dead) break; else { if (dead || qipan[x - i][y + i]) dead = true; ++sz_qixing[dead][number]; } } } if (sz_qixing[false][4] || (sz_qixing[true][4] + sz_qixing[false][3]) >= 2) _value += 1000000; _value += sz_qixing[false][3] * 10000; _value += sz_qixing[true][3] * 1000; _value += sz_qixing[false][2] * 100; _value += sz_qixing[true][2] * 10; return _value; }
[ "pkuzhd@pku.edu.cn" ]
pkuzhd@pku.edu.cn
cb70bcdd5ff36e2a7d758db629c0ae1cdf415f34
6cc00c07a75bf18a2b1824383c3acc050098d9ed
/CodeChef/Easy/E0034.cpp
8b0e042dd591f11ae41cddc5d38bbbd3f36fd170
[ "MIT" ]
permissive
Mohammed-Shoaib/Coding-Problems
ac681c16c0f7c6d83f7cb46be71ea304d238344e
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
refs/heads/master
2022-06-14T02:24:10.316000
2022-03-20T20:04:16
2022-03-20T20:04:16
145,226,886
75
31
MIT
2020-10-02T07:46:58
2018-08-18T14:31:33
C++
UTF-8
C++
false
false
372
cpp
// Problem Code: ALEXNUMB #include <iostream> #include <vector> using namespace std; long magicPairs(vector<int> &a){ long N = a.size(); return N*(N-1)/2; } int main(){ int T, n, num; vector<int> a; cin >> T; while(T--){ cin >> n; for(int i=0 ; i<n ; i++){ cin >> num; a.push_back(num); } cout << magicPairs(a) << endl; a.clear(); } return 0; }
[ "shoaib98libra@gmail.com" ]
shoaib98libra@gmail.com
0f14955c67c8ded4e0b25301b31b8648ae16b52f
4985aad8ecfceca8027709cf488bc2c601443385
/build/Android/Debug/app/src/main/include/Fuse.Resources.Resour-7da5075.h
bb740adfa48c8d9b5e34d9b3bf2a2c23882e8030
[]
no_license
pacol85/Test1
a9fd874711af67cb6b9559d9a4a0e10037944d89
c7bb59a1b961bfb40fe320ee44ca67e068f0a827
refs/heads/master
2021-01-25T11:39:32.441000
2017-06-12T21:48:37
2017-06-12T21:48:37
93,937,614
0
0
null
null
null
null
UTF-8
C++
false
false
883
h
// This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Nodes/1.0.2/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Fuse{namespace Resources{struct ResourceConverters;}}} namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{ namespace Fuse{ namespace Resources{ // internal static class ResourceConverters :3538 // { uClassType* ResourceConverters_typeof(); void ResourceConverters__Get_fn(uType* __type, uObject** __retval); struct ResourceConverters : uObject { static uSStrong< ::g::Uno::Collections::Dictionary*> _converters_; static uSStrong< ::g::Uno::Collections::Dictionary*>& _converters() { return ResourceConverters_typeof()->Init(), _converters_; } static uObject* Get(uType* __type); }; // } }}} // ::g::Fuse::Resources
[ "newreality64@gmail.com" ]
newreality64@gmail.com
33fa115e3d756b655d4b8fd3fc840eb94198c8be
012784e8de35581e1929306503439bb355be4c4f
/problems/37. 解数独/3.cc
84bf778bd32645766fc6275be6ca3a9a288a96dc
[]
no_license
silenke/my-leetcode
7502057c9394e41ddeb2e7fd6c1b8261661639e0
d24ef0970785c547709b1d3c7228e7d8b98b1f06
refs/heads/master
2023-06-05T02:05:48.674000
2021-07-01T16:18:29
2021-07-01T16:18:29
331,948,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
cc
#include "..\..\leetcode.h" class Solution { public: void solveSudoku(vector<vector<char>>& board) { row = col = box = vector<int>(9); int count = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') count++; else fill(i, j, i / 3 * 3 + j / 3, board[i][j] - '1'); } } dfs(count, board); } private: vector<int> row, col, box; void fill(int i, int j, int k, int n) { row[i] |= 1 << n; col[j] |= 1 << n; box[k] |= 1 << n; } void zero(int i, int j, int k, int n) { row[i] &= ~(1 << n); col[j] &= ~(1 << n); box[k] &= ~(1 << n); } int possible(int i, int j) { return ~(row[i] | col[j] | box[i / 3 * 3 + j / 3]) & ((1 << 9) - 1); } pair<int, int> next(vector<vector<char>>& board) { pair<int, int> res; int min_count = INT_MAX; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') continue; int c = count(possible(i, j)); if (c < min_count) { min_count = c; res = {i, j}; } } } return res; } bool dfs(int count, vector<vector<char>>& board) { if (count == 0) return true; auto [i, j] = next(board); int p = possible(i, j); int k = i / 3 * 3 + j / 3; while (p) { int n = __builtin_ctz(p & -p); board[i][j] = n + '1'; fill(i, j, k, n); if (dfs(count - 1, board)) return true; board[i][j] = '.'; zero(i, j, k, n); p &= p - 1; } return false; } int count(int p) { int count = 0; while (p) { count++; p &= p - 1; } return count; } };
[ "2595756713@qq.com" ]
2595756713@qq.com
b68966c17d5045233b5646054d6eadc547b96397
9d34ceb787b7e7a0aa9d242e401f0b13c2e4ea94
/JoaoScaravonatti.cpp
7278f4a435cc05195b6a61560ed065092c4ef52a
[]
no_license
joaoscaravonatti/projeto-final-algoritmos
31a5d2ed39afd6d918894869e2c43972f44f0be7
23f6d11aacbe714471cc064490da6a634ac0bfa9
refs/heads/master
2020-03-30T09:37:17.994000
2018-10-01T12:21:17
2018-10-01T12:21:17
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
6,611
cpp
#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<locale.h> #include<windows.h> #define tam 1000 struct cliente{ int codigo; char nome[50]; char sexo[20]; char dataNascimento[12]; char cpf[12]; char telefone[11]; char email[100]; }; int id = 0; int i = 0; struct cliente clientes[tam]; void cadastrar(){ id++; clientes[id].codigo = id; printf("\nColoque o nome completo: "); scanf(" %[^\n]s",&clientes[id].nome); printf("\nColoque o CPF sem formatação: "); scanf("%s",&clientes[id].cpf); printf("\nColoque o sexo (masculino/feminino): "); scanf("%s",&clientes[id].sexo); printf("\nColoque a data de nascimento no formato XX/XX/XXXX: "); scanf("%s",&clientes[id].dataNascimento); printf("\nColoque o telefone sem formatação: "); scanf("%s",&clientes[id].telefone); printf("\nColoque o email: "); scanf("%s",&clientes[id].email); } void excluir(int codigo){ clientes[codigo].codigo = 0; strcpy(clientes[codigo].nome,""); } void consultarCod(int codigo){ int verificar=0; system("cls"); if(codigo != 0){ for(i=0;i<tam;i++){ if(clientes[i].codigo == codigo){ printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[i].codigo,clientes[i].nome,clientes[i].sexo,clientes[i].dataNascimento,clientes[i].cpf,clientes[i].telefone,clientes[i].email); verificar++; } } } if(verificar==0){ printf("\nEsse cliente não está cadastrado!"); } printf("\n_______________________________\n"); } void consultarNome(char nome[]){ int codigo=0; system("cls"); if(strcmp(nome,"")!=0){ for(i=0;i<tam;i++){ if(strcmp(nome,clientes[i].nome)==0){ codigo = i; printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[codigo].codigo,clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email); printf("\n_______________________________\n"); } } } if(codigo == 0){ printf("\nEsse cliente não está cadastrado!\n"); } } void listar(){ system("cls"); for(i=0;i<tam;i++){ if(clientes[i].codigo != 0){ printf("\nCliente de código %i: %s\n",clientes[i].codigo,clientes[i].nome); printf("_______________________________\n"); } } } void vrau(){ clientes[1].codigo = 1; strcpy(clientes[1].nome,"juca silva"); strcpy(clientes[1].sexo,"masculino"); strcpy(clientes[1].dataNascimento,"18/01/2000"); strcpy(clientes[1].cpf,"08816690917"); strcpy(clientes[1].telefone,"49999743090"); strcpy(clientes[1].email,"jvscaravonatti@gmail.com"); clientes[2].codigo = 2; strcpy(clientes[2].nome,"juca silva"); strcpy(clientes[2].sexo,"masculino"); strcpy(clientes[2].dataNascimento,"18/01/2000"); strcpy(clientes[2].cpf,"08816690917"); strcpy(clientes[2].telefone,"49999743090"); strcpy(clientes[2].email,"jvscaravonatti@gmail.com"); } void alterar(int codigo){ char opcao[1]; char confirm[1]; confirm[0] = '0'; if(codigo != 0){ do{ printf("\nQual informação deseja alterar?\n"); printf("\n1 - Nome: %s\n2 - Sexo: %s\n3 - Data de nascimento: %s\n4 - CPF: %s\n5 - Telefone: %i\n6 - E-mail: %s\nSua opção: ",clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email); fflush(stdin); opcao[0] = getche(); switch(opcao[0]){ case '1': printf("\nColoque o novo nome: "); scanf(" %[^\n]s",&clientes[codigo].nome); break; case '2': printf("\nColoque o novo sexo: "); scanf("%s",clientes[codigo].sexo); break; case '3': printf("\nColoque a nova data de nascimento: "); scanf("%s",&clientes[codigo].dataNascimento); break; case '4': printf("\nColoque o novo CPF: "); scanf("%s",&clientes[codigo].cpf); break; case '5': printf("\nColoque o novo telefone: "); scanf("%s",&clientes[codigo].telefone); break; case '6': printf("\nColoque o novo e-mail: "); scanf("%s",&clientes[codigo].email); break; default: printf("\nOpção inválida!"); } printf("\nContinuar editando? 0 para sim e 1 para não: "); confirm[0] = getche(); }while(confirm[0] !='1'); } } int main(){ //vrau(); setlocale(LC_ALL,"portuguese"); char opcao[1]; char flag[1]; int param=0; char paramChar[50]; char escolha[1]; flag[0] = '0'; printf("\nCadstro de clientes HyperSoft\n_____________________________\n"); Sleep(500); do{ printf("\n\nSelecione uma opção:\n\n"); printf("1 - Cadastro do cliente\n"); printf("2 - Alterar dados do cliente\n"); printf("3 - Exclusão de cliente\n"); printf("4 - Consultar cliente\n"); printf("5 - Listar clientes\n"); printf("6 - Sair\n"); printf("Sua opção: "); fflush(stdin); opcao[0] = getche(); system("cls"); switch(opcao[0]){ system("cls"); case '1': cadastrar(); break; case '2': printf("\nInsira o código do cliente a ser alterado: "); scanf("%i",&param); alterar(param); break; case '3': printf("\nInsira o código do cliente a ser exclúido: "); scanf("%i",&param); excluir(param); break; case '4': printf("\n1 - Consultar por nome\n2 - Consultar por código\n3 - Voltar\nSua opção: "); fflush(stdin); escolha[0] = getche(); switch(escolha[0]){ case '1': printf("\nInsira o nome do cliente a ser consultado: "); scanf(" %[^\n]s",&paramChar); consultarNome(paramChar); break; case '2': printf("\nInsira o código do cliente a ser consultado: "); scanf("%i",&param); consultarCod(param); break; case '3': break; default: printf("\nOpção mal informada"); } break; case '5': listar(); break; case '6': printf("\nPressione 1 para sair: "); flag[0] = getche(); break; default: printf("\nEstá opção não existe\n"); break; } }while(flag[0] != '1'); printf("\n\aFIM"); return 0; }
[ "jvscaravonatti@gmail.com" ]
jvscaravonatti@gmail.com
95790908e8d1d2460d9b4d434899e825f5607a16
34bbcd08f3d14f265c507b49746e2997d74ec519
/SFML-MashSim/Spring.cpp
eef2414f96c2c0fe7ea2e01d2dc4757e9a9b4d57
[]
no_license
SenKetZu/SFML-MashSim
cd866d6dc083d1b064f365511fbdcb79aca7f8b0
532b6ca3341888efc0b2a62bdc59301a92075711
refs/heads/master
2023-05-27T23:01:36.185000
2021-06-09T02:57:41
2021-06-09T02:57:41
374,864,394
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include "Spring.h" #include "DrawAgent.h" Spring::Spring(MassPoint& anchor, MassPoint& exterior): _Anchor(anchor), _Exterior(exterior), _Spring(exterior<<=anchor), _SpringLenght(100.0f), _K(10.0f), _Damping(1.0f), _TimeSP(.01f), //variables trancicion _SpringForce(0.0f), _DampForce(0.0f), _Accel(0.0f), _Vel(0.0f), _Force(0.0f) {} void Spring::Update() { //get timesp _TimeSP = DrawAgent::getInstance().DeltaTime()*100.0f; //calcular spring _Spring = _Exterior <<= _Anchor; //calculo de fuerzas _SpringForce = _K * (_Spring.getMagnitude() - _SpringLenght); _DampForce = _Damping * _Vel; _Force = _SpringForce +10 /*massXgrav*/ - _DampForce; _Accel = _Force / 1 /*mass*/; _Vel += _Accel * _TimeSP; //push masspoint _Exterior.push(MathVector(_Vel*_TimeSP,_Spring.getAngle())); }
[ "fahler114@gmail.com" ]
fahler114@gmail.com
a4107844dad660b1e38707bc33b03c52f16b4cbd
61442c0297fef23453b7bc43ab5bbd6a52c95fa7
/grappletation/Source/Grappletation/Gem.cpp
44c2698bb81fe1bfc4a986a9d39c8944aae59d65
[]
no_license
AshleyThew/GameProgramming
c9cf634ef81dd7e1753b3ef45d56a6ee38b9a072
22032cf7b141222d498c083527e81a854864e694
refs/heads/main
2023-08-23T15:51:59.141000
2021-10-25T10:01:57
2021-10-25T10:01:57
420,814,528
1
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
#include "Gem.h" #include "Entity.h" #include "Renderer.h" #include "Sprite.h" Gem::Gem(int x, int y) { id.x = x; id.y = y; } Gem::~Gem() { } bool Gem::Initialise(Renderer& renderer, const char* gemType, float scale) { m_pSprite = renderer.CreateSprite(gemType); m_pSprite->SetScale(scale); m_position.x = (scale * 8) + (id.x * scale * 16); m_position.y = (scale * 8) + (id.y * scale * 16); Reset(); return false; } void Gem::Process(float deltaTime) { Entity::Process(deltaTime); } void Gem::Draw(Renderer& renderer) { Entity::Draw(renderer); } bool Gem::GetCollected() { return collected; } void Gem::SetCollected() { collected = true; SetDead(true); } void Gem::Reset() { collected = false; SetDead(false); } Vector2 Gem::GetID() { return id; }
[ "ashl.e.thew@gmail.com" ]
ashl.e.thew@gmail.com
6121382505592535a09b239e90ed50ff680fc2e6
91fcb836ee5af301a2125624ddb96cf49b19494d
/queue/restoreQueue.cpp
2e49fc23784e34f26b2deade801fe414d1b21cb1
[]
no_license
hellozxs/C
fe11911222595ffcdc425218407711bbe59a3b10
1f3815966a8d5668f149ff9957672819a2d2b57d
refs/heads/master
2020-04-06T07:03:14.596000
2016-09-18T10:25:27
2016-09-18T10:25:27
65,121,708
0
0
null
null
null
null
UTF-8
C++
false
false
1,272
cpp
//对一个队列执行以下操作后,发现输出为 1,2,3,4,……,n // 操作:(如果队列不为空) // 1:取队头元素,放入队尾,将队头pop // 2;输出队头,将队头pop // 输入n,求原始队列? // //输入:z -> 表示将要输入的数据的个数 //输入z个n的具体值 #include <iostream> #include <vector> using namespace std; typedef struct MyData { int _data; bool _flag; }MyData; int main() { int z; cin >> z; vector<int> arr(z); for (int i = 0; i < z; i++) { cin >> arr[i]; } int i = 0; for (i = 0; i< z; i++) { if (arr[i] == 1) cout << 1 << endl; else { vector<MyData> a(arr[i]); int j = 0; int count = arr[i]; int tmp = 1; for (; count--; j ++) { int flag = 1; while (flag) { if (j == arr[i]) j = 0; if (a[j]._flag == false) flag--; j++; } if (j == arr[i]) j = 0; while (a[j]._flag == true) { j++; if (j == arr[i]) j = 0; } a[j]._data =tmp++; a[j]._flag = true; } int k = 0; for (; k < arr[i]; k++) cout << a[k]._data << " "; cout << endl; } } return 0; }
[ "526591420@qq.com" ]
526591420@qq.com
0e5baca75fdd2c54621542f6cf7b7bde1bdf4164
fdebe3129bb47afc1924e45e1ed3c97ee9213ac4
/GA-TSP/test.cpp
3bbfaacce92afe022185cf0c23ee0c0d44e5e17d
[]
no_license
SYSU532/artificial-intelligence
3604e07b3670555d65ac2d36dbbf458f69658a07
e0847fb1d181415137580e1c3e529e2120ed09d4
refs/heads/master
2020-04-05T20:26:14.953000
2019-01-11T12:50:27
2019-01-11T12:50:27
157,179,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
#include <node.h> namespace demo{ using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Number; // Method1 实现一个 输出"hello world ONE !" 的方法 void Method1(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !")); } // Method2 实现一个 加一 的方法 void Method2(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); Local<Number> value = Local<Number>::Cast(args[0]); double num = value->NumberValue() + 1; char buf[128] = {0}; sprintf(buf,"%f", num); args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf)); } void init(Local<Object> exports){ NODE_SET_METHOD(exports, "hello1", Method1); NODE_SET_METHOD(exports, "addOne", Method2); } NODE_MODULE(addon, init) }
[ "chenmliang@mail2.sysu.edu.cn" ]
chenmliang@mail2.sysu.edu.cn
921e1b5170f7720987763bafac17b4348a900a5c
9053a16ac04bc9b1273c8d8c31ab9d6e299ba1c6
/unittest/test_boxqp.cpp
c40951d78f74638bfead8aaa863057b94743abff
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ggory15/crocoddyl
7b734313b46a137b44f33d5448057507e23a7fa1
4708428676f596f93ffe2df739faeb5cc38d2326
refs/heads/master
2021-02-08T06:08:35.739000
2020-08-03T15:06:49
2020-08-05T13:46:45
244,117,610
0
0
BSD-3-Clause
2020-03-01T09:02:49
2020-03-01T09:02:48
null
UTF-8
C++
false
false
6,040
cpp
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2019-2020, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include <boost/random.hpp> #include "crocoddyl/core/solvers/box-qp.hpp" #include "unittest_common.hpp" using namespace boost::unit_test; using namespace crocoddyl::unittest; void test_constructor() { // Setup the test std::size_t nx = random_int_in_range(1, 100); crocoddyl::BoxQP boxqp(nx); // Test dimension of the decision vector BOOST_CHECK(boxqp.get_nx() == nx); } void test_unconstrained_qp_with_identity_hessian() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx); Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx); Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // Checking the solution of the problem. Note that it the negative of the gradient since Hessian // is identity matrix BOOST_CHECK((sol.x + gradient).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized case double reg = random_real_in_range(1e-9, 1e2); boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); BOOST_CHECK((sol_reg.x + gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nx); BOOST_CHECK(sol.clamped_idx.size() == 0); BOOST_CHECK(sol_reg.free_idx.size() == nx); BOOST_CHECK(sol_reg.clamped_idx.size() == 0); } void test_unconstrained_qp() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd H = Eigen::MatrixXd::Random(nx, nx); Eigen::MatrixXd hessian = H.transpose() * H; hessian = 0.5 * (hessian + hessian.transpose()).eval(); Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx); Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // Checking the solution against the KKT solution Eigen::VectorXd xkkt = -hessian.inverse() * gradient; BOOST_CHECK((sol.x - xkkt).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized KKT problem double reg = random_real_in_range(1e-9, 1e2); boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); Eigen::VectorXd xkkt_reg = -(hessian + reg * Eigen::MatrixXd::Identity(nx, nx)).inverse() * gradient; BOOST_CHECK((sol_reg.x - xkkt_reg).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nx); BOOST_CHECK(sol.clamped_idx.size() == 0); BOOST_CHECK(sol_reg.free_idx.size() == nx); BOOST_CHECK(sol_reg.clamped_idx.size() == 0); } void test_box_qp_with_identity_hessian() { std::size_t nx = random_int_in_range(2, 5); crocoddyl::BoxQP boxqp(nx); boxqp.set_reg(0.); Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx); Eigen::VectorXd gradient = Eigen::VectorXd::Ones(nx); for (std::size_t i = 0; i < nx; ++i) { gradient(i) *= random_real_in_range(-1., 1.); } Eigen::VectorXd lb = Eigen::VectorXd::Zero(nx); Eigen::VectorXd ub = Eigen::VectorXd::Ones(nx); Eigen::VectorXd xinit = Eigen::VectorXd::Random(nx); crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit); // The analytical solution is the a bounded, and negative, gradient Eigen::VectorXd negbounded_gradient(nx), negbounded_gradient_reg(nx); std::size_t nf = nx, nc = 0, nf_reg = nx, nc_reg = 0; double reg = random_real_in_range(1e-9, 1e2); for (std::size_t i = 0; i < nx; ++i) { negbounded_gradient(i) = std::max(std::min(-gradient(i), ub(i)), lb(i)); negbounded_gradient_reg(i) = std::max(std::min(-gradient(i) / (1 + reg), ub(i)), lb(i)); if (negbounded_gradient(i) != -gradient(i)) { nc += 1; nf -= 1; } if (negbounded_gradient_reg(i) != -gradient(i) / (1 + reg)) { nc_reg += 1; nf_reg -= 1; } } // Checking the solution of the problem. Note that it the negative of the gradient since Hessian // is identity matrix BOOST_CHECK((sol.x - negbounded_gradient).isMuchSmallerThan(1.0, 1e-9)); // Checking the solution against a regularized case boxqp.set_reg(reg); crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit); BOOST_CHECK((sol_reg.x - negbounded_gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9)); // Checking the all bounds are free and zero clamped BOOST_CHECK(sol.free_idx.size() == nf); BOOST_CHECK(sol.clamped_idx.size() == nc); BOOST_CHECK(sol_reg.free_idx.size() == nf_reg); BOOST_CHECK(sol_reg.clamped_idx.size() == nc_reg); } void register_unit_tests() { framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_constructor))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp_with_identity_hessian))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp))); framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_box_qp_with_identity_hessian))); } bool init_function() { register_unit_tests(); return true; } int main(int argc, char* argv[]) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }
[ "carlos.mastalli@gmail.com" ]
carlos.mastalli@gmail.com
a702a5d40a3a672624e691115d63b4a004c979d0
7aa189c718f8a63c256685a435d027ace3833f6b
/include/ogonek/error.h++
ca7ff1f2bc1d6ac11fcbdaacee61fbdef1c7430d
[ "CC0-1.0" ]
permissive
rmartinho/ogonek
d5523145108de1255298a17c1c25065beb19b82c
0042f30c6c674effd21d379c53658c88054c58b9
refs/heads/devel
2020-05-21T15:17:39.490000
2019-09-29T10:58:31
2019-09-29T10:58:31
8,255,019
16
3
null
null
null
null
UTF-8
C++
false
false
4,549
// Ogonek // // Written in 2017 by Martinho Fernandes <ogonek@rmf.io> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. /** * Error handling * ============== */ #ifndef OGONEK_ERROR_HPP #define OGONEK_ERROR_HPP #include <ogonek/error_fwd.h++> #include <ogonek/concepts.h++> #include <ogonek/types.h++> #include <ogonek/encoding.h++> #include <range/v3/range_concepts.hpp> #include <range/v3/range_traits.hpp> #include <stdexcept> namespace ogonek { /** * .. class:: unicode_error * * The base class for all Unicode-related errors. */ struct unicode_error : virtual std::exception { char const* what() const noexcept override { return u8"Unicode error"; } }; /** * .. class:: template <EncodingForm Encoding>\ * encode_error : virtual unicode_error * * :thrown: when an error occurs during an encoding operation. */ template <typename Encoding> struct encode_error : virtual unicode_error { CONCEPT_ASSERT(EncodingForm<Encoding>()); char const* what() const noexcept override { return u8"encoding failed "; } }; /** * .. class:: template <EncodingForm Encoding>\ * decode_error : virtual unicode_error * * :thrown: when an error occurs during a decoding operation. */ template <typename Encoding> struct decode_error : virtual unicode_error { CONCEPT_ASSERT(EncodingForm<Encoding>()); char const* what() const noexcept override { return u8"decoding failed"; } }; /** * .. var:: auto assume_valid * * A tag used to request that encoding/decoding functions assume the * input has been validated before. * * .. warning:: * * Using this tag with input that isn't actually valid yields * undefined behavior. */ struct assume_valid_t {} constexpr assume_valid {}; /** * .. var:: auto discard_errors * * An error handler for encoding/decoding functions that simply * discards the portions of the input that have errors. */ struct discard_errors_t { template <typename E> optional<code_point> operator()(E) const { return {}; } } constexpr discard_errors {}; CONCEPT_ASSERT(EncodeErrorHandler<discard_errors_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<discard_errors_t, archetypes::EncodingForm>()); /** * .. var:: auto replace_errors * * An error handler for encoding/decoding functions that replaces * portions of the input that have errors with a replacement character. * When decoding, this is |u-fffd|, but when encoding and the target * doesn't support it, some encoding-specific character is used * instead. */ struct replace_errors_t { template <typename Encoding, CONCEPT_REQUIRES_(EncodingForm<Encoding>())> optional<code_point> operator()(encode_error<Encoding>) const { return replacement_character_v<Encoding>; } template <typename Encoding, CONCEPT_REQUIRES_(EncodingForm<Encoding>())> optional<code_point> operator()(decode_error<Encoding>) const { return { U'\uFFFD' }; } } constexpr replace_errors {}; CONCEPT_ASSERT(EncodeErrorHandler<replace_errors_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<replace_errors_t, archetypes::EncodingForm>()); /** * .. var:: auto throw_error * * An error handler for encoding/decoding functions that throws when an * error is found in the input. */ struct throw_error_t { template <typename E> optional<code_point> operator()(E e) const { throw e; } } constexpr throw_error {}; CONCEPT_ASSERT(EncodeErrorHandler<throw_error_t, archetypes::EncodingForm>()); CONCEPT_ASSERT(DecodeErrorHandler<throw_error_t, archetypes::EncodingForm>()); } // namespace ogonek #endif // OGONEK_ERROR_HPP
[ "rmf@rmf.io" ]
rmf@rmf.io
fdb075167409c531a8ffa63f4eb5c358ff9f4c08
8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340
/src/chila/lib/node/util.hpp
51b98169af1da8738e7ec4fea35fe3d0da6b3455
[]
no_license
blockspacer/chila
6884a540fafa73db37f2bf0117410c33044adbcf
b95290725b54696f7cefc1c430582f90542b1dec
refs/heads/master
2021-06-05T10:22:53.536000
2016-08-24T15:07:49
2016-08-24T15:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,721
hpp
/* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra (chilabot@gmail.com) * (C.I.: 1.439.390 - Paraguay) */ #ifndef CHILA_LIB_NODE__UTIL_HPP #define CHILA_LIB_NODE__UTIL_HPP #include <chila/lib/misc/util.hpp> #include "exceptions.hpp" #define my_assert CHILA_LIB_MISC__ASSERT #define CHILA_META_NODE__DEF_CHECK_BASES_ELEM(n, data, elem) \ chila::lib::node::checkAndAdd(list, [&]{ elem::check(newData.get()); }); #define CHILA_META_NODE__DEF_CHECK_BASES(Bases, defMyCheck) \ BOOST_PP_IF(defMyCheck, chila::lib::node::CheckDataUPtr createCheckData(chila::lib::node::CheckData *data) const;, ); \ BOOST_PP_IF(defMyCheck, void myCheck(chila::lib::node::CheckData *data = nullptr) const;, ); \ void check(chila::lib::node::CheckData *data = nullptr) const override \ { \ chila::lib::node::CheckExceptionList list; \ auto newData = BOOST_PP_IF(defMyCheck, createCheckData(data), chila::lib::node::CheckDataUPtr()); \ BOOST_PP_SEQ_FOR_EACH(CHILA_META_NODE__DEF_CHECK_BASES_ELEM,,Bases) \ BOOST_PP_IF(defMyCheck, BOOST_PP_IDENTITY(\ chila::lib::node::checkAndAdd(list, [&]{ myCheck(newData.get()); }); \ ), BOOST_PP_EMPTY)(); \ if (!list.exceptions.empty()) throw list; \ } #define CHILA_META_NODE__DEF_CHECK \ void check(chila::lib::node::CheckData *data = nullptr) const override; #include "nspDef.hpp" MY_NSP_START { template <typename CheckFun> void checkAndAdd(chila::lib::node::CheckExceptionList &list, const CheckFun &checkFun) try { checkFun(); } catch (ExceptionWrapper &ex) { list.add(ex.ex); } catch (CheckExceptionList &ex) { list.add(ex); } catch (Exception &ex) { list.add(ex); } chila::lib::misc::Path getNodePath(const Node &node); // to avoid cyclical dependency template <typename Fun> inline auto catchThrow(const Node &node, const Fun &fun) -> decltype(fun()) try { return fun(); } catch (const boost::exception &ex) { ex << chila::lib::misc::ExceptionInfo::Path(getNodePath(node)); throw; } template <typename ToType, typename Node> inline const ToType &castNode(const Node &node) try { return catchThrow(node, [&]() -> const ToType& { return chila::lib::misc::dynamicCast<ToType>(node); }); } catch (const boost::exception &ex) { InvalidNode exx; insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom) insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo) insert_error_info(chila::lib::misc::ExceptionInfo::ActualType) insert_error_info(chila::lib::misc::ExceptionInfo::Path) BOOST_THROW_EXCEPTION(exx); } template <typename ToType, typename Node> inline ToType &castNode(Node &node) try { return catchThrow(node, [&]() -> ToType& { return chila::lib::misc::dynamicCast<ToType>(node); }); } catch (const boost::exception &ex) { InvalidNode exx; insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom) insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo) insert_error_info(chila::lib::misc::ExceptionInfo::ActualType) insert_error_info(chila::lib::misc::ExceptionInfo::Path) BOOST_THROW_EXCEPTION(exx); } NodeWithChildren &mainParent(NodeWithChildren &node); PathVec getReferences( NodeWithChildren &node, const chila::lib::misc::Path &path); void replaceReferences(NodeWithChildren &node, const PathVec &paths, const Node &newRefNode); } MY_NSP_END #include "nspUndef.hpp" #endif
[ "chilabot@gmail.com" ]
chilabot@gmail.com
f387d41d0e3251ca4e290372f77e819aa8f41c08
8c8ea797b0821400c3176add36dd59f866b8ac3d
/AOJ/aoj0578.cpp
9b35642e4fd0541224a11ccbbf275376f137bc2c
[]
no_license
fushime2/competitive
d3d6d8e095842a97d4cad9ca1246ee120d21789f
b2a0f5957d8ae758330f5450306b629006651ad5
refs/heads/master
2021-01-21T16:00:57.337000
2017-05-20T06:45:46
2017-05-20T06:45:46
78,257,409
0
0
null
null
null
null
UTF-8
C++
false
false
682
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <string> using namespace std; int N; bool isName(string shop, string board) { int m = board.length(); for(int step=1; step<=m; step++) { for(int i=0; i<m; i++) { string s = ""; for(int j=i; j<m; j+=step) { s += board[j]; } if(s.find(shop) != string::npos) return true; } } return false; } int main(void) { cin >> N; string shop, board; cin >> shop; int ans = 0; for(int i=0; i<N; i++) { cin >> board; if(isName(shop, board)) ans++; } cout << ans << endl; return 0; }
[ "okmt52@gmail.com" ]
okmt52@gmail.com
9b6b1ec168b70a357f4e47169b73b0f2e0538b9b
6565182c28637e21087007f09d480a70b387382e
/code/901.股票价格跨度.cpp
61b63105d48efcafe008368d50a272d85d3e8c15
[]
no_license
liu-jianhao/leetcode
08c070f0f140b2dd56cffbbaf25868364addfe53
7cbbe0585778517c88aa6ac1d2f2f8478cc931e5
refs/heads/master
2021-07-17T05:54:58.228000
2020-08-17T07:03:52
2020-08-17T07:03:52
188,854,718
1
1
null
null
null
null
UTF-8
C++
false
false
792
cpp
/* * @lc app=leetcode.cn id=901 lang=cpp * * [901] 股票价格跨度 */ class StockSpanner { public: StockSpanner() { } int next(int price) { if(_i == 0 || price < _prices.back()) { _dp.push_back(1); } else { int j = _i - 1; while(j >= 0 && price >= _prices[j]) { j -= _dp[j]; } _dp.push_back(_i - j); } ++_i; _prices.push_back(price); return _dp.back(); } private: vector<int> _dp; vector<int> _prices; int _i = 0; }; /** * Your StockSpanner object will be instantiated and called as such: * StockSpanner* obj = new StockSpanner(); * int param_1 = obj->next(price); */
[ "jianhaoliu17@gmail.com" ]
jianhaoliu17@gmail.com
c1be7ed8331d413fbb32c4f4da225eabb0c94905
2d4346d0da0a4145f6bcc91a8cb2c0ab4d669d7e
/chat-up-server/src/Authentication/AuthenticationService.h
b172c8a7281e736007294715851af51947b6b669
[]
no_license
xgallom/chat-up
5570d069a495acf6398bdf1f62b1fb1d91289376
7cb664ce745cf041fb508b04165d2179563aa010
refs/heads/master
2020-04-18T05:40:58.487000
2019-01-29T22:36:04
2019-01-29T22:36:04
167,287,878
0
0
null
null
null
null
UTF-8
C++
false
false
608
h
// // Created by xgallom on 1/27/19. // #ifndef CHAT_UP_AUTHENTICATIONSERVICE_H #define CHAT_UP_AUTHENTICATIONSERVICE_H #include <Messaging/Message.h> #include <Messaging/MessageSender.h> #include <Outcome.h> #include <Authentication/User.h> class AuthenticationStorage; class AuthenticationService { AuthenticationStorage &m_storage; User m_user = User(); public: AuthenticationService() noexcept; Outcome::Enum run(MessageSender &sender, const Message &message); bool registerUser(const User &user); User user() const noexcept; }; #endif //CHAT_UP_AUTHENTICATIONSERVICE_H
[ "gallo.milan.jr@gmail.com" ]
gallo.milan.jr@gmail.com
d906994d3f90133151039af0434882e3553ba719
1c02e13a776e5e8bc3e2a6182b5df4efb2c71d32
/core/unit_test/tstDeepCopy.hpp
b3fdab4da5ef0b61357d256cf996dae1b69884f0
[ "BSD-3-Clause" ]
permissive
junghans/Cabana
91b82827dd9fb8321bea9ea3750c196946a6aac0
7b9078f81bde68c949fd6ae913ce80eeaf0f8f8a
refs/heads/master
2021-06-14T09:57:01.658000
2019-01-04T22:24:45
2019-01-04T22:24:45
150,330,482
1
1
BSD-3-Clause
2019-01-07T16:24:20
2018-09-25T21:17:53
C++
UTF-8
C++
false
false
5,252
hpp
/**************************************************************************** * Copyright (c) 2018 by the Cabana authors * * All rights reserved. * * * * This file is part of the Cabana library. Cabana is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include <Cabana_DeepCopy.hpp> #include <Cabana_AoSoA.hpp> #include <Cabana_Types.hpp> #include <gtest/gtest.h> namespace Test { //---------------------------------------------------------------------------// // Check the data given a set of values. template<class aosoa_type> void checkDataMembers( aosoa_type aosoa, const float fval, const double dval, const int ival, const int dim_1, const int dim_2, const int dim_3 ) { auto slice_0 = aosoa.template slice<0>(); auto slice_1 = aosoa.template slice<1>(); auto slice_2 = aosoa.template slice<2>(); auto slice_3 = aosoa.template slice<3>(); for ( std::size_t idx = 0; idx < aosoa.size(); ++idx ) { // Member 0. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) for ( int k = 0; k < dim_3; ++k ) EXPECT_EQ( slice_0( idx, i, j, k ), fval * (i+j+k) ); // Member 1. EXPECT_EQ( slice_1( idx ), ival ); // Member 2. for ( int i = 0; i < dim_1; ++i ) EXPECT_EQ( slice_2( idx, i ), dval * i ); // Member 3. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) EXPECT_EQ( slice_3( idx, i, j ), dval * (i+j) ); } } //---------------------------------------------------------------------------// // Perform a deep copy test. template<class DstMemorySpace, class SrcMemorySpace, int DstVectorLength, int SrcVectorLength> void testDeepCopy() { // Data dimensions. const int dim_1 = 3; const int dim_2 = 2; const int dim_3 = 4; // Declare data types. using DataTypes = Cabana::MemberTypes<float[dim_1][dim_2][dim_3], int, double[dim_1], double[dim_1][dim_2] >; // Declare the AoSoA types. using DstAoSoA_t = Cabana::AoSoA<DataTypes,DstMemorySpace,DstVectorLength>; using SrcAoSoA_t = Cabana::AoSoA<DataTypes,SrcMemorySpace,SrcVectorLength>; // Create AoSoAs. int num_data = 357; DstAoSoA_t dst_aosoa( num_data ); SrcAoSoA_t src_aosoa( num_data ); // Initialize data with the rank accessors. float fval = 3.4; double dval = 1.23; int ival = 1; auto slice_0 = src_aosoa.template slice<0>(); auto slice_1 = src_aosoa.template slice<1>(); auto slice_2 = src_aosoa.template slice<2>(); auto slice_3 = src_aosoa.template slice<3>(); for ( std::size_t idx = 0; idx < src_aosoa.size(); ++idx ) { // Member 0. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) for ( int k = 0; k < dim_3; ++k ) slice_0( idx, i, j, k ) = fval * (i+j+k); // Member 1. slice_1( idx ) = ival; // Member 2. for ( int i = 0; i < dim_1; ++i ) slice_2( idx, i ) = dval * i; // Member 3. for ( int i = 0; i < dim_1; ++i ) for ( int j = 0; j < dim_2; ++j ) slice_3( idx, i, j ) = dval * (i+j); } // Deep copy Cabana::deep_copy( dst_aosoa, src_aosoa ); // Check values. checkDataMembers( dst_aosoa, fval, dval, ival, dim_1, dim_2, dim_3 ); } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_to_host_same_layout_test ) { testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,16>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_from_host_same_layout_test ) { testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,16>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_to_host_different_layout_test ) { testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,32>(); testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,64,8>(); } //---------------------------------------------------------------------------// TEST_F( TEST_CATEGORY, deep_copy_from_host_different_layout_test ) { testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,64,8>(); testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,32>(); } //---------------------------------------------------------------------------// } // end namespace Test
[ "slatterysr@ornl.gov" ]
slatterysr@ornl.gov
cb50f617109e0944e114883af3fc3af8be9a6b7e
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_Buff_PreventDismount_functions.cpp
7e18c4f1010b3ae0b9f98e0ea4d779d40e1340ba
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076000
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,490
cpp
// ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_PreventDismount_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript // () void ABuff_PreventDismount_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.UserConstructionScript"); ABuff_PreventDismount_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ABuff_PreventDismount_C::ExecuteUbergraph_Buff_PreventDismount(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Buff_PreventDismount.Buff_PreventDismount_C.ExecuteUbergraph_Buff_PreventDismount"); ABuff_PreventDismount_C_ExecuteUbergraph_Buff_PreventDismount_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
5ac2daee273b036045797a05ba6d6c787fc58545
3ec6a0f09686dfc885fce0c60b1cf25e24fe4dd0
/obs-node/src/cpp_old/display.cpp
a8bcfa820cdbe66dad1260e0bd265bb13b394bb9
[]
no_license
aidangoettsch/hydro-bot
dcaff8ce46970f87aef4d36f5c86b81f6b9979c4
ecbb3902ea0de38de7f39a372aee9c0cb375e6df
refs/heads/master
2023-03-22T10:35:28.261000
2021-03-11T17:07:31
2021-03-11T17:07:31
335,796,934
1
0
null
null
null
null
UTF-8
C++
false
false
3,609
cpp
// Most of code in this file are copied from // https://github.com/stream-labs/obs-studio-node/blob/staging/obs-studio-server/source/nodeobs_display.cpp #include "display.h" #include "./platform/platform.h" Display::Display(void *parentHandle, int scaleFactor, std::string &sourceName) { this->parentHandle = parentHandle; this->scaleFactor = scaleFactor; // create window for display this->windowHandle = createDisplayWindow(parentHandle); // create display gs_init_data gs_init_data = {}; gs_init_data.adapter = 0; gs_init_data.cx = 1; gs_init_data.cy = 1; gs_init_data.num_backbuffers = 1; gs_init_data.format = GS_RGBA; gs_init_data.zsformat = GS_ZS_NONE; #ifdef _WIN32 gs_init_data.window.hwnd = windowHandle; #elif __APPLE__ gs_init_data.window.view = static_cast<objc_object *>(windowHandle); #endif obs_display = obs_display_create(&gs_init_data, 0x0); if (!obs_display) { throw std::runtime_error("Failed to create the display"); } // obs source obs_source = obs_get_source_by_name(sourceName.c_str()); obs_source_inc_showing(obs_source); // draw callback obs_display_add_draw_callback(obs_display, displayCallback, this); } Display::~Display() { obs_display_remove_draw_callback(obs_display, displayCallback, this); if (obs_source) { obs_source_dec_showing(obs_source); obs_source_release(obs_source); } if (obs_display) { obs_display_destroy(obs_display); } destroyWindow(windowHandle); } void Display::move(int x, int y, int width, int height) { this->x = x; this->y = y; this->width = width; this->height = height; moveWindow(windowHandle, x, y, width, height); obs_display_resize(obs_display, width * scaleFactor, height * scaleFactor); } void Display::displayCallback(void *displayPtr, uint32_t cx, uint32_t cy) { auto *dp = static_cast<Display *>(displayPtr); // Get proper source/base size. uint32_t sourceW, sourceH; if (dp->obs_source) { sourceW = obs_source_get_width(dp->obs_source); sourceH = obs_source_get_height(dp->obs_source); if (sourceW == 0) sourceW = 1; if (sourceH == 0) sourceH = 1; } else { obs_video_info ovi = {}; obs_get_video_info(&ovi); sourceW = ovi.base_width; sourceH = ovi.base_height; if (sourceW == 0) sourceW = 1; if (sourceH == 0) sourceH = 1; } gs_projection_push(); gs_ortho(0.0f, (float)sourceW, 0.0f, (float)sourceH, -1, 1); // Source Rendering obs_source_t *source; if (dp->obs_source) { obs_source_video_render(dp->obs_source); /* If we want to draw guidelines, we need a scene, * not a transition. This may not be a scene which * we'll check later. */ if (obs_source_get_type(dp->obs_source) == OBS_SOURCE_TYPE_TRANSITION) { source = obs_transition_get_active_source(dp->obs_source); } else { source = dp->obs_source; obs_source_addref(source); } } else { obs_render_main_texture(); /* Here we assume that channel 0 holds the primary transition. * We also assume that the active source within that transition is * the scene that we need */ obs_source_t *transition = obs_get_output_source(0); source = obs_transition_get_active_source(transition); obs_source_release(transition); } obs_source_release(source); gs_projection_pop(); }
[ "aidangoettsch@gmail.com" ]
aidangoettsch@gmail.com
8b494503d9bf74ff5d28e840affc467e8a440a51
34a3165ded55c6ac5ffe2ff17c9996c66e0e80b5
/cpp/ETProtect.cpp
989ebb94e3100accc0e0e0fd02bff4f34144df29
[]
no_license
monkeyde17/et-protect-package
d806a3196c28c4176374bc21e7ec5769faa72347
77e04d1834d0723c2de7f424a1cbc1efd2321991
refs/heads/master
2016-09-06T05:53:58.824000
2014-12-07T02:29:37
2014-12-07T02:29:37
27,655,865
0
1
null
null
null
null
UTF-8
C++
false
false
1,888
cpp
// // ETProtect.cpp // testcpp // // Created by etond on 14/12/3. // // #include "ETProtect.h" bool ETProtect::isOriginPackage() { unsigned int uHashValue = calculateValueFromFile(); unsigned int uReadValue = readValueFromFile(); #if (ETPROTECTDEBUG) CCLOG("[log] -- hash %u", uHashValue); CCLOG("[log] -- read %u", uReadValue); #endif if (uReadValue == 0 || uHashValue == 0) { return false; } return uReadValue == uHashValue; } unsigned int ETProtect::readValueFromFile(std::string filename /* default = config.et */) { unsigned int uValue = 0; Data data = FileUtils::getInstance()->getDataFromFile(filename); if (data.getSize() > 0) { uValue = ((ETProtectData *)data.getBytes())->getHashValue(); } return uValue; } unsigned int ETProtect::calculateValueFromFile(unsigned int seed /* default = 0x12345678 */) { std::string path = ""; #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo minfo; bool isHave = JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/cpp/AppActivity", "getPath", "()Ljava/lang/String;"); if (isHave) { jobject jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID); /* get the return value */ path = JniHelper::jstring2string((jstring)jobj).c_str(); CCLOG("JNI SUCCESS!"); } #endif unsigned int value = 0; if (path.length() > 0) { ssize_t len = 0; unsigned char *buf = FileUtils::getInstance()->getFileDataFromZip(path, "classes.dex", &len); if (buf) { value = XXH32(buf, len, seed); } delete[] buf; } return value; }
[ "monkey_tv@126.com" ]
monkey_tv@126.com
4ff557683a174bc39aea59e06a19b563d55927d6
cde943952b79d67f4972d180d20b97fc823db548
/preprocesser/preprocesser/self2.hpp
0892b2563bae695f02d2254829e81a6cb84c630e
[]
no_license
yourgracee/preprocesser
e66a0b0c9680442717652185e9ed2dc5172f7771
349453d4092ffe7927b0c1067d3cefc8bf2bdfff
refs/heads/master
2020-04-09T10:52:16.135000
2018-12-04T02:46:03
2018-12-04T02:46:03
160,285,495
0
0
null
null
null
null
UTF-8
C++
false
false
10,701
hpp
#ifdef LIMIT_2 #include "tuple.hpp" #define START_2 TUPLE(0, LIMIT_2) #define FINISH_2 TUPLE(1, LIMIT_2) #undef DEPTH #define DEPTH 2 # if START_2 <= 0 && FINISH_2 >= 0 # define ITERATION_2 0 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 1 && FINISH_2 >= 1 # define ITERATION_2 1 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 2 && FINISH_2 >= 2 # define ITERATION_2 2 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 3 && FINISH_2 >= 3 # define ITERATION_2 3 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 4 && FINISH_2 >= 4 # define ITERATION_2 4 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 5 && FINISH_2 >= 5 # define ITERATION_2 5 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 6 && FINISH_2 >= 6 # define ITERATION_2 6 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 7 && FINISH_2 >= 7 # define ITERATION_2 7 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 8 && FINISH_2 >= 8 # define ITERATION_2 8 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 9 && FINISH_2 >= 9 # define ITERATION_2 9 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 10 && FINISH_2 >= 10 # define ITERATION_2 10 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 11 && FINISH_2 >= 11 # define ITERATION_2 11 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 12 && FINISH_2 >= 12 # define ITERATION_2 12 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 13 && FINISH_2 >= 13 # define ITERATION_2 13 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 14 && FINISH_2 >= 14 # define ITERATION_2 14 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 15 && FINISH_2 >= 15 # define ITERATION_2 15 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 16 && FINISH_2 >= 16 # define ITERATION_2 16 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 17 && FINISH_2 >= 17 # define ITERATION_2 17 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 18 && FINISH_2 >= 18 # define ITERATION_2 18 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 19 && FINISH_2 >= 19 # define ITERATION_2 19 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 20 && FINISH_2 >= 20 # define ITERATION_2 20 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 21 && FINISH_2 >= 21 # define ITERATION_2 21 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 22 && FINISH_2 >= 22 # define ITERATION_2 22 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 23 && FINISH_2 >= 23 # define ITERATION_2 23 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 24 && FINISH_2 >= 24 # define ITERATION_2 24 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 25 && FINISH_2 >= 25 # define ITERATION_2 25 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 26 && FINISH_2 >= 26 # define ITERATION_2 26 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 27 && FINISH_2 >= 27 # define ITERATION_2 27 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 28 && FINISH_2 >= 28 # define ITERATION_2 28 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 29 && FINISH_2 >= 29 # define ITERATION_2 29 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 30 && FINISH_2 >= 30 # define ITERATION_2 30 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 31 && FINISH_2 >= 31 # define ITERATION_2 31 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 32 && FINISH_2 >= 32 # define ITERATION_2 32 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 33 && FINISH_2 >= 33 # define ITERATION_2 33 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 34 && FINISH_2 >= 34 # define ITERATION_2 34 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 35 && FINISH_2 >= 35 # define ITERATION_2 35 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 36 && FINISH_2 >= 36 # define ITERATION_2 36 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 37 && FINISH_2 >= 37 # define ITERATION_2 37 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 38 && FINISH_2 >= 38 # define ITERATION_2 38 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 39 && FINISH_2 >= 39 # define ITERATION_2 39 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 40 && FINISH_2 >= 40 # define ITERATION_2 40 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 41 && FINISH_2 >= 41 # define ITERATION_2 41 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 42 && FINISH_2 >= 42 # define ITERATION_2 42 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 43 && FINISH_2 >= 43 # define ITERATION_2 43 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 44 && FINISH_2 >= 44 # define ITERATION_2 44 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 45 && FINISH_2 >= 45 # define ITERATION_2 45 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 46 && FINISH_2 >= 46 # define ITERATION_2 46 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 47 && FINISH_2 >= 47 # define ITERATION_2 47 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 48 && FINISH_2 >= 48 # define ITERATION_2 48 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 49 && FINISH_2 >= 49 # define ITERATION_2 49 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 50 && FINISH_2 >= 50 # define ITERATION_2 50 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 51 && FINISH_2 >= 51 # define ITERATION_2 51 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 52 && FINISH_2 >= 52 # define ITERATION_2 52 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 53 && FINISH_2 >= 53 # define ITERATION_2 53 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 54 && FINISH_2 >= 54 # define ITERATION_2 54 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 55 && FINISH_2 >= 55 # define ITERATION_2 55 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 56 && FINISH_2 >= 56 # define ITERATION_2 56 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 57 && FINISH_2 >= 57 # define ITERATION_2 57 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 58 && FINISH_2 >= 58 # define ITERATION_2 58 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 59 && FINISH_2 >= 59 # define ITERATION_2 59 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 60 && FINISH_2 >= 60 # define ITERATION_2 60 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 61 && FINISH_2 >= 61 # define ITERATION_2 61 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 62 && FINISH_2 >= 62 # define ITERATION_2 62 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 63 && FINISH_2 >= 63 # define ITERATION_2 63 # include FILENAME_2 # undef ITERATION_2 # endif # if START_2 <= 64 && FINISH_2 >= 64 # define ITERATION_2 64 # include FILENAME_2 # undef ITERATION_2 # endif #undef DEPTH #define DEPTH 1 #endif
[ "noreply@github.com" ]
noreply@github.com
fa606684822edaeb65a3facbab4e69b8044c96ef
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/SOC/2011/simd/boost/simd/toolbox/constant/include/constants/minexponent.hpp
0fd6c857f2cef5aa7fcc1f22aca4daf4a5f7a9c3
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452000
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
232
hpp
#ifndef BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED #define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED #include <boost/simd/toolbox/constant/constants/minexponent.hpp> #endif
[ "loufoque@gmail.com" ]
loufoque@gmail.com
36a545137c7c8972f084997716e578ad86d3ac15
afcce85e08d8fc5141a840fe77bf7bf93f49df54
/tests/2015-09-10/fft_shift/main.cpp
5fd27aab9e2480a56af1d2bf0dfe2ab2e4eeaa98
[]
no_license
icopavan/Automatic-Modulation-Classification-ELEN4012
ff8f58a467129b371a9d2b042169fc99620b2959
d72e3b4d36ad88b2872a8b33606c120f18b974e6
refs/heads/master
2021-01-12T21:07:15.807000
2015-10-09T21:29:56
2015-10-09T21:29:56
44,043,227
2
1
null
2015-10-11T07:30:41
2015-10-11T07:30:40
null
UTF-8
C++
false
false
910
cpp
#include "mainwindow.h" #include <QApplication> #include <fftw3.h> #include <cmath> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); double PI = 4 * atan(1); int N = 512; // number of samples double fs = 10e3; // sampling frequency double fc = 1000; // signal frequency double t[N]; fftw_complex * x = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); double f[N]; // calculation for (int n = 0; n < N; ++n) { t[n] = n/fs; x[n][0] = cos(2*PI*fc*t[n]); x[n][1] = 0; f[n] = (n - N/2) * fs / (N-1); } fftw_complex *out; fftw_plan plan_forward; out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N); plan_forward = fftw_plan_dft_1d(N, x, out, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan_forward); w.plot(f, out, N); return a.exec(); }
[ "anthonyjamesfarquharson@gmail.com" ]
anthonyjamesfarquharson@gmail.com
d46a3b3f4252a9ed58f62fd5e8068ade7c69129b
aa701c8621b90137f250151db3c74881767acb6d
/core/nes/mapper/042.cpp
20039b24a52dade8d098a2f5e8052ce2675d369c
[]
no_license
ptnnx/e-mulator-PSP
3215bbfe0870a41b341f207ba11a2d1fe2b64b56
538c700096fcef34bba9145750f7f9e44d3e7446
refs/heads/main
2023-02-05T09:57:34.046000
2020-12-31T08:59:04
2020-12-31T08:59:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
cpp
STATIC void NES_mapper42_Init(); STATIC void NES_mapper42_Reset(); STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data); STATIC void NES_mapper42_HSync(u32 scanline); ///////////////////////////////////////////////////////////////////// // Mapper 42 STATIC void NES_mapper42_Init() { g_NESmapper.Reset = NES_mapper42_Reset; g_NESmapper.MemoryWrite = NES_mapper42_MemoryWrite; g_NESmapper.HSync = NES_mapper42_HSync; } STATIC void NES_mapper42_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_bank3(0); g_NESmapper.set_CPU_bank4(g_NESmapper.num_8k_ROM_banks-4); g_NESmapper.set_CPU_bank5(g_NESmapper.num_8k_ROM_banks-3); g_NESmapper.set_CPU_bank6(g_NESmapper.num_8k_ROM_banks-2); g_NESmapper.set_CPU_bank7(g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } STATIC void NES_mapper42_MemoryWrite(u32 addr, u8 data) { switch(addr & 0xE003) { case 0x8000: g_NESmapper.set_PPU_banks8(((data&0x1f)<<3)+0,((data&0x1f)<<3)+1,((data&0x1f)<<3)+2,((data&0x1f)<<3)+3,((data&0x1f)<<3)+4,((data&0x1f)<<3)+5,((data&0x1f)<<3)+6,((data&0x1f)<<3)+7); break; case 0xE000: { g_NESmapper.set_CPU_bank3(data & 0x0F); } break; case 0xE001: { if(data & 0x08) { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } else { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT); } } break; case 0xE002: { if(data & 0x02) { g_NESmapper.Mapper42.irq_enabled = 1; } else { g_NESmapper.Mapper42.irq_enabled = 0; g_NESmapper.Mapper42.irq_counter = 0; } } break; } // LOG("W " << HEX(addr,4) << " " << HEX(data,2) << endl); } STATIC void NES_mapper42_HSync(u32 scanline) { if(g_NESmapper.Mapper42.irq_enabled) { if(g_NESmapper.Mapper42.irq_counter < 215) { g_NESmapper.Mapper42.irq_counter++; } if(g_NESmapper.Mapper42.irq_counter == 215) { NES6502_DoIRQ(); g_NESmapper.Mapper42.irq_enabled = 0; } } } /////////////////////////////////////////////////////////////////////
[ "75588890+pierrelouys@users.noreply.github.com" ]
75588890+pierrelouys@users.noreply.github.com
bba7327fa47b292b7a2a12379dbea888640a0e70
58790459d953a3e4b6722ed3ee939f82d9de8c3e
/my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/PIBrokerSDK/simple-ipc-lib/src/pipe_win.h
4625bef0dc76752fdcc7b3a4966d087839cbd12f
[]
no_license
tisn05/VS
bb84deb993eb18d43d8edaf81afb753afa3d3188
da56d392a518ba21edcb1a367b4b4378d65506f0
refs/heads/master
2020-09-25T05:49:31.713000
2016-08-22T01:22:16
2016-08-22T01:22:16
66,229,337
0
1
null
null
null
null
UTF-8
C++
false
false
1,659
h
// Copyright (c) 2010 Google Inc. // // 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 SIMPLE_IPC_PIPE_WIN_H_ #define SIMPLE_IPC_PIPE_WIN_H_ #include "os_includes.h" #include "ipc_constants.h" class PipePair { public: PipePair(bool inherit_fd2 = false); HANDLE fd1() const { return srv_; } HANDLE fd2() const { return cln_; } static HANDLE OpenPipeServer(const wchar_t* name, bool low_integrity = false); static HANDLE OpenPipeClient(const wchar_t* name, bool inherit, bool impersonate); private: HANDLE srv_; HANDLE cln_; }; class PipeWin { public: PipeWin(); ~PipeWin(); bool OpenClient(HANDLE pipe); bool OpenServer(HANDLE pipe, bool connect = false); bool Write(const void* buf, size_t sz); bool Read(void* buf, size_t* sz); bool IsConnected() const { return INVALID_HANDLE_VALUE != pipe_; } private: HANDLE pipe_; }; class PipeTransport : public PipeWin { public: static const size_t kBufferSz = 4096; size_t Send(const void* buf, size_t sz) { return Write(buf, sz) ? ipc::RcOK : ipc::RcErrTransportWrite; } char* Receive(size_t* size); private: IPCCharVector buf_; }; #endif // SIMPLE_IPC_PIPE_WIN_H_
[ "tisn05@gmail.com" ]
tisn05@gmail.com
ca83a558bcc72c5055c6fbf661b26acbaf1aeb08
6701a2c3fb95baba0da5754b88d23f79a2b10f7f
/protocol/mcbp/libmcbp/mcbp_packet_printer.cc
6329b15ffaeaf2a08d698518c5c195e5ef3a5e8b
[]
no_license
teligent-ru/kv_engine
80630b4271d72df9c47b505a586f2e8275895d3e
4a1b741ee22ae3e7a46e21a423451c58186a2374
refs/heads/master
2018-11-07T20:52:54.132000
2018-01-15T16:34:10
2018-01-17T08:29:54
117,808,163
1
0
null
2018-01-17T08:34:05
2018-01-17T08:34:05
null
UTF-8
C++
false
false
4,594
cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017 Couchbase, Inc. * * 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 <getopt.h> #include <mcbp/mcbp.h> #include <platform/dirutils.h> #include <platform/memorymap.h> #include <platform/sized_buffer.h> #include <algorithm> #include <iostream> enum class Format { Raw, Gdb, Lldb }; Format parseFormat(std::string format) { std::transform(format.begin(), format.end(), format.begin(), toupper); if (format == "RAW") { return Format::Raw; } if (format == "GDB") { return Format::Gdb; } if (format == "LLDB") { return Format::Lldb; } throw std::invalid_argument("Unknown format: " + format); } int main(int argc, char** argv) { Format format{Format::Raw}; static struct option longopts[] = { {"format", required_argument, nullptr, 'f'}, {nullptr, 0, nullptr, 0}}; int cmd; while ((cmd = getopt_long(argc, argv, "f:", longopts, nullptr)) != -1) { switch (cmd) { case 'f': try { format = parseFormat(optarg); } catch (const std::invalid_argument& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } break; default: std::cerr << "Usage: " << cb::io::basename(argv[0]) << " [options] file1-n" << std::endl << std::endl << "\t--format=raw|gdb|lldb\tThe format for the input file" << std::endl << std::endl << "For gdb the expected output would be produced by " "executing: " << std::endl << std::endl << "(gdb) x /24xb c->rcurr" << std::endl << "0x7f43387d7e7a: 0x81 0x0d 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << "0x7f43387d7e82: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << "0x7f43387d7e8a: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00" << std::endl << std::endl << "For lldb the expected output would be generated by " "executing: " << std::endl << std::endl << "(lldb) x -c 32 c->rbuf" << std::endl << "0x7f43387d7e7a: 81 0d 00 01 04 00 00 00 00 00 00 06 00 " "00 00 06 ................" << std::endl << "0x7f43387d7e7a: 14 bf f4 26 8a e0 00 00 00 00 00 00 61 " "61 81 0a ................" << std::endl << std::endl; return EXIT_FAILURE; } } if (optind == argc) { std::cerr << "No file specified" << std::endl; return EXIT_FAILURE; } while (optind < argc) { try { cb::byte_buffer buf; std::vector<uint8_t> data; cb::MemoryMappedFile map(argv[optind], cb::MemoryMappedFile::Mode::RDONLY); map.open(); buf = {static_cast<uint8_t*>(map.getRoot()), map.getSize()}; switch (format) { case Format::Raw: break; case Format::Gdb: data = cb::mcbp::gdb::parseDump(buf); buf = {data.data(), data.size()}; break; case Format::Lldb: data = cb::mcbp::lldb::parseDump(buf); buf = {data.data(), data.size()}; break; } cb::mcbp::dumpStream(buf, std::cout); } catch (const std::exception& error) { std::cerr << error.what() << std::endl; return EXIT_FAILURE; } ++optind; } return EXIT_SUCCESS; }
[ "daver@couchbase.com" ]
daver@couchbase.com
ab5bc031413c9ef1306cacfd08a9878b7b902ed5
35e79b51f691b7737db254ba1d907b2fd2d731ef
/AtCoder/ABC/007/D.cpp
1f7d6ef9dd955d37b91e67aebfabda6b728594c7
[]
no_license
rodea0952/competitive-programming
00260062d00f56a011f146cbdb9ef8356e6b69e4
9d7089307c8f61ea1274a9f51d6ea00d67b80482
refs/heads/master
2022-07-01T02:25:46.897000
2022-06-04T08:44:42
2022-06-04T08:44:42
202,485,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
#include <bits/stdc++.h> #define chmin(a, b) ((a)=min((a), (b))) #define chmax(a, b) ((a)=max((a), (b))) #define fs first #define sc second #define eb emplace_back using namespace std; typedef long long ll; typedef pair<int, int> P; typedef tuple<int, int, int> T; const ll MOD=1e9+7; const ll INF=1e18; int dx[]={1, -1, 0, 0}; int dy[]={0, 0, 1, -1}; template <typename T> inline string toString(const T &a){ostringstream oss; oss<<a; return oss.str();}; ll solve(string &s){ int n=s.size(); ll dp[20][2][2]; // dp[決めた桁数][未満フラグ][4または9を含むか] := 求める総数 memset(dp, 0, sizeof(dp)); dp[0][0][0]=1; for(int i=0; i<n; i++){ // 桁 int D=s[i]-'0'; for(int j=0; j<2; j++){ // 未満フラグ for(int k=0; k<2; k++){ // k=1 のとき4または9を含む for(int d=0; d<=(j?9:D); d++){ dp[i+1][j || (d<D)][k || d==4 || d==9]+=dp[i][j][k]; } } } } return dp[n][0][1]+dp[n][1][1]; } int main(){ ll a, b; cin>>a>>b; string A=toString(a-1), B=toString(b); cout << solve(B) - solve(A) << endl; }
[ "dragondoor0912@yahoo.co.jp" ]
dragondoor0912@yahoo.co.jp
README.md exists but content is empty.
Downloads last month
16