blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
b76173db5c33bbd6149e0de9ce5686ccac44dfdc
C++
ANTAR-NANDI/Competetive-Programming
/Bitwise-Recursion-Structure.cpp
UTF-8
272
2.765625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Person{ int roll; string name; }; int main() { int a,b; struct Person Antar,Rimon; cin>>Antar.name>>Rimon.name; cin>>Antar.roll>>Rimon.roll; cout<<Antar.name<<" "<<Rimon.name; cin>>a>>b; cout<<(a&b); }
true
6636a97ac55faea7059949c0b44ae99956599af5
C++
Pablourquia/IB-Practica4
/CONTARDINERO.cc
UTF-8
1,470
3.515625
4
[]
no_license
#include <iostream> using namespace std; int main(){ int monedas01; int monedas05; int monedas10; int monedas20; int monedas50; int billetes5; int billetes10; int billetes20; int billetes50; int billetes100; int billetes200; int billetes500; cout << "Cuantas monedas de 1 cent tienes?"; cin >> monedas01; cout << "Cuantas monedas de 5 cent tienes?"; cin >> monedas05; cout << "Cuantas monedas de 10 cent tienes?"; cin >> monedas10; cout << "Cuantas monedas de 20 cent tienes?"; cin >> monedas20; cout << "Cuantas monedas de 50 cent tienes?"; cin >> monedas50; cout << "Cuantos billetes de 5 euros tienes?"; cin >> billetes5; cout << "Cuantos billetes de 10 euros tienes?"; cin >> billetes10; cout << "Cuantos billetes de 20 euros tienes?"; cin >> billetes20; cout << "Cuantos billetes de 50 euros tienes?"; cin >> billetes50; cout << "Cuantos billetes de 100 euros tienes?"; cin >> billetes100; cout << "Cuantos billetes de 200 euros tienes?"; cin >> billetes200; cout << "Cuantos billetes de 500 euros tienes?"; cin >> billetes500; cout << "En total tienes " << monedas01 * 0.01 + monedas05 * 0.05 + monedas10 * 0.1 + monedas20 * 0.2 + monedas50 * 50 + billetes5 * 5 + billetes10 * 10 + billetes20 * 20 + billetes50 * 50 + billetes100 *100 + billetes200 * 200 + billetes500 * 500 << " euros" << endl; }
true
37be7e3d94d96df0f8223b2d526bbbffd080d87c
C++
PeteTheN00b/programmiersprachen-aufgabe-1
/TDD/source/aufgabe1-8.cpp
UTF-8
1,670
3.265625
3
[ "MIT" ]
permissive
//Sorry that I called this aufgabe1-8 instead of tests.cpp, I had to change some stuff about the cmake file because I didn't notice that but I still got it to work #define CATCH_CONFIG_RUNNER #include "catch2/catch.hpp" #include <cmath> bool divisible(int n, int div) { return n % div == 0; } int gcd(int a, int b) { if (a == 0 || b == 0) //These inputs would always be incorrect, therefore we will return -1 as an error if we ever get them, otherwise these would provide us with an infinite loop { std::cout << "Invalid Input 0 Detected, Returning -1"; return -1; } a = a < 0 ? -a : a; //Convert a and b to their positive values if they are negative, if we didn't do this we'd have to make sure our initial gcd test was positive and the smaller value b = b < 0 ? -b : b; //Could technically use the cmath abs() function, I didn't want to int gcd = a < b ? a : b; //set n to equal a if it is smaller than b, otherwise b (pick the smaller of the two to start with, and work down from there) while (!(divisible(a, gcd) && divisible(b, gcd))) //decrement our gcd by 1 until it passes this test, this could technically be done with a for loop but I think it looks cleaner this way gcd--; return gcd; } TEST_CASE("describe_gcd", "[gcd]") { REQUIRE(gcd(2, 4) == 2); REQUIRE(gcd(9, 6) == 3); REQUIRE(gcd(3, 7) == 1); REQUIRE(gcd(0, 0) == -1); REQUIRE(gcd(1, -1) == 1); REQUIRE(gcd(53, -23) == 1); //The following tests should always fail, uncomment them one by one to show that the test check works properly //REQUIRE(gcd(0, 1) == 1); //REQUIRE(gcd(3, 2) == 2); } int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); }
true
377c63dfeabfc728d1c182a58b78c4417452bd61
C++
joilar/cgol
/src/Messages.h
UTF-8
224
2.5625
3
[]
no_license
#include <iostream> #include <typeinfo> #define FUNCTION_NOT_IMPLEMENTED_MESSAGE \ std::cerr << "Function " << __func__ << " not implemented in class " \ << typeid(*this).name() << "." << std::endl;
true
19cb5b85d513983ab5eca78276c7dac64d31cf38
C++
nakamura106/-autumn-production
/Libraly/DataBank/DataBank.h
SHIFT_JIS
4,250
2.53125
3
[]
no_license
#ifndef DATABANK_H_ #define DATABANK_H_ #include "../Object/Definition.h" class DataBank { public: static DataBank* Instance(); //̃Q[ŏȂƂȂl void ResetData(); void SetPlayerHp(int hp) { m_player_hp = hp; } void SetNote(int note1_, int note2_, int note3_) { note1 = note1_; note2 = note2_; note3 = note3_; } void SetBulletType(int bullet_type_) { m_bullet_type = bullet_type_; } void SetfgPos(float fg_) { m_fg = fg_; } void Setfloor1Pos(float floor1_) { m_floor1 = floor1_; } void SetPlayerMapPos(float mPos) { m_map_pos = mPos; } void SetSleepGauge(float sleep_hp) { m_sleep_gauge = sleep_hp; } void SetFatigueGauge(float fatigue_hp) { m_fatigue_gauge = fatigue_hp; } void SetIsGameClear(bool is_game_clear_) { m_is_game_clear = is_game_clear_; } void SetPlayerType(int Which_type_of_player) { m_PlayerType = Which_type_of_player; }; void SetMapType(int Which_type_of_map) { m_MapType = Which_type_of_map; }; void SetIsGameOver(bool is_game_over_) { m_is_game_over = is_game_over_; } void SetPlayerDirection(int direction_) { m_Pdirection = direction_; } void SetPlayerEffect(P_effect effect_); void SetWaveState(WaveState wave_state_) { m_wave_state = wave_state_; } void SetState(int state_) { m_state = state_; } void SetWave(WaveType wave_,bool torf_) { m_wave_change[(int)wave_] = torf_; } void SetIsDebuff(bool is_debuff) { m_is_debuff = is_debuff; } void SetIsHitBanana(bool is_hit_banana) { m_is_hit_banana = is_hit_banana; } void SetIsHitShit(bool is_hit_shit) { m_is_hit_shit = is_hit_shit; } void SetDoEnemyDeadlyAi(bool do_e_deadly_ai_) { m_do_enemy_deadly_ai = do_e_deadly_ai_; } void SetBulletDeathPos(Position pos) { m_bullet_death_pos.x = pos.x; m_bullet_death_pos.y = pos.y; } void SetBulletDeathPosClear() { m_bullet_death_pos.x = 0.f; m_bullet_death_pos.y = 0.f; } void SetGameStartFlame(int flame) { m_game_start_flame = flame; } void SetGameEndFlame(int flame) { m_game_end_flame = flame; } int GetPlayerHp() { return m_player_hp; } int GetNote1() { return note1; } int GetNote2() { return note2; } int GetNote3() { return note3; } int GetBulletType() { return m_bullet_type; } int GetPlayerType() { return m_PlayerType; } int GetMapType() { return m_MapType; } int GetPlayerHp()const { return m_player_hp; } int GetPlayerdirection() { return m_Pdirection; } int GetPlayerEffect(P_effect p_effect_); int GetState() { return m_state; } float GetfgPos(){ return m_fg; } float Getfloor1Pos() { return m_floor1; } float GetPlayerMapPos() { return m_map_pos; } float GetSleepGauge() { return m_sleep_gauge; } float GetFatigueGauge() { return m_fatigue_gauge; } bool GetIsSleepMax() { return m_sleep_gauge >= Sleep_Gauge_Max; } bool GetIsFatigueGauge() { return m_fatigue_gauge >= Fatigue_Gauge_Max; } bool GetIsGameClear() { return m_is_game_clear; } bool GetIsGameOver() { return m_is_game_over; } bool GetWavetype(WaveType wave_) { return m_wave_change[(int)wave_]; } bool GetIsDebuff() { return m_is_debuff; } bool GetIsHitBanana() { return m_is_hit_banana; } bool GetIsHitShit() { return m_is_hit_shit; } bool GetDoEnemyDeadlyAi() { return m_do_enemy_deadly_ai; } int GetGameStartFlame() { return m_game_start_flame; } int GetGameEndFlame() { return m_game_end_flame; } Position GetBulletDeathPos() { return m_bullet_death_pos; } WaveState GetWaveState() { return m_wave_state; } protected: DataBank(); ~DataBank(); private: int m_player_hp; int note1; int note2; int note3; int m_bullet_type; // PlayerBulletTypeۑϐ int m_PlayerType; int m_MapType; int m_state; float m_map_pos; float m_fg; float m_floor1; float m_sleep_gauge, m_fatigue_gauge; bool m_is_debuff; bool m_is_hit_banana; bool m_is_hit_shit; bool m_is_game_clear; bool m_is_game_over; bool m_wave_change[(int)WaveType::WaveMax]; bool m_PlayerEffect[(int)P_effect::MaxEffect]; int m_Pdirection; Position m_centerpos; WaveState m_wave_state; bool m_do_enemy_deadly_ai;//G̕KEZĂ邩ǂ Position m_bullet_death_pos; // vC[̋ʂ񂾂Ƃ̍W int m_game_start_flame, m_game_end_flame; private: static DataBank* p_instance; }; #endif
true
001120e8d9490e4901dc9c47c6da8840b28368a4
C++
OlaKa/PartikelAccelerator
/src/Particle.cpp
UTF-8
720
2.671875
3
[]
no_license
/* * Particle.cpp * * Created on: 31 jul 2017 * Author: ola */ #include "Particle.h" #include <stdlib.h> #include <math.h> namespace monitor { Particle::Particle() : m_x(0), m_y(0) { init(); //m_speed *= m_speed; } void Particle::init(){ m_direction = (2 * M_PI * rand()) / RAND_MAX; m_speed = (0.00009 * rand())/RAND_MAX; } Particle::~Particle() { } void Particle::update(int interval) { m_direction += interval*0.0004; double xspeed = m_speed * cos(m_direction); double yspeed = m_speed * sin(m_direction); m_x += xspeed*interval; m_y += yspeed*interval; if(m_x <-1||m_x > 1 || m_y <-1||m_y > 1){ init(); } if(rand() < RAND_MAX/100){ init(); } } } /* namespace monitor */
true
6c0905f197ac24c64f14e7e8affa549e4e809f3a
C++
bgoonz/UsefulResourceRepo2.0
/_REPO/MICROSOFT/PowerToys/src/modules/fancyzones/FancyZonesLib/ZoneSet.h
UTF-8
8,025
2.78125
3
[ "MIT", "BSL-1.0", "Unlicense", "LicenseRef-scancode-generic-cla" ]
permissive
#pragma once #include "Zone.h" #include "Settings.h" namespace FancyZonesDataTypes { enum class ZoneSetLayoutType; } /** * Class representing single zone layout. ZoneSet is responsible for actual calculation of rectangle coordinates * (whether is grid or canvas layout) and moving windows through them. */ interface __declspec(uuid("{E4839EB7-669D-49CF-84A9-71A2DFD851A3}")) IZoneSet : public IUnknown { // Mapping zone id to zone using ZonesMap = std::map<size_t, winrt::com_ptr<IZone>>; /** * @returns Unique identifier of zone layout. */ IFACEMETHOD_(GUID, Id)() const = 0; /** * @returns Type of the zone layout. Layout type can be focus, columns, rows, grid, priority grid or custom. */ IFACEMETHOD_(FancyZonesDataTypes::ZoneSetLayoutType, LayoutType)() const = 0; /** * Add zone to the zone layout. * * @param zone Zone object (defining coordinates of the zone). */ IFACEMETHOD(AddZone)(winrt::com_ptr<IZone> zone) = 0; /** * Get zones from cursor coordinates. * * @param pt Cursor coordinates. * @returns Vector of indices, corresponding to the current set of zones - the zones considered active. */ IFACEMETHOD_(std::vector<size_t>, ZonesFromPoint)(POINT pt) const = 0; /** * Get index set of the zones to which the window was assigned. * * @param window Handle of the window. * @returns A vector of size_t, 0-based index set. */ IFACEMETHOD_(std::vector<size_t>, GetZoneIndexSetFromWindow) (HWND window) const = 0; /** * @returns Array of zone objects (defining coordinates of the zone) inside this zone layout. */ IFACEMETHOD_(ZonesMap, GetZones) () const = 0; /** * Assign window to the zone based on zone index inside zone layout. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param index Zone index within zone layout. */ IFACEMETHOD_(void, MoveWindowIntoZoneByIndex) (HWND window, HWND workAreaWindow, size_t index) = 0; /** * Assign window to the zones based on the set of zone indices inside zone layout. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param indexSet The set of zone indices within zone layout. */ IFACEMETHOD_(void, MoveWindowIntoZoneByIndexSet) (HWND window, HWND workAreaWindow, const std::vector<size_t>& indexSet) = 0; /** * Assign window to the zone based on direction (using WIN + LEFT/RIGHT arrow), based on zone index numbers, * not their on-screen position. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param vkCode Pressed arrow key. * @param cycle Whether we should move window to the first zone if we reached last zone in layout. * * @returns Boolean which is always true if cycle argument is set, otherwise indicating if there is more * zones left in the zone layout in which window can move. */ IFACEMETHOD_(bool, MoveWindowIntoZoneByDirectionAndIndex) (HWND window, HWND workAreaWindow, DWORD vkCode, bool cycle) = 0; /** * Assign window to the zone based on direction (using WIN + LEFT/RIGHT/UP/DOWN arrow), based on * their on-screen position. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param vkCode Pressed arrow key. * @param cycle Whether we should move window to the first zone if we reached last zone in layout. * * @returns Boolean which is always true if cycle argument is set, otherwise indicating if there is more * zones left in the zone layout in which window can move. */ IFACEMETHOD_(bool, MoveWindowIntoZoneByDirectionAndPosition) (HWND window, HWND workAreaWindow, DWORD vkCode, bool cycle) = 0; /** * Extend or shrink the window to an adjacent zone based on direction (using CTRL+WIN+ALT + LEFT/RIGHT/UP/DOWN arrow), based on * their on-screen position. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param vkCode Pressed arrow key. * * @returns Boolean indicating whether the window was rezoned. False could be returned when there are no more * zones available in the given direction. */ IFACEMETHOD_(bool, ExtendWindowByDirectionAndPosition) (HWND window, HWND workAreaWindow, DWORD vkCode) = 0; /** * Assign window to the zone based on cursor coordinates. * * @param window Handle of window which should be assigned to zone. * @param workAreaWindow The m_window of a WorkArea, it's a hidden window representing the * current monitor desktop work area. * @param pt Cursor coordinates. */ IFACEMETHOD_(void, MoveWindowIntoZoneByPoint) (HWND window, HWND workAreaWindow, POINT ptClient) = 0; /** * Calculate zone coordinates within zone layout based on number of zones and spacing. * * @param workAreaRect The rectangular area on the screen on which the zone layout is applied. * @param zoneCount Number of zones inside zone layout. * @param spacing Spacing between zones in pixels. * * @returns Boolean indicating if calculation was successful. */ IFACEMETHOD_(bool, CalculateZones)(RECT workAreaRect, int zoneCount, int spacing) = 0; /** * Check if the zone with the specified index is empty. Returns true if the zone with passed zoneIndex does not exist. * * @param zoneIndex The index of of the zone within this zone set. * * @returns Boolean indicating whether the zone is empty. */ IFACEMETHOD_(bool, IsZoneEmpty)(int zoneIndex) const = 0; /** * Returns all zones spanned by the minimum bounding rectangle containing the two given zone index sets. * * @param initialZones The indices of the first chosen zone (the anchor). * @param finalZones The indices of the last chosen zone (the current window position). * * @returns A vector indicating describing the chosen zone index set. */ IFACEMETHOD_(std::vector<size_t>, GetCombinedZoneRange)(const std::vector<size_t>& initialZones, const std::vector<size_t>& finalZones) const = 0; }; struct ZoneSetConfig { ZoneSetConfig( GUID id, FancyZonesDataTypes::ZoneSetLayoutType layoutType, HMONITOR monitor, int sensitivityRadius, OverlappingZonesAlgorithm selectionAlgorithm = {}) noexcept : Id(id), LayoutType(layoutType), Monitor(monitor), SensitivityRadius(sensitivityRadius), SelectionAlgorithm(selectionAlgorithm) { } GUID Id{}; FancyZonesDataTypes::ZoneSetLayoutType LayoutType{}; HMONITOR Monitor{}; int SensitivityRadius; OverlappingZonesAlgorithm SelectionAlgorithm = OverlappingZonesAlgorithm::Smallest; }; winrt::com_ptr<IZoneSet> MakeZoneSet(ZoneSetConfig const& config) noexcept;
true
10422c405e7fa0fae73a3553fbe83e527a5af98b
C++
huhumeng/dvo-cpp
/include/core/point_selection.h
UTF-8
1,993
2.734375
3
[]
no_license
#pragma once #include "core/rgbd_image.h" namespace dvo { namespace core { class PointSelectionPredicate { public: PointSelectionPredicate() : intensity_threshold(0.0f), depth_threshold(0.0f) { } bool isPointOk(const size_t &x, const size_t &y, const float &z, const float &idx, const float &idy, const float &zdx, const float &zdy) const { return z == z && zdx == zdx && zdy == zdy && (std::abs(idx) > intensity_threshold || std::abs(idy) > intensity_threshold || std::abs(zdx) > depth_threshold || std::abs(zdy) > depth_threshold); } float intensity_threshold; float depth_threshold; }; class PointSelection { public: typedef PointWithIntensityAndDepth::VectorType PointVector; typedef PointVector::iterator PointIterator; PointSelection(const PointSelectionPredicate &predicate); PointSelection(RgbdImagePyramid &pyramid, const PointSelectionPredicate &predicate); ~PointSelection() = default; RgbdImagePyramid &getRgbdImagePyramid(); void setRgbdImagePyramid(RgbdImagePyramid &pyramid); size_t getMaximumNumberOfPoints(const size_t &level); void select(const size_t &level, PointIterator &first_point, PointIterator &last_point); bool getDebugIndex(const size_t &level, cv::Mat &dbg_idx); void debug(bool v) { debug_ = v; } bool debug() const { return debug_; } private: struct Storage { public: PointVector points; PointIterator points_end; bool is_cached; cv::Mat debug_idx; Storage(); void allocate(size_t max_points); }; PointIterator selectPointsFromImage(const RgbdImage &img, const PointIterator &first_point, const PointIterator &last_point, cv::Mat &debug_idx); RgbdImagePyramid *pyramid_; std::vector<Storage> storage_; const PointSelectionPredicate &predicate_; bool debug_; }; } // namespace core } // namespace dvo
true
64feec5382bede63285d2e57ff7afac8cb931cb5
C++
yakushstanislav/frontend-learning
/HTML_JavaScript/TempMonitor/Arduino/TemperatureMonitor/TemperatureMonitor.ino
UTF-8
468
2.59375
3
[]
no_license
#include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS 2 #define SERIAL_BAUD_RATE 9600 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); void setup() { pinMode(13, OUTPUT); Serial.begin(SERIAL_BAUD_RATE); sensors.begin(); } void loop() { digitalWrite(13, LOW); sensors.requestTemperatures(); digitalWrite (13, HIGH); Serial.print("TEMP: "); Serial.print(sensors.getTempCByIndex(0)); Serial.print("\n"); }
true
87d09099033704fecd6b042620c300e9bc69eb44
C++
iznilul/leetcode-
/editor/cn/[剑指 Offer 34]二叉树中和为某一值的路径.cpp
UTF-8
1,603
3.4375
3
[]
no_license
//输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。 // // // // 示例: //给定如下二叉树,以及目标和 sum = 22, // // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ / \ // 7 2 5 1 // // // 返回: // // [ // [5,4,11,2], // [5,8,4,5] //] // // // // // 提示: // // // 节点总数 <= 10000 // // // 注意:本题与主站 113 题相同:https://leetcode-cn.com/problems/path-sum-ii/ // Related Topics 树 深度优先搜索 // 👍 133 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector<vector<int>> ans; vector<int> path; public: void recur(TreeNode* root,int target){ if(root==nullptr) return; int val = root->val; path.push_back(val); target -= val; if(target==0&&root->left==nullptr&&root->right==nullptr) ans.push_back(path); recur(root->left, target); recur(root->right, target); path.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { recur(root, sum); return ans; } }; //leetcode submit region end(Prohibit modification and deletion)
true
117de6f1a4314e61ca0324ca654431e8a2ddd4c4
C++
wzzydezy/C-learning
/n!.cpp
UTF-8
545
2.6875
3
[]
no_license
#include <iostream> #include <vector> #include <string.h> #include <unordered_map> #include <sstream> #include <queue> #include <stack> #include <math.h> #include <stdlib.h> #include <algorithm> #include <limits.h> #include <list> #include <stdlib.h> using namespace std; int trailingZeroes(int n) { int m = n; int count5 = 0; for(int i=5;i<=n;i=i+5){ int j = i; while(j>=5){ j=j/5; count5++; } } return count5; } int main(){ int res = trailingZeroes(30); return 0; }
true
34c55b0615cf01ba9ce9b39107f8bf65eab68bae
C++
WangDrop/WangDropExercise
/Interview/bitSmallTrans.cpp
UTF-8
188
2.515625
3
[]
no_license
#include <stdint.h> int32_t bigSmallTrans(int32_t num){ return (num & 0x000000FF) << 24 | (num & 0x0000FF00) << 8 | (num & 0x00FF0000) >> 8 | (num & 0xFF000000) >> 24; }
true
aac75251e378c075b95973cc0be736eb94e10b75
C++
onur-yildiz/cmd-pacman
/character.cpp
UTF-8
1,830
3.203125
3
[ "MIT" ]
permissive
#include "character.h" #include <ncurses.h> Character::Character(WINDOW * win, int y, int x, char _symbol, bool _hunter) { window = win; yLoc = ySpawnLoc = y; xLoc = xSpawnLoc = x; symbol = _symbol; hunter = _hunter; direction = KEY_DOWN; getmaxyx(window, yMax, xMax); } int Character::getX() { return xLoc; } int Character::getNextX() { if (direction == KEY_LEFT) return xLoc - 1; else if (direction == KEY_RIGHT) return xLoc + 1; else return xLoc; } int Character::getY() { return yLoc; } int Character::getNextY() { if (direction == KEY_UP) return yLoc - 1; else if (direction == KEY_DOWN) return yLoc + 1; else return yLoc; } int Character::getDirection() { return direction; } bool Character::checkCollision(int y, int x) { if (mvwinch(window, y, x) == wall || mvwinch(window, y, x) == symbol) { return true; } return false; } bool Character::checkEnemyCollision(char enemy, int y, int x) { if (mvwinch(window, yLoc, xLoc) == enemy ) { return true; } else if (mvwinch(window, y, x) == enemy ) { return true; } return false; } void Character::display() { mvwaddch(window, yLoc, xLoc, symbol); } void Character::revive() { mvwaddch(window, yLoc, xLoc, ' '); yLoc = ySpawnLoc; xLoc = xSpawnLoc; } void Character::moveUp() { if (!checkCollision(yLoc - 1, xLoc)) { mvwaddch(window, yLoc, xLoc, ' '); yLoc--; } } void Character::moveDown() { if (!checkCollision(yLoc + 1, xLoc)) { mvwaddch(window, yLoc, xLoc, ' '); yLoc++; } } void Character::moveLeft() { if (!checkCollision(yLoc, xLoc - 1)) { mvwaddch(window, yLoc, xLoc, ' '); if (xLoc - 1 == -1) xLoc = 22; else xLoc--; } } void Character::moveRight() { if (!checkCollision(yLoc, xLoc + 1)) { mvwaddch(window, yLoc, xLoc, ' '); if (xLoc + 1 == 23) xLoc = 0; else xLoc++; } }
true
950cd4b93661c5214a3b9b28f9a10e631e4e3d36
C++
Bsm-B/iot_workshop
/HelloWorld/HelloWorld.ino
UTF-8
643
3.0625
3
[]
no_license
/** * * @author Bousselmi Bessem * Sources for this can be found at: * https://github.com/bassouma21001/iot_workshop * */ // the setup function runs once when you press reset or power the board #define LED 16 void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
true
595588b3d84811d09f4f9d44fda8ead78370706d
C++
XY-F/algorithm-note
/正文/二分查找区间.cpp
GB18030
2,041
3.890625
4
[]
no_license
#include<cstdio> //A[]ΪУxΪѯصһڵxԪصλ //½Ϊұյ[left,right]ijֵΪ[0,n] int lower_bound(int A[],int left,int right,int x){ int mid; //midΪleftrightе while(left<right){ //[left,right]˵left==rightζҵΨһλ //ҪصһڵxԪصλãҪжԪxǷڣ //ڣصҲǡڣӦôڵλáǵ //left==rightʱ[left,right]պܼгΨһλãҪĽ mid=left+(right-left)/2; //ȡе if(A[mid]>=x){ //мڵx right=mid; //[left,mid] }else{ //мСx left=mid+1; //[mid+1,right] } } if(A[left]<x)return left+1; else return left; //жleft<right,ʵleft==rightleft>right //Ϊؽ } //A[]ΪУxΪѯصһxԪصλ //½Ϊұյ[left,right]ijֵΪ[0,n] int upper_bound(int A[],int left,int right,int x){ int mid; //midΪleftrightе while(left<right){ //[left,right]˵left==rightζҵΨһλ //Ͳ mid=left+(right-left)/2; //ȡе if(A[mid]>x){ //мx right=mid; //[left,mid] }else{ //мСڵxעСڵ left=mid+1; //[mid+1,right] } } if(A[left]<=x)return left+1; else return left; //ؼгλ } int main(){ const int n=5; int A[n]={1,3,3,3,6}; printf("%d %d\n",lower_bound(A,0,4,3),upper_bound(A,0,4,3)); printf("%d %d\n",lower_bound(A,0,4,5),upper_bound(A,0,4,5)); printf("%d %d\n",lower_bound(A,0,4,6),upper_bound(A,0,4,6)); printf("%d %d\n",lower_bound(A,0,4,8),upper_bound(A,0,4,8)); return 0; }
true
a9659c9bf30ce57ae705be6d8d3b49bcfc0ca884
C++
Cirthy/DSLR
/sources/trainer.cpp
UTF-8
488
2.734375
3
[]
no_license
#include "trainer.h" void improve_weights(double weights[4][14], Student* students, int m) { for(int h = 0 ; h < 4 ; h++) improve_thetas(weights[h], students, m, (House)h); } void improve_thetas(double thetas[14], Student* students, int m, House house) { double tmp[14]; int i; for(i = 0 ; i < 14 ; i++) tmp[i] = thetas[i]; for(i = 0 ; i < 14 ; i++) thetas[i] -= LEARNING_RATE * partial_derivative(i, tmp, students, m, house); }
true
e7f46f1e2a209f189350921cd835a968fe0e0276
C++
sagarramdev173/Recursion
/binary_combo.cpp
UTF-8
831
3.421875
3
[]
no_license
/* Print N-bit binary numbers having more 1’s than 0’s numbers having more 1’s than 0’s for any prefix Input: n=3 Output: 111 110 101 */ #include<iostream> #include<string> #include<vector> #define fo(i,n) for(int i=0;i<=n;i++) using namespace std; void solve(int n,int one,int zero,vector<string> &v,string op) { if(n==0) { v.push_back(op); return; } string op1=op; op1.push_back('1'); solve(n-1,one+1,zero,v,op1); if(one>zero) { string op2=op; op2.push_back('0'); solve(n-1,one,zero+1,v,op2); } return; } int main(int argc, char const *argv[]) { int n=3; int one=0; int zero=0; vector<string> v; string op=""; solve(n,one,zero,v,op); for(string i:v) cout<<i<<endl; return 0; }
true
8b30e3fd8eb03cdfa32c0d242defe34da70d73cc
C++
FeibHwang/OJ-Leetcode
/Code/257_Binary_Tree_Paths.cpp
UTF-8
1,493
3.859375
4
[]
no_license
/* Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] */ /* recurrsive algorithm is most straight forward */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> leftstr; vector<string> rightstr; if((root)) { if((root->left)) { leftstr = binaryTreePaths(root -> left); for(int i = 0; i < leftstr.size(); ++i) { leftstr[i] = to_string(root->val) + "->" + leftstr[i]; } } if((root->right)) { rightstr = binaryTreePaths(root -> right); for(int i = 0; i < rightstr.size(); ++i) { rightstr[i] = to_string(root->val) + "->" + rightstr[i]; } } if(!(root->left) && !(root->right)) { leftstr.push_back(to_string(root->val)); } } else { return {}; } leftstr.insert(leftstr.end(),rightstr.begin(),rightstr.end()); return leftstr; } };
true
7ada3d86bd4461323c69be0276751cd6644244c4
C++
targodan/gameProgramming
/engine/src/ECSCommon/PerformanceMetricsSystem.h
UTF-8
1,985
2.59375
3
[ "MIT" ]
permissive
#ifndef PERFORMACEMETRICSSYSTEM_H #define PERFORMACEMETRICSSYSTEM_H #include "../ECS/System.h" #include "../ECS/EntityManager.h" #include "../ECS/Entity.h" #include "TextComponent.h" namespace engine { namespace ECSCommon { using namespace engine::ECS; class PerformanceMetricsSystem : public System { private: static systemId_t systemId; protected: Entity text; float lastUpdateTime = 0; float lastRenderTime = 0; int numUpdates = 0; float timeInUpdates = 0; int numRenders = 0; float timeInRenders = 0; void resetUpdateTimers(); void resetRenderTimers(); RichText renderText() const; public: PerformanceMetricsSystem(EntityManager& em) : text(em.createEntity("PerformanceMetrics")) { this->text.addComponent<TextComponent>(); this->text.getComponent<TextComponent>().setXPixel(10); this->text.getComponent<TextComponent>().setYPixel(20); } PerformanceMetricsSystem(const PerformanceMetricsSystem& orig) = delete; virtual ~PerformanceMetricsSystem() {} void run(EntityManager& em, float deltaTimeSeconds) override; bool isUpdateSystem() const override { return true; } bool isRenderSystem() const override { return true; } systemId_t getSystemTypeId() const override; std::string getSystemName() const override { return "PerformanceMetricsSystem"; } static systemId_t systemTypeId(); static void setSystemTypeId(systemId_t id); }; } } #endif /* PERFORMACEMETRICSSYSTEM_H */
true
d2ef1ea298c6270af2e68bbdd620688db29783ae
C++
SmallE0529/Binary_Tree_Force_Cpp
/binary_tree_force.cpp
UTF-8
2,829
3.75
4
[]
no_license
#include "binary_tree_force.h" #include <queue> using namespace std; void binary_tree::pre_order(tree_node *current) { if(current != nullptr) { cout << current->str << " "; pre_order(current->left_child); pre_order(current->right_child); } } void binary_tree::in_order(tree_node *current) { if(current != nullptr) { in_order(current->left_child); cout << current->str << " "; in_order(current->right_child); } } void binary_tree::post_order(tree_node *current) { if(current != nullptr) { post_order(current->left_child); post_order(current->right_child); cout << current->str << " "; } } void binary_tree::level_order() { queue<tree_node*> q; q.push(this->root); while(!q.empty()) { tree_node *current = q.front(); q.pop(); cout << current->str << " "; if(current->left_child != nullptr) { q.push(current->left_child); } if(current->right_child != nullptr) { q.push(current->right_child); } } } tree_node* binary_tree::left_most(tree_node *current) { while(current->left_child != nullptr) { current = current->left_child; } return current; } tree_node* binary_tree::right_most(tree_node *current) { while(current->right_child != nullptr) { current = current->right_child; } return current; } tree_node* binary_tree::in_order_successor(tree_node *current) { if(current->right_child != nullptr) { return left_most(current->right_child); } tree_node* successor = current->parent; while(successor != nullptr && current == successor->right_child) { current = successor; successor = current->parent; } return successor; } tree_node* binary_tree::in_order_predecessor(tree_node *current) { if(current->left_child != nullptr) { return right_most(current->left_child); } tree_node* predecessor = current->parent; while(predecessor != nullptr && current == predecessor->left_child) { current = predecessor; predecessor = current->parent; } return predecessor; } void binary_tree::in_order_by_parent(tree_node *root) // sequcnce print tree { tree_node* current = new tree_node; current = left_most(root); while (current != nullptr) { cout << current->str << " "; current = in_order_successor(current); } } void binary_tree::in_order_reverse(tree_node *root) // reverse print tree { tree_node* current = new tree_node; current = right_most(root); while(current != nullptr) { cout << current->str << " "; current = in_order_predecessor(current); } }
true
31278adb703d4a878282bd2f014c8a33c6bbf2a0
C++
raysayantan/CodeSignal
/firstDuplicate.cpp
UTF-8
1,377
4.09375
4
[]
no_license
/* Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. Example For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3. There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3. For a = [2, 2], the output should be firstDuplicate(a) = 2; For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1. Input/Output [execution time limit] 0.5 seconds (cpp) [input] array.integer a Guaranteed constraints: 1 ≤ a.length ≤ 105, 1 ≤ a[i] ≤ a.length. [output] integer The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1. */ //Only the function int firstDuplicate(std::vector<int> a) { set<int> container; int l = a.size(); for(int i = 0; i < l; i++){ if(container.find(a[i]) != container.end()){ return a[i]; } container.insert(a[i]); } return -1; }
true
42e0e1075ca00856ea70f7e2a4fefd7b403b9daf
C++
apankrat/cpp-serializer
/example.cpp
UTF-8
1,020
2.8125
3
[ "BSD-2-Clause" ]
permissive
/* * CPP Seializer - Fast and simple data serialization for C++. * * https://swapped.ch/cpp-serializer * * The code is distributed under terms of the BSD license. * Copyright (c) 2019 Alex Pankratov. All rights reserved. */ #include "serialize.h" #include "serialize_obj.h" #include <assert.h> /* * 1. Define your structs */ struct foo { bool val_b; std::string val_s; uint16_t val_u; double val_d; }; struct bar { std::map<uint32_t, foo> baz; std::vector<std::string> qux; }; /* * 2. Specify which fields to serialize */ OBJECT_SPEC( foo ) __f( val_b ), __f( val_s ), __f( val_u ), __f( val_d ) END_OF_SPEC OBJECT_SPEC( bar ) __f( baz ), __f( qux ) END_OF_SPEC /* * 3. ... and done! Serialize at will. */ int main(int argc, char ** argv) { /* * store */ buffer buf; bar in; store(buf, in); /* * parse */ parser par; bar out; par.init(buf); parse(par, out); assert( par.eof() ); // "out" is now the same as "in" return 0; }
true
a0004d438843edbd11892335680ca6b9b8171e63
C++
Crazyfighting/PTT
/Viewer.h
BIG5
759
3.046875
3
[]
no_license
#pragma once #include<iostream> class Viewer { public: void printMenu(){ std::cout << "wӨaX,пJb,άOJguestιCȼҦiJ,JnewЫطsb,JrhX:"; } void printchooseBoard() { std::cout << "JsiJwݪO,Jr^:"; } void printviewBoard() { std::cout << "JsiJwK,Jr^:"; } void printPost() { std::cout << "Jr^:"; } void printMailBoard() { std::cout << "JsiJwl,Jwritegl,JdeleteRl,Jr^:"; } void printMail() { std::cout << "Jreply^жl,D(RE:^жl󪺼D),Jr^:"; } };
true
77abbbfdcea02090e8b8bcbb43f8d19180ccc4b4
C++
AviciiPL/aimp-control-plugin
/src/jsonrpc/jsonrpc_response_serializer.cpp
UTF-8
3,342
2.75
3
[ "MIT" ]
permissive
// Copyright (c) 2014, Alexey Ivanov #include "stdafx.h" #include "jsonrpc/response_serializer.h" #include "jsonrpc/value.h" #include "jsonrpc/writer.h" #include "rpc/value.h" #include "rpc/exception.h" #include <cassert> namespace JsonRpc { const std::string kMIME_TYPE = "application/json"; struct ResponseSerializerImpl { Json::FastWriter writer; }; ResponseSerializer::ResponseSerializer() : impl_(new ResponseSerializerImpl) {} ResponseSerializer::~ResponseSerializer() { delete impl_; } void convertRpcValueToJsonRpcValue(const Rpc::Value& rpc_value, Json::Value* json_rpc_value); // throws Rpc::Exception void ResponseSerializer::serializeSuccess(const Rpc::Value& root_response, std::string* response) const { Json::Value jsonrpc_response; convertRpcValueToJsonRpcValue(root_response, &jsonrpc_response); jsonrpc_response["jsonrpc"] = "2.0"; *response = impl_->writer.write(jsonrpc_response); } void ResponseSerializer::serializeFault(const Rpc::Value& root_request, const std::string& error_msg, int error_code, std::string* response) const { Json::Value response_value; if ( root_request.isMember("id") ) { convertRpcValueToJsonRpcValue(root_request["id"], &response_value["id"]); } else { response_value["id"] = Json::Value::null; } response_value["jsonrpc"] = "2.0"; Json::Value& error = response_value["error"]; error["message"] = error_msg; error["code"] = error_code; *response = impl_->writer.write(response_value); } const std::string& ResponseSerializer::mimeType() const { return kMIME_TYPE; } void convertRpcValueToJsonRpcValue(const Rpc::Value& rpc_value, Json::Value* json_rpc_value) // throws Rpc::Exception { assert(json_rpc_value); switch ( rpc_value.type() ) { case Rpc::Value::TYPE_NONE: // treat none rpc value as null json value. ///??? case Rpc::Value::TYPE_NULL: Json::Value().swap(*json_rpc_value); break; case Rpc::Value::TYPE_BOOL: *json_rpc_value = bool(rpc_value); break; case Rpc::Value::TYPE_INT: *json_rpc_value = int(rpc_value); break; case Rpc::Value::TYPE_UINT: *json_rpc_value = unsigned int(rpc_value); break; case Rpc::Value::TYPE_DOUBLE: *json_rpc_value = double(rpc_value); break; case Rpc::Value::TYPE_STRING: *json_rpc_value = static_cast<const std::string&>(rpc_value); break; case Rpc::Value::TYPE_ARRAY: json_rpc_value->resize( rpc_value.size() ); for (size_t i = 0, size = json_rpc_value->size(); i != size; ++i) { convertRpcValueToJsonRpcValue(rpc_value[i], &((*json_rpc_value)[i])); } break; case Rpc::Value::TYPE_OBJECT: { *json_rpc_value = Json::Value(); auto member_it = rpc_value.getObjectMembersBegin(), end = rpc_value.getObjectMembersEnd(); for (; member_it != end; ++member_it) { convertRpcValueToJsonRpcValue( member_it->second, &((*json_rpc_value)[member_it->first]) ); } } break; default: throw Rpc::Exception("unknown type", Rpc::TYPE_ERROR); } } } // namespace JsonRpc
true
15df4976646e7774d21fea875e33a61921c29bf7
C++
baifengbai/c
/c++基础学习/Day13/test05/furniture.h
UTF-8
677
2.984375
3
[ "Apache-2.0" ]
permissive
#ifndef _FURNITURE_H_ #define _FURNITURE_H_ #include<iostream> using namespace::std; //再次抽象sofa和bed class furniture { public: furniture(int weight=0); void set_weight(int weight) { m_weight = weight; cout<<"weight: "<<m_weight<<endl; } private: int m_weight; }; class sofa:virtual public furniture{ public: sofa(int weight=0); void WatchTv() { cout<<"WatchTv"<<endl; } }; class bed :virtual public furniture{ public: bed(int weight=0); void sleep() { cout<<"sleep"<<endl; } }; class SofaBed: public sofa, public bed { public: SofaBed(int weight=0); void foldout() { cout<<"foldout"<<endl; } }; #endif
true
6dcbfc2b3ddadaa7396b2984977ff7b1e420af55
C++
BogdanAriton/starter_kit_cpp
/modern-cpp-features/c++11/functor.cpp
UTF-8
374
4.125
4
[]
no_license
#include <iostream> // this is a functor struct add_x { // this is a constexpr because it can be evaluated at compile time constexpr add_x(int val) : x(val) {} // Constructor constexpr int operator()(int y) const { return x + y; } private: int x; }; int main() { constexpr add_x adder(10); std::cout << adder(20) << '\n'; // prints 30 (will add 10 + 20) }
true
87381b67d350e85ca304511bf65a61705c146d56
C++
jackbergus/NotesOnProgramming2020
/include/utils/orders/LexicographicalOrder.h
UTF-8
1,176
3.21875
3
[]
no_license
// // Created by giacomo on 31/01/2020. // #ifndef TUTORIALS_LEXICOGRAPHICALORDER_H #define TUTORIALS_LEXICOGRAPHICALORDER_H #define ForAll2(T,U) template <typename T, typename U> /** * Defining an ordering over vectors following the lexicographical order * @tparam T Type associated to the container * @tparam U Type associated to the content */ ForAll2(T,U) struct LexicographicalOrder { std::less<U> lesscmp; // Default comparator for the content bool operator()(const T& lhs, const T& rhs) const { return compare(lhs, rhs, 0); } private: bool compare(const T& lhs, const T& rhs, size_t idx) const { if (idx == lhs.size()) { return !(idx == rhs.size()); } else { if (idx == rhs.size()) { return false; } else { if (lesscmp(lhs[idx], rhs[idx])) { return true; } else if (lesscmp(rhs[idx], lhs[idx])) { return false; } else { return compare(lhs, rhs, idx+1); } } } } }; #endif //TUTORIALS_LEXICOGRAPHICALORDER_H
true
94406c6d005f6ca6df35545afe090b8fcec20d9e
C++
Redyz/space-invaders
/src/game/utility.cpp
UTF-8
2,100
3.015625
3
[ "MIT" ]
permissive
#include "utility.h" #include "config.h" #include <fstream> #include <string> #include <ctime> #include <time.h> #include <stdio.h> #include <cstdlib> #include <iostream> #include <sys/stat.h> #ifdef IS_NT #include <direct.h> #endif Utility::Utility(Window *window){ this->window = window; } Utility::~Utility(){ } void Utility::print(std::string text){ //window->display(text); } void Utility::print(std::string text, int x, int y){ //window->display(text, x, y); } int Utility::log(std::string){ return 0; } bool Utility::directory_exists(std::string path){ struct stat info; stat(path.c_str(), &info); if(info.st_mode & S_IFDIR) return true; return false; } // Returns 0 on success, 1 on error (path exists, can't create) int Utility::create_directory(std::string path){ #ifdef IS_NT return mkdir(path.c_str()) == 0 ? 0 : 1; #else return mkdir(path.c_str(), 0755) == 0 ? 0 : 1; #endif } void Logger::log(std::string message){ time_t currentTime = std::time(0); //now struct tm *currentTimeStruct = localtime(&currentTime); //TODO: constant if(!Utility::directory_exists("logs")) Utility::create_directory("logs"); char buffer[100]; std::fstream logFile; logFile.open(LOG_PATH, std::ios::out | std::fstream::app); if(!logFile.is_open()){ std::cout << "Could not open log file! Cowardly exiting!" << std::endl; std::exit(0); } strftime(buffer, sizeof(buffer), "[%Y-%m-%d][%X] ", currentTimeStruct); logFile << buffer << message << std::endl; logFile.close(); } // http://stackoverflow.com/questions/23526556/c11-analog-of-c-sharp-stopwatch typedef std::chrono::high_resolution_clock precise_clock; Timer::Timer(std::string message){ this->message = message; start_time = precise_clock::now(); } void Timer::stop(){ auto end_time = precise_clock::now(); auto diff = end_time - start_time; auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(diff); //char buffer[200]; //sprintf(buffer, "'%s' took %i ns to complete", message.c_str(), (int)nanoseconds.count()); //Logger::log(buffer); }
true
2571eca6bbd783b4040809d794d4d22cb07dd997
C++
chuckinSpace/OOP344
/w6/Product.cpp
UTF-8
689
2.9375
3
[]
no_license
// Name: Carlos Moyano // Seneca Student ID: 123435174 // Seneca email: cmoyano-rugiero@mysenecac.ca // Date of completion: 10-31-18 // // I confirm that the content of this file is created by me, // with the exception of the parts provided to me by my professor. #include <iostream> #include <iomanip> #include "Product.h" using namespace std; namespace w6{ Product::Product(string pNum, const double price){ _pPrice = price; _pNumber = pNum; } double Product::getPrice()const{ return _pPrice; } void Product::display(std::ostream& os) const{ os << std::right << std::setw(16) << _pNumber << std::setprecision(2) << std::setw(16) << _pPrice; } }
true
c3a44d3b62bea8c1fcfe1ad4a1576d08028aead9
C++
AshburnLee/LeetCode
/_67AddBinary.cpp
UTF-8
2,206
3.1875
3
[]
no_license
// // Created by junhui on 18/03/19. // #include <iostream> #include <string> //#include <stdlib.h> using namespace std; class Solution{ public: // string addBinary2(string a, string b){ // prepare a & b int N = maxN(a,b); a.insert(0, N - a.size(), '0'); b.insert(0, N - b.size(), '0'); //logic int jinwei = 0; string res = ""; int sum = 0; for (int i=N-1; i>=0; i--){ sum = char2int(a[i]) + char2int(b[i]) + jinwei; int value; jinwei = sum/2; value = sum%2; // res.insert(res.begin(), int2char(value)); res = int2char(value) + res; // faster than the above one!!!!!!!!!!!! } if (jinwei == 1) res.insert(res.begin(), int2char(jinwei)); if (res[0] == '0') res.erase(0,1); return res; } int char2int(char c){ int res; return res = c == '0'?0:1; } char int2char(int i){ char res; return res = i == 1?'1':'0'; } int maxN(string a, string b){ return static_cast<int>(a.size() > b.size() ? a.size()+1 : b.size()+1); } string addBinary(string a, string b) { int i = a.size()-1; int j = b.size()-1; int carry = 0; string ret = ""; while (i >= 0 || j >= 0 || carry!=0) { if (i >= 0) { carry += a[i]=='0'?0:1; i--; } if (j >= 0) { carry += b[j]=='0'?0:1; j--; } ret = ((carry%2)==0?"0":"1") + ret; carry /= 2; } return ret; } }; int main(int argc, char** argv){ string a = "101101"; string b = "1011"; // int n = Solution().maxN(a,b); // // a.insert(0, n-a.size(), '0'); // b.insert(0, n-b.size(), '0'); // // cout<<a<<endl; // cout<<b<<endl; cout<<"***********************"<<endl; string res = Solution().addBinary2(a,b); cout<<res<<endl; string res2 = Solution().addBinary(a,b); cout<<res2<<endl; // string x = "123"; // char y = 'u'; // cout<<y+x<<endl; return 0; }
true
36ebce68f3054cade4eab5d28e0fceeb65413c7b
C++
lfxy/netframe
/Socket.cpp
UTF-8
1,152
2.625
3
[]
no_license
#include "Socket.h" #include "InetAddress.h" #include "SocketOps.h" #include <netinet/in.h> #include <netinet/tcp.h> #include <strings.h> Socket::~Socket() { SocketOps::close(m_sockfd); } void Socket::bindAddress(const InetAddress& localaddr) { SocketOps::bindOrDie(m_sockfd, localaddr.getSockAddrInet()); } void Socket::listen() { SocketOps::listenOrDie(m_sockfd); } int Socket::accept(InetAddress* peeraddr) { struct sockaddr_in addr; bzero(&addr, sizeof(addr)); int connfd = SocketOps::accept(m_sockfd, &addr); if(connfd >= 0) { peeraddr->setSockAddrInet(addr); } return connfd; } void Socket::shutdownWrite() { SocketOps::shutdownWrite(m_sockfd); } void Socket::setTcpNoDelay(bool on) { int optval = on ? 1: 0; ::setsockopt(m_sockfd, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval)); } void Socket::setReuseAddr(bool on) { int optval = on ? 1: 0; ::setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); } void Socket::setKeepAlive(bool on) { int optval = on ? 1: 0; ::setsockopt(m_sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)); }
true
0154dc647637d6855d27d341ed24b3cb69708fc0
C++
Mrhero-web/leetcode-pp
/code/ch03/3.5.2.longestPalindromeSubseq.cpp
UTF-8
698
2.984375
3
[ "MIT" ]
permissive
#include <cstdlib> #include <string> #include <algorithm> using namespace std; class Solution { public: int longestPalindromeSubseq(string s) { int n = s.length(); int *pre = (int *)malloc(n * sizeof(int)); int *cur = (int *)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) pre[i] = cur[i] = 0; for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { if (i == j) cur[j] = 1; else if (s[i] == s[j]) cur[j] = pre[j - 1] + 2; else cur[j] = max(pre[j], cur[j - 1]); } for (int j = 0; j < n; j++) pre[j] = cur[j]; } int ans = pre[n - 1]; free(pre); free(cur); return ans; } };
true
9ac1c2e11ebfc39d01ab5277889eaf6ff94898fb
C++
Techno1109/DxLib-ClassicRayTracing
/Geometory/Geometry.cpp
UTF-8
3,872
3.28125
3
[]
no_license
#include"Geometry.h" #include<DxLib.h> #include<cmath> void Rect::Draw() { DxLib::DrawBox(Left()*2, Top()*2, Right()*2, Bottom()*2, 0xffffffff, false); } void Rect::Draw(Vector2& offset) { DxLib::DrawBox((Left()+offset.x)*2, (Top()+offset.y)*2, (Right()+offset.x)*2, (Bottom()+offset.y)*2, 0xffffffff, false); } void Vector2::operator*=(float scale) { x *= scale; y *= scale; } Vector2 Vector2::operator*(float scale) { return Vector2(x*scale, y*scale); } Vector2 operator+(const Vector2& va, const Vector2 vb) { return Vector2(va.x + vb.x, va.y + vb.y); } Vector2 operator-(const Vector2& va, const Vector2 vb) { return Vector2(va.x - vb.x, va.y - vb.y); } float Vector2::Magnitude()const { return hypot(x, y); } void Vector2::Normalize() { float mag = Magnitude(); x /= mag; y /= mag; } Vector2 Vector2::Normalized() { float mag = Magnitude(); return Vector2(x / mag, y /mag); } float Dot(const Vector2& va, const Vector2& vb) { return va.x*vb.x + va.y*vb.y; } float Cross(const Vector2& va, const Vector2& vb) { return va.x*vb.y - vb.x*va.y; } float operator*(const Vector2& va, const Vector2& vb) { return Dot(va, vb); } float operator%(const Vector2& va, const Vector2& vb) { return Cross(va, vb); } Color operator*(const Color va, const Color vb) { Color Return = Color(va.Red*vb.Red, va.Green*vb.Green, va.Blue*vb.Blue); Return.Clamp(); return Return; } void Vector2::operator+=(const Vector2& v) { x += v.x; y += v.y; } void Vector2::operator-=(const Vector2& v) { x -= v.x; y -= v.y; } void Vector3::operator*=(float scale) { x *= scale; y *= scale; z *= scale; } Vector3 Vector3::operator*(float scale)const { return Vector3(x*scale, y*scale,z*scale); } Vector3 operator+(const Vector3& va, const Vector3 vb) { return Vector3(va.x + vb.x, va.y + vb.y,va.z+vb.z); } Vector3 operator-(const Vector3& va, const Vector3 vb) { return Vector3(va.x - vb.x, va.y - vb.y,va.z-vb.z); } float Vector3::Magnitude()const { return sqrt(x*x+y*y+z*z); } void Vector3::Normalize() { float mag = Magnitude(); x /= mag; y /= mag; z /= mag; } Vector3 Vector3::Normalized() { float mag = Magnitude(); return Vector3(x / mag, y / mag,z/mag); } float Dot(const Vector3& va, const Vector3& vb) { return va.x*vb.x + va.y*vb.y+va.z*vb.z; } Vector3 Cross(const Vector3& va, const Vector3& vb) { return Vector3(va.z*vb.y-va.y*vb.z,va.z*vb.x-va.x*vb.z,va.x*vb.y - vb.x*va.y); } float operator*(const Vector3& va, const Vector3& vb) { return Dot(va, vb); } Vector3 operator%(const Vector3& va, const Vector3& vb) { return Cross(va, vb); } void Vector3::operator+=(const Vector3& v) { x += v.x; y += v.y; z += v.z; } void Vector3::operator-=(const Vector3& v) { x -= v.x; y -= v.y; z -= v.z; } void Color::ApplyDiffuse(float& Diffuse) { Red *= (Diffuse); Green *= (Diffuse); Blue *= (Diffuse); } void Color::ApplySpecular(float& Specular) { Red += Specular; Green += Specular; Blue += Specular; } void Color::AppplyMaterial(Material & Mat) { ApplyDiffuse(Mat.DiffuseB); ApplySpecular(Mat.SpecularB); Clamp(); } void Color::Clamp(const float Min, const float Max) { Red = max(min(Red, Max), Min); Green = max(min(Green, Max), Min); Blue = max(min(Blue, Max), Min); } void Color::BlendColor(const Color vb,float Alpha) { Red = Red * (1 - Alpha) + (vb.Red*Alpha); Blue = Blue * (1 - Alpha) + (vb.Blue*Alpha); Green = Green * (1 - Alpha) + (vb.Green*Alpha); Clamp(); } Color Color::operator*(float scale) const { Color ReturnCol; ReturnCol.Red = Red*scale; ReturnCol.Blue = Blue* scale; ReturnCol.Green = Green*scale; return ReturnCol; }
true
b3edaa821bbc3912f34e5b6f4e2cfa0a7d3abac4
C++
d093w1z/ASCIIChess
/Peice.hpp
UTF-8
580
2.640625
3
[]
no_license
#include <vector> typedef std::vector <std::pair <int,int>> pos_list; typedef std::pair <int,int> pos_pair; class Peice { char P_col; char P_id; pos_pair P_pos; pos_list avail_moves; public: bool in_game; Peice(); void set(char id,char col,int x,int y,bool ig); void set(char id,char col, bool ig); char id(){ return P_id; } char col(){ return P_col; } std::pair <int,int> pos(){ return P_pos; }; int move(Peice &p); bool check_move(Peice (&b)[8][8],int x,int y); void capture(); Peice operator=(Peice &p); };
true
03f11668bb0b93b01eac44c3ce42f60662e62f4b
C++
ceKyleLee/cad20-tgls
/Simulation/src/parser/FileReader.h
UTF-8
887
2.75
3
[ "MIT" ]
permissive
#ifndef FILEREADER_H #define FILEREADER_H #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <string> using std::string; class FileReader { private: char* filename; char* ptr; struct stat sb; public: FileReader(char* f, void* pPos = NULL): filename(f) { int fd = open(filename, O_RDONLY); fstat(fd, &sb); ptr = static_cast<char*>(mmap( pPos, sb.st_size, PROT_READ, MAP_SHARED, fd, 0)); } ~FileReader() { close(); } void close() { if (ptr != MAP_FAILED) munmap(ptr, sb.st_size); } inline char* getPtr () const { return ptr; } inline void* getFileEnd () const { return (void*)(ptr+sb.st_size); } inline off_t getFileSize() const { return sb.st_size; } }; #endif
true
1c44851908abc28aaf87004acd6c69f74fcf7541
C++
braindigitalis/sleepy-discord
/include/sleepy_discord/voice.h
UTF-8
1,409
2.546875
3
[ "MIT" ]
permissive
#pragma once #include "discord_object_interface.h" #include "snowflake.h" namespace SleepyDiscord { //forward declearion struct Server; struct Channel; struct User; struct VoiceState : public DiscordObject { Snowflake<Server> serverID; Snowflake<Channel> channelID; Snowflake<User> userID; std::string sessionID; bool deaf; bool mute; bool selfDeaf; bool selfMute; bool suppress; }; /* Voice Region Structure Field Type Description id string unique ID for the region name string name of the region sample_hostname string an example hostname for the region sample_port integer an example port for the region vip bool true if this is a vip-only server optimal bool true for a single server that is closest to the current user's client deprecated bool whether this is a deprecated voice region (avoid switching to these) custom bool whether this is a custom voice region (used for events/etc) */ struct VoiceRegion : IdentifiableDiscordObject<VoiceRegion> { VoiceRegion(); VoiceRegion(const std::string * rawJson); VoiceRegion(const std::vector<std::string> values); std::string name; std::string sampleHostname; int samplePort; bool vip; bool optimal; bool deprecated; bool custom; private: const static std::initializer_list<const char*const> fields; }; }
true
ec0392659f83a70668723dd738fd58d1d0c86987
C++
ryokamoi/competitiveprog
/poj/poj1182.cpp
UTF-8
1,440
2.8125
3
[]
no_license
#include <iostream> using namespace std; #define REP(i, n) for(int i=0; i<n; i++) int par[3 * 50050]; int rk[3 * 50050]; void init (int n) { REP(i, n) { par[i] = i; rk[i] = 0; } } int find (int x) { if (par[x] == x) { return x; } else { return par[x] = find(par[x]); } } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) { return ; } else { if (rk[x] < rk[y]) { par[x] = y; } else { par[y] = x; if (rk[x] == rk[y]) { rk[x] += 1; } } return ; } } bool same(int x, int y) { return find(x) == find(y); } int main() { int n, k; cin >> n >> k; init(3*n); int miss = 0; REP(i, k) { int t, x, y; scanf("%d %d %d", &t, &x, &y); if (x<=0 || x>n || y<=0 || y>n) { miss ++; continue; } x --; y--; if (t == 1) { if (same(x, n+y) || same(x, 2*n+y)) { miss++; } else { unite(x, y); unite(x+n, y+n); unite(x+2*n, y+2*n); } } if (t == 2) { if (same(x, y) || same(x, 2*n+y)) { miss++; } else { unite(x, y+n); unite(x+n, y+2*n); unite(x+2*n, y); } } } printf("%d\n", miss); }
true
c462da45c8d5163f5ce786f4185074ca61c002ef
C++
birdmanmandbir/leetcode-record
/leetleet/lc1111有效括号的嵌套深度/1111.cpp
UTF-8
727
3.203125
3
[]
no_license
#include <string> #include <stack> #include <iostream> #include <vector> using namespace std; // 1. 嵌套深度即为栈长度 // 2. 按嵌套深度的奇偶性来区分 vector<int> maxDepthAfterSplit(string seq) { vector<int> result(seq.size(), 0); stack<char> sk; vector<int> depth(seq.size()); int i = 0; for (char c : seq) { if (c == '(') { sk.push(c); depth[i] = sk.size(); } else { depth[i] = sk.size(); sk.pop(); } i++; } i = 0; for (int d:depth){ if(d%2==0){ result[i]=1; } i++; } return result; }
true
aaa487cdae640eb9c41ca92e320af7ed64a039cf
C++
grahammc-bit/CSCE240
/CSCE240/exam2/inc/char_matrix.h
UTF-8
1,166
2.84375
3
[]
no_license
// Copyright 2020 Matthew Graham #ifndef INC_CHAR_MATRIX_H_ // NOLINT #define INC_CHAR_MATRIX_H_ // NOLINT // CharMatrix Points: // Compiles: 1 (make test_char_matrix) // Lints: 1 (cpplint --root=./ */char_matrix.*) // TestFillConstructor: 1 // TestCopyConstructor: 1 // TestAssignOperator: 1 // test_char_matrix_memory: 1 (make test_char_matrix_memory) #include <cstddef> // using size_t /* This is a small character matrix class to test your ability to manage * memory in a class. You must Implement a fill constructor, a copy constructor, * and assignment operator, and a destructor. */ class CharMatrix { public: /* implement default constructor, does not need to allocate memory */ CharMatrix(); /* chars is a two-dimensional array with rows x cols cells */ CharMatrix(const char** chars, size_t rows, size_t cols); /* implement me */ CharMatrix(const CharMatrix& that); /* implement me */ ~CharMatrix(); /* implement me */ const CharMatrix& operator=(const CharMatrix& rhs); friend class CharMatrixTester; // ignore me private: char **matrix_; size_t rows_; size_t cols_; }; #endif // NOLINT
true
106ff6eb48d1ad75a6279cb81b04968254b60a72
C++
MichaelxhJiang/LeetCode
/LongestSubstringNoRepeatingCharacters.cc
UTF-8
271
2.765625
3
[]
no_license
int longestSubstring(string s) { unordered_map<char, int> map; int ans = 0; for (int i = 0, j = 0; i < s.length(); i++) { if (map.find(s[i]) != map::end) { j = map.at(s[i]); } if (i - j > ans) ans = i - j; map.insert({s[i], i}); } return ans; }
true
1be8afd4741467b21d8375b2a6d3b51ffc2bbb8d
C++
ccpang96/SGI_STL
/SGI_STL/Memory_Management_Header/per_class_allocator.h
GB18030
461
2.765625
3
[]
no_license
#pragma once namespace per_class_allocator { void per_class_allocator_function(); class Screen { public: Screen(int x) : i(x) {}; int get() { return i; } void* operator new(size_t); void operator delete(void*, size_t); private: Screen * next; //ֶ4ֽڣͰٷְ٣mallocĴȥcookie,һһnextָ static Screen* freeStore; static const int screenChunk; private: int i; }; }
true
6f14860266dcd2ab18954fe198bb1ced2cccdf2d
C++
eujuu/Algorithm
/baekjoon/백준 1654 랜선 자르기.cpp
UTF-8
812
2.765625
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <string> #include <algorithm> using namespace std; int main() { vector<int> arr; long long start = 1; long long end = 0; long long max = 0; int n, k, tmp; scanf("%d%d", &n, &k); //cin >> n >> k; // for(int i=0; i < n; i++) { scanf("%d", &tmp);// cin >> tmp; arr.push_back(tmp); if (tmp > end) end = tmp; } while (start <= end) { long long mid = (start + end) / 2; int cnt = 0; //cout << start << " " << end << " " << mid << " " << endl; for (int i = 0; i < n; i++) cnt += (arr[i] / mid); //cout << arr[i] << " " << mid << " " << cnt << endl; //cout << cnt << " " << k << endl; if (cnt >= k) { start = mid + 1; if (mid > max) max = mid; } else end = mid - 1; } cout << max << endl; }
true
f6c24bbc02f643b1546a36b94aa72ad53c5a5e48
C++
TheDizzler/RPGEngine
/Source/Engine/Camera.cpp
UTF-8
2,301
3.046875
3
[]
no_license
#include "Camera.h" Camera::Camera(int vwprtWdth, int vwprtHght) { zoom = 1.0f; viewportWidth = vwprtWdth; viewportHeight = vwprtHght; viewportCenter = Vector3(viewportWidth * .5, viewportHeight * .5, 0); position = Vector2::Zero; } Camera::~Camera() { } void Camera::setMap(MAPFile * mapFile) { map = mapFile; mapWidth = map->mapWidth * map->tileWidth; mapHeight = map->mapHeight* map->tileHeight; viewX = (viewportWidth / zoom / 2); viewY = (viewportHeight / zoom / 2); } void Camera::adjustZoom(float amount) { zoom += amount; if (zoom < 0.5f) zoom = 0.5f; else if (zoom > 2.5) zoom = 2.5; viewX = (viewportWidth / zoom / 2); viewY = (viewportHeight / zoom / 2); } void Camera::moveCamera(Vector2 cameraMovement, bool clampToMap) { Vector2 newPos = position + cameraMovement; if (clampToMap) mapClampedPosition(newPos); position = newPos; } RECT* Camera::viewportWorldBoundary() { Vector2* viewportCorner = screenToWorld(Vector2::Zero); Vector2* viewportBottomCorner = screenToWorld(Vector2(viewportWidth, viewportHeight)); RECT* rect = new RECT{(int) viewportCorner->x, (int) viewportCorner->y, (int) (viewportBottomCorner->x - viewportCorner->x), (int) (viewportBottomCorner->y - viewportCorner->y)}; delete viewportCorner; delete viewportBottomCorner; return rect; } void Camera::centerOn(Vector2 pos, bool clampToMap) { if (clampToMap) mapClampedPosition(pos); position = pos; } Vector2* Camera::screenToWorld(Vector2 screenPosition) { Vector2* vec = new Vector2(); Vector2::Transform(screenPosition, translationMatrix().Invert(), *vec); return vec; } void Camera::mapClampedPosition(Vector2& position) { Vector2 cameraMax = Vector2( mapWidth - viewX, mapHeight - viewY); Vector2 cameraMin = Vector2(viewX, viewY); if (cameraMax.x < cameraMin.x) position.Clamp(cameraMax, cameraMin); else /*if (cameraMax.y < cameraMin.y) position.Clamp(cameraMax, cameraMin); else*/ position.Clamp(cameraMin, cameraMax); } Matrix Camera::translationMatrix() { // casting to int prevents filtering artifacts?? return Matrix::CreateTranslation(-(int) position.x, -(int) position.y, 0) * Matrix::CreateRotationZ(rotation) * Matrix::CreateScale(zoom, zoom, 1) * Matrix::CreateTranslation(viewportCenter); }
true
e54ef4110a994386af9489348b6f483e30a4f28c
C++
bk2earth/KV_Store_Engine_TaurusDB_Race
/KV_Store_Engine_TaurusDB_Race_stage2/example/kv_store/rpc_process.cc
UTF-8
4,626
2.609375
3
[ "MIT" ]
permissive
#include "rpc_process.h" #include <unistd.h> #include <thread> #include "utils.h" bool RpcProcess::Insert(char * buf, int len, DoneCbFunc cb) { if (buf == nullptr || len < PACKET_HEADER_SIZE) { KV_LOG(ERROR) << "insert to RpcProcess failed. size: " << len; return false; } auto & rpc = *(Packet *)buf; if (rpc.len + PACKET_HEADER_SIZE != len) { KV_LOG(ERROR) << "expect size: " << rpc.len << " buf size: " << len - PACKET_HEADER_SIZE; return false; } uint32_t sum = rpc.Sum(); if (sum != rpc.crc) { KV_LOG(ERROR) << "crc error, expect: " << rpc.crc << " get: " << sum; return false; } else { std::lock_guard<std::mutex> lock(mutex_); reqQ_.emplace_back(buf, cb); cv_.notify_one(); return true; } } bool RpcProcess::Run(const char * dir, bool clear) { const char * data_ext = ".data"; const char * meta_ext = ".meta"; dir_ = dir; data_.Init(dir_.Buf(), data_ext); meta_.Init(dir_.Buf(), meta_ext); if (clear) { data_.Clear(); meta_.Clear(); data_.Init(dir_.Buf(), data_ext); meta_.Init(dir_.Buf(), meta_ext); } std::thread th(&RpcProcess::process, this); th.detach(); } void RpcProcess::Stop() { run_ = false; sleep(1); } bool RpcProcess::process() { run_ = true; while(run_) { std::list<PacketInfo> packets; do { std::unique_lock<std::mutex> lock(mutex_); cv_.wait(lock, [&] ()->bool { return !reqQ_.empty() || !run_; }); packets = std::move(reqQ_); } while(0); for(auto packet: packets) { auto & req = *(Packet *)packet.buf; switch(req.type) { case KV_OP_META_APPEND: processAppend(meta_, packet.buf, packet.cb); break; case KV_OP_META_GET: processGet(meta_, packet.buf, packet.cb); break; case KV_OP_DATA_APPEND: processAppend(data_, packet.buf, packet.cb); break; case KV_OP_DATA_GET: processGet(data_, packet.buf, packet.cb); break; case KV_OP_CLEAR: //TODO: clear local data break; default: LOG(ERROR) << "unknown rpc type: " << req.type; packet.cb(nullptr, 0); break; } delete [] packet.buf; } } } void RpcProcess::processAppend(DataMgr & target, char * buf, DoneCbFunc cb) { auto & req = *(Packet *) buf; int key_size = *(int *)req.buf; int val_size = *(int *)(req.buf + sizeof(int)); if (key_size + val_size + sizeof(int) * 2 > req.len) { KV_LOG(ERROR) << "kv size error: " << key_size << "+" << val_size << "-" << req.len; return; } KVString key; KVString val; char * key_buf = new char [key_size]; char * val_buf = new char [val_size]; memcpy(key_buf, req.buf + sizeof(int) * 2, key_size); memcpy(val_buf, req.buf + sizeof(int) * 2 + key_size, val_size); key.Reset(key_buf, key_size); val.Reset(val_buf, val_size); auto pos = target.Append(key, val); int ret_len = PACKET_HEADER_SIZE + sizeof(pos); char * ret_buf = new char [ret_len]; auto & reply = *(Packet *)ret_buf; memcpy(reply.buf, (char *)&pos, sizeof(pos)); reply.len = sizeof(pos); reply.sn = req.sn; reply.type = req.type; reply.crc = reply.Sum(); cb(ret_buf, ret_len); delete [] ret_buf; } void RpcProcess::processGet(DataMgr & target, char * buf, DoneCbFunc cb) { auto & req = *(Packet *)buf; if (req.len < sizeof(int64_t) ) { KV_LOG(ERROR) << "index size error: " << req.len; return; } auto idx = *(uint64_t *)req.buf; KVString key; KVString val; target.Get(idx, key, val); int key_size = key.Size(); int val_size = val.Size(); int ret_len = PACKET_HEADER_SIZE + sizeof(int) * 2 + key_size + val_size; char * ret_buf = new char[ret_len]; auto & reply = *(Packet *)ret_buf; memcpy(reply.buf, (char *)&key_size, sizeof(int)); memcpy(reply.buf + sizeof(int), (char *)&val_size, sizeof(int)); memcpy(reply.buf + sizeof(int) * 2, key.Buf(), key_size); memcpy(reply.buf + sizeof(int) * 2 + key_size, val.Buf(), val_size); reply.len = sizeof(int) * 2 + key_size + val_size; reply.sn = req.sn; reply.type = req.type; reply.crc = reply.Sum(); cb(ret_buf, ret_len); delete [] ret_buf; }
true
cda05d98e4ecacd70a5f45d7b9b85c81ede6b673
C++
beata-d/planner
/planner/planner_project/plan_services/sources/DailyPlansService.cpp
UTF-8
5,033
3.21875
3
[]
no_license
#include <boost/date_time/gregorian/gregorian.hpp> #include "SqlConnection.h" #include "DailyPlan.h" #include "DailyPlansService.h" #include "View.h" void DailyPlansService::create_plan(View& view) { PlansService::create_plan(view); DailyPlan plan(description, category, date); SqlConnection sql_connection; sql_connection.add_plan(plan); } void DailyPlansService::mark_done(Plan& plan) { PlansService::mark_done(plan); SqlConnection sql_connection; sql_connection.mark_daily_done(plan); } //change description or category of a plan void DailyPlansService::update_plan(Plan& plan, View& view) { PlansService::update_plan(plan, view); SqlConnection sql_connection; sql_connection.update_daily_plan(plan); } void DailyPlansService::read_plans(View& view, std::vector<std::unique_ptr<Plan>>& plans) { PlansService::read_plans(view, plans); SqlConnection sql_connection; sql_connection.read_all_daily_plans(plans, date); view.create_daily_plans_window(plans, date); } void DailyPlansService::remove_plan(const Plan& plan) { SqlConnection sql_connection; sql_connection.delete_daily_plan(plan); } boost::gregorian::date DailyPlansService::get_date_from_user(const View& view, bool for_reading_plans) { bool exception_flag = true; //get a day, month and year from a user; repeat until a date is correct while (exception_flag) { try { if (for_reading_plans) { date = get_date_from_user_for_reading_plans(view); } else { date = get_date_from_user_for_creating_plan(view); } exception_flag = false; } catch (std::out_of_range&) { } } return date; } boost::gregorian::date DailyPlansService::get_date_from_user_for_reading_plans(const View& view) { int day = 0, month = 0, year = 0; std::array<std::string, 3> array_date; //contains day,month,year //get day, month and year from user //if any parameter is empty - set it to the current one //if value entered by user is an integer value - convert it to int do { array_date = view.get_date_from_user(); if (array_date[0].length()==0) { day = boost::gregorian::day_clock::local_day().day().as_number(); } else if (is_int(array_date[0])) { day = stoi(array_date[0]); } if (array_date[1].length()==0) { month = boost::gregorian::day_clock::local_day().month().as_number(); } else if (is_int(array_date[1])) { month = stoi(array_date[1]); } if (array_date[2].length()==0) { year = boost::gregorian::day_clock::local_day().year(); } else if (is_int(array_date[2])) { year = stoi(array_date[2]); } //when a date is invalid (e.g. 30.02) throw an exception try { date = boost::gregorian::date(year, month, day); } catch (std::out_of_range&) { throw; } } //continue if user entered values that are not ints while (date.is_not_a_date()); return date; } boost::gregorian::date DailyPlansService::get_date_from_user_for_creating_plan(const View& view) { int day = 0, month = 0, year = 0; std::array<std::string, 3> array_date; //contains day,month,year //get day, month and year from user //if any parameter is empty - set it to the current one //if value entered by user is an integer value - convert it to int do { array_date = view.get_date_from_user(); if (array_date[0].length()==0) { day = boost::gregorian::day_clock::local_day().day().as_number()+1; } else if (is_int(array_date[0])) { day = stoi(array_date[0]); } if (array_date[1].length()==0) { month = boost::gregorian::day_clock::local_day().month().as_number(); } else if (is_int(array_date[1])) { month = stoi(array_date[1]); } if (array_date[2].length()==0) { year = boost::gregorian::day_clock::local_day().year(); } else if (is_int(array_date[2])) { year = stoi(array_date[2]); } //when a date is invalid (e.g. 30.02) throw an exception try { date = boost::gregorian::date(year, month, day); } catch (std::out_of_range&) { throw; } } //continue if user entered values that are not ints or if entered date is from the past while (date.is_not_a_date() || date<boost::gregorian::day_clock::local_day()); return date; } void DailyPlansService::set_date(const boost::gregorian::date& date) { DailyPlansService::date = date; } bool DailyPlansService::is_int(const std::string& str) { return str.find_first_not_of("0123456789")==std::string::npos; } const boost::gregorian::date& DailyPlansService::get_date() const { return date; }
true
2c78194a387473c7d3fc57312da7d74d504d4cf8
C++
chang-yu0928/algorithms
/solutions/LastKNode.cpp
UTF-8
918
3.5625
4
[]
no_license
#include <iostream> using namespace std; struct Node { int val; Node* next; Node(int v): val(v), next(NULL) {} }; Node *lastKNode(Node* head, int k) { Node *fast = head, *slow = head; for(int i = 0;i < k;i ++) { if(fast == NULL) { break; } fast = fast->next; } while(fast != NULL) { fast = fast->next; slow = slow->next; } return slow; } int main() { Node *head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4); head->next->next->next->next = new Node(5); head->next->next->next->next->next = new Node(6); head->next->next->next->next->next->next = new Node(7); head->next->next->next->next->next->next->next = new Node(8); head->next->next->next->next->next->next->next->next = new Node(9); head->next->next->next->next->next->next->next->next->next = new Node(10); cout<<lastKNode(head, 11)->val<<endl; return 0; }
true
11ad4c13adcd4861cbc8c6c7e50c2337b4a2107c
C++
shubhgkr/Codechef
/Beginner/PLAYPIAN.cpp
UTF-8
555
2.9375
3
[]
no_license
/* * @author Shubham Kumar Gupta (shubhgkr) * github: http://www.github.com/shubhgkr * Created on 21/12/19. * Problem link: https://www.codechef.com/problems/PLAYPIAN */ #include <iostream> #include <string> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; std::string s; while (t--) { std::cin >> s; int len = s.length(); bool flag = true; for (int i = 0; i < len; i += 2) { if (s[i] == s[i + 1]) { flag = false; break; } } std::cout << (flag ? "yes\n" : "no\n"); } return 0; }
true
cf52dcef70c7777b0188706183f2f6cd8afbb3a8
C++
jbailleux/Encryption
/src/CryptageMessage.hpp
ISO-8859-1
650
2.765625
3
[]
no_license
/* * CryptageMessage.hpp * * Created on: 25 fvr. 2015 * Author: jrmy & ccile */ #ifndef CRYPTAGEMESSAGE_HPP_ #define CRYPTAGEMESSAGE_HPP_ #include <string> using namespace std; class CryptageMessage { public: CryptageMessage(const string,const string); virtual ~CryptageMessage(); void cryptage(); void decryptage(); string getTexteInitial()const; string getTexteApresTraitement() const; string getClef()const; private: void setClef(const string); void setTexteInitial( const std::string); std::string clef; std::string texteInitial; std::string texteApresTraitementCry; }; #endif /* CRYPTAGEMESSAGE_HPP_ */
true
5af1890054bcc15bf578a99620d88e428a193fcf
C++
suraj0803/DSA
/16.Dynamic Programming/Fibonacci_BottomUp.cpp
UTF-8
313
2.96875
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; // Bottom down Approch int fib(int n) { int dp[100] = {0}; dp[1] = 1; for(int i=2; i<=n; i++){ dp[i] = dp[i-1] + dp[i-2]; } return dp[n]; } int main() { int n; cin>>n; cout<<fib(n); return 0; }
true
c198fcde7758e887d8d19ab1468005ce87c462e5
C++
shacharosn/War-game
/Armor.cpp
UTF-8
563
2.78125
3
[]
no_license
// // Created by shachar on 12/21/2017. // #include "ShieldArmor.h" #include "BodyArmor.h" #include <sstream> shared_ptr<Armor> Armor::make_armor(string type,stringstream& stream) { char temp; short s; double x,y; stream>>s>>temp>>temp>>x>>y>>temp; if (type == "BodyArmor") return std::make_shared<BodyArmor>(s,x,y); if (type == "ShieldArmor")return std::make_shared<ShieldArmor>(s,x,y); return nullptr; } Armor::~Armor() = default; Armor::Armor(const short strength):armor_strength(strength) { }
true
8f31bad6ef1d080e2467339f383350f070944879
C++
Butter-89/HeapManager
/MyHeapManager/HeapManager.h
UTF-8
1,887
2.875
3
[]
no_license
#pragma once #include "BlockDescriptor.h" class HeapManager { private: HeapManager* p_managerAddr; BlockDescriptor* p_currentDescriptor; BlockDescriptor* p_outstandingBlockStartAddr; BlockDescriptor* p_freeBlockStartAddr; void* p_firstUsableAddr; void* p_currentMemPtr; //ptr to the actual usable memory space (for actual allocation by block descriptor) unsigned int numTotalDescriptors; unsigned int numOutstandingBlocks; unsigned int numFreeBlocks; size_t totalMemorySize; //the total memory size of the heap (both descriptors and memory blocks) size_t usableMemorySize; public: HeapManager(unsigned int i_numDescriptors, void* i_pMemory, size_t i_sizeMemory); ~HeapManager(); void InitFreeBlocks(); void ShowFreeBlocks() const; void ShowOutstandingBlocks() const; void* alloc(size_t i_size, unsigned int i_alignment); void* alloc(size_t i_size); void* AllocateWithCurrentBlock(BlockDescriptor* pCurrent, size_t i_size, unsigned int i_alignment); void* AllocateWithCurrentBlock(BlockDescriptor* pCurrent, size_t i_size); bool Free(void* i_ptr); bool InsertFreeLinkNode(void* i_ptr); //void* Allocate(size_t i_size); void* RoundUp(void* i_addr, unsigned int i_align); BlockDescriptor* GetFirstFreeDescriptor(); BlockDescriptor* FindDescriptor(void* i_ptr); BlockDescriptor* PickOutDescriptor(void* i_ptr); //size_t AlignmentOffset(void* i_addr, unsigned int i_align); void Collect(); BlockDescriptor* Contains(void* i_ptr) const; BlockDescriptor* IsAllocated(void* i_ptr) const; void SortLinkedList(); void SwapDescriptor(BlockDescriptor* i_blockA, BlockDescriptor* i_blockB); BlockDescriptor* GetFreeBlock(); bool CheckFreeBlock(); //check if there is available free 0 size block bool SetRemaining(BlockDescriptor* i_block, void* i_startMemAddr, size_t i_size); void MergeBlocks(BlockDescriptor* i_currentBlock, BlockDescriptor* i_nextBlock); };
true
8385a26b597fb61d1622a5d062eb1a9c5f03ae21
C++
Mohsina-Jannat/Competitive_Programming
/dijkstra.cpp
UTF-8
1,608
2.90625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; template<class T> struct Dijkstra { int n; vector<vector<pair<T,int> > > adj; vector<int> dist; vector<T> parent; //dist printing Dijkstra(int n):n(n),adj(n) {} void add_edge(int a,int b,T w) { adj[a].push_back({b,w}); adj[b].push_back({a,w}); } void find_shortest_path(int src) { priority_queue<pair<T,int>,vector<pair<T,int> >,greater<pair<T,int> > > Q; dist=vector<T>(n,numeric_limits<T>::max()); parent=vector<int>(n,-1); dist[src]=0,Q.push({0,src}); while(!Q.empty()) { auto p = Q.top(); Q.pop(); int u = p.second; for(int i = 0; i<adj[u].size(); i++) { pair< T, int> q = adj[u][i]; int v = q.first; T d = q.second; if(dist[v] - d > dist[u]){ dist[v] = dist[u] + d; parent[v] = u; Q.push({dist[v], v}); } } } } }; int main() { int t, tst = 1; scanf("%d", &t); while(t--) { int n, m, s, tt; scanf("%d %d %d %d", &n, &m, &s, &tt); Dijkstra<int> D(n+1); for(int i = 0; i<m; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); D.add_edge(u, v, w); } D.find_shortest_path(s); printf("Case #%d: ", tst++); if(D.dist[tt]==numeric_limits<int>::max()) printf("unreachable\n"); else printf("%d\n", D.dist[tt]); } return 0; }
true
9e5361d12f085bc0154cf3800d094570d2254761
C++
usernamegenerator/leetcode
/1.two-sum.cpp
UTF-8
2,033
3.71875
4
[]
no_license
/* * @lc app=leetcode id=1 lang=cpp * * [1] Two Sum */ #include <vector> #include <map> using namespace std; // @lc code=start class Solution { public: /* brute force solution: iterate the array from the first index iterate the array from next index check if they add up to the targe */ /* vector<int> twoSum(vector<int> &nums, int target) { vector<int> res; bool resFound = false; for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) { if(resFound) break; for (vector<int>::iterator ij = it + 1; ij != nums.end(); ij++) { if (*it + *ij == target) { res.push_back(it - nums.begin()); res.push_back(ij - nums.begin()); resFound = true; break; } } } return res; } */ // use hashmap look up solution: /* iterate through the array, push the elements to map, <key,value> = <element, index> iterate through the array again, take target-element, and look up in the map if found, return results */ vector<int> twoSum(vector<int> &nums, int target) { map<int, int> m; vector<int> res; for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) { m.insert(pair<int, int>(*it, it - nums.begin())); } for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++) { int remain = target - *it; map<int, int>::iterator ij = m.find(remain); // make sure it doesn't count itself // e.g. [3,2,4] 6, will not return [0,0] which is 3+3 if (ij != m.end() && (ij->second != it-nums.begin())) { res.push_back(it - nums.begin()); res.push_back(ij->second); return res; } } return res; } }; // @lc code=end
true
a990e0f0071b48ee7ec42b1321b5a476365e80d2
C++
clamugi/AtCoder-solutions
/ABC/001~100/056/056b.cpp
UTF-8
181
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main (){ int W, a, b; cin >> W >> a >> b; if (abs(a-b)<=W )cout << 0 << endl; else cout << abs(a-b)-W << endl; }
true
81b98a11c4f58afb887f5c3793837aa28ce328ae
C++
Zorgie/Robotics
/mapping/src/PlaneDetector_stash_for_photoshoot.cpp
UTF-8
8,340
2.84375
3
[]
no_license
/* * PlaneDetector.cpp * * Created on: Nov 18, 2013 * Author: robo */ #include "PlaneDetector.h" PlaneDetector::PlaneDetector() { } PlaneDetector::~PlaneDetector() { // TODO Auto-generated destructor stub } bool PlaneDetector::linesMatch(Vec4i& line1, Vec4i& line2) { if (isHorizontal(line1) != isHorizontal(line2)) return false; bool horiz = isHorizontal(line1); if (horiz) { if (!((line2[0] < line1[2] && line2[2] > line1[0]) || (line2[2] > line1[0] && line2[0] < line1[2]))) { return false; } } else { if (!((line2[1] < line1[3] && line2[3] > line1[1]) || (line2[3] > line1[1] && line2[1] < line1[3]))) { return false; } } double slope1 = (double) (line1[3] - line1[1]) / (line1[2] - line1[0]); double slope2 = (double) (line2[3] - line2[1]) / (line2[2] - line2[0]); double maxSlope = max(abs(slope1), abs(slope2)); double slope1norm = slope1 / maxSlope; double slope2norm = slope2 / maxSlope; if (abs(slope1norm - slope2norm) > 0.1) return false; double m1 = line1[1] - slope1 * line1[0]; double m2 = line2[1] - slope2 * line2[0]; if (abs(m2 - m1) < 50) { printf("Matched (%d, %d), (%d, %d) to (%d, %d), (%d, %d)\n", line1[0], line1[1], line1[2], line1[3], line2[0], line2[1], line2[2], line2[3]); return true; } return false; } float PlaneDetector::pointOnPlane(Point3d point, Point3d plane) { return point.x * plane.x + point.y * plane.y + point.z * plane.z + 1; } Point3d PlaneDetector::depthCloseToPoint(Point2d p, PointCloud<PointXYZ>& pcl, int maxDelta) { for (int delta = 0; delta <= maxDelta; delta++) { for (int y = p.y - delta; y <= p.y + delta; y++) { for (int x = p.x - delta; x <= p.x + delta; x++) { if (!isnan(pcl.points[px(x, y)].z)) { Point3d p(pcl.points[px(x, y)].x, pcl.points[px(x, y)].y, pcl.points[px(x, y)].z); return p; } } } } return Point3d(-1, -1, -1); } vector<Vec4d> PlaneDetector::getWalls(Mat& rgbImage, PointCloud<PointXYZ>& pcl) { vector<Vec4d> walls; vector<Vec4i> lines = ic.getHoughLines(rgbImage); // Find the front wall. return walls; } bool PlaneDetector::isHorizontal(Vec4i &line) { return abs(line[0] - line[2]) > abs(line[1] - line[3]); } void PlaneDetector::fixLineCoords(Vec4i &line) { if (isHorizontal(line)) { if (line[0] > line[2]) { // Flip if x1 is larger than x2. Point2i temp = Point(line[0], line[1]); line[0] = line[2]; line[1] = line[3]; line[2] = temp.x; line[3] = temp.y; } } else { // Vertical line if (line[1] > line[3]) { // Flip if y1 is larger than y2. Point2i temp = Point(line[0], line[1]); line[0] = line[2]; line[1] = line[3]; line[2] = temp.x; line[3] = temp.y; } } } vector<Point2i> PlaneDetector::surroundingDots(Mat& rgbImage, PointCloud<PointXYZ>& pcl, Vec4i line, double distFromStart) { vector<Point2i> result; fixLineCoords(line); Point2i a; Point2i b; distFromStart = min(0.8, distFromStart); distFromStart = max(0.2, distFromStart); for (int j = 0; j < 2; j++) { Point2i diff = b - a; float len = cv::norm(diff); Point2i mid1(a.x + diff.x * (distFromStart - 0.2), a.y + diff.y * (distFromStart - 0.2)); Point2i mid2(a.x + diff.x * (distFromStart), a.y + diff.y * (distFromStart)); Point2i mid3(a.x + diff.x * (distFromStart + 0.2), a.y + diff.y * (distFromStart + 0.2)); Point2i rotated; if (j == 0) rotated = Point2i(-diff.y, diff.x); else rotated = Point2i(diff.y, -diff.x); result.push_back( Point2i(mid1.x + distFromStart * (rotated.x / 5), mid1.y + distFromStart * (rotated.y / 5))); result.push_back( Point2i(mid2.x + distFromStart * (rotated.x / 2), mid2.y + distFromStart * (rotated.y / 2))); result.push_back( Point2i(mid3.x + distFromStart * (rotated.x / 5), mid3.y + distFromStart * (rotated.y / 5))); } return result; } cv::Point3d PlaneDetector::getPlane(vector<Point3d> points) { // as seen in: http://stackoverflow.com/questions/1400213/3d-least-squares-plane if (points.size() < 3) { std::cerr << "WARNING: Giving less than three points for least squares plane computation." << std::endl; } cv::Mat A = cv::Mat::zeros(points.size(), 3, CV_64F); cv::Mat b = cv::Mat::zeros(points.size(), 1, CV_64F); for (int i = 0; i < points.size(); i++) { A.at<double>(i, 0) = points[i].x; A.at<double>(i, 1) = points[i].y; A.at<double>(i, 2) = points[i].z; b.at<double>(i, 0) = -1.0; } cv::Mat At = A.t(); cv::Mat AtA = At * A; cv::Mat Atb = At * b; cv::Mat AtA_inv = AtA.inv(); cv::Mat x = AtA_inv * Atb; cv::Point3d plane_eq(x.at<double>(0, 0), x.at<double>(1, 0), x.at<double>(2, 0)); return plane_eq; } vector<Point3d> PlaneDetector::getPlanes(Mat& rgbImage, PointCloud<PointXYZ>& pcl, vector<Vec4i>& lines) { vector<Point3d> foundPlanes; for (int i = 0; i < 2; i++) { Vec4i line = lines[i]; Point2i a = Point2i(line[0], line[1]); Point2i b = Point2i(line[2], line[3]); if (norm(b - a) < 100) continue; for (int j = 0; j < 2; j++) { Point2i diff = b - a; float len = cv::norm(diff); Point2i mid1(a.x + 4 * diff.x / 10, a.y + 3 * diff.y / 10); Point2i mid2(a.x + 5 * diff.x / 10, a.y + 5 * diff.y / 10); Point2i mid3(a.x + 6 * diff.x / 10, a.y + 7 * diff.y / 10); Point2i rotated; if (j == 0) rotated = Point2i(-diff.y, diff.x); else rotated = Point2i(diff.y, -diff.x); Point2i check1; Point2i check2; Point2i check3; Point3d d1; Point3d d2; Point3d d3; if (i==0){ check1.x=300; check1.y=260; check2.x=320; check2.y=220; check3.x=340; check3.y=240; d1 = depthCloseToPoint(check1, pcl, 10); d2 = depthCloseToPoint(check2, pcl, 10); d3 = depthCloseToPoint(check3, pcl, 10); // Point2i check1(mid1.x + rotated.x / 5, mid1.y + rotated.y / 5); // Point2i check2(mid2.x + rotated.x / 2, mid2.y + rotated.y / 2); // Point2i check3(mid3.x + rotated.x / 5, mid3.y + rotated.y / 5); // int pt_1_x = 300; // int pt_2_x = 320; // int pt_3_x = 340; // int pt_1_y = 260; // int pt_2_y = 220; // int pt_3_y = 240; } else { check1.x=330; check1.y=400; check2.x=450; check2.y=420; check3.x=390; check3.y=380; // check1(400, 260); // check2(420, 220); // check3(380, 240); d1 = depthCloseToPoint(check1, pcl, 10); d2 = depthCloseToPoint(check2, pcl, 10); d3 = depthCloseToPoint(check3, pcl, 10); } // Point3d d1 = depthCloseToPoint(check1, pcl, 10); // Point3d d2 = depthCloseToPoint(check2, pcl, 10); // Point3d d3 = depthCloseToPoint(check3, pcl, 10); bool planeAlreadyFound = false; for (int j = 0; j < foundPlanes.size(); j++) { if (fabs(pointOnPlane(d1, foundPlanes[j])) < DIST_EPSILON || fabs(pointOnPlane(d2, foundPlanes[j])) < DIST_EPSILON || fabs(pointOnPlane(d3, foundPlanes[j])) < DIST_EPSILON) { planeAlreadyFound = true; break; } } if (planeAlreadyFound) { cv::line(rgbImage, check1, check2, Scalar(0, 0, 255), 3, 8); cv::line(rgbImage, check2, check3, Scalar(0, 0, 255), 3, 8); cv::line(rgbImage, check3, check1, Scalar(0, 0, 255), 3, 8); continue; } cv::line(rgbImage, check1, check2, Scalar(255, 0, 0), 3, 8); cv::line(rgbImage, check2, check3, Scalar(255, 0, 0), 3, 8); cv::line(rgbImage, check3, check1, Scalar(255, 0, 0), 3, 8); if (d1.z != -1 && d2.z != -1 && d3.z != -1) { printf( "3dots: %.2f %.2f %.2f, %.2f %.2f %.2f, %.2f %.2f %.2f\n", d1.x, d1.y, d1.z, d2.x, d2.y, d2.z, d3.x, d3.y, d3.z); cv::line(rgbImage, check1, check2, Scalar(255, 255, 255), 3, 8); cv::line(rgbImage, check2, check3, Scalar(255, 255, 255), 3, 8); cv::line(rgbImage, check3, check1, Scalar(255, 255, 255), 3, 8); vector<Point3d> v; v.push_back(d1); v.push_back(d2); v.push_back(d3); Point3d plane = getPlane(v); printf("Plane: %.2f %.2f %.2f\n", plane.x, plane.y, plane.z); foundPlanes.push_back(plane); } } } return foundPlanes; } vector<Point3d> PlaneDetector::sweep(int y, PointCloud<PointXYZ>& pcl) { vector<Point3d> res; for(int x=0; x<pcl.width; x++){ int pixnum = px(x,y); Point3d pixel = Point3d(pcl.points[pixnum].x,pcl.points[pixnum].y,pcl.points[pixnum].z); if(!isnan(pixel.z)){ res.push_back(pixel); } } return res; }
true
3af86d9c7b2b4cf5f507a37e88de7c667b8a5fc6
C++
jmc359/sdl_dev
/include/game.hpp
UTF-8
1,462
2.59375
3
[]
no_license
#ifndef game_hpp #define game_hpp #include <SDL2/SDL.h> #include <SDL2/SDL_Image.h> #include <SDL2/SDL_TTF.h> #include <stdlib.h> #include <time.h> #include <iostream> #include <deque> #include <ctime> #include "agent.hpp" class Game{ public: Game(); ~Game(); void init(const char *title, int width, int height, bool fullscreen, bool logger); void run(); protected: void handleEvents(); void update(); void checkPause(); void render(); void clean(); void createSurfaces(); void updateRect(SDL_Rect *rect, int x, int y, int w, int h); bool running(){ return isRunning; } void log(const char *message, const char *level="DEBUG"); void startScreen(double blinkRate); bool detectCollision(SDL_Rect *r1, SDL_Rect *r2); void addEnemy(float rate); void updateObjects(int enemy_speed, int missile_speed, std::deque<Missile *>& missiles); void renderEnemies(); SDL_Texture *generateTexture(const char *filename); SDL_Texture *generateFont(const char *filename, int fontSize, const char *text, SDL_Color color); const Uint8 *keystate = SDL_GetKeyboardState(NULL); clock_t lastEnemyTime = clock(); double lastBlink = time(NULL); int width; int height; bool isRunning, logger; const char *title; Player *player; std::deque<Triangle *> enemies; SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *spaceTex1, *spaceTex2, *messageTex, *instructionTex; SDL_Rect spaceRect1, spaceRect2, messageRect, instructionRect; }; #endif
true
c5383bf316b7e690cd7a958991752400bffbb9ed
C++
karygauss03/IEEE-Xtreme14.0-Solutions-SUPCOM_SB
/Rotational Lights/Rotational Lights.cpp
UTF-8
1,251
2.703125
3
[ "MIT" ]
permissive
//KARYGAUSS03 #include <bits/stdc++.h> using namespace std; void updatex(vector<long> &x, long step, long T) { for (auto &t : x) t = (t + step) % T; unsigned long i = x.size() - 1; while (x[i] < x[i - 1]) i--; if (i == x.size() - 1) return; vector<long> tmp(x.begin() + i + 1, x.end()); x.insert(x.begin(), tmp.begin(), tmp.end()); x.erase(x.begin() + i + 1 + tmp.size(), x.end()); } void updated(vector<long> &x, vector<long> &table, long t, long n) { table[0] = t + x[0] - x[n - 1]; for(int i = 1; i < n; i++)table[i] = x[i] - x[i - 1]; } int main(int argc, char const *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); long n, t; cin >> n >> t; vector<long> x(n); vector<long> xx; for (auto &tmp : x) { cin >> tmp; xx.push_back(tmp); } vector<long> table(n); updated(x, table, t, n); long offset = 0; updatex(x, table[offset], t); long sum = table[offset]; offset = n - 1; while (xx != x) { sum += table[offset]; updatex(x, table[offset], t); offset--; offset %= n; } cout << --sum << endl; return 0; }
true
3ef7bfbe31004ed262f4fc1706f0c6163c22bc54
C++
TheFloHub/PluginTest
/src/Core/src/SceneObject.cpp
UTF-8
6,992
3.15625
3
[]
no_license
#include "Core/SceneObject.h" #include "Core/Component.h" #include <algorithm> #include <string> #include <typeinfo> #include <unordered_map> #include <vector> /********** Impl start ************/ class SceneObject::Impl final { public: Impl(SceneObject * d); ~Impl(); Impl(Impl const &) = delete; Impl & operator=(Impl const &) = delete; Impl(Impl &&) = delete; Impl & operator=(Impl &&) = delete; bool addComponent(Component * pComponent); void removeComponent(Component * pComponent); SceneObject * getParent(); SceneObject const * getParent() const; bool addChild(SceneObject * pChild); void update(double deltaTime); void render() const; size_t getNumberOfChildren() const; bool isLeafNode() const; SceneObject * getChild(size_t index); SceneObject const * getChild(size_t index) const; void setEnabled(bool isEnabled); bool isEnabled() const; private: /** * Removes the child from this scene object committing ownership to the * caller. Only call this, if you know what you're doing. */ void removeChild(SceneObject * child); /** Checks if the given node is a descendant of this scene object. */ bool isNodeDescendant(SceneObject const * pNode) const; /** The parent scene object. */ SceneObject * m_parent{nullptr}; /** The children scene objects. */ std::vector<SceneObject *> m_children{}; /** * The map of all components. The key is a unique identifier * of the component class. Thus only one instance of one * specific component type is allowed, which is part of the concept. */ std::unordered_map<size_t, Component *> m_components{}; /** * If a scene object is disabled then its components as well as its children * are neither updated nor rendered. */ bool m_isEnabled{true}; SceneObject * m_d; }; SceneObject::Impl::Impl(SceneObject * d) : m_d(d) {} SceneObject::Impl::~Impl() { if (m_parent != nullptr) { m_parent->m_impl->removeChild(m_d); } for (auto & component : m_components) { component.second->m_sceneObject = nullptr; // detach component delete component.second; // delete component } m_components.clear(); for (auto & child : m_children) { child->m_impl->m_parent = nullptr; // detach node delete child; // delete node } m_children.clear(); } bool SceneObject::Impl::addComponent(Component * pComponent) { // don't add if null or if there already exists an owner if (pComponent == nullptr || pComponent->m_sceneObject != nullptr) return false; // insert the component if there isn't a component of the same type yet. auto infoPair = m_components.insert(std::pair<size_t, Component *>( typeid(*pComponent).hash_code(), pComponent)); // if insertion was successfull set this as the owner if (infoPair.second) { infoPair.first->second->m_sceneObject = m_d; } return infoPair.second; } void SceneObject::Impl::removeComponent(Component * pComponent) { auto id = typeid(*pComponent).hash_code(); auto cIter = m_components.find(id); if (cIter != std::end(m_components) && cIter->second == pComponent) { m_components.erase(cIter); } } SceneObject * SceneObject::Impl::getParent() { return m_parent; } SceneObject const * SceneObject::Impl::getParent() const { return m_parent; } bool SceneObject::Impl::addChild(SceneObject * pChild) { if (pChild == nullptr || pChild == m_d || pChild->m_impl->m_parent == m_d) return false; // if there already exists a parent for the new child if (pChild->m_impl->m_parent != nullptr) { // and it's not valid to add the child return false. if (pChild->m_impl->isNodeDescendant(m_d)) { return false; } // otherwise detach the child else { pChild->m_impl->m_parent->m_impl->removeChild(pChild); } return false; } pChild->m_impl->m_parent = m_d; m_children.push_back(pChild); return true; } void SceneObject::Impl::update(double deltaTime) { // HINT: no need to update transform for (auto iter = m_components.begin(); iter != m_components.end(); ++iter) { if (iter->second->isEnabled()) { iter->second->update(deltaTime); } } for (auto iter = m_children.begin(); iter != m_children.end(); ++iter) { if ((*iter)->isEnabled()) { (*iter)->update(deltaTime); } } } void SceneObject::Impl::render() const { // HINT: no need to render transform for (auto iter = m_components.cbegin(); iter != m_components.cend(); ++iter) { if (iter->second->isEnabled()) { iter->second->render(); } } } size_t SceneObject::Impl::getNumberOfChildren() const { return m_children.size(); } bool SceneObject::Impl::isLeafNode() const { return m_children.empty(); } SceneObject * SceneObject::Impl::getChild(size_t index) { return m_children[index]; } SceneObject const * SceneObject::Impl::getChild(size_t index) const { return m_children[index]; } void SceneObject::Impl::setEnabled(bool isEnabled) { m_isEnabled = isEnabled; } bool SceneObject::Impl::isEnabled() const { return m_isEnabled; } void SceneObject::Impl::removeChild(SceneObject * child) { auto iter = m_children.begin(); auto last = m_children.end(); while (iter != last && (*iter) != child) { ++iter; } if (iter != last) { m_children.erase(iter); child->m_impl->m_parent = nullptr; } } bool SceneObject::Impl::isNodeDescendant(SceneObject const * pNode) const { if (pNode == nullptr) return false; SceneObject const * pCurrentNode = pNode; while (pCurrentNode != nullptr && pCurrentNode != m_d) { pCurrentNode = pCurrentNode->m_impl->m_parent; } return pCurrentNode == m_d; } /******************** Impl end *************************************/ SceneObject::SceneObject() : m_impl(new Impl(this)) {} SceneObject::~SceneObject() = default; bool SceneObject::addComponent(Component * pComponent) { return m_impl->addComponent(pComponent); } void SceneObject::removeComponent(Component * pComponent) { return m_impl->removeComponent(pComponent); } SceneObject * SceneObject::getParent() { return m_impl->getParent(); } SceneObject const * SceneObject::getParent() const { return m_impl->getParent(); } bool SceneObject::addChild(SceneObject * pChild) { return m_impl->addChild(pChild); } void SceneObject::update(double deltaTime) { m_impl->update(deltaTime); } void SceneObject::render() const { m_impl->render(); } size_t SceneObject::getNumberOfChildren() const { return m_impl->getNumberOfChildren(); } bool SceneObject::isLeafNode() const { return m_impl->isLeafNode(); } SceneObject * SceneObject::getChild(size_t index) { return m_impl->getChild(index); } SceneObject const * SceneObject::getChild(size_t index) const { return m_impl->getChild(index); } void SceneObject::setEnabled(bool isEnabled) { m_impl->setEnabled(isEnabled); } bool SceneObject::isEnabled() const { return m_impl->isEnabled(); }
true
817381f9a3c5c9874814759a19d3c38241ff6cf7
C++
jotaves/exercises
/queue/include/AbsQueue.h
UTF-8
609
3
3
[]
no_license
#ifndef ABSQUEUE_H #define ABSQUEUE_H /**Classe interface fila (não pode ser instanciada!). */ template < class Object > class AbsQueue { public: AbsQueue ( void ) { /* Empty */ } // Default constructor virtual ~AbsQueue( void ) { /* Empty */ } // Default destructor // Basic members virtual void enqueue ( const Object & x ) = 0; virtual Object dequeue ( void ) = 0; virtual Object getFront ( void ) const = 0; virtual bool isEmpty ( void ) const = 0; virtual void makeEmpty ( void ) = 0; private: // Disable copy constructor AbsQueue ( const AbsQueue & ) { /* Empty */ } }; #endif
true
f5c4ff41a487ffb574a18b6128adba8bba4a3477
C++
iamslash/learntocode
/leetcode/BestTimetoBuyandSellStockwithCooldown/20181210.a.cpp
UTF-8
839
3.140625
3
[]
no_license
// Copyright (C) 2018 by iamslash #include <cstdio> #include <vector> #include <limits> #include <algorithm> // s0 <-cooldown- s2 // \ ^ // buy sell // \ / // -> s1 / class Solution { public: int maxProfit(const std::vector<int>& P) { if (P.size() <= 1) return 0; int n = P.size(); std::vector<int> s0(n, 0); std::vector<int> s1(n, 0); std::vector<int> s2(n, 0); s0[0] = 0; s1[0] = -P[0]; s2[0] = std::numeric_limits<int>::min(); for (int i = 1; i < n; ++i) { s0[i] = std::max(s0[i-1], s2[i-1]); s1[i] = std::max(s1[i-1], s0[i-1]-P[i]); s2[i] = s1[i-1]+P[i]; } return std::max(s0[n-1], s2[n-1]); } }; int main() { std::vector<int> P = {1, 2, 3, 0, 2}; Solution sln; printf("%d\n", sln.maxProfit(P)); return 0; }
true
b1719169e453612708944b9d0123392d5b945440
C++
memoiry/miscellaneous
/c++/EssentialCpp/Chapter 1. Basic C++ Programming/1.7.cpp
UTF-8
801
3.171875
3
[]
no_license
// // Essential C++ // Stanley Lippman // Chen Chen @ November 27th, 2014 // #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream readFile("TestFile_1.7.txt"); if (! readFile.is_open()) cerr << "Sorry, the file fails to read!" << endl; string word; vector<string> vecWord; while (readFile >> word) vecWord.push_back(word); cout << "Original text: "; for (vector<string>::iterator itr = vecWord.begin(), vecEnd = vecWord.end(); itr != vecEnd; ++itr) cout << *itr << " "; sort(vecWord.begin(),vecWord.end()); cout << endl << "Sorted text: "; for (vector<string>::iterator itr = vecWord.begin(), vecEnd = vecWord.end(); itr != vecEnd; ++itr) cout << *itr << " "; return 0; }
true
6acd724dc677ffb9726604c7fc2afa3341455c71
C++
christian-rauch/conversion_test
/src/conversion_test_node.cpp
UTF-8
959
2.5625
3
[]
no_license
#include <cv_bridge/cv_bridge.h> #include <opencv2/opencv.hpp> #include <iostream> int main(int argc, char * argv[]) { // create 16bit integer image const std::string fmt = sensor_msgs::image_encodings::MONO16; cv_bridge::CvImage im0; im0.image = cv::Mat(100, 100, cv_bridge::getCvType(fmt)); im0.image = 2500; im0.encoding = fmt; std::cout << "orig type: " << im0.image.type() << std::endl; double max_org; cv::minMaxLoc(im0.image, nullptr, &max_org); std::cout << "orig max: " << max_org << std::endl; // convert to message and back sensor_msgs::CompressedImage::ConstPtr msg = im0.toCompressedImageMsg(cv_bridge::PNG); cv_bridge::CvImage im1 = *cv_bridge::toCvCopy(msg, fmt).get(); std::cout << "converted type: " << im1.image.type() << std::endl; double max_conv; cv::minMaxLoc(im1.image, nullptr, &max_conv); std::cout << "converted max: " << max_conv << std::endl; return 0; }
true
2cf7add9b87d0a6df57a39cdfd40ad9e6408060c
C++
Ansou1/CPP
/cpp_bomberman/BomberGUI/Background.cpp
UTF-8
2,219
2.546875
3
[]
no_license
// // Background.cpp for lol in /home/lerman_v/Git/C++/cpp_bomberman/BomberGUI // // Made by lerman_v // Login <lerman_v@epitech.net> // // Started on Fri May 30 14:58:12 2014 lerman_v // Last update Fri Jun 13 13:39:29 2014 Boulot // #include "Background.hh" #define PI 3.14159265f Background::Background(std::string const &textPath, glm::vec3 const &pos, float fov, float ratio, bool front) { initialize(textPath); _isFront = front; resetPos(pos, fov, ratio); } Background::~Background() { } void Background::resetPos(glm::vec3 const &pos, float fov, float ratio) { _position = glm::vec3(0, 0, 0); _rotation = glm::vec3(0, 0, 0); _scale = glm::vec3(1.0, 1.0, 1.0); fov /= 2.0f; translate(pos); if (pos.z != 0.0) { rotate(glm::vec3(-1, 0, 0), atan(pos.y / pos.z) * 180 / PI); } if (pos.z != 0.0) { rotate(glm::vec3(0, 1, 0), atan(pos.x / pos.z) * 180 / PI); } scale(glm::vec3(sqrt(pow(2.0 * pos.x, 2.0) + pow(2.0 * pos.y, 2.0) + pow(2.0 * pos.z, 2.0)) * tan(ratio * fov * PI / 180.0f) * 2.0 - 4.0, sqrt(pow(2.0 * pos.x, 2.0) + pow(2.0 * pos.y, 2.0) + pow(2.0 * pos.z, 2.0)) * tan(fov * PI / 180.0) * 2.0 , 1.0) ); if (_isFront) rotate(glm::vec3(0, 1, 0), 180.0); } bool Background::initialize(std::string const &textPath) { std::string err; if (_texture.load(textPath) == false) { err = std::string("Cannot load texture (") + textPath + std::string (")"); throw my_exception(err.c_str()); } _geometry.setColor(glm::vec4(1, 1, 1, 1)); _geometry.pushVertex(glm::vec3(0.50f, 0.50f, 0.0f)); _geometry.pushVertex(glm::vec3(0.50f, -0.5f, 0.0f)); _geometry.pushVertex(glm::vec3(-0.5f, -0.5f, 0.0f)); _geometry.pushVertex(glm::vec3(-0.5f, 0.50f, 0.0f)); _geometry.pushUv(glm::vec2(1.0f, 1.0f)); _geometry.pushUv(glm::vec2(1.0f, 0.0f)); _geometry.pushUv(glm::vec2(0.0f, 0.0f)); _geometry.pushUv(glm::vec2(0.0f, 1.0f)); _geometry.build(); return (true); } void Background::updateAnime(gdl::Clock const &clock) { (void)(clock); } void Background::draw(gdl::AShader &shader, gdl::Clock const &clock) { (void)clock; _texture.bind(); _geometry.draw(shader, getTransformation(), GL_QUADS); }
true
499e9a0585c088756f5497a8a613881dead00aa1
C++
jannekoiv/bullet_test
/src/mesh.cpp
UTF-8
6,433
2.90625
3
[]
no_license
// // Created by jak on 4/11/16. // #include <sstream> #include <iostream> #include "mesh.h" using namespace std; GLuint Mesh::glMatView = 0; GLuint Mesh::glMatProjection = 0; GLuint Mesh::glLightPosition = 0; Mesh::Mesh() { vertexBuffer = 0; normalBuffer = 0; textureCoordinateBuffer = 0; colorBuffer = 0; indexBuffer = 0; vertexShader = shaderFromFile(GL_VERTEX_SHADER, "shader.vert"); fragmentShader = shaderFromFile(GL_FRAGMENT_SHADER, "shader.frag"); shaderProgram = programFromShaders(vertexShader, fragmentShader); vertexCount = 0; indexCount = 0; subMeshes = nullptr; subMeshCount = 0; subMeshes = nullptr; glMatWorld = glGetUniformLocation(shaderProgram, "matWorld"); Mesh::glMatView = glGetUniformLocation(shaderProgram, "matView"); Mesh::glMatProjection = glGetUniformLocation(shaderProgram, "matProjection"); Mesh::glLightPosition = glGetUniformLocation(shaderProgram, "lightPosition"); } Mesh::~Mesh() { glDeleteBuffers(1, &vertexBuffer); glDeleteBuffers(1, &normalBuffer); glDeleteBuffers(1, &colorBuffer); glDeleteBuffers(1, &indexBuffer); glDetachShader(shaderProgram, vertexShader); glDetachShader(shaderProgram, fragmentShader); glDeleteProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } std::string Mesh::readFile(const char *file) { std::ifstream t(file); std::stringstream buffer; buffer << t.rdbuf(); std::string fileContent = buffer.str(); return fileContent; } GLuint Mesh::shaderFromFile(int type, std::string filename) { int shader = glCreateShader(type); std::string source = readFile(filename.c_str()); const char *rawSource = source.c_str(); int length = source.length(); glShaderSource(shader, 1, &rawSource, &length); glCompileShader(shader); int compileStatus = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus); if (compileStatus == 1) { std::cout << "Shader compiled.\n"; } else { std::cout << "Shader compilation failed.\n"; } return shader; } GLuint Mesh::programFromShaders(int vertexShader, int fragmentShader) { int program = glCreateProgram(); glBindAttribLocation(program, 0, "inPosition"); glBindAttribLocation(program, 1, "inNormal"); glBindAttribLocation(program, 2, "inTextureCoordinate"); glBindAttribLocation(program, 3, "inColor"); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); int linkStatus = 0; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus == 1) { std::cout << "Program linked.\n"; } else { std::cout << "Program linking failed.\n"; } return program; } GLuint Mesh::createVertexBuffer(glm::vec3 *vertices, int vertexCount) { GLuint vertexBuffer = 0; glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertexCount, (GLfloat *) vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); return vertexBuffer; } GLuint Mesh::createNormalBuffer(glm::vec3 *normals, int vertexCount) { GLuint normalBuffer = 0; glGenBuffers(1, &normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertexCount, (GLfloat *) normals, GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); return normalBuffer; } GLuint Mesh::createTextureCoordinateBuffer(glm::vec2 *textureCoordinates, int count) { GLuint buffer = 0; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * count, (GLfloat *) textureCoordinates, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); return buffer; } GLuint Mesh::createIndexBuffer(GLint *indices, int indexCount) { GLuint indexBuffer = 0; glGenBuffers(1, &indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indexCount, indices, GL_STATIC_DRAW); return indexBuffer; } int Mesh::readFromFile(std::ifstream &ifstream) { ifstream.read((char *) &subMeshCount, sizeof(int)); subMeshes = new SubMesh[subMeshCount]; for (int i = 0; i < subMeshCount; i++) { subMeshes[i].readFromFile(ifstream); } ifstream.read((char *) &vertexCount, sizeof(int)); glm::vec3 *vertices = new glm::vec3[vertexCount]; glm::vec3 *normals = new glm::vec3[vertexCount]; glm::vec2 *textureCoordinates = new glm::vec2[vertexCount]; for (int i = 0; i < vertexCount; i++) { ifstream.read((char *) &vertices[i], sizeof(glm::vec3)); ifstream.read((char *) &normals[i], sizeof(glm::vec3)); ifstream.read((char *) &textureCoordinates[i], sizeof(glm::vec2)); } vertexBuffer = createVertexBuffer(vertices, vertexCount); normalBuffer = createNormalBuffer(normals, vertexCount); textureCoordinateBuffer = createTextureCoordinateBuffer(textureCoordinates, vertexCount); indexBuffer = createIndexBuffer(subMeshes[0].indices, subMeshes[0].indexCount); return 0; } int Mesh::draw(glm::vec3 &lightPosition, glm::mat4 &worldMatrix, glm::mat4 &viewMatrix, glm::mat4 &projectionMatrix) { glUseProgram(shaderProgram); glUniformMatrix4fv(glMatWorld, 1, GL_FALSE, &worldMatrix[0][0]); glUniformMatrix4fv(Mesh::glMatView, 1, GL_FALSE, &viewMatrix[0][0]); glUniformMatrix4fv(Mesh::glMatProjection, 1, GL_FALSE, &projectionMatrix[0][0]); glUniform3fv(Mesh::glLightPosition, 1, &lightPosition[0]); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, textureCoordinateBuffer); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_TRIANGLES, subMeshes[0].indexCount, GL_UNSIGNED_INT, 0); // glDrawArrays(GL_POINTS, 0, vertexCount); } int Mesh::heh() { }
true
1b9dc8a291ece146cfc8685798564149e2a4a10d
C++
mattjoncas/opengl-engine
/Renderer/Renderer/Light.h
UTF-8
1,263
2.796875
3
[]
no_license
#pragma once #include <glm/glm.hpp> namespace mor{ class Light { public: Light(); //point light Light(glm::vec3 _position, glm::vec4 _ambient, glm::vec4 _diffuse, glm::vec4 _specular, float _size, float _drop_rate, bool cast_shadows); //directional light Light(glm::vec3 _direction, glm::vec4 _ambient, glm::vec4 _diffuse, glm::vec4 _specular); ~Light(); inline glm::vec4 Position() { return position; }; inline glm::vec4 Direction() { return direction; }; inline glm::vec4 Ambient() { return ambient; }; inline glm::vec4 Diffuse() { return diffuse; }; inline glm::vec4 Specular() { return specular; }; void SetPosition(glm::vec3 _pos); void SetDirection(glm::vec4 _dir); void SetAmbient(glm::vec4 _amb); void SetDiffuse(glm::vec4 _diff); void SetSpecular(glm::vec4 _spec); void CastShadows(bool cast_shadows); inline bool ToggleOn(){ if (isOn){ isOn = false; } else{ isOn = true; } update_ubo = true; return isOn; } inline void SetOn(bool _isOn){ isOn = _isOn; } inline bool IsOn(){ return isOn; } bool UpdateCheck(); //public for now float size, drop_off_rate; private: glm::vec4 position, direction, ambient, diffuse, specular; bool isOn, update_ubo; }; }
true
f11140c2715d2257489ccc22afd4dd86248e99a5
C++
ukaea/UDA
/source/client2/udaGetAPI.cpp
UTF-8
2,118
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
#include "udaGetAPI.h" #include "client.hpp" #include "thread_client.hpp" #include "exceptions.hpp" #include <unordered_map> int udaGetAPI(const char *data_object, const char *data_source) { auto& client = uda::client::ThreadClient::instance(); try { return client.get(data_object, data_source); } catch (uda::exceptions::UDAException& ex) { return -1; } } int udaGetBatchAPI(const char** data_signals, const char** data_sources, int count, int* handles) { auto& client = uda::client::ThreadClient::instance(); try { std::vector<std::pair<std::string, std::string>> requests; requests.reserve(count); for (int i = 0; i < count; ++i) { requests.emplace_back(std::make_pair(data_signals[i], data_sources[i])); } auto handle_vec = client.get(requests); for (int i = 0; i < count; ++i) { handles[i] = handle_vec[i]; } return 0; } catch (uda::exceptions::UDAException& ex) { return -1; } } int udaGetAPIWithHost(const char *data_object, const char *data_source, const char *host, int port) { auto& client = uda::client::ThreadClient::instance(); client.set_host(host); client.set_port(port); try { return client.get(data_object, data_source); } catch (uda::exceptions::UDAException& ex) { return -1; } } int udaGetBatchAPIWithHost(const char** data_signals, const char** data_sources, int count, int* handles, const char* host, int port) { auto& client = uda::client::ThreadClient::instance(); client.set_host(host); client.set_port(port); try { std::vector<std::pair<std::string, std::string>> requests; requests.reserve(count); for (int i = 0; i < count; ++i) { requests.emplace_back(std::make_pair(data_signals[i], data_sources[i])); } auto handle_vec = client.get(requests); for (int i = 0; i < count; ++i) { handles[i] = handle_vec[i]; } return 0; } catch (uda::exceptions::UDAException& ex) { return -1; } }
true
fe6b7742d6cbf2bc9ebf394d4f01cfe63438b9f7
C++
tabatafeeh/URI
/C++/1013.cpp
UTF-8
293
3.03125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int a = 0, b = 0, c = 0, maiorAB = 0, maior = 0; cin >> a; cin >> b; cin >> c; maiorAB = (a + b + abs(a - b)) / 2; maior = (maiorAB + c + abs(maiorAB - c)) / 2; printf("%d eh o maior\n", maior); return 0; }
true
1b88f522b355bd38f243057e347370a6dcadc479
C++
huannd0101/KTLT_HaUI
/BTH3-B/Bai3.3.cpp
UTF-8
541
3.625
4
[]
no_license
/*Bài 3.3.B. Viết hàm đệ quy tính giá trị của biểu thức: F(x, n) = 2017 + x + x2 + x3 +…+ xn ; với n nguyên dương. Viết chương trình chính minh họa cách sử dụng hàm trên.*/ #include<bits\stdc++.h> using namespace std; double F(double x, int n){ if(n == 1) return 2017 + x; return F(x, n - 1) + pow(x, n); } int main(){ double x; int n; cout << "Nhap x = "; cin >> x; cout << "Nhap n = "; cin >> n; cout << "F(" << x << ", " << n << ") = " << F(x, n); return 0; }
true
55dc71b9b5e4c76aeff87c38ca29b087a6351a7f
C++
PhamKhoa96/DataStructure_Algorithm
/OOP/35_DynamicMemory2demensionArray.cpp
UTF-8
416
3.125
3
[]
no_license
/* Mảng hai chiều cấp phát động */ #include <iostream> using namespace std; int main() { int a[10][10]; int** array, array2, array3; float** floatArray; char** friends; array = new int* [10]; for (size_t i = 0; i < 10; i++) { array[i] = new int[10]; } for (size_t i = 0; i < 10; i++) { for (size_t j = 0; j < 10; j++) { cout << array[i][j] << " "; } cout << endl; } return 0; }
true
625e64e5100ec3f99f91c30bede75a1894d36d43
C++
sshikshu/spoj
/stpar/main.cpp
UTF-8
1,176
2.90625
3
[]
no_license
#include <iostream> #include <array> using namespace std; int main(int argc, char *argv[]) { int n, mobile, arranged, i, firstInSideStreet = -1; const int limit = 1000; array<int, limit> lovemobiles; array<int, limit> sideStreet; while (true) { cin >> n; if (n == 0) { break; } arranged = 0; firstInSideStreet = -1; sideStreet.fill(0); lovemobiles.fill(0); for (i = 0; i < n; ++i) { cin >> lovemobiles[i]; } for (int lovemobile : lovemobiles) { if (lovemobile == 0) { break; } if (lovemobile == arranged + 1) { ++arranged; } //cout << lovemobile << " " << arranged << " "; if (firstInSideStreet != -1) { while (sideStreet[firstInSideStreet] == arranged + 1) { ++arranged; --firstInSideStreet; } //cout << firstInSideStreet << " " << sideStreet[firstInSideStreet]; } //cout << endl; if (lovemobile > arranged) { sideStreet[++firstInSideStreet] = lovemobile; } } if (firstInSideStreet == -1) { cout << "yes" << endl; } else { cout << "no" << endl; } } }
true
c52e33cf4b387f14545a7fb2c2a989fd9a0416c4
C++
YFSHEN97/Othello
/agent.h
UTF-8
2,550
3.171875
3
[]
no_license
#ifndef AGENT_H #define AGENT_H #include <cstdint> #include <fdeep/fdeep.hpp> #include "bitboard.h" #include "position.h" // class for an AI Agent that plays the game class Agent { public: // constructor Agent(Color c); // dummy destructor for cleanup purposes virtual ~Agent() {}; // optional function: do some post-processing work internally if necessary virtual void acknowledge_move(int move) {}; // recommend a move using the policy on the given position int recommend_move(Position& pos); protected: // one of two values, BLACK or WHITE Color side; // returns optimal move given a position; this function MUST be redefined virtual int policy(Position& pos) { return 0; }; }; // a wrapper for a human player for consistence with Agent interface class HumanAgent : public Agent { public: using Agent::Agent; private: int policy(Position& pos); }; // a computer AI that makes random moves class RandomComputerAgent : public Agent { public: using Agent::Agent; private: int policy(Position& pos); }; // used to support MC tree structure struct TreeNode; // wrapper for a rollout policy function; type of function is "Rollout" typedef int (*Rollout)(Position& pos); // a computer AI that uses Monte Carlo Tree Search for policy class MCTSComputerAgent : public Agent { public: // constructor // user must specify a function for the Rollout policy! MCTSComputerAgent(Color c, uint32_t iterations, Rollout f); // destructor ~MCTSComputerAgent(); // after a move has been made, preserve relevant search tree branches void acknowledge_move(int move); private: // how many rollouts to conduct during MCTS uint32_t iterations; // store the search tree from previous MCTS iterations TreeNode *tree; // policy function that returns the best move given a position int policy(Position& pos); // do one iteration of MCTS and update stats in place void MCTS(TreeNode *node, Position& pos); // do a rollout according to a particular default policy, and return game outcome Rollout rollout; }; // a computer AI that uses an externally trained CNN to predict best moves class CNNComputerAgent : public Agent { public: // constructor CNNComputerAgent(Color c, fdeep::model& model); // destructor ~CNNComputerAgent() {}; private: // the externally trained CNN model fdeep::model model; // policy function that returns the best move given a position int policy(Position& pos); }; #endif
true
c54c2dc089db4c3952fd3071550cf0048fcef21d
C++
Fritz1414213562/cafemol_utility
/include/DCD/old_src/calc_H32DNA_ang.cpp
UTF-8
1,744
2.875
3
[]
no_license
#include"DCDAnalyzer.hpp" #include<string> #include<iostream> #include<fstream> #include<memory> #include<array> #include<vector> #include<numeric> #include<cmath> #include<typeinfo> template<typename T, std::size_t N> inline std::array<T, N> operator*(const std::array<T, N> lhs, const std::array<T, N> rhs) { std::array<T, N> result; for (std::size_t iN = 0; iN < N; ++iN) { result[iN] = lhs[iN] * rhs[iN]; } return result; } int main() { // constant const float PI = 4 * atan(1); std::string input_file_name = "test.dcd"; std::string output_file_name = "test_angle.txt"; std::unique_ptr<caf::DCDAnalyzer>dparser = std::make_unique<caf::DCDAnalyzer>(input_file_name); const int base1_id = 308; // Chain A in 1kx5_601-200bp_CGmodel.pdb const int base2_id = 311; // chain C in 1kx5_601-200bp_CGmodel.pdb const int histone8mer_id_begin = 1199; const int histone8mer_id_end = 2178; std::vector<std::array<float, 3>> vecs = dparser->makeVector(base1_id, base2_id, histone8mer_id_begin, histone8mer_id_end); // reference vector(unit vector) std::array<float, 3> reference_vector(vecs[0]); std::ofstream ofs; ofs.open(output_file_name); for (const std::array<float, 3>& ivec : vecs) { // calculate inner_product std::array<float, 3> ref_and_ivec = reference_vector * ivec; const float inner_pro = std::accumulate(ref_and_ivec.begin(), ref_and_ivec.end(), 0.0); // calculate the angle between the reference vec and current vec float angle_inframe = 180 * std::acos(inner_pro) / PI; //ofs << inner_pro << std::endl; ofs << angle_inframe << std::endl; } ofs.close(); return 0; }
true
8a5c4a65bf42282e0c5dc7f24f2dace2edb02335
C++
noopwafel/VossII
/src/external/circuit-isomatch/src/circuitTree.cpp
UTF-8
2,846
2.578125
3
[ "Apache-2.0", "LGPL-3.0-only" ]
permissive
//------------------------------------------------------------------- // Copyright 2020 Carl-Johan Seger // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------- #include "circuitTree.h" #include "circuitGroup.h" #include "debug.h" #include <cassert> using namespace std; size_t CircuitTree::nextCircuitId = 0; CircuitTree::CircuitTree() : curHistoryTime(1), lastAlterationTime(1), // 1: nothing memoized yet ancestor_(NULL), circuitId(nextCircuitId) { nextCircuitId++; } CircuitTree::~CircuitTree() {} sign_t CircuitTree::sign(int level) { if(level < (int)memoSig.size() && memoSig[level].timestamp >= lastAlterationTime) return memoSig[level].sig; sign_t signature = computeSignature(level); while((int)memoSig.size() <= level) // Create [level] cell memoSig.push_back(MemoSign(0, 0)); // 0 is always invalid memoSig[level] = MemoSign(curHistoryTime, signature); return signature; } bool CircuitTree::equals(CircuitTree* oth) { if(circType() != oth->circType()) return false; return innerEqual(oth); } void CircuitTree::unplug() { unplug_common(); for(auto conn = io_begin(); conn != io_end(); ++conn) { (*conn)->disconnect(this); } } sign_t CircuitTree::computeSignature(int level) { // Depends only on the gate's type and contents. sign_t inner = innerSignature(); if(level <= 0) return inner; // inpSig is the sum of the signatures of order `level - 1` of all // directly input-adjacent gates. sign_t inpSig = 0; for(auto wire = inp_begin(); wire != inp_end(); ++wire) { for(auto circ = (*wire)->adjacent_begin(); circ != (*wire)->adjacent_end(); ++circ) { inpSig += (*circ)->sign(level-1); } } // Idem with output-adjacent gates sign_t outSig = 0; for(auto wire = out_begin(); wire != out_end(); ++wire) { for(auto circ = (*wire)->adjacent_begin(); circ != (*wire)->adjacent_end(); ++circ) { outSig += (*circ)->sign(level-1); } } // Sum of the IO signatures of the connected wires. For more details on // what's an IO signature, see `CircuitGroup::ioSigOf`'s docstring. sign_t ioSig = 0; if(ancestor_ != nullptr) { for(auto wire = io_begin(); wire != io_end(); ++wire) ioSig += ancestor_->ioSigOf(*wire); } return inner + ioSig + inpSig - outSig; } void CircuitTree::unplug_common() { alter(); if(ancestor_ != nullptr) ancestor_->disconnectChild(this); ancestor_ = nullptr; } void CircuitTree::alter(bool uprec) { curHistoryTime++; lastAlterationTime = curHistoryTime; if(uprec && ancestor_ != nullptr) ancestor_->alteredChild(); }
true
0e1c007d3794101d0c8bcd5b91b4e96bf44a2ff8
C++
Rohitaharwar2003/Networks-Evoting-System
/client/http_response_parser.cpp
UTF-8
1,151
3
3
[]
no_license
#include "http_response_parser.h" using namespace std; HttpResponseParser::HttpResponseParser(string & data){ size_t new_line_index = data.find("\r\n"); //if there is no new line then throw an exception if (new_line_index == string::npos) throw -1; this->statusLine = data.substr(0,new_line_index); //if invalid header found or using an unsupported http version //then throw an exception if (this->statusLine.substr(0,8) != "HTTP/1.0") throw -1; string code = this->statusLine.substr(9,3); stringstream ss(code); ss >> this->statusCode; //if invalid or not supported status code found then throw an exception if (!(this->statusCode == 200 || this->statusCode == 404)) throw -1; //TODO: try to avoid copying the data into body this->body = data.substr(new_line_index,data.length()-1); } string & HttpResponseParser::getResponseBody(){ return this->body; } int HttpResponseParser::getStatusCode(){ return this->statusCode; } string HttpResponseParser::getStatusLine(){ return this->statusLine; } //destructor HttpResponseParser::~HttpResponseParser(){}
true
7849c0d5a5a6cf927f37bae4be9ebfb21333e012
C++
Totol-Luzh/Laba
/Laba 4.cpp
UTF-8
781
2.578125
3
[]
no_license
#include <locale.h> #include <stdio.h> #include <stdlib.h> int main() { int n, i, s0, s1, j, k; int *ms; setlocale(LC_ALL, "RUS"); printf("Введите размер сигнала "); scanf_s("%d", &n); ms = (int*)calloc(n*3, sizeof(int)); if (!ms) { printf("Место под массив не выделено"); return 1; } printf("Введите утроенный сигнал "); for (k = 0; k < n*3; k++) scanf_s("%d", &ms[k]); for (k = 0; k < n*3; k++) printf("%d", ms[k]); printf("\n"); for (j = 0; j < n; j++) { s0 = 0; s1 = 0; for (i = 0; i < 3; i++) { if (ms[j * 3 + i] == 0) s0 = s0 + 1; else s1 = s1 + 1; } if (s0 > s1) printf("0"); else printf("1"); } return 0; }
true
d4d08aa4a87ab3bc7c369b233194f5b388ef7155
C++
remymuller/boost.simd
/doc/examples/reduction.cpp
UTF-8
1,981
2.828125
3
[ "BSL-1.0" ]
permissive
//! [reduc] #include <boost/simd/constant/zero.hpp> #include <iostream> #include <numeric> #include <vector> #include <boost/simd/meta/cardinal_of.hpp> #include <boost/simd/pack.hpp> //! [reduc-inc] #include <boost/simd/function/sum.hpp> //! [reduc-inc] int main() { //! [reduc-simd-types] namespace bs = boost::simd; using pack_t = bs::pack<int32_t>; constexpr std::size_t size = 64; std::int32_t card_int = bs::cardinal_of<pack_t>(); std::vector<int32_t> array(size); std::iota(array.begin(), array.end(), 0); //! [reduc-simd-types] //! [reduc-scalar] // Scalar version int32_t sum = 0; for (size_t i = 0; i < size; ++i) { sum += array[i]; } //! [reduc-scalar] std::cout << "Scalar sum for size " << size << " is " << sum << std::endl; //! [reduc-simd-l] sum = 0; bs::pack<int32_t, size> array_pack(array.data()); sum = bs::sum(array_pack); //! [reduc-simd-l] std::cout << "SIMD sum 1 for size " << size << " is " << sum << std::endl; //! [reduc-simd-o] sum = 0; pack_t sum_p{0}; for (size_t i = 0; i < size; i += card_int) { sum_p += pack_t(array.data() + i); } sum = bs::sum(sum_p); //! [reduc-simd-o] std::cout << "SIMD sum 2 for size " << size << " is " << sum << std::endl; //! [reduc-simd-r] // The input data is an arbitrary size size_t newsize = size + 13; array.resize(newsize); std::iota(array.begin(), array.end(), 0); sum_p = bs::Zero<pack_t>(); size_t i = 0; for (; i + card_int <= newsize; i += card_int) { sum_p += pack_t(array.data() + i); } sum = bs::sum(sum_p); for (; i < newsize; ++i) { sum += array[i]; } //! [reduc-simd-r] std::cout << "SIMD sum 3 for size " << newsize << " is " << sum << std::endl; return 0; } //! [reduc-compile] // This code can be compiled using (for instance for gcc) // g++ reduction.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o reduction // -I/path_to/boost_simd/ -I/path_to/boost/ //! [reduc-compile] //! [reduc]
true
c8997be8a23f1e923c543da15bc5e767f08c902c
C++
alonso804/cs3402-lab4
/compilers/Parser.hpp
UTF-8
1,204
3
3
[]
no_license
#pragma once #include <vector> #include "FlexScanner.hpp" #include "Token.hpp" namespace utec { namespace compilers { // Grammar: // S -> AB // A -> aA | a ===> a [A] // B -> bB | b ===> b [B] class Parser { public: Parser(std::istream& arg_yyin, std::ostream& arg_yyout) : scanner(arg_yyin, arg_yyout) {} void expect(Categoria cat_expected){ auto token = scanner.query_token(); if (token._atributo == cat_expected){ scanner.get_token(); } else{ errors.push_back("caracter " + token._lexema + " unexpected"); } } void A() { expect(Categoria::A); if( scanner.query_token()._atributo == Categoria::A ){ A(); } } void B() { expect(Categoria::B); if( scanner.query_token()._atributo == Categoria::B ){ B(); } } void S(){ A(); B(); } std::vector<std::string> parse() { S(); expect(Categoria::END); return errors; // if( scanner.query_token()._atributo == Categoria::END // && errors.empty()) // return true; // return false; } private: std::vector<std::string> errors; FlexScanner scanner; }; } // namespace compilers } // namespace utec
true
e190756c8c3adba1695f24774d115f7ba3632883
C++
br-lovanshi/Data_Structures_Algorithms_In_Cplusplus
/Factorial-large.cpp
UTF-8
741
2.890625
3
[]
no_license
You are asked to calculate factorials of some small positive integers. Input An integer T, denoting the number of testcases, followed by T lines, each containing a single integer N. Output For each integer N given at input, output a single line the value of N! Input Constraint 1 <= T <= 100 1 <= N <= 100 SAMPLE INPUT 4 1 2 5 3 SAMPLE OUTPUT 1 2 120 6 #include<bits/stdc++.h> using namespace std; int main() { int t; int a[200]; int n,i,j,temp,m,x; scanf("%d",&t); while(t--) { scanf("%d",&n); a[0]=1; m=1; temp = 0; for(i=1;i<=n;i++) { for(j=0;j<m;j++) { x = a[j]*i+temp; a[j]=x%10; temp = x/10; } while(temp>0) { a[m]=temp%10; temp = temp/10; m++; } } for(i=m-1;i>=0;i--) printf("%d",a[i]); printf("\n"); } return 0; }
true
5c1e6fff61e2bb7e48d11a3ac5bd240cc7d283f0
C++
liuweiyu/C-Programs
/NaiveBayesClassifier/NaiveBayesClassifier/Reader.cpp
UTF-8
3,246
2.875
3
[]
no_license
#include "Reader.h" #include "Tools.h" #include <iostream> #include <fstream> using namespace std; Reader::Reader(void) { LoadConfigFile(attrConfig, ATTRTYPEINFO_FILE, 2); attrAndLableNum = attrConfig.size(); LoadRawDataFile(rawData, RAWDATA_FILE); } Reader::~Reader(void) { } /* @parameters: result: attrConfig map fileName: file's name elemNum: expected amount of elements in each line @function: load data from attrConfig file into attrConfig map @return: */ void Reader::LoadConfigFile(outerStrVector& result, string fileName, int elemNum){ Tools tools; ifstream file; file.open(fileName); if(!file.is_open()){ cout << "Problem opening file " << fileName << endl; return; } int line = 1; string curLine = ""; while(getline(file, curLine)){ strVector elements = tools.StringSplit(curLine, SPLIT_TOKEN); if(elements.size() != elemNum){ cout << "Incomplete record at line " << line << endl; }else{ result.push_back(elements); } line++; } cout << "Successfully loaded attrConfig file." << endl; file.close(); } /* @function: load data from "abalone.data" file to member variable rawData, and set rawDataLen, trainDataLen and testDataLen @parameters: rawData: member variable fileName: raw data file name @return: no return value */ void Reader::LoadRawDataFile(outerStrVector& rawData, string fileName){ Tools tools; ifstream file; file.open(RAWDATA_FILE); if(!file.is_open()){ cout << "Problem opening file " << RAWDATA_FILE << endl; return; }else{ int line = 0; string curLine = ""; while(getline(file, curLine)){ strVector elements = tools.StringSplit(curLine, SPLIT_TOKEN); if(elements.size() != attrAndLableNum){ cout << "Incomplete record at line " << line + 1 << " in file " << RAWDATA_FILE << endl; }else{ rawData.insert(rawData.end(), elements); } line++; } rawDataLen = line; trainDataLen = (int)(rawDataLen*TRAIN_DATA_PERCENTAGE); testDataLen = rawDataLen - trainDataLen; } } /* @parameters: attrClassifiers: array of all attributes' classifier lableClassifier: lable's classifier test: Test object @function: load raw data from raw data file "abalone.data" to attributes' classifiers, lable's classifier and test object @return: no return value */ void Reader::LoadTrainDataAndTestData(vector<AttrClassifier*>* attrClassifiers, LableClassifier* lableClassifier, Test* test){ //set the first percentage of TRAIN_DATA_PERCENTAGE to train data for(int i = 0; i < trainDataLen; i++){ strVector elements = rawData.at(i); string curLableValue = elements[attrAndLableNum - 1]; for(int i = 0; i < attrAndLableNum-1; i++){ string cur = elements.at(i); (attrClassifiers->at(i))->GetNewData(cur, curLableValue); } lableClassifier->GetNewData(curLableValue); } //set the rest data as test data for(int j = trainDataLen; j < rawDataLen; j++){ strVector elements = rawData.at(j); test->GetNewData(elements); } } /* @parameters: none @function: get pointer to attrConfig map @return: pointer to attrConfig map */ outerStrVector* Reader::GetAttrConfig(){ return &attrConfig; } /* @parameters: none @function: get attrNum @return: attrNum */ int Reader::GetAttrNum(){ return attrAndLableNum; }
true
8efe4a5230e36a639928c3ddb9652424899c6943
C++
chgogos/oop
/various/OPENEDG/ch2/q8.cpp
UTF-8
218
2.90625
3
[ "MIT" ]
permissive
#include <iostream> #include <list> #include <algorithm> using namespace std; int main() { list<int> mylist{3,9,2,4,5}; mylist.erase(mylist.begin()); for(auto x: mylist){ cout << x << " "; } }
true
d66ed353ff39c059dc09148f452ef7dc0fdaf7ec
C++
mattlacorte/ECGR3123_SC
/server_man.cpp
UTF-8
2,566
2.75
3
[]
no_license
//server arch | client - server #include <ws2tcpip.h> #include <iostream> #include <string> #pragma comment(lib, "ws2_32.lib") using namespace std; int main() { // setup WSADATA wsData; WORD ver = MAKEWORD(2, 2); // check for startup proper int wsOK = WSAStartup(ver, &wsData); if (wsOK != 0) { // bad start cerr << "Can't initialize WINSOCK! See ya" << endl;; return 0; } // socket creation. all hail the socket lord SOCKET listening = socket(AF_INET, SOCK_STREAM, 0); if (listening == INVALID_SOCKET) { // bad listener cerr << "Can't create no socket. See ya" << endl; return 0; } // bind the socket. like a leather book sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(54000); // Host TO Network Short hint.sin_addr.S_un.S_addr = INADDR_ANY; // also use inet_pton bind(listening, (sockaddr*)&hint, sizeof(hint)); // binding the socket // tell winsock the socket is for listen listen(listening, SOMAXCONN); // max connection ~ 15 // wait for connection sockaddr_in client; int clientsize = sizeof(client); // can check for invalid socket SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientsize); // accept connection char host[NI_MAXHOST]; // client's remotoe name char service[NI_MAXSERV]; // service client1 is connected on ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXSERV); if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) { cout << host << " connected on port " << service << endl; } else { inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST); cout << host << " connected on port " << ntohs(client.sin_port) << endl; } // close listening socket closesocket(listening); // message echoing char buff[4096]; // up to 4096 characters while (true) { ZeroMemory(buff, 4096); // reset the message int bytesRecieved = recv(clientSocket, buff, 4096, 0); if (bytesRecieved == SOCKET_ERROR) { // too much or something cerr << "Error in recv(). See ya" << endl; break; } if (bytesRecieved == 0) { // no more data transmitting cout << "Client disconnected." << endl; break; } // handling client1 messages if (bytesRecieved != 2) { // 2 bytes == nothing sent cout << "Client: " << buff << endl; // repeat message to server //cout << " | Bytes Received = " << bytesRecieved << endl; send(clientSocket, buff, bytesRecieved, 0); // acknowledge & repeat message } } // close socket closesocket(clientSocket); WSACleanup(); return 0; }
true
cea0473105d666463e4fb99f549af73659f5dde2
C++
acutkosky/shuffler
/shuffler.cpp
UTF-8
4,963
2.96875
3
[]
no_license
#include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <cstdio> #include <vector> #include <ctime> #define IN_MEMORY_SIZE 100000 #define BUFFER_LINE 1000 #define BRANCHING 15 using namespace std; string getFileNameFromPath(string path) { std::size_t lastSlash = path.rfind('/'); string name = path.substr(lastSlash+1, path.length()); return name; } int splitFile(string sourceFile, vector<string> destFiles) { string line; int lineCount = 0; ifstream sourceStream(sourceFile); if (!sourceStream.is_open()) { return -1; } ofstream* destStreams = new ofstream[destFiles.size()]; string* outbuffers = new string[destFiles.size()]; int* outbuffer_lengths = new int[destFiles.size()]; int numDests = destFiles.size(); for(int i=0; i<destFiles.size(); i++) { destStreams[i].open(destFiles[i]); if(!destStreams[i].is_open()) return -1; outbuffers[i].clear(); outbuffer_lengths[i] = 0; } while (getline(sourceStream, line)) { lineCount ++; int destination = rand() % numDests; outbuffers[destination] += line + '\n'; outbuffer_lengths[destination] ++; if(outbuffer_lengths[destination] > BUFFER_LINE) { destStreams[destination] << outbuffers[destination]; outbuffers[destination].clear(); outbuffer_lengths[destination] = 0; } } for(int i=0; i<numDests; i++) { if(outbuffer_lengths[i] > 0) { destStreams[i] << outbuffers[i]; } destStreams[i].close(); } sourceStream.close(); delete [] destStreams; delete [] outbuffers; delete [] outbuffer_lengths; return lineCount; } int mergeFiles(string destFile, vector<string> sourceFiles) { string line; ofstream destStream(destFile); string buffer; int buffer_length = 0; if (!destStream.is_open()) return 1; for(int i=0; i<sourceFiles.size(); i++) { ifstream sourceStream(sourceFiles[i]); if(!sourceStream.is_open()) return 1; while(getline(sourceStream, line)) { buffer += line + '\n'; buffer_length ++; if(buffer_length > BUFFER_LINE) { destStream << buffer; buffer_length = 0; buffer.clear(); } } sourceStream.close(); if (buffer_length > 0) { destStream << buffer; } buffer_length = 0; buffer.clear(); } destStream.close(); return 0; } int inMemoryShuffle(string toShuffle, string destination) { vector<string> linesInFile; string line; ifstream filePointer(toShuffle); if (!filePointer.is_open()) return 1; while (getline(filePointer, line)) { linesInFile.push_back(line); } filePointer.close(); int length = linesInFile.size(); int* ordering = new int[length]; //generate a random shuffle for (int i=0; i<length; i++) { ordering[i] = i; } for (int i=0; i<length; i++) { int swapIndex = rand()%(length-i); int tmp = ordering[i]; ordering[i] = ordering[i+swapIndex]; ordering[i+swapIndex] = tmp; } ofstream destStream(destination); if(!destStream.is_open()) return 1; for(int i=0; i<length; i++) { destStream << linesInFile[ordering[i]] << '\n'; } destStream.close(); return 0; } int copyFile(string fileToCopy, string destFile) { string line; ofstream destStream(destFile); if (!destStream.is_open()) return 1; ifstream sourceStream(fileToCopy); if (!sourceStream.is_open()) return 1; while (getline(sourceStream, line)) { destStream << line << '\n'; } sourceStream.close(); return 0; } int mergeShuffle(string fileToShuffle, string destination, int branching, int depth) { vector<string> splitFiles; vector<string> shuffledFiles; char buf[10]; for(int i=0;i<10;i++) { buf[i] = 0; } string tmp = string("/tmp/"); sprintf(buf , "%d", rand()); tmp += buf; for(int i=0; i<branching; i++) { sprintf(buf , "%d", i); splitFiles.push_back(tmp + getFileNameFromPath(fileToShuffle) + "-split" + buf); shuffledFiles.push_back(tmp + getFileNameFromPath(fileToShuffle) + "-shuffled"+buf); } int lines = splitFile(fileToShuffle, splitFiles); if (lines < 0) return 1; if (lines <= branching * IN_MEMORY_SIZE) { for(int i=0; i< branching; i++) { inMemoryShuffle(splitFiles[i], shuffledFiles[i]); remove(splitFiles[i].c_str()); } } else { for(int i=0; i< branching; i++) { if(mergeShuffle(splitFiles[i], shuffledFiles[i], branching, depth+1)) return 1; remove(splitFiles[i].c_str()); } } if(mergeFiles(destination, shuffledFiles)) return 1; for(int i=0; i<branching; i++) { remove(shuffledFiles[i].c_str()); } return 0; } void printUsage() { cout<<"Usage: shuffler fileToShuffle outputFile\n"; } int main(int argc, char* argv[]) { srand (time(NULL)); if (argc<3) { printUsage(); return 0; } return mergeShuffle(string(argv[1]), string(argv[2]), BRANCHING, 1); }
true
ba2401008399355495d69e5275ea2ee577fffe83
C++
cpwilliams57/CSCE121
/storeBackend/store.cpp
UTF-8
2,980
3.1875
3
[]
no_license
// // store.cpp // storeBackend // // Created by Cody Williams on 10/27/16. // Copyright © 2016 Cody Williams. All rights reserved. // #include <string> #include <stdexcept> #include "store.h" #include "product.h" #include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include "customer.h" using namespace std; Store::Store(string name1){ name = name1; } //getters string Store::getName(){ return name; } //setters void Store::setName(string name1){ name = name1; } //** void Store::addProduct(int productID1, string productName1){ for(int i=0;i<products.size();++i) { if(products[i].getID() == productID1){ throw runtime_error("Product already exists"); } } Product newProduct(productID1, productName1); products.push_back(newProduct); } //** void Store::addCustomer(int customerID1, std::string customerName1){ for(int i = 0; i < customers.size(); ++i){ if(customers[i].getID() == customerID1){ throw runtime_error("Customer already exists"); } } bool credit1; Customer newCustomer(customerName1,customerID1, credit1); customers.push_back(newCustomer); } //** Product& Store::getProduct(int productID){ bool foundProduct = false; int index = 0; for(int i = 0; i < products.size(); ++i){ if(products.at(i).getID() == productID){ foundProduct = true; index = i; } } if(foundProduct == false){throw runtime_error("Product not found");} return products.at(index); } //** Customer& Store::getCustomer(int customerID){ bool foundCustomer = false; int index = 0; for(int i = 0; i < customers.size(); ++i){ if(customers.at(i).getID() == customerID){ foundCustomer = true; index = i; } } if(foundCustomer == false){throw runtime_error("Customer not found");} return customers.at(index); } //**FIXME void Store::takeShipment(int productID1, int quantity1, double cost1){ Product &thisProduct = getProduct(productID1); thisProduct.addShipment(quantity1, cost1); } //** void Store::makePurchase(int customerID1, int productID1, int quantity1){ Customer &thisCustomer = getCustomer(customerID1); Product &thisProduct = getProduct(productID1); double totalPrice = thisProduct.getPrice() * quantity1; thisCustomer.processPurchase(totalPrice, thisProduct); thisProduct.reduceInventory(quantity1); } //** void Store::takePayment(int customerID1, double amount1){ Customer &thisCustomer = getCustomer(customerID1); thisCustomer.processPayment(amount1); } //** void Store::listCustomers(){ for(int i = 0; i < customers.size(); ++i){ Customer thisCustomer = customers.at(i); cout<<thisCustomer<<endl; } } //** void Store::listProducts(){ for(int i = 0; i < products.size(); ++i){ Product thisProduct = products.at(i); cout << thisProduct << endl; } }
true
93dc06961e702004d1e1df38914837570bd4d176
C++
jt2603099/ThavisayJohnny_CSC5_42480
/Hmwk/Assignment_2/Savitch_9thEd_Ch2_ProgProj_1/main.cpp
UTF-8
1,477
3.203125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: jt2603099 * Artificial Sweetener Diet Soda * Created on March 11, 2018, 2:40 PM */ #include <iostream> #include <cstdlib> using namespace std; int main(int argc, char** argv) { //Declare variables char ans; double mouse_mass(5), mouse_sweetener(35), soda_can(350), dieting_weight, dieter_sweetener, GRAMS(454), dieter_can_grams, dieter_gram, dieter_can; double const diet_soda_sweetener(0.001); do { cout << "Find out how much diet soda pop you can drink according to your weight."<<endl; cout << "Each can of diet soda contains 0.001% of artificial sweetener."<<endl; cout << "Please input your weight when you'll stop dieting"<<endl; cin >> dieting_weight; //Inputs to Outputs dieting_weight = dieting_weight * GRAMS;//convert pounds to grams dieter_sweetener = (mouse_mass / mouse_sweetener) * dieting_weight; //Find amount of grams of sweetener to kill dieter dieter_can_grams = dieter_sweetener / diet_soda_sweetener; dieter_can = dieter_can_grams / 350; cout << "The amount of Diet Soda Can's to kill the dieter is: " << dieter_can <<endl; cout << "Calculate again?"<<endl; cout << "Type y or Y to repeat"<<endl; cin >> ans; } while (ans == 'y'||ans == 'Y'); }
true
58ac2a4653f589f43fba387e268af3b5b9c6d693
C++
mrlukasbos/Chess
/chesspieces/Rook.cpp
UTF-8
576
3.21875
3
[]
no_license
// Created by Lukas Bos on 04/12/2017. #include "Rook.h" Rook::Rook(Board *board, Square *location, PieceColor color) : ChessPiece(board, location, color) { type = ROOK; name = "Rook"; letter = 'R'; } std::vector<Square *> Rook::getAvailableSquares(bool considerCheck) { Vector2i horizontalAndVerticalDirections[] = { Vector2i(0, 1), // Down Vector2i(1, 0), // Right Vector2i(0, -1), // Up Vector2i(-1, 0) // Left }; return calculateMovesForDirections(location, horizontalAndVerticalDirections, board, color, 4, 7, considerCheck); }
true
4fbab2d1eedec55d1384d622e4d06be1137a67d8
C++
michalgregor/msi-gt72s-keyboard
/src/Keyboard.h
UTF-8
795
2.75
3
[ "BSD-3-Clause" ]
permissive
#ifndef KEYBOARD_H #define KEYBOARD_H #include <map> #include <hidapi/hidapi.h> #include "Color.h" extern std::map<std::string, char> RegionNames; extern std::map<std::string, char> ModeNames; char parseRegion(const std::string& region); char parseMode(const std::string& mode); class Keyboard { private: hid_device* _dev = nullptr; public: //! Sends a mode setting message to the keyboard. void sendModeMsg(char mode); //! Sends a color setting message to the keyboard, coloring all regions //! (1-7) using the specified color. void sendColorMsg(Color color); //! Sends a color setting message to the keyboard, coloring the specified //! region using the specified color. void sendColorMsg(char region, Color color); public: Keyboard(); ~Keyboard(); }; #endif // KEYBOARD_H
true
f261a4ba8359ab492684b6a5053a4f1eb65860ed
C++
ytz12345/Project-Euler-solutions
/348.cpp
UTF-8
1,024
2.859375
3
[]
no_license
#include "eulerlib.h" const ll N = 1e10; ll rev(int x, int num, bool isOdd = false) { static char ch[20]; static ll y; ch[0] = y = 0; while (x > 0) ch[++ ch[0]] = x % 10, x /= 10; for (int i = 1, j = ch[0]; i < j; i ++, j --) swap(ch[i], ch[j]); if (isOdd) ch[++ ch[0]] = num; for (int i = ch[0] - isOdd; i > 0; i --) ch[++ ch[0]] = ch[i]; for (int i = 1; i <= ch[0]; i ++) y = y * 10 + ch[i]; return y; } bool judge(ll x) { int cnt = 0; for (ll i = 1, j; ; i ++) { j = i * i * i; if (j >= x) break; if (is_sqr(x - j)) cnt ++; } return cnt == 4; } int main() { ll x, ans = 0; for (int i = 1; i <= 10000; i ++) { x = rev(i, 0, 0); if (x > N) break; if (judge(x)) ans += x; for (int j = 0; j < 10; j ++) { x = rev(i, j, 1); if (x > N) break; if (judge(x)) ans += x; } } cout << ans << endl; print_time(); } // 1004195061 // Time elapsed: 0.847673 s.
true
87974fea77e42ba40bb3d137f2d21d81ddffce60
C++
Gugurumbe/tarotv2
/client/q_requests.cpp
UTF-8
13,030
2.578125
3
[]
no_license
#include "q_requests.hpp" #include <QString> using namespace tarotv; using namespace protocol; using namespace client; using namespace std; request::request(QObject * parent): QObject(parent), sock(0){ } void request::do_request(value_socket * sock, const value & v){ this->sock = sock; QObject::connect(sock, SIGNAL(value(tarotv::protocol::value)), this, SIGNAL(response(tarotv::protocol::value))); QObject::connect(sock, SIGNAL(error(QString)), this, SIGNAL(error(QString))); QObject::connect(sock, SIGNAL(disconnected()), this, SLOT(send_disconnection_error())); QObject::connect(this, SIGNAL(response(tarotv::protocol::value)), this, SLOT(disconnect_from_socket())); QObject::connect(this, SIGNAL(error(QString)), this, SLOT(disconnect_from_socket())); sock->send(v); } void request::disconnect_from_socket(){ if(sock){ disconnect(sock, 0, this, 0); sock = 0; } } void request::send_disconnection_error(){ qDebug()<<"The server closed the connection."; emit error("The server closed the connection."); } tarotv_request::tarotv_request(QObject * parent): request(parent){ QObject::connect(this, SIGNAL(response(tarotv::protocol::value)), this, SLOT(get_response(tarotv::protocol::value))); } void tarotv_request::do_request(value_socket * sock, QString name, std::vector<tarotv::protocol::value> args){ value table(args); value v = value::of_labelled(name.toStdString(), table); request::do_request(sock, v); } void tarotv_request::get_response(value v){ value res; string code; if(v.to_labelled(code, res)){ if(code == "OK"){ emit tarotv_response(res); } else if(code == "ERR"){ qDebug()<<"ERR received : " << QString::fromStdString(v.print()); emit tarotv_refused(res); } else{ QString err = "The server didn't understand a request: " + QString::fromStdString(v.print()); qDebug()<<err; emit error(err); } } else{ QString err = "The server can't answer the request: " + QString::fromStdString(v.print()); qDebug()<<err; emit error(err); } } config_request::config_request(QObject * parent): tarotv_request(parent){ QObject::connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SLOT(transform(tarotv::protocol::value))); QObject::connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SLOT(has_refused(tarotv::protocol::value))); } void config_request::do_request(value_socket * sock){ std::vector<value> args; tarotv_request::do_request(sock, "configuration", args); } void config_request::transform(tarotv::protocol::value v){ value c; string nom; if(v.to_labelled(nom, c) && nom == "config"){ try{ config cfg(c); emit config_response(cfg); } catch(invalid_config_structure i){ QString err = "Cannot parse config response from " + QString::fromStdString(c.print()) + ". " + QString::fromStdString(i.what()); qDebug()<<err; emit error(err); } } else{ QString err = "Cannot parse config response from " + QString::fromStdString(v.print()) + "."; qDebug()<<err; emit error(err); } } void config_request::has_refused(tarotv::protocol::value v){ QString err = "Configuration request has been refused: " + QString::fromStdString(v.print()); emit error(err); } id_request::id_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SLOT(id_transform(tarotv::protocol::value))); connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SLOT(id_refused(tarotv::protocol::value))); } void id_request::do_request(value_socket * sock, QString name){ std::vector<value> args; args.push_back(value::of_labelled("nom", value(name.toStdString()))); tarotv_request::do_request(sock, "identifier", args); } void id_request::id_transform(value v){ value id; string n; if(!v.to_labelled(n, id) || id.type() != value::is_string){ QString err = "Cannot parse id response from " + QString::fromStdString(v.print()) + "."; qDebug()<<err; emit error(err); } else if(n != "id"){ QString err = "Cannot parse id response from " + QString::fromStdString(v.print()) + ": unexpected argument '" + QString::fromStdString(n) + "', expected 'id'."; qDebug()<<err; emit error(err); } else{ emit id_accepted(QString::fromStdString(id.to_string())); } } void id_request::id_refused(tarotv::protocol::value){ emit id_refused(); } out_request::logout_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SIGNAL(logged_out())); } void logout_request::do_request(value_socket * sock, QString id){ std::vector<value> args; args.push_back(value::of_labelled("id", value(id.toStdString()))); tarotv_request::do_request(sock, "deconnecter", args); } peek_request::peek_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SLOT(peek_transform(tarotv::protocol::value))); connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SLOT(peek_refused(tarotv::protocol::value))); } void peek_request::do_request(value_socket * sock, QString id){ std::vector<value> args; args.push_back(value::of_labelled("id", value(id.toStdString()))); tarotv_request::do_request(sock, "peek_message", args); } void peek_request::peek_transform(tarotv::protocol::value v){ string label; value rep; if(!v.to_labelled(label, rep)){ QString err = "Cannot parse peek response from " + QString::fromStdString(v.print()) + "."; qDebug()<<err; emit error(err); } else{ try{ message msg = get_message(v); emit has_message(msg); } catch(invalid_message_structure i){ QString err = "Cannot parse peek response from " + QString::fromStdString(v.print()) + ". " + QString::fromStdString(i.what()); qDebug()<<err; emit error(err); } } } void peek_request::peek_refused(tarotv::protocol::value v){ QString err = "Peek request has been refused: " + QString::fromStdString(v.print()); qDebug()<<err; emit error(err); } pop_request::pop_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SIGNAL(ok())); } void pop_request::do_request(value_socket * sock, QString id){ std::vector<value> args; args.push_back(value::of_labelled("id", value(id.toStdString()))); tarotv_request::do_request(sock, "next_message", args); } msg_request::msg_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SIGNAL(ok())); connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SIGNAL(too_chatty())); } void msg_request::do_request(value_socket * sock, QString id, QString message){ std::vector<value> args; args.push_back(value::of_labelled("id", value(id.toStdString()))); args.push_back(value::of_labelled("message", value(message.toStdString()))); tarotv_request::do_request(sock, "dire", args); } inv_request::inv_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SIGNAL(ok())); connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SIGNAL(invalid())); } void inv_request::do_request(value_socket * sock, QString id, QStringList invites, QMap<QString, value> parametres){ std::vector<value> args; std::map<std::string, value> p; for(QMap<QString, value>::Iterator i = parametres.begin(); i != parametres.end(); i++){ p.insert(std::pair<std::string, value>(i.key().toStdString(), i.value())); } std::vector<value> i; for(QStringList::Iterator j = invites.begin(); j != invites.end(); j++){ i.push_back(value(j->toStdString())); } args.push_back(value::of_labelled("invites", value(i))); args.push_back(value::of_labelled("id", value(id.toStdString()))); args.push_back(value::of_labelled("parametre", value::of_table(p))); tarotv_request::do_request(sock, "inviter", args); } cancel_inv_request::cancel_inv_request(QObject * parent): tarotv_request(parent){ connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SIGNAL(ok())); connect(this, SIGNAL(tarotv_refused(tarotv::protocol::value)), this, SIGNAL(invalid())); } void cancel_inv_request::do_request(value_socket * sock, QString id){ std::vector<value> args; args.push_back(value::of_labelled("id", value(id.toStdString()))); tarotv_request::do_request(sock, "annuler_invitation", args); } msg_bus::msg_bus(const QHostAddress & addr, const QString & id, QObject * parent): QObject(parent), m_running(false), m_addr(addr), m_id(id){ } void msg_bus::run(){ qDebug()<<"Running the bus."; if(!m_running){ m_running = true; value_socket * sock = new value_socket(); QObject::connect(sock, SIGNAL(disconnected()), sock, SLOT(deleteLater())); sock->connectToHost(m_addr, 45678); peek_request * req = new peek_request(sock); QObject::connect(req, SIGNAL(has_message(tarotv::protocol::message)), this, SIGNAL(has_message(tarotv::protocol::message))); QObject::connect(req, SIGNAL(has_message(tarotv::protocol::message)), this, SLOT(check(tarotv::protocol::message))); QObject::connect(req, SIGNAL(error(QString)), this, SLOT(set_idle(QString))); req->do_request(sock, m_id); qDebug()<<"Peek request done."; } } void msg_bus::check(tarotv::protocol::message message){ qDebug()<<"Peek response type : " << (int)(message.t); if(message.t == tarotv::protocol::is_en_jeu){ m_running = false; emit end(); qDebug()<<"End of the bus."; } else { qDebug()<<"Should pop."; should_pop(); } } void msg_bus::should_pop(){ qDebug()<<"Requesting pop."; if(m_running){ qDebug()<<"Bus running : ok"; m_running = false; value_socket * sock = new value_socket(); QObject::connect(sock, SIGNAL(disconnected()), sock, SLOT(deleteLater())); sock->connectToHost(m_addr, 45678); pop_request * req = new pop_request(sock); QObject::connect(req, SIGNAL(response(tarotv::protocol::value)), this, SLOT(run())); QObject::connect(req, SIGNAL(error(QString)), this, SLOT(run())); // I could care less #xkcd req->do_request(sock, m_id); qDebug()<<"Pop done."; } } void msg_bus::set_idle(QString why){ qDebug()<<"Bus idle : "<<why; m_running = false; if(why == "The remote host closed the connection"){ qDebug()<<"NP."; run(); } else { qDebug() << "Bus error."; emit error(why); } } tarotv_game_request::tarotv_game_request(QObject * parent): tarotv_request(parent){ QObject::connect(this, SIGNAL(tarotv_response(tarotv::protocol::value)), this, SLOT(tarotv_accepted(tarotv::protocol::value))); } void tarotv_game_request::do_request(value_socket * sock, QString id, QString commande, QStringValueMap q_sous_args){ std::vector<value> args; std::map<std::string, tarotv::protocol::value> sous_args; for(QStringValueMap::const_iterator i = q_sous_args.begin(); i != q_sous_args.end(); i++){ sous_args.insert (std::pair<std::string, tarotv::protocol::value> (i.key().toStdString(), i.value())); } value v = value::of_labelled(commande.toStdString(), value::of_table(sous_args)); args.push_back(value::of_labelled("id", value(id.toStdString()))); args.push_back(value::of_labelled("arguments", v)); tarotv_request::do_request(sock, "jeu", args); } void tarotv_game_request::tarotv_accepted(tarotv::protocol::value accepte){ value res; string code; if(accepte.to_labelled(code, res)){ if(code == "OK"){ emit tarotv_game_response(res); } else if(code == "ERR"){ emit tarotv_game_refused(res); } else{ QString err = "The game server didn't understand a request: " + QString::fromStdString(accepte.print()); emit error(err); } } else{ QString err = "The game server can't answer the request: " + QString::fromStdString(accepte.print()); emit error(err); } } game_peek_message::game_peek_message(QObject * parent): tarotv_game_request(parent){ QObject::connect(this, SIGNAL(tarotv_game_response(tarotv::protocol::value)), this, SLOT(decrypter(tarotv::protocol::value))); } void game_peek_message::do_request(value_socket * sock, QString id){ tarotv_game_request::do_request(sock, id, "peek_message", QStringValueMap()); } void game_peek_message::decrypter(value v){ try{ message_jeu msg = get_message_jeu(v); emit has_message(msg); } catch(invalid_message_structure i){ QString err = "Cannot parse peek response from " + QString::fromStdString(v.print()) + ". " + QString::fromStdString(i.what()); emit error(err); } }
true
175b25cb78803838d27cce3c4121f8f69366c6a5
C++
gerry2206/DS_ALGO_prep
/Dynamic-Programming/increasing-subsequence.cpp
UTF-8
776
2.953125
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; #define vi vector<int> #define rep(i,n) for(int i=0;i<n;i++) #define all(a) a.begin(),a.end() #define fastio ios_base::sync_with_stdio(0), cout.tie(0), cin.tie(0) //EDITORIAL /*dp[i] denotes if LIS of length i can be constructed ; for each value x check 1/ if(lower_bound(x)) != dp.end() repalce *it=x; 2/if it==dp.end() dp.pb(x) to find strictly LIS change lower_bound to upper_bound */ int32_t main() { fastio; int n; cin >> n; vi dp; rep(i, n) { int x; cin >> x; auto it = lower_bound(all(dp), x); if (it == dp.end()) dp.push_back(x); else { *it = x; } } cout<<dp.size()<<"\n"; }
true
8cb311a08d7a40ff6cf26c81a08bdf3add780b4b
C++
xcesek/Petri-Net-on-Arduino
/Transition.h
UTF-8
851
2.671875
3
[]
no_license
#ifndef Transition_h #define Transition_h #include "Arduino.h" #include "Helper.h" #include "Place.h" class Transition { private: char *id; int pin; FunctionType functionType; int extended; Place **inPlaces; int inPlacesCount; Place **outPlaces; int outPlacesCount; int analogTreshold; int analogTresholdRangeLow; int analogTresholdRangeHigh; public: Transition(char* id, Place **_inPlaces, int _inPlacesCount, Place **_outPlaces, int _outPlacesCount); Transition(char* id, int _pin, FunctionType _functionType, Place **_inPlaces, int _inPlacesCount, Place **_outPlaces, int _outPlacesCount); void fire(); int isActive(); void setAnalogTreshold(int _analogTreshold); void setAnalogTresholdRange(int _analogTresholdRangeLow, int _analogTresholdRangeHigh); }; #endif
true
27efc1d06b8b8034ade3566c5c917ffa0eacbb22
C++
wangyongliang/nova
/poj/1159/POJ_1159_2430100_AC_1700MS_68K.cpp
UTF-8
511
2.578125
3
[]
no_license
#include<stdio.h> #include<iostream.h> //pku 3181 char str[5010]; short dp[2][5010]={0}; short minimum(short a,short b) { return a<b?a:b; } void main() { int n,i,j,flag; while(scanf("%d",&n)!=EOF) { flag=0; scanf("%s",str+1); for(i=n;i>0;i--,flag=1-flag) for(j=0;j<=n;j++) { if(i>=j) continue; if(str[i]==str[j]) dp[flag][j]=dp[1-flag][j-1]; else dp[flag][j]=minimum(dp[1-flag][j],dp[flag][j-1])+1; } printf("%d\n",dp[1-flag][n]); } }
true
41beb6234adb5c92cc95a35a8cff995c08b9debf
C++
BPAishwarya/INFM_Course_Projects
/Arduino projects/Breatheeffect/randNumberGuess/randNumberGuess.ino
UTF-8
2,403
3.28125
3
[]
no_license
#include <stdlib.h> int randomNumber; //the random number that the user is trying to guess //const char *chGuess; String guess = ""; String newChar = ""; void setup() { randomSeed(analogRead(7)); //seed the random number generator based on a 'random' reading from an unconnected analog input randomNumber = random(100); //generate a random number Serial.begin(9600); //start the Serial port at a baud rate of 9600 bits per second (bps) //print prompts Serial.println("Hello! Please enter a number between 0 and 100. "); //uncomment the next 2 lines if you want to see the random number for debugging Serial.print("Random Number: "); Serial.println(randomNumber); } //setup() is done, go to loop() void genRandom(){ randomSeed(analogRead(7)); //seed the random number generator based on a 'random' reading from an unconnected analog input randomNumber = random(100); //generate a random number Serial.println("Hello! Please enter a number between 0 and 100. "); } void loop() { //check is there are any characters incoming on the serial buffer. if(Serial.available() > 0) { guess = Serial.parseInt(); //Serial.parseInt is an advanced version of Serial.read(). Serial.parseInt() reads several characters and trys to create an integer out of them. This operation takes longer than a standard Serial.read() which just reads one character at a time delay(100); unsigned char text[0] = guess; int intValue; sscanf(text,"%04d",&intValue); Serial.println(intValue); // Serial.print("You Guessed: "); //print static text // Serial.println(guess); //print the data that was recieved // // if(guess == randomNumber) // { // Serial.println("You guessed correctly!"); //print static text // Serial.flush(); // delay(1000); // Serial.println("Press any character to continue"); // genRandom(); // } // if(guess > randomNumber) // { // Serial.println("You Guess is too high"); //print static text // } // else if(guess < randomNumber) // { // Serial.println("Here in low"); // Serial.println("You Guess is too low"); //print static text // } // } //Serial.println("Outside if loop"); delay(100); }//go back to the first line in loop()
true
c4b0a37557da5ba1483f9601b6b5b58ba8d33615
C++
silky/MicroMacro
/slitscan/src/Slicer.h
UTF-8
979
2.609375
3
[ "MIT" ]
permissive
// // Slicer.h // slitscan // // Created by Chris on 09/03/2015. // // #pragma once #include "ofMain.h" #include "AlphaMask.h" // Slicer chops up an image/texture into vertical strips and draw the output into an FBO // Basic usage: call begin() draw any texture and call end() and then draw() class Slicer { public: void setup(int w=0, int h=0); void update(); void draw(int x=0, int y=0); void setThickness(int thickness); void setVertical(bool isVertical); void refresh(); void begin(); void end(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); AlphaMask mask; int thickness; bool isVertical; };
true
f88a5be98ac542d46b5061986005f73c6a63b9da
C++
limon2009/ACM-UVA-Online-Judge-solution
/10097.cpp
UTF-8
1,386
2.875
3
[]
no_license
#include<iostream> #include<queue> #define maxn 102 using namespace std; struct ss { int u, v; int cost; }; queue<ss>Q; char F[maxn][maxn]; int Link[maxn][maxn], N; int n1, n2, n3, game; int BFS() { ss temp, dum; int u, v; F[n1][n2] = F[n2][n1] = 1; temp.u = n1; temp.v = n2; temp.cost = 0; Q.push(temp); while(!Q.empty()) { dum = Q.front(); Q.pop(); u = Link[dum.u][dum.v]; v = Link[dum.v][dum.u]; if(u) { if(u == n3) return dum.cost + 1; if(F[u][dum.v] == 0) { F[u][dum.v] = F[dum.v][u] = 1; temp.u = u; temp.v = dum.v; temp.cost = dum.cost + 1; Q.push(temp); } } if(v) { if(v == n3) return dum.cost + 1; if(F[v][dum.u] == 0){ F[v][dum.u] = F[dum.u][v] = 1; temp.u = v; temp.v = dum.u; temp.cost = dum.cost + 1; Q.push(temp); } } } return 0; } void Cal() { int d; cin>>n1>>n2>>n3; cout<<"Game #"<<game++<<endl; if(n1 == n3 || n2 == n3) { cout<<"Minimum Number of Moves = 0\n"; return; } d = BFS(); if(d > 0) cout<<"Minimum Number of Moves = "<<d<<endl; else cout<<"Destination is Not Reachable !"<<endl; } int main() { int i, j; game = 1; //freopen("h.txt","r",stdin); while(cin>>N && N) { for(i = 1; i<= N; i++) { for(j = 1; j<= N; j++) { cin>>Link[i][j]; F[i][j] = 0; } } Cal(); cout<<endl; while(!Q.empty()) Q.pop(); } return 0; }
true
b401eb5a46b68d1228afc65be370170977166e24
C++
zuev-stepan/PhysicsEngine
/ShapeFactory.h
UTF-8
3,510
3.15625
3
[]
no_license
#ifndef SHAPEFACTORY #define SHAPEFACTORY #include "World.h" class ShapeFactory { public: World* w; ShapeFactory(World &world) { w = &world; } void createRagdoll(float x, float y) { Particle* head = w->createParticle(x, y, 20); Particle* neck = w->createParticle(x, y + 35, 10); Particle* lh1 = w->createParticle(x - 30, y + 35, 10); Particle* lh2 = w->createParticle(x - 60, y + 35, 10); Particle* rh1 = w->createParticle(x + 30, y + 35, 10); Particle* rh2 = w->createParticle(x + 60, y + 35, 10); Particle* ass = w->createParticle(x, y + 95, 10); Particle* ll1 = w->createParticle(x - 30, y + 120, 10); Particle* ll2 = w->createParticle(x - 60, y + 145, 10); Particle* rl1 = w->createParticle(x + 30, y + 120, 10); Particle* rl2 = w->createParticle(x + 60, y + 145, 10); w->createConnection(head, neck); w->createConnection(neck, lh1); w->createConnection(lh1, lh2); w->createConnection(neck, rh1); w->createConnection(rh1, rh2); w->createConnection(neck, ass); w->createConnection(ass, ll1); w->createConnection(ll1, ll2); w->createConnection(ass, rl1); w->createConnection(rl1, rl2); w->createLenConnection(neck, lh2); w->createLenConnection(neck, rh2); w->createLenConnection(ass, ll2); w->createLenConnection(ass, rl2); w->createLenConnection(neck, ll1); w->createLenConnection(neck, rl1); w->createLenConnection(ass, lh1); w->createLenConnection(ass, rh1); } void createTriangle(float x, float y) { Particle* p1 = w->createParticle(x, y, 10); Particle* p2 = w->createParticle(x + 30, y + 50, 10); Particle* p3 = w->createParticle(x - 30, y + 50, 10); w->createConnection(p1, p2); w->createConnection(p2, p3); w->createConnection(p3, p1); } void createCube(float x, float y) { Particle* p1 = w->createParticle(x - 50, y - 50, 10); Particle* p2 = w->createParticle(x + 50, y - 50, 10); Particle* p3 = w->createParticle(x + 50, y + 50, 10); Particle* p4 = w->createParticle(x - 50, y + 50, 10); w->createConnection(p1, p2); w->createConnection(p2, p3); w->createConnection(p3, p4); w->createConnection(p4, p1); w->createLenConnection(p1, p3); w->createLenConnection(p2, p4); } void createGum(float x, float y, int h) { Particle* p[100][100]; for (int i = 0; i < h; i++) { for (int j = 0; j < h; j++) { p[i][j] = w->createParticle(x + j * 30, y + i * 30, 10); if (j > 0) w->createLenConnection(p[i][j], p[i][j - 1]); if (i > 0) w->createLenConnection(p[i][j], p[i - 1][j]); if (i > 0 && j > 0) w->createLenConnection(p[i][j], p[i - 1][j - 1]); } } } void createCloth(float x, float y, int h) { Particle* p[100][100]; for (int i = 0; i < h; i++) { for (int j = 0; j < h; j++) { p[i][j] = w->createParticle(x + j * 30, y + i * 30, 1); p[i][j]->mask = 0; if (j > 0) w->createLenConnection(p[i][j], p[i][j - 1])->s = 0.002; if (i > 0) w->createLenConnection(p[i][j], p[i - 1][j])->s = 0.002; } } for (int i = 0; i < h; i++) w->createPin(p[0][i], x + i * 30, y); } void createGish(float x, float y) { Particle* p[50]; float r = 100; for (int i = 0; i < 50; i++) { p[i] = w->createParticle(x + r * cos(pi / 25 * i), y + r * sin(pi / 25 * i)); if (i > 0) w->createConnection(p[i], p[i - 1]); if (i == 49) w->createConnection(p[i], p[0]); } for (int i = 0; i < 25; i++) w->createLenConnection(p[i], p[i + 25], (p[i]->pos - p[i + 25]->pos).len(), 0.0002); } }; #endif SHAPEFACTORY
true
f4c32ceb19eeb1a947e4bf6b10689102f468443f
C++
EpicStep/surl-hackathon
/main.cpp
UTF-8
738
2.53125
3
[]
no_license
#include <iostream> #include <cpr/cpr.h> int main(int argc, char* argv[]) { const std::string url = "http://localhost:8000/api/json/v2"; std::string methodStr; if (argc <= 1) { methodStr = "systemInfo"; } else { methodStr = argv[1]; } std::string body = R"({"id":0, "jsonrpc":"2.0","method":")" + methodStr + R"(","params":[]})"; cpr::Response r = cpr::Post(cpr::Url{url}, cpr::Body(body)); if (r.error) { std::cout << "(surl) " + r.error.message << std::endl; return 0; } if (r.text.empty()) { std::cout << "(surl) server doesnt return any text in response." << std::endl; } else { std::cout << r.text << std::endl; } return 0; }
true
c5f45beb0489dc4b6629dec374796d7217c06ca7
C++
sly1061101/440-BreakThrough
/Src/GameBoard.hpp
UTF-8
1,242
2.90625
3
[]
no_license
// // GameBoard.hpp // 448-BreakThrough // // Created by Liuyi Shi on 10/25/17. // Copyright © 2017 Liuyi Shi. All rights reserved. // #ifndef GameBoard_hpp #define GameBoard_hpp #include <stdio.h> #include <vector> namespace board { enum cellstatus {Player0, Player1, Empty}; typedef enum cellstatus CellStatus; typedef std::pair<unsigned int, unsigned int> Coor; typedef struct cell{ unsigned int row; unsigned int col; CellStatus Status; }Cell; class GameBoard{ private: unsigned int row_size; unsigned int col_size; std::vector<Cell> CellList; public: GameBoard(unsigned int col_size = 8, unsigned int row_size = 8); unsigned int CoorToId(unsigned row, unsigned col){ return (row * row_size + col); } Coor IdToCoor(unsigned int Id); void SetStatus(unsigned Id, CellStatus status); CellStatus GetStatus(unsigned Id); unsigned int GetRowSize(){ return row_size; } unsigned int GetColSize(){ return col_size; } unsigned int GetStatusNum(CellStatus status); void PrintBoard(); }; } #endif /* GameBoard_hpp */
true
1087e78bee2371b6ee0b92e5e85c9388b1e71648
C++
GroupOfRobots/MiniRysV3Tests
/mpu6050/main.cpp
UTF-8
595
2.953125
3
[]
no_license
#include <iostream> #include <csignal> #include "IMU.hpp" bool exitFlag = false; void sigintHandler(int signum) { if (signum == SIGINT) { exitFlag = true; } } int main(int argc, char * argv[]) { signal(SIGINT, sigintHandler); std::cout << "initializing imu\n"; IMU * imu = new IMU(); imu->initialize(); std::cout << "reading\n"; while(!exitFlag) { IMU::ImuData data; try { imu->getData(&data); } catch (std::string & error) { std::cout << "[IMU] Error getting IMU reading: " << error << std::endl; continue; } usleep(50 * 1000); } delete imu; return 0; }
true
47c05ee84297a7dda172341674d01dbf32d7ce34
C++
michaelmeixner/Arduino-Projects
/EE452L Labs/Lab 3/sketch_feb25a/sketch_feb25a.ino
UTF-8
1,339
2.921875
3
[]
no_license
// Michael Meixner, EE452 Lab 3 const int EWgreen = 8, EWyellow = 9, EWred = 10, NSgreen = 11, NSyellow = 12, NSred = 13; const int buttonPin = 3; int buttonState = 0; void setup() { // put your setup code here, to run once: pinMode(EWgreen, OUTPUT); pinMode(EWyellow, OUTPUT); pinMode(EWred, OUTPUT); pinMode(NSgreen, OUTPUT); pinMode(NSyellow, OUTPUT); pinMode(NSred, OUTPUT); pinMode(buttonPin, INPUT); } void loop() { // put your main code here, to run repeatedly: buttonState = digitalRead(buttonPin); if(buttonState == LOW) { digitalWrite(EWgreen, LOW); digitalWrite(EWyellow, LOW); digitalWrite(NSgreen, LOW); digitalWrite(NSyellow, LOW); digitalWrite(EWred, HIGH); digitalWrite(NSred, HIGH); delay(20000); digitalWrite(EWred, LOW); digitalWrite(NSred, LOW); } else { digitalWrite(EWgreen, HIGH); digitalWrite(NSred, HIGH); delay(25000); digitalWrite(EWgreen, LOW); digitalWrite(EWyellow, HIGH); delay(5000); digitalWrite(NSred, LOW); digitalWrite(EWyellow, LOW); digitalWrite(EWred, HIGH); digitalWrite(NSgreen, HIGH); delay(20000); digitalWrite(NSgreen, LOW); digitalWrite(NSyellow, HIGH); delay(4000); digitalWrite(EWred, LOW); digitalWrite(NSyellow, LOW); } }
true
d414a5480f6ee57029cc35b7442e1f1f04a42689
C++
ReturnJohn/SteamSpace2
/SteamSpace/SteamSpace/Player.cpp
UTF-8
657
2.96875
3
[]
no_license
#include "Player.h" #include "GameObject.h" #include "SOIL.h" Player::Player(float initX, float initY, float initZ) : GameObject(initX,initY,initZ) { x = initX; y = initY; z = initZ; direction = 0; texture = SOIL_load_OGL_texture("Plane.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y); //Load texture through soil glBindTexture(GL_TEXTURE_2D, texture); } void Player::Move(float gameTime) { switch (direction) { case 1: x -= 1.5f * gameTime; break; case 2: x += 1.5f * gameTime; break; case 3: y += 1.5f * gameTime; break; case 4: y -= 1.5f * gameTime; break; default: break; } } Player::~Player() { }
true