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
b21bad33411ba1a55ca5e24cdca8df06401ade07
C++
iceseyes/mlogo
/src/interpreter.hpp
UTF-8
4,793
3
3
[]
no_license
/** * @file: interpreter.hpp * * created on: 1 settembre 2017 * author: Massimo Bianchi <bianchi.massimo@gmail.com> */ #ifndef __INTERPRETER_HPP__ #define __INTERPRETER_HPP__ #include <boost/algorithm/string.hpp> #include <iostream> #include <stdexcept> #include <string> #include "defines.hpp" #include "eval.hpp" #include "exceptions.hpp" #include "memory.hpp" #include "parser.hpp" namespace mlogo { struct InterpreterState { static InterpreterState &instance() { static InterpreterState __instance; return __instance; } void bye() { _running = false; } bool running() const { return _running; } private: InterpreterState() : _running(true) {} InterpreterState(const InterpreterState &) = delete; InterpreterState(InterpreterState &&) = delete; InterpreterState &operator=(const InterpreterState &) = delete; InterpreterState &operator=(InterpreterState &&) = delete; bool _running; }; template <typename InputStream, typename OutputStream, typename ErrorStream = OutputStream> class Interpreter { public: Interpreter(InputStream &is, OutputStream &os, ErrorStream &es, bool wPrompt, bool rethrow) : _iStream(is), _oStream(os), _eStream(es), _interactive(wPrompt), _rethrow(rethrow) {} void run() { using namespace std; using namespace boost; using namespace mlogo::parser; using namespace mlogo::eval; using namespace mlogo::memory; string str; Procedure *currentProc{nullptr}; Statement stmt; showPrompt(); while (InterpreterState::instance().running() && getline(_iStream, str)) { AST ast; try { if (currentProc) { if (currentProc->addLine(str)) { Stack::instance().setProcedure(*currentProc); delete currentProc; currentProc = nullptr; if (_interactive) _eStream << "Procedure recorded." << endl; showPrompt(); } continue; } else stmt = parse(str); if (stmt.isStartProcedure()) { currentProc = new Procedure(stmt); continue; } if (!currentProc) { ast = make_ast(stmt); ast(); } } catch (logic_error &e) { _eStream << "I don't know how to " << str << " (" << e.what() << ")" << endl; if (_rethrow) throw e; } showPrompt(); } } /** * Parse one string and if is a valid logo statement try to * run it. It does not support procedure definition. * * @param[in] line a string to parse and execute. * @throw mlogo::exceptions::Syntaxerror is string is not right * @throw mlogo::exceptions::InvalidStatmentException if string is a * procedure definition. */ void one(const std::string &line) const { using namespace mlogo::parser; using namespace mlogo::eval; auto stmt = parse(line); if (stmt.isStartProcedure()) throw exceptions::InvalidStatmentException(line); auto ast = make_ast(stmt); ast.exec(); } void startup() const { auto line = mlogo::memory::Stack::instance().getVariable("startup").toString(); one(line); } protected: void showPrompt() { if (_interactive) _eStream << "? "; } private: InputStream &_iStream; OutputStream &_oStream; ErrorStream &_eStream; bool _interactive; bool _rethrow; }; template <typename InputStream, typename OutputStream, typename ErrorStream = OutputStream> Interpreter<InputStream, OutputStream, ErrorStream> getInterpreter( InputStream &is, OutputStream &os, ErrorStream &es, bool wPrompt = true, bool rethrow = false) { return Interpreter<InputStream, OutputStream, ErrorStream>( is, os, es, wPrompt, rethrow); } template <typename InputStream, typename OutputStream, typename ErrorStream = OutputStream> Interpreter<InputStream, OutputStream, ErrorStream> *getInterpreterPtr( InputStream &is, OutputStream &os, ErrorStream &es, bool wPrompt = true, bool rethrow = false) { return new Interpreter<InputStream, OutputStream, ErrorStream>( is, os, es, wPrompt, rethrow); } using StdDynamicInterpreter = Interpreter<std::istream, std::ostream, std::ostream>; } // namespace mlogo #endif /* __INTERPRETER_HPP__ */
true
19a91049383f4474da5c485a505cc5067526f66d
C++
diverjoe/TasmotaSlave
/examples/SlaveRespondTele/SlaveRespondTele.ino
UTF-8
2,785
2.890625
3
[]
no_license
/* SlaveRespondTele.ino - Example for TasmotaSlave to respond to SlaveSend ON and SlaveSend OFF commands via console or telemetry. In this example the ON and OFF is case sensitive so needs to be sent in capital letters from the Tasmota device. Upon receiving ON/OFF the slave will turn the LED on/off respectively and respond with a telemetry message sent back to Tasmota that will be published for telemetry and rules processing on the Tasmota device. Copyright (C) 2019 Andre Thomas This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <Arduino.h> #include <TasmotaSlave.h> TasmotaSlave slave(&Serial); /*******************************************************************\ * Normal setup() function for Arduino to configure the serial port * speed (which should match what was configured in Tasmota) and * attach any callback functions associated with specific requests * or commands that are sent by Tasmota. \*******************************************************************/ void setup() { // Configure the LED pin as OUTPUT pinMode(LED_BUILTIN, OUTPUT); // Configure the serial port for the correct baud rate Serial.begin(57600); // Attach the callback function which will be called when Tasmota requests it slave.attach_FUNC_COMMAND_SEND(user_FUNC_RECEIVE); } /*******************************************************************\ * Function which will be called when Tasmota sends a * SlaveSend command \*******************************************************************/ void user_FUNC_RECEIVE(char *data) { if (!strcmp(data, "ON")) { // SlaveSend ON digitalWrite(LED_BUILTIN, HIGH); char response[20]; sprintf(response,"{\"LED\":\"ON\"}"); slave.SendTele(response); } if (!strcmp(data, "OFF")) { // SlaveSend OFF digitalWrite(LED_BUILTIN, LOW); char response[20]; sprintf(response,"{\"LED\":\"OFF\"}"); slave.SendTele(response); } } void loop() { slave.loop(); // Call the slave loop function every so often to process incoming requests }
true
7be66d18e843a3f34a1b7dd7ca85e789f87940e2
C++
Yen/LysOld
/Client/src/graphics/graphicsprofile.hpp
UTF-8
505
2.578125
3
[]
no_license
#pragma once #include <GL\glew.h> #include <string> namespace lys { class GraphicsProfile { private: std::string _vendor; std::string _renderer; std::string _version; unsigned short _maxTextureSlots; unsigned short _maxSamples; public: GraphicsProfile(); const std::string &getVendor() const; const std::string &getRenderer() const; const std::string &getVersion() const; const unsigned short &getMaxTextureSlots() const; const unsigned short &getMaxSamples() const; }; }
true
f240103dfca138eb61f76f1bccd5fa736137bb95
C++
ih8mylyf/Mergesort
/Mergesort.cpp
UTF-8
1,170
3.390625
3
[]
no_license
#include <iostream> #include <cassert> using namespace std; void msort(int a[], int x[], int s, int e) { if(e-s > 1){ int m = (s+(e-1))/2; msort(a, x, s, m+1); msort(a, x, m+1, e); int j = s; int c = m+1; int t = s; while(j < m+1 && c < e){ if(a[j] >= a[c]) x[t++] = a[c++]; else x[t++] = a[j++]; } while(j < m+1) x[t++] = a[j++]; while(c < e) x[t++] = a[c++]; for(int q = s; q < e; q++) a[q] = x[q]; } } void mergesort(int a[], int n) { int *x = new int[n]; msort(a, x, 0, n); delete []x; } bool sorted(int a[], int n) { for (int x = 0;x < n-1;x++) if (a[x] > a[x+1]) return false; return true; } int main(int argc, char * args[]) { int a[1000]; for (int i = 0; i < 1000; ++i) a[i] = -50 + rand() % 100; mergesort(a, 1000); assert(sorted(a, 1000)); int b[1001]; for (int i = 0; i < 1001; ++i) b[i] = -50 + rand() % 100; mergesort(b, 1001); assert(sorted(b, 1001)); int c[] = { 2 }; mergesort(c, 1); assert(sorted(c, 1)); int d[] = { 1, 2, 3, 4, 5 }; mergesort(d, 5); assert(sorted(d, 5)); int e [0]; mergesort (e, 0); assert (sorted (e, 0)); cout << "All tests passed." << endl; }
true
72a4a78e57dfdc892f02b0ed3fcb3a503aaceaa2
C++
LayicheS/algorithm_cpp
/[牛客] 反转链表.cpp
UTF-8
941
3.34375
3
[]
no_license
#include <iostream> #include<map> #include<vector> #include<string> #include<regex> #include<queue> #include<stack> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; ListNode* ReverseList(ListNode* pHead) { if(!pHead) return NULL; //操作三个指针或者节点存成数组然后循环 ListNode *p1,*p2,*p3; p1=pHead; p2=p1->next; p1->next=NULL; while(p2){ p3=p2->next; p2->next=p1; p1=p2; p2=p3; } return p1; } int main(){ vector<int> temp={}; ListNode* dummy=new ListNode(0); ListNode *p=dummy; for(int i=0;i<temp.size();i++){ ListNode *node=new ListNode(temp[i]); p->next=node; p=p->next; } ListNode* re=ReverseList(dummy->next); while(re){ cout<<re->val<<endl; re=re->next; } return 0; }
true
e84a7408c0e308db8c0430d27f5aae551f491554
C++
MarceloPaganini/exercicios_c
/exercicio23.cpp
ISO-8859-2
817
2.609375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <math.h> #include <conio.h> #include <iostream> int main() { float tempo, distancia, litros_usados; int veloc; setlocale(LC_ALL, "PORTUGUESE"); printf("\t\t\n * Exercicio 23 - Quantidade de litros de combustvel * \n\n"); printf(" Tempo gasto na viagem: "); scanf("%f", &tempo); printf(" Velocidade mdia da viagem: "); scanf("%i", &veloc); distancia = tempo * veloc; litros_usados = distancia/12; printf(" \n Velocidade Mdia: %.2ikm/h\n", veloc); printf(" Tempo Gasto: %.2fHs\n", tempo); printf(" Distancia Percorrida: %.2fkm\n", distancia); printf(" Total de Combustivel Utilizado: %.2fL\n\n", litros_usados); system("pause"); return 0; }
true
816ade034d343575796349fcf6ef4345705c75ee
C++
zhangchunbao515/leetcode
/leetcode-01/cpp/leetcode/168. excel-sheet-column-title.cpp
GB18030
395
2.921875
3
[]
no_license
#include "public.h" //simple solution 4ms, 87.86% //ѧ class Solution { public: string convertToTitle(int n) { //ͣس26 //! string res = ""; while (n > 0) { if (n % 26 == 0) { res.insert(res.begin(), 'Z'); n /= 26; n--; } else { res.insert(res.begin(), n % 26 + 'A' - 1); n /= 26; } } return res; } };
true
65d9f40719fe1681953bf0c358ee1befe5809b06
C++
megrad79/Udacity_RoboSE_P5_HomeServiceRobot
/src/pick_objects/src/pick_objects.cpp
UTF-8
1,796
2.515625
3
[]
no_license
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient; int main(int argc, char** argv){ ros::init(argc, argv, "pick_objects"); //tell the action client that we want to spin a thread by default MoveBaseClient ac("move_base", true); //wait for the action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } move_base_msgs::MoveBaseGoal goal; //we'll send a goal to the robot to move to first goal (-2,-1) goal.target_pose.header.frame_id = "map"; goal.target_pose.header.stamp = ros::Time::now(); goal.target_pose.pose.position.x = -1; goal.target_pose.pose.position.y = 2; goal.target_pose.pose.orientation.w = 1.0; ROS_INFO("Sending goal"); ac.sendGoal(goal); ac.waitForResult(); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED){ ROS_INFO("Robot reached its 1st goal! ^-^"); } else { ROS_INFO("Robot FAILED to reach its 1st goal! >:["); } // Wait 5 secs ros::Duration(5).sleep(); // Goal 2 move_base_msgs::MoveBaseGoal goal2; //we'll send a goal to the robot to move to second goal (0,-2) goal2.target_pose.header.frame_id = "map"; goal2.target_pose.header.stamp = ros::Time::now(); goal2.target_pose.pose.position.x = -2; goal2.target_pose.pose.position.y = 0; goal2.target_pose.pose.orientation.w = 1.0; ROS_INFO("Sending goal 2"); ac.sendGoal(goal2); if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED){ ROS_INFO("Robot reached its 2nd goal! ^-^"); } else { ROS_INFO("Robot FAILED to reach its 2nd goal! >:["); } return 0; }
true
583ebc7f04dcde277ef2198b5193580b7a1b909a
C++
slanden/basicAI
/Graph.cpp
UTF-8
3,371
2.578125
3
[]
no_license
#include "Graph.h" #include "Solver.h" #include <iostream> unsigned int Graph::addNode(const vec2 &pos) { if (m_nNodes == m_maxNodes) return -1; m_positions[m_nNodes] = pos; m_nNodes++; return m_nNodes -1; } bool Graph::setEdge(unsigned int nid1, unsigned int nid2, float weight) { if (nid1 >= m_nNodes || nid2 >= m_nNodes || weight < 0) return false; m_adjacencyMatrix[nid1][nid2] = weight; m_adjacencyMatrix[nid2][nid1] = weight; return true; } int Graph::findNode(const vec2 &pos) { for (int i = 0; i < m_nNodes; ++i) { //distanceSqr(pos, m_positions[0]); } return 1; } Graph *Graph::makeGrid(int rows, int cols, float width, float height) { Graph *r = new Graph(rows*cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { int nid = r->addNode(vec2((j + 1) * width / (cols + 1), (i + 1) * height / (rows + 1) )); if (i != 0) r->setEdge( (i - 1) * cols + j, i * cols + j, 10); if (j != 0) r->setEdge (i * cols + j - 1, i * cols + j, 10); if (i != 0 && j != 0)// diags right r->setEdge((i - 1) * cols + j - 1, i * cols + j,14); if (i != 0 && j != cols-1)// diags left r->setEdge((i - 1) * cols + j + 1, i * cols + j, 14); } } //for (int i = 0; i < r->size(); ++i) //{ // r->setEdge(i-1,i); //} return r; } void Graph::removeBlock(std::vector<aabb> a) { for each(aabb o in a) { for (int i = 0; i < m_nNodes; ++i) { for (int j = 0; j < m_nNodes; ++j) { //if (m_positions[i].x > o.min().x && m_positions[i].y > o.min().y && // m_positions[i].x < o.max().x && m_positions[i].y < o.max().y) if (m_positions[i].x > o.min().x && m_positions[i].y > o.min().y && m_positions[i].x < o.max().x && m_positions[i].y < o.max().y) { m_adjacencyMatrix[i][j] = 0; m_adjacencyMatrix[j][i] = 0; } if (m_adjacencyMatrix[i][j] != 0 || m_adjacencyMatrix[j][i] != 0) { if (line_aabb(line(m_positions[i], m_positions[j]), o).result) { m_adjacencyMatrix[i][j] = 0; m_adjacencyMatrix[j][i] = 0; } } } } } } void drawGrid(const mat4 &m, const Graph &g, const Solver &md, int start, int end) { for (int i = 0; i < g.size(); ++i) { vec4 color; switch (md.getMD()[i].state) { case eFrontier: color = { .357f, .68f, .40f, 1 }; break; case eDiscovered: color = { .357f, .40f, .68f, 1 }; break; case eExplored: color = { 106.f / 255, 106.f / 255, 106.f / 255, 1 }; break; case ePath: color = { .5f, .30f, .30f, 1 }; break; } if (start == i) color = { .7f, .1f, .1f, 1 }; if (end == i) color = { .68f, .40f, .357f, 1 }; draw_point(m, point(g.getPositions()[i]), color); for (int j = i + 1; j < g.size(); ++j) if (g.getWeight(i, j) > 0) { draw_line(m, line(g.getPositions()[i], g.getPositions()[j]),vec4(.2,.2,.2, 1)); } } } //int balls(int b) //{ // int t = 3; // switch (b) // { // case 1: t = 12; // case 2: t = 4; // case 5: t = 6; // } // return t; //} /* int array[rows * cols]; int array2d[rows][cols]; for(int x = 0; x < rows; ++x) for(int y = 0; y < cols; ++y) { array[x*cols + y]; array2d[x][y]; left arra y171 [(x-1)*cols + y]; array2d[x-1][y]; right array[(x+1)*cols + y]; array2d[x+1][y]; up array[(x)*cols + y +1]; array2d[x][y+1]; down array[(x)*cols + y -1]; array2d[x][y-1]; } */
true
5736d976e15729ffffca9cf30c861d2e87040b21
C++
MasterHoracio/Uva
/10062/10062.cpp
UTF-8
2,141
3.140625
3
[]
no_license
#include <cstdio> #include <vector> #include <algorithm> #include <cstring> using namespace std; struct par{ int ASCII; int frequency; }; bool cmp(par x, par y){ if(x.frequency < y.frequency) return true; return false; } bool cmpf(par x, par y){ if(x.ASCII > y.ASCII) return true; return false; } int main() { char str[1000], c; vector <par> freq; int tam, pos, k; bool found, line = false; par tmp; while(gets(str)){ tam = strlen(str); for(int i = 0; i < tam; i++){ c = str[i];found = false; for(int j = 0; j < freq.size(); j++){ if(freq.at(j).ASCII == c){ pos = j; found = true; break; } } if(found) freq.at(pos).frequency++; else{ tmp.ASCII = c; tmp.frequency = 1; freq.push_back(tmp); } } if(line) printf("\n"); line = true; stable_sort(freq.begin(),freq.end(),cmp); for(int i = 0; i < freq.size(); i++){ if(i + 1 < freq.size()){ if(freq.at(i).frequency != freq.at(i + 1).frequency) printf("%d %d\n",freq.at(i).ASCII,freq.at(i).frequency); else{ k = i; for(int l = i; l < freq.size() - 1; l++){ if(freq.at(l).frequency == freq.at(l + 1).frequency) k++; else break; } stable_sort(freq.begin() + i,freq.begin() + k + 1, cmpf); for(int j = i; j <= k; j++) printf("%d %d\n",freq.at(j).ASCII,freq.at(j).frequency); i = k; } }else printf("%d %d\n",freq.at(i).ASCII,freq.at(i).frequency); } freq.clear(); } return 0; }
true
f35860eae633472461a2872f0529a4f42d1e214b
C++
dh434/leetcode
/tree/572. 另一个树的子树.cpp
UTF-8
1,341
3.734375
4
[]
no_license
/* 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 示例 1: 给定的树 s: 3 / \ 4 5 / \ 1 2 给定的树 t: 4 / \ 1 2 返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。 示例 2: 给定的树 s: 3 / \ 4 5 / \ 1 2 / 0 给定的树 t: 4 / \ 1 2 返回 false。 */ /** * 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: bool isSubtree(TreeNode* s, TreeNode* t) { if(s==NULL || t == NULL) return false; return checkSubtree(s,t) || isSubtree(s->left,t) || isSubtree(s->right,t); } bool checkSubtree(TreeNode* s, TreeNode* t){ if(s == NULL && t == NULL) return true; if(s == NULL || t == NULL || s->val != t->val) return false; return checkSubtree(s->left, t->left) && checkSubtree(s->right, t->right); } };
true
8e4c51c185387cb0bbb5bef8e43d3768e62e4572
C++
NixSane/OpenGL-Renderer
/Graphics Engine/Mesh.cpp
UTF-8
2,871
2.921875
3
[]
no_license
#include "Mesh.h" Mesh::Mesh(Vertex a_vertices[], int a_index[]) { /** Generate IDs to access the objects **/ glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glGenBuffers(1, &ibo); /** Bind the Objects and buffers that are going to be drawn **/ /** And allocate the geometry and construction data in the current object being drawn **/ glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(Vertex), &a_vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(a_index), a_index, GL_STATIC_DRAW); // Position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); // Normal glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)8); // UV glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)16); // Reset once everything is allocated glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } Mesh::~Mesh() { glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); } void Mesh::initialiseQuad() { // Check if the mesh has been initialised assert(vao == 0); // Generate Buffers glGenBuffers(1, &vbo); glGenVertexArrays(1, &vao); // Bind vertex array or the mesh wrapper glBindVertexArray(vao); // bind vartex buffer glBindBuffer(GL_ARRAY_BUFFER, vbo); // Mesh Data glm::vec3 vertices[] = { glm::vec3(-0.5f, 0.5f, 0.0f), glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(-0.5f, 0.5f, 1.0f), glm::vec3(-0.5f, -0.5f, 1.0f), glm::vec3(0.5f, -0.5f, 1.0f), glm::vec3(0.5f, 0.5f, 1.0f) }; // Refers to the points of each triangle int index_buffer[]{ 3,1,0, // First triangle 3,2,1 // Second triangle /* And so on~~~ */ }; glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_buffer), index_buffer, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0); // Reset once everything is allocated glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } //void Mesh::draw() //{ // glBindVertexArray(vao); // // using indices or just vertices? // if (ibo != 0) // glDrawElements(GL_TRIANGLES, 3 * tri_count, GL_UNSIGNED_INT, 0); // else // glDrawArrays(GL_TRIANGLES, 0, 3 * tri_count); //} GLint Mesh::getVAO() const { return vao; } GLint Mesh::getVBO() const { return vbo; } GLint Mesh::getIBO() const { return ibo; }
true
6e744f77ee6dbdcf96f5e31756fff2aae2b3cd54
C++
wexpect/udacity_self_driving_car_nanodegree
/5_planning/1_behavior_plannng/16_implement_a_second_cost_functin_in_c++/cost.cpp
UTF-8
1,134
3.140625
3
[]
no_license
#include "cost.h" #include <stdlib.h> #include <cmath> #include <iostream> double inefficiency_cost(int target_speed, int intended_lane, int final_lane, const std::vector<int> &lane_speeds) { // Cost becomes higher for trajectories with intended lane and final lane // that have traffic slower than target_speed. /** * TODO: Replace cost = 0 with an appropriate cost function. */ // double cost = 0; double intended_speed = lane_speeds[intended_lane]; std::cout << "intended_lane = " << intended_lane << ", intended_speed = " << intended_speed << std::endl; double final_speed = lane_speeds[final_lane]; std::cout << "final_lane = " << final_lane<< ", final_speed = " << final_speed << std::endl; // both options work // Option 1 // double abs_speed_diff = abs(intended_speed - target_speed) + abs(final_speed - target_speed); // double cost = 1 - exp(-1 * abs_speed_diff); // Option 2 double cost = ( abs(intended_speed - target_speed) / double(target_speed) + abs(final_speed - target_speed) / double(target_speed) ) / 2; return cost; }
true
bac6b5ebb81fa7ab0183d99911f2b32df627c4c7
C++
SimoHayha/GLStuff
/Renderer/Graphics.h
UTF-8
2,805
2.59375
3
[]
no_license
#pragma once #include <future> #include <string> #include <map> #include <list> #include <condition_variable> #include <mutex> #include <glm\glm.hpp> #include <GL/glew.h> // Mesh are loaded in a parallel thread, but we can only generate buffers in the main thread. // The loaded thread will wait for the Condition variable to be released. The main thread will release it. // The GenBuffers struct is a link between both threads. // The BufferIds vector will contains all the ids. struct GenBuffers { GenBuffers() { Mutex = new std::mutex; } ~GenBuffers() { delete Mutex; } size_t ThreadId; std::mutex* Mutex; std::condition_variable Condition; GLuint Count; std::vector<GLuint> BuffersIds; }; struct MaterialConstants { MaterialConstants(); glm::vec4 Ambient; glm::vec4 Diffuse; glm::vec4 Specular; glm::vec4 Emissive; float SpecularPower; float Padding0; float Padding1; float Padding2; }; struct LightConstants { LightConstants(); glm::vec4 Ambient; glm::vec4 LightColor[4]; glm::vec4 LightAttenuation[4]; glm::vec4 LightDirection[4]; glm::vec4 LightSpecularIntensity[4]; GLuint IsPointLight[4]; GLuint ActiveLight; float Padding0; float Padding1; float Padding2; }; struct ObjectConstants { ObjectConstants(); glm::mat4x4 LocalToWorld4x4; glm::mat4x4 LocalToProjected4x4; glm::mat4x4 WorldToLocal4x4; glm::mat4x4 WorldToView4x4; glm::mat4x4 UvTransform4x4; glm::vec3 EyePosition; float Padding0; }; struct MiscConstants { MiscConstants(); float ViewportWidth; float ViewportHeight; float Time; float Padding1; }; struct GLFWwindow; class Mesh; class Graphics { public: Graphics(); ~Graphics(); Graphics(Graphics const&) = delete; Graphics(Graphics&&) = delete; Graphics& operator=(Graphics const&) = delete; Graphics& operator=(Graphics&&) = delete; void SetWindow(GLFWwindow* window); GLFWwindow* GetWindow() const; GLuint GetMaterialConstants() const; GLuint GetLightConstants() const; GLuint GetObjectConstants() const; GLuint GetMiscConstants() const; std::future<GLuint> GetOrCreateShaderAsync(std::string const& shaderName); void Update(); void UpdateGenBuffers(); void AddGenBuffers(GenBuffers* task); void AddMeshToCollect(Mesh* mesh); void UpdateMaterialConstants(MaterialConstants& data) const; void UpdateLightConstants(LightConstants& data) const; void UpdateObjectConstants(ObjectConstants& data) const; void UpdateMiscConstants(MiscConstants& data) const; private: std::map<std::string, GLuint> m_shaderResources; std::map<std::string, GLuint> m_textureResources; GLuint m_materialConstants; GLuint m_lightConstants; GLuint m_objectConstants; GLuint m_miscConstants; std::list<GenBuffers*> m_genBuffers; std::mutex m_genBuffersLock; GLFWwindow* m_window; };
true
73adf98cb585d8b6f5f683c4a0a03aba05a5b50e
C++
leonardoaraujosantos/NLPPytorch
/src/cpp14/vanilla_matcher/conceptmatcher.cpp
UTF-8
1,477
3.359375
3
[]
no_license
#include "conceptmatcher.h" ConceptMatcher::ConceptMatcher() { } void ConceptMatcher::AddConcept(std::string concept) { std::transform(concept.begin(), concept.end(), concept.begin(), ::tolower); m_set_concepts.insert(concept); } list<string> ConceptMatcher::GetTokens(std::string input) { // Regular expression to filter text regex re("[^0-9a-zA-Z]+"); list<string> retList; // Transform input to lowercase std::transform(input.begin(), input.end(), input.begin(), ::tolower); // Tokenize text, filtering and adding results to list std::copy( std::sregex_token_iterator(input.begin(), input.end(), re, -1), std::sregex_token_iterator(), std::back_inserter(retList)); return retList; } // Look for matches between the list of tokens from the input and the concepts list<string> ConceptMatcher::GetMatches(string input) { list<string> retList; list<string> inTokens = GetTokens(input); // Iterate on input tokens looking for a concept for (const auto &token : inTokens) { // Searching on a hash table is O(1) on average auto search = m_set_concepts.find(token); if(search != m_set_concepts.end()) { // Concept found add on retList retList.push_back(token); //std::cout << "Found " << (*search) << '\n'; } } return retList; }
true
4f79c153e0fca1c93054e6971b3eb73f3b3db549
C++
hung4564/Cautrucdulieu
/C++/CTDL/CTDL/Source.cpp
UTF-8
2,437
3.40625
3
[]
no_license
#include<iostream> #include "Array.h" #include"Queue.h" #include"Stack.h" #include "LinkedList.h" #include "D_LinkedList.h" #include "C_LinkedList.h" #include "Node.h" #include"BinaryTree.h" using namespace std; void main_BST() { BinaryTree tree; tree.Add(50); tree.Add(30); tree.Add(20); tree.Add(40); tree.Add(35); tree.Add(32); tree.Show(); cout << endl; tree.Delete(30); tree.Delete(40); cout << endl; tree.Show(); } void main_linkedlist() { LinkedList list; for (int i = 0; i<3; i++) { list.Add(i); } list.Show(); cout << "\n"; list.AddFirst(-10); list.AddAfter(-10, 2); list.AddBefore(2, 3); list.DeleteNode(1); list.Show(); } void main_D_linkedlist() { D_LinkedList list; for (size_t i = 0; i < 4; i++) { list.AddLast(i); } list.Show(); cout << "\n"; list.AddFirst(4); list.AddLast(-1); list.Show(); cout << "\n"; list.DeleteFirst(); list.DeleteLast(); list.Show(); cout << "\n"; list.AddAffter(2, 12); list.Show(); cout << "\n"; list.AddBefore(2, 11); list.Show(); cout << "\n"; } void main_C_linkedlist() { C_LinkedList list; for (int i = 0; i <10; i++) { list.Add(i); } for (int i = 0; i < 5; i++) { list.Delete(i); } list.Show(); cout << "\n"; } void main_stack() { Stack stack; for (size_t i = 0; i < 10; i++) { stack.Push(i); } while (!stack.IsEmpty()) { cout << stack.Pop() << "; "; } } void main_queue() { Queue queue; for (int i = 0; i < 10; i++) { queue.Enqueue(i); } while (!queue.IsEmpty()) { cout << queue.Dequeue() << ";"; } } void array_main() { Array arrary; arrary.Push(5); arrary.Push(3); arrary.Push(2); arrary.Push(1); for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } arrary.Insert(2, -1); cout << endl; for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } arrary.Prepend(-2); cout << endl; for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } cout << endl; cout << arrary.Find(-2); arrary.Delete(5); cout << endl; for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } for (size_t i = 0; i < 3; i++) { arrary.Push(7); } cout << endl; for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } arrary.Remove(7); cout << endl; for (int i = 0; i < arrary.Count(); i++) { cout << arrary.At(i) << ";"; } } int main() { array_main(); cout << endl; system("pause"); return 0; }
true
54cc922dd85646993be26f7347dc68ab1280c8c7
C++
Stefan9283/Umbra2D
/Dependencies/Source/FrameBuffer.cpp
UTF-8
2,585
2.734375
3
[]
no_license
#include "FrameBuffer.h" #include "Window.h" #include "Texture.h" #include "Engine.h" extern Umbra2D::Engine* umbra; namespace Umbra2D { FrameBuffer::FrameBuffer(int type, glm::ivec2 resolution) { // framebuffer configuration // ------------------------- glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); // or bind(); // create a color attachment texture unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, type, resolution.x, resolution.y, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID, 0); // create a renderbuffer object for depth and stencil attachment (we won't be sampling these) glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, resolution.x, resolution.y); // use a single renderbuffer object for both a depth AND stencil buffer. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); // now actually attach it // now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); // or unbind(); texture = new TEXTURE(textureID, resolution, "framebuffer"); } FrameBuffer::~FrameBuffer() { /* TODO */ delete texture; glDeleteRenderbuffers(1, &rbo); glDeleteFramebuffers(1, &fbo); } void FrameBuffer::bind() { glBindFramebuffer(GL_FRAMEBUFFER, fbo); glm::ivec2 resolution = texture->getResolution(); glViewport(0, 0, resolution.x, resolution.y); } void FrameBuffer::unbind() { glBindFramebuffer(GL_FRAMEBUFFER, 0); glm::ivec2 resolution = WINDOW->getSize(); glViewport(0, 0, resolution.x, resolution.y); } TEXTURE* FrameBuffer::getTexture() { return texture; } }
true
a51f4766f8a260ce96ec3690c9945dd48697f4b6
C++
DV1537/assignment-a1-oson21
/main1A.cpp
UTF-8
841
2.8125
3
[]
no_license
#include "func1A.h" int main(int argc, const char *argv[]){ const char *fileName = argv[1]; int n = 0, a = 0; double average = 0.0, sum = 0.0; CountInput(fileName,n); double *array = new double[n]; std::ifstream myReadFile; myReadFile.open(fileName); if(myReadFile){ int counter = 0; while(myReadFile >> a){ sum += a; array[counter] = a; counter++; } myReadFile.close(); average = sum/n; PrintNumbers(average, array, n); delete [] array; array = 0; return 0; } else{ myReadFile.close(); std::cout << "Error with opening file has occured"; delete[] array; array = 0; exit(EXIT_FAILURE); } }
true
3c281c7879c97ec29d4e352e9ecf357786489739
C++
davishyer/Introduction_to_Programming
/Zipped Projects/Lab 10 RPG/Lab 10 RPG/Archer.cpp
UTF-8
412
2.828125
3
[]
no_license
#include "Archer.h" Archer::Archer(string name, int maxhp, int st, int sp, int mag) : Fighter(name, maxhp, st, sp, mag)//add rest { ASpeed = sp; } int Archer::getDamage() { int damage = Speed; return damage; } void Archer::reset() { Fighter::reset(); Speed = ASpeed; } bool Archer::useAbility() { Speed++; bool used = true; return used; } Archer::~Archer(void) { }
true
32e9bbcc0233e07bb1660bce07657898ddda2666
C++
byu-mechatronics/motor_control
/stepper_motor_control/stepper_motor_control.ino
UTF-8
5,344
2.796875
3
[]
no_license
#define toggle A0 #define dcMotor 3 #define dirPin A5 #define stepPin A4 #define stepNumber 50 #define stepSpeed .25 #define delay1 250 #define led 13 int motorSpeed; //Represents dc speed value bewteen 0 and 255 int toggleStatus; int getOut = 0; //Used to control Stepper using EiBotBoard (EBB) const int stepperTime = 5000; //Time in milliseconds that the stepper motor will move for unsigned long nextTime; //Used for this particular stepper motor controller as a the duration of the move void setup() { Serial.begin(9600); pinMode(toggle, INPUT_PULLUP); //Set the pin as input, which is a high impedence state with a pull-up resistor. This means current is limited and signal is default pulled HIGH pinMode(dcMotor, OUTPUT); //Set the motor control pin as an output } void loop() { //Serial.println("The Loop has Started"); //testing toggleStatus = digitalRead(toggle); //Determine to control the DC motor or the Stepper motor //Serial.println(toggleStatus); //testing switch(toggleStatus) { //------------------------------------------------------------------------------------------------------------------- case 0: //DC Motor, switch is grounding the toggle pin Serial.println("Case 0"); //testing Serial.println("DC Motor Speed Up"); //testing digitalWrite(led, !digitalRead(led)); //Toggle led for( motorSpeed = 0; motorSpeed <= 255; motorSpeed++) //Speed up for around 25.5 seconds { analogWrite(dcMotor, motorSpeed); delay(25); toggleStatus = digitalRead(toggle); if(toggleStatus != 0) break; } if(toggleStatus != 1) //If the toggle hasn't been switched, then continue to slowly occilate { Serial.println("DC Motor Slow Down"); //testing digitalWrite(led, !digitalRead(led)); //Toggle led for( motorSpeed = 255; motorSpeed >= 0; motorSpeed--) //Slow down for around 25.5 seconds { analogWrite(dcMotor, motorSpeed); delay(25); toggleStatus = digitalRead(toggle); if(toggleStatus != 0) break; } } else //If the toggle has been switched, turn off the dc motor analogWrite(dcMotor,0); break; //Break out of case 0, DC motor demo //-------------------------------------------------------------------------------------------------------------------------------- case 1: //Stepper Motor, controlled via EggBotBoard rev2, toggle pin is free (not pulled to ground) Serial.println("Case 1"); //testing rotate(stepNumber*8,stepSpeed); delay(delay1); toggleStatus = digitalRead(toggle); //Determine to control the DC motor or the Stepper motor if(toggleStatus == 1) { rotate(-stepNumber*8,stepSpeed); delay(delay1); } /* //Control stepper motor with EBB stepper driver Serial.write("EM,1,1"); //Turn on stepper motor Serial.write("SM,stepperTime, 200, 200"); //Command movement lasting "stepperTime" and equal to 200 steps nextTime = millis() + stepperTime; //Determine the time at which the motor fully moved while((millis() <= nextTime) && (toggleStatus == 1)) //While the current time is not yet the ending time && the toggle is still switched to stepper { toggleStatus = digitalRead(toggle); //Check switch status for change to DC motor demo if(toggleStatus == 0) //If DC motor selected... { Serial.write("EM,0,0"); //Turn of stepper motor } } Serial.write("SM,stepperTime, -200, -200"); //Command movement lasting "stepperTime" and equal to 200 steps nextTime = millis() + stepperTime; //Determine the time at which the motor fully moved while((millis() <= nextTime && getOut != 1) && (toggleStatus == 1)) //While the current time is not yet the ending time && the toggle is still switched to stepper { toggleStatus = digitalRead(toggle); if(toggleStatus == 0) { Serial.write("EM,0,0"); //Turn on stepper motor } } Serial.write("EM,0,0"); //Turn on stepper motor */ break; //Break out of case 1, stepper motor demo }//End of switch statement }//End of Void Loop void rotate(int steps, float speed) //Control stepper motor with EasyDriver board from Sparkfun { //rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement) //speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger int dir = (steps > 0)? HIGH:LOW; steps = abs(steps); digitalWrite(dirPin,dir); digitalWrite(led, !digitalRead(led)); //Toggle led float usDelay = (1/speed) * 70; for(int i=0; i < steps; i++) { digitalWrite(stepPin, HIGH); delayMicroseconds(usDelay); digitalWrite(stepPin, LOW); delayMicroseconds(usDelay); } }
true
f3f016995b8a3153ba2c5b6b117821d8ef2a65ec
C++
wld0595/Batch
/MyBatch/MyBatch/Texture.cpp
UTF-8
3,124
2.609375
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "Texture.h" /* Create an array of 10 Texture* */ std::vector<Texture*> Texture::vTextures(10); Texture::Texture() :uiTextureHandle(0) ,iTexWidth(0) ,iTexHeight(0) {} Texture::~Texture() {} GLvoid Texture::loadTexture(const GLchar *pTextureFilePath) { /* Load the texture file with stbi_load_from_file */ GLint iChannel = 0; FILE *pFile = fopen(pTextureFilePath, "rb"); const unsigned char *pImageData = stbi_load_from_file(pFile, &iTexWidth, &iTexHeight, &iChannel, 0); //assert(pImageData); /* check the texture picture */ if (pImageData==NULL) { fprintf(stderr,"The %s texture picture is null.Please check.\n", pTextureFilePath); getchar(); glfwTerminate(); return ; } /* Generate the texture id */ glGenTextures(1, &uiTextureHandle); glBindTexture(GL_TEXTURE_2D, uiTextureHandle); /* Ensure available the any size texture */ glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /* check the texture id */ assert(glIsTexture(uiTextureHandle)); /*if (glIsTexture(m_iTexture)==GL_FALSE) { fprintf(stderr,"Is not currently the name of texture.Or some error occurs.Please check.\n"); getchar(); glfwTerminate(); return ; }*/ /* Generate the texture */ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, iTexWidth, iTexHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, pImageData); /* Release the texture picture buffer */ free((void *) pImageData); pImageData = NULL; /* Set the texture parameters */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } GLvoid Texture::addManageTexture() { vTextures.push_back(this); } GLuint Texture::getTextureID() { return uiTextureHandle; } GLuint* Texture::getAddTextureID() { return &uiTextureHandle; } GLint Texture::getTexHeight() { return iTexHeight; } GLvoid Texture::setTexHeight(GLint iHeight) { iTexHeight = iHeight; } GLint Texture::getTexWidth() { return iTexWidth; } GLvoid Texture::setTexWidth(GLint iWidth) { iTexWidth = iWidth; } GLvoid Texture::bind() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, uiTextureHandle); } GLvoid Texture::bind(GLint iUnit) { glActiveTexture(GL_TEXTURE0 + iUnit); glBindTexture(GL_TEXTURE_2D, uiTextureHandle); } GLboolean Texture::notEqual(const Texture &aTexture) { if ( (aTexture.uiTextureHandle != this->getTextureID()) && (aTexture.iTexWidth != this->getTexWidth()) && (aTexture.iTexHeight != this->getTexHeight())) { return GL_TRUE; } else { return GL_FALSE; } } GLvoid Texture::deleteTexture() { if (uiTextureHandle != 0) { glDeleteTextures(1, &uiTextureHandle); uiTextureHandle = 0; } }
true
4ffbd8ba9997a0d25cdbba130333511fe2bbd4d1
C++
kai-v/RoundRobinSimulation
/rr_scheduler.cpp
UTF-8
8,654
3.125
3
[]
no_license
#include <iostream> #include "process.h" #include "rr_scheduler.h" #include <queue> RR_Scheduler::RR_Scheduler(std::queue<process> process_list, int quantum, int block_duration) { this->process_list = process_list; this->quantum = quantum; this->block_duration = block_duration; } RR_Scheduler::~RR_Scheduler() { // destructor does nothing } // create the round-robin algorithm in a private function // for encapsulation and security reason void RR_Scheduler::RR() { std::cout << "*************************************************\n"; int num_finished = 0; int simulation_time = 0; // queues to keep track of ready_queue, wait_queue, terminated processes std::queue<process> ready_queue; std::queue<process> wait_queue; std::queue<process> finished_queue; bool curr_process_is_valid = true; int num_processes = this->process_list.size(); bool cpu_is_idle = false; // status codes for why a process gets switched out char status_codes[] = {'I', 'Q', 'B', 'T'}; char status_code = ' '; int start_time = -1; int finished_time = -1; int terminated_time = -1; // keep track of previous process's name, so when a new process start // we know to print out the result line for why the previous process // get switched out, its start time and how long it run. std::string prev_process = ""; while (num_finished < num_processes) { // check arrival time of latest process in the list if (!process_list.empty() && simulation_time >= process_list.front().get_arrival_time()) { // remove process and add process to ready_queue list ready_queue.push(process_list.front()); process_list.pop(); } if (!ready_queue.empty()) { // if the cpu was previously idle, then we print the result in this iteration. if (status_code == 'I') { finished_time = simulation_time; std::cout << start_time << " " << prev_process << " " << finished_time - start_time << " " << status_code << std::endl; // reset status code status_code = ' '; } cpu_is_idle = false; // current active process running process &curr_process = ready_queue.front(); curr_process_is_valid = true; // if this process is different from the previous process // update the prev_process and set the start time of the // current NEW process to curr_time if (curr_process.get_name().compare(prev_process) != 0) { prev_process = std::string(curr_process.get_name()); start_time = simulation_time; } // check if process has used up its quantum if (curr_process.get_quantum_left() == 0) { // process has used its quantum // just move to end of ready_queue since it might resume soon ready_queue.pop(); // reset the quantum for next run // keep the same cpu_burst_left curr_process.set_quantum_left(quantum); ready_queue.push(curr_process); finished_time = simulation_time; status_code = status_codes[1]; // if there is process is the only process in the queue and gets preempted, // it is going to resume again in the same clock-cycle anyway. // don't print "Q" output since it actually doesn't really get preempted. if (ready_queue.size() > 1) { std::cout << start_time << " " << prev_process << " " << finished_time - start_time << " " << status_code << std::endl; } // current process technically finished BEFORE this iteration, thus, we should // decrement the current time, so when a process starts in the next iteration, // it is going to begin at the same clock-cycle. simulation_time--; curr_process_is_valid = false; } else if (curr_process.get_cpu_burst_left() == 0) { // if process hasn't used up its quantum, yet it is about to block for i/o // remove from ready_queue and add to wait_queue ready_queue.pop(); // set the point in time where this process blocks curr_process.set_time_since_blocked(simulation_time); // reset quantum_left for this process curr_process.set_quantum_left(quantum); // reset cpu_burst for next run curr_process.set_cpu_burst_left(curr_process.get_cpu_burst()); wait_queue.push(curr_process); // current process is not valid because it's blocked currently curr_process_is_valid = false; // print output finished_time = simulation_time; status_code = status_codes[2]; std::cout << start_time << " " << prev_process << " " << finished_time - start_time << " " << status_code << std::endl; // current process is blocked so technically another process should start in this clock-cycle // decrement simulation_time so next iteration starts at the same clock-cycle simulation_time--; } // if current process is still active if (curr_process_is_valid) { // decrements curr_process.set_cpu_burst_left(curr_process.get_cpu_burst_left() - 1); curr_process.set_quantum_left(curr_process.get_quantum_left() - 1); curr_process.set_total_time_left(curr_process.get_total_time_left() - 1); if (curr_process.get_total_time_left() == 0) { // current process has now finished num_finished++; // since we check one iteration too early, so we set finished time to the next clock-cycle. finished_time = simulation_time + 1; curr_process.set_finished_time(finished_time); // removed from ready_queue list and add to finished_queue. ready_queue.pop(); finished_queue.push(curr_process); // current process is not active curr_process_is_valid = false; // print output with status "T" status_code = status_codes[3]; std::cout << start_time << " " << prev_process << " " << finished_time - start_time << " " << status_code << std::endl; simulation_time--; } } } else { // if there are no active processes to be run, // CPU IS IDLE cpu_is_idle = true; prev_process = std::string("[IDLE]"); // start time of current [IDLE] state is the last active process's finished time start_time = finished_time; status_code = status_codes[0]; } // check if any wait_queue process can be moved back to ready_queue list if (!wait_queue.empty() && (simulation_time - wait_queue.front().get_time_since_blocked() >= block_duration)) { // if a process has finished blocking, move it back to the ready_queue list process active_again = wait_queue.front(); wait_queue.pop(); active_again.set_time_since_blocked(-1); ready_queue.push(active_again); if (cpu_is_idle && !ready_queue.empty()) { simulation_time--; } } simulation_time++; } std::cout << finished_time << " [END]\n"; std::cout << "*****************************************************************************************\n"; int turnaround_sum = 0; while (!finished_queue.empty()) { process p = finished_queue.front(); finished_queue.pop(); std::cout << "Process " << p.get_name() << " " << p.get_finished_time() - p.get_arrival_time() << ".\n"; turnaround_sum += (p.get_finished_time() - p.get_arrival_time()); } // print average turnover time std::cout << (float)turnaround_sum / num_finished << std::endl; } // outsider can only access the public run() void RR_Scheduler::run() { RR(); }
true
f84dadaf21e10fc16ac956d30077b4efaa829e58
C++
shoeisha-books/dokushu-cpp
/ch03/list_3.23/main.cpp
UTF-8
1,033
3.921875
4
[ "MIT" ]
permissive
#include <iostream> class S { static int count; // インスタンスの数を数えるstaticメンバー変数 public: S(); ~S(); void show_count() const; }; int S::count = 0; // staticメンバー変数の実体を定義して0で初期化する S::S() { // インスタンスが作られたらインクリメントする ++count; } S::~S() { // 破棄されたらデクリメントする --count; } void S::show_count() const { std::cout << "S::count: " << count << std::endl; } void function() { S a; a.show_count(); // インスタンスはmain()のaとこの関数内のaの2つがある // この関数内のaは関数が終了すると同時に破棄される(詳細は4.3節) } int main() { S a; a.show_count(); // aのコンストラクターでインクリメントされるので1が出力される function(); a.show_count(); // function()関数内のaは破棄されているので1となる }
true
f65dd61fda32272e2aeaaa6afbb7c1aa6fdd710b
C++
matyx44/GLNSModified
/geom.hpp
UTF-8
3,385
2.625
3
[]
no_license
/** * File: geom.hpp * * Date: 4.12.18 * Author: Jan Mikula * E-mail: mikula.miki@gmail.com * */ #ifndef POLY_MAPS_GEOM_HPP #define POLY_MAPS_GEOM_HPP #include <cmath> #include <vector> namespace pmap { namespace geom { typedef double geom_float; struct FPoint { geom_float x; geom_float y; FPoint(); FPoint(geom_float x, geom_float y); FPoint operator+(const FPoint &p) const; FPoint operator-(const FPoint &p) const; FPoint operator*(geom_float f) const; FPoint operator/(geom_float f) const; bool operator==(const FPoint &p) const; bool operator!=(const FPoint &p) const; geom_float vectNorm() const; geom_float distanceTo(FPoint p) const; }; typedef std::vector<FPoint> FPoints; typedef FPoints FPolygon; typedef std::vector<FPolygon> FPolygons; typedef FPolygons FMap; struct OFPoint { geom_float x; geom_float y; geom_float phi; OFPoint(); OFPoint(geom_float x, geom_float y, geom_float phi = 0.0); explicit OFPoint(FPoint p, geom_float phi = 0.0); OFPoint operator+(const OFPoint &p) const; OFPoint operator-(const OFPoint &p) const; bool operator==(const OFPoint &p) const; bool operator!=(const OFPoint &p) const; FPoint point() const; geom_float distanceTo(FPoint p) const; geom_float distanceTo(OFPoint p) const; }; typedef std::vector<OFPoint> OFPoints; typedef OFPoint FPosition; typedef OFPoints FPositions; struct WFPoint { geom_float x; geom_float y; geom_float w; WFPoint(); WFPoint(geom_float x, geom_float y, geom_float w = 0.0); explicit WFPoint(FPoint p, geom_float w = 0.0); bool operator==(const WFPoint &p) const; bool operator!=(const WFPoint &p) const; FPoint point() const; geom_float distanceTo(FPoint p) const; geom_float distanceTo(WFPoint p) const; }; typedef std::vector<WFPoint> WFPoints; struct WOFPoint { geom_float x; geom_float y; geom_float phi; geom_float w; WOFPoint(); WOFPoint(geom_float x, geom_float y, geom_float phi = 0.0, geom_float w = 0.0); explicit WOFPoint(FPoint p, geom_float phi = 0.0, geom_float w = 0.0); explicit WOFPoint(OFPoint p, geom_float w = 0.0); explicit WOFPoint(WFPoint p, geom_float phi = 0.0); bool operator==(const WOFPoint &p) const; bool operator!=(const WOFPoint &p) const; FPoint point() const; OFPoint opoint() const; WFPoint wpoint() const; geom_float distanceTo(FPoint p) const; geom_float distanceTo(OFPoint p) const; geom_float distanceTo(WFPoint p) const; geom_float distanceTo(WOFPoint p) const; }; typedef std::vector<WOFPoint> WOFPoints; typedef WOFPoint FParticle; typedef WOFPoints FParticles; } } #endif //POLY_MAPS_GEOM_HPP
true
4aed508a9f92433921a5513d789698d494e59696
C++
abbymartin1/CreatureOfTheForestGame
/CreatureOfForestGame/Source/Game/GameBoard.h
UTF-8
1,081
2.640625
3
[ "Apache-2.0" ]
permissive
#pragma once #include "GameEngine/EntitySystem/Entity.h" #include <SFML/System/Vector2.hpp> #include <vector> namespace Game { //Used for storing and controlling all game related entities, as well as providing an entry point for the "game" side of application class PlayerEntity; class GameBoard { public: GameBoard(); virtual ~GameBoard(); void Update(); bool IsGameOver() { return false; } bool m_isGameOver; void SpawnRandomLeafBlock(); void SpawnRandomHeartBlock(); private: void CreatePlayer(); void CreateKillerPlant(); void CreateBackground(); void CreatePlatforms(); void CreateRandomSeedBlocks(const sf::Vector2f& pos); void CreateRandomLeafBlocks(const sf::Vector2f& pos); void CreateRandomHearts(const sf::Vector2f& pos); void SpawnRandomSeedBlock(); void GameOver(); GameEngine::Entity* m_player; GameEngine::Entity* m_killerPlant; protected: float RandomFloatRange(float a, float b) { return ((b - a) * ((float)rand() / RAND_MAX)) + a; } float m_resourceTimer; float m_lastObstacleSpawnTimer; }; }
true
f5da7a27cb56de0df2bb9ae7d1c1be1de50225e7
C++
Rogi1246/programmiersprachen-aufgabenblatt-2
/source/tests.cpp
UTF-8
6,463
2.875
3
[ "MIT" ]
permissive
#define CATCH_CONFIG_RUNNER #define _USE_MATH_DEFINES #define NOGDI #include <catch.hpp> #include "vec2.hpp" #include "mat2.hpp" #include "color.hpp" #include "rectangle.hpp" #include "circle.hpp" int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); std::cin.get(); return 0; } TEST_CASE("Test cases for Vec2") { Vec2 a = Vec2{}; Vec2 b = Vec2{ 5.0f,2.0f }; Vec2 c = Vec2{ 2.0f,1.0f }; SECTION("Empty constructor test") { REQUIRE(a.x == 0.0f); REQUIRE(a.y == 0.0f); } SECTION("Constructor test") { REQUIRE(b.x == 5.0f); REQUIRE(b.y == 2.0f); } SECTION("Operator += test") { a += b; b += c; REQUIRE(b.x == 7.0f); REQUIRE(b.y == 3.0f); REQUIRE(a.x == 5.0f); REQUIRE(a.y == 2.0f); } SECTION("Operator -= test") { a -= b; b -= c; REQUIRE(b.x == 3.0f); REQUIRE(b.y == 1.0f); REQUIRE(a.x == -5.0f); REQUIRE(a.y == -2.0f); } SECTION("Operator *= test") { b *= 3.0f; c *= 3.0f; REQUIRE(b.x == 15.0f); REQUIRE(b.y == 6.0f); REQUIRE(c.x == 6.0f); REQUIRE(c.y == 3.0f); } SECTION("Operator /= test") { b /= 2; c /= 2; REQUIRE(b.x == 2.5f); REQUIRE(b.y == 1.0f); REQUIRE(c.x == 1.0f); REQUIRE(c.y == 0.5f); } SECTION("Operator + test") { Vec2 d = b + a; REQUIRE(d.x == 5.0f); REQUIRE(d.y == 2.0f); d = b + c; REQUIRE(d.x == 7.0f); REQUIRE(d.y == 3.0f); } SECTION("Operator - test") { Vec2 d = b - a; REQUIRE(d.x == 5.0f); REQUIRE(d.y == 2.0f); d = b - c; REQUIRE(d.x == 3.0f); REQUIRE(d.y == 1.0f); } SECTION("Operator * test") { Vec2 d = b * 5.0f; REQUIRE(d.x == 25.0f); REQUIRE(d.y == 10.0f); d = c * 3; REQUIRE(d.x == 6.0f); REQUIRE(d.y == 3.0f); } SECTION("Operator / test") { Vec2 d = b / 2.0f; REQUIRE(d.x == 2.5f); REQUIRE(d.y == 1.0f); d = c / 2.0f; REQUIRE(d.x == 1.0f); REQUIRE(d.y == 0.5f); } SECTION("is_inside test") { Vec2 point{ 100.0f,100.0f }; Rectangle rect{ {0.0f,0.0f},{200.0f,200.0f },{0.0f,0.0f,0.0f} }; REQUIRE(rect.is_inside(point)); point = { 300.0f,-15.4f }; REQUIRE(!rect.is_inside(point)); } } TEST_CASE("Test cases for Mat2") { Mat2 a = {{2.0f,1.0f},{1.0f,3.0f}}; Mat2 b = { {1.0f,4.0f},{2.0f,1.0f} }; Mat2 c = {}; Vec2 r = { 5.0f,7.0f }; SECTION("Operator *= test") { a *= b; REQUIRE(a.firstRow_.x == 6.0f); REQUIRE(a.firstRow_.y == 13.0f); REQUIRE(a.secondRow_.x == 5.0f); REQUIRE(a.secondRow_.y == 5.0f); b *= c; REQUIRE(b.firstRow_.x == 1.0f); REQUIRE(b.firstRow_.y == 4.0f); REQUIRE(b.secondRow_.x == 2.0f); REQUIRE(b.secondRow_.y == 1.0f); } SECTION("Operator * test") { Mat2 d = a*b; REQUIRE(d.firstRow_.x == 6.0f); REQUIRE(d.firstRow_.y == 13.0f); REQUIRE(d.secondRow_.x == 5.0f); REQUIRE(d.secondRow_.y == 5.0f); Mat2 e = a * c; REQUIRE(e.firstRow_.x == 2.0f); REQUIRE(e.firstRow_.y == 1.0f); REQUIRE(e.secondRow_.x == 1.0f); REQUIRE(e.secondRow_.y == 3.0f); } SECTION("Operator * with Vec2 test") { Vec2 q = a * r; REQUIRE(q.x == 17.0f); REQUIRE(q.y == 26.0f); q = r * a; REQUIRE(q.x == 17.0f); REQUIRE(q.y == 26.0f); } SECTION("Determinant method test") { REQUIRE(a.det() == 5.0f); REQUIRE(b.det() == -7.0f); } SECTION("Inverse test") { Mat2 t = inverse(a); REQUIRE(t.firstRow_.x == Approx(0.6f)); REQUIRE(t.firstRow_.y == Approx(-0.2f)); REQUIRE(t.secondRow_.x == Approx(-0.2f)); REQUIRE(t.secondRow_.y == Approx(0.4f)); t = inverse(b); REQUIRE(t.firstRow_.x == Approx(-1 / (double) 7)); REQUIRE(t.firstRow_.y == Approx(4 / (double) 7)); REQUIRE(t.secondRow_.x == Approx(2/ (double)7)); REQUIRE(t.secondRow_.y == Approx(-1/ (double)7)); } SECTION("Transpose test") { Mat2 t = transpose(a); REQUIRE(t.firstRow_.x == 2); REQUIRE(t.firstRow_.y == 1); REQUIRE(t.secondRow_.x == 1); REQUIRE(t.secondRow_.y == 3); t = transpose(b); REQUIRE(t.firstRow_.x == 1); REQUIRE(t.firstRow_.y == 2); REQUIRE(t.secondRow_.x == 4); REQUIRE(t.secondRow_.y == 1); } SECTION("Rotation matrix test") { Mat2 t = make_rotation_mat2((float)M_PI_2); REQUIRE(t.firstRow_.x == Approx(0.0f)); REQUIRE(t.firstRow_.y == Approx(1.0f)); REQUIRE(t.secondRow_.x == Approx(-1.0f)); REQUIRE(t.secondRow_.y == Approx(0.0f)); t = make_rotation_mat2((float)M_PI); REQUIRE(t.firstRow_.x == Approx(-1.0f)); REQUIRE(t.firstRow_.y == Approx(0.0f)); REQUIRE(t.secondRow_.x == Approx(0.0f)); REQUIRE(t.secondRow_.y == Approx(-1.0f)); } } TEST_CASE("Test cases für Color") { SECTION("Constructor test"){ Color black{ 0.0 }; REQUIRE(black.r_ == Approx(0.0f)); REQUIRE(black.g_ == Approx(0.0f)); REQUIRE(black.b_ == Approx(0.0f)); Color red{ 1.0,0.0,0.0 }; REQUIRE(red.r_ == Approx(1.0f)); REQUIRE(red.g_ == Approx(0.0f)); REQUIRE(red.b_ == Approx(0.0f)); Color error{ 5.0 }; REQUIRE(error.r_ == Approx(0.0f)); REQUIRE(error.g_ == Approx(0.0f)); REQUIRE(error.b_ == Approx(0.0f)); } } TEST_CASE("Test cases for Rectangle") { Rectangle a{}; Rectangle b{ { 1.0,1.0 },{ 2.0,2.0 }, {1.0f} }; SECTION("Consturctor test") { REQUIRE(a.min().x == Approx(0.0f)); REQUIRE(a.min().y == Approx(0.0f)); REQUIRE(a.max().x == Approx(0.0f)); REQUIRE(a.max().y == Approx(0.0f)); REQUIRE(b.min().x == Approx(1.0f)); REQUIRE(b.min().y == Approx(1.0f)); REQUIRE(b.max().x == Approx(2.0f)); REQUIRE(b.max().y == Approx(2.0f)); } SECTION("Circumference test") { REQUIRE(a.circumference() == Approx(0.0f)); REQUIRE(b.circumference() == Approx(4.0f)); } } TEST_CASE("Test cases for Circle") { Circle a{}; Circle b{ { 1.0,1.0 },5.0, {1.0} }; SECTION("Consturctor test") { REQUIRE(a.center().x == Approx(0.0f)); REQUIRE(a.center().y == Approx(0.0f)); REQUIRE(a.radius() == Approx(0.0f)); REQUIRE(b.center().x == Approx(1.0f)); REQUIRE(b.center().y == Approx(1.0f)); REQUIRE(b.radius() == Approx(5.0f)); } SECTION("Circumference test") { REQUIRE(a.circumference() == Approx(0.0f)); REQUIRE(b.circumference() == Approx(31.4159f)); } SECTION("Is_inside test") { REQUIRE(!a.is_inside({ 1.0f,0.0f })); REQUIRE(b.is_inside({ 0.0f,0.0f })); } }
true
8982b99f8b74f0260e293f34c151ff1fd6a13c48
C++
laprej/LORAIN
/Foo4/test/test-if-else-catch.cpp
UTF-8
693
2.84375
3
[ "BSD-3-Clause-Clear" ]
permissive
#include "catch.hpp" extern "C" { int test_if_else_x; int test_if_else_x_condition; void undo_test_if_else(void); void test_if_else(void); } TEST_CASE("simple/if-else true", "A simple test if true") { test_if_else_x = 3; test_if_else_x_condition = 1; int y = test_if_else_x; test_if_else(); REQUIRE(test_if_else_x != y); undo_test_if_else(); REQUIRE(test_if_else_x == y); } TEST_CASE("simple/if-else false", "A simple test if false") { test_if_else_x = 3; test_if_else_x_condition = 0; int y = test_if_else_x; test_if_else(); REQUIRE(test_if_else_x != y); undo_test_if_else(); REQUIRE(test_if_else_x == y); }
true
5c53f8ca3eda27371087a1840c0cab0f5e6b7dc1
C++
lbellmann/ConsensLib
/src/Examples/Example.cpp
UTF-8
3,510
3.1875
3
[ "BSD-3-Clause" ]
permissive
#include <algorithm> #include <iostream> #include <numeric> #include <vector> #include "ConsensLib/Consens.hpp" class Graph { public: Graph(const std::vector<std::vector<size_t>>& adjacency) : m_adjacency(adjacency) { std::vector<size_t> tempNodes(adjacency.size()); std::iota(tempNodes.begin(), tempNodes.end(), 0); m_nodes = std::move(tempNodes); } const std::vector<size_t>& getNodes() const { return m_nodes; } const std::vector<size_t>& getNeighbors(size_t pos) const { return m_adjacency.at(pos); } private: std::vector<size_t> m_nodes; std::vector<std::vector<size_t>> m_adjacency; }; namespace ConsensLib { template<> struct GraphTraits<Graph> { using Node = size_t; using Iterator = std::vector<size_t>::const_iterator; static Iterator adjancencyBegin( const Node& node, const Graph& graph) { return graph.getNeighbors(node).begin(); } static Iterator adjancencyEnd( const Node& node, const Graph& graph) { return graph.getNeighbors(node).end(); } static Iterator nodesBegin(const Graph& graph) { return graph.getNodes().begin(); } static Iterator nodesEnd(const Graph& graph) { return graph.getNodes().end(); } static constexpr bool listsSorted() { return true; } }; } struct IsPathFilter { bool operator()(const std::vector<size_t>& subgraph) const { if (subgraph.size() < 3) { return true; } unsigned degreeSum = 0; for (size_t node : subgraph) { unsigned degree = 0; for (size_t neighbor : graph->getNeighbors(node)) { std::vector<size_t>::const_iterator iter = std::lower_bound(subgraph.begin(), subgraph.end(), neighbor); if (iter != subgraph.end() && *iter == neighbor) { ++degree; } } if (degree > 2) { return false; } degreeSum += degree; } if (degreeSum > 2 * subgraph.size() - 2) { return false; } return true; } Graph* graph; }; int main() { std::vector<std::vector<size_t>> adjacency = {{1}, {0, 2, 3, 4}, {1, 3}, {1, 2}, {1}}; Graph graph(adjacency); std::cout << "--INPUT GRAPH--\n\n" " 0 \n" " \\ \n" " 1--4 \n" " / \\ \n" " 2---3 \n\n"; std::vector<std::vector<size_t>> subgraphs = ConsensLib::runConsens(graph); std::cout << "Node sets of all connected induced subgraphs are\n\n"; for (const std::vector<size_t>& subgraph : subgraphs) { std::cout << "{"; for (unsigned i = 0; i < subgraph.size(); ++i) { if (i != 0) { std::cout << ", "; } std::cout << subgraph.at(i); } std::cout << "}\n"; } IsPathFilter filter{&graph}; std::vector<std::vector<size_t>> paths = ConsensLib::runConsens(graph, std::numeric_limits<size_t>::max(), filter); std::cout << "\nNode sets of all induced paths are\n\n"; for (const std::vector<size_t>& path : paths) { std::cout << "{"; for (unsigned i = 0; i < path.size(); ++i) { if (i != 0) { std::cout << ", "; } std::cout << path.at(i); } std::cout << "}\n"; } return 0; }
true
9be8afd44a5e819f0a05e5333bb1a03030be615b
C++
higsyuhing/leetcode_easy
/1863.cpp
UTF-8
1,018
3.03125
3
[]
no_license
class Solution { public: int subsetXORSum(vector<int>& nums) { // nums.length < 13, then we can use a unsigned integer for the select mask int res = 0; for (auto i = 1; i < (1 << nums.size()); ++i) { int total = 0; for (auto j = 0; j < nums.size(); ++j) if (i & (1 << j)) total ^= nums[j]; res += total; } return res; } }; /* int subsetXORSum(vector<int>& nums,int sum=0) { for(int n:nums) sum|=n; return sum*pow(2,nums.size()-1); } int subsetXORSum(vector<int>& nums) { return allSubs(0, nums, 0); } int allSubs(int cur, vector<int>& nums, int xoR) { if (cur == nums.size()) { return xoR; } // Include int include = allSubs(cur + 1, nums, nums[cur] ^ xoR); // Exclude int exclude = allSubs(cur + 1, nums, xoR); return include + exclude; } */
true
720e6bf18265044b9a8f6733e7467c3a48f7ad38
C++
i-kuzmin/hw
/Hiew.cpp
UTF-8
5,429
2.828125
3
[]
no_license
#include "Hiew.h" #include <iomanip> #include <cstdint> #include <vector> const char * const Hiew::m_trans [] = { u8" ", u8"☺", u8"☻", u8"♥", u8"♦", u8"♣", u8"♠", u8"•", u8"◘", u8"○", u8"◙", u8"♂", u8"♀", u8"♪", u8"♫", u8"☼", u8"►", u8"◄", u8"↕", u8"‼", u8"¶", u8"§", u8"▬", u8"↨", u8"↑", u8"↓", u8"→", u8"←", u8"∟", u8"↔", u8"▲", u8"▼", u8" ", u8"!", u8"\"", u8"#", u8"$", u8"%", u8"&", u8"'", u8"(", u8")", u8"*", u8"+", u8",", u8"-", u8".", u8"/", u8"0", u8"1", u8"2", u8"3", u8"4", u8"5", u8"6", u8"7", u8"8", u8"9", u8":", u8";", u8"<", u8"=", u8">", u8"?", u8"@", u8"A", u8"B", u8"C", u8"D", u8"E", u8"F", u8"G", u8"H", u8"I", u8"J", u8"K", u8"L", u8"M", u8"N", u8"O", u8"P", u8"Q", u8"R", u8"S", u8"T", u8"U", u8"V", u8"W", u8"X", u8"Y", u8"Z", u8"[", u8"\\", u8"]", u8"^", u8"_", u8"`", u8"a", u8"b", u8"c", u8"d", u8"e", u8"f", u8"g", u8"h", u8"i", u8"j", u8"k", u8"l", u8"m", u8"n", u8"o", u8"p", u8"q", u8"r", u8"s", u8"t", u8"u", u8"v", u8"w", u8"x", u8"y", u8"z", u8"{", u8"|", u8"}", u8"~", u8"⌂", u8"А", u8"Б", u8"В", u8"Г", u8"Д", u8"Е", u8"Ж", u8"З", u8"И", u8"Й", u8"К", u8"Л", u8"М", u8"Н", u8"О", u8"П", u8"Р", u8"С", u8"Т", u8"У", u8"Ф", u8"Х", u8"Ц", u8"Ч", u8"Ш", u8"Щ", u8"Ъ", u8"Ы", u8"Ь", u8"Э", u8"Ю", u8"Я", u8"а", u8"б", u8"в", u8"г", u8"д", u8"е", u8"ж", u8"з", u8"и", u8"й", u8"к", u8"л", u8"м", u8"н", u8"о", u8"п", u8"░", u8"▒", u8"▓", u8"│", u8"┤", u8"╡", u8"╢", u8"╖", u8"╕", u8"╣", u8"║", u8"╗", u8"╝", u8"╜", u8"╛", u8"┐", u8"└", u8"┴", u8"┬", u8"├", u8"─", u8"┼", u8"╞", u8"╟", u8"╚", u8"╔", u8"╩", u8"╦", u8"╠", u8"═", u8"╬", u8"╧", u8"╨", u8"╤", u8"╥", u8"╙", u8"╘", u8"╒", u8"╓", u8"╫", u8"╪", u8"┘", u8"┌", u8"█", u8"▄", u8"▌", u8"▐", u8"▀", u8"р", u8"с", u8"т", u8"у", u8"ф", u8"х", u8"ц", u8"ч", u8"ш", u8"щ", u8"ъ", u8"ы", u8"ь", u8"э", u8"ю", u8"я", u8"Ё", u8"ё", u8"Є", u8"є", u8"Ї", u8"ї", u8"Ў", u8"ў", u8"°", u8"∙", u8"·", u8"√", u8"№", u8"¤", u8"■", u8" " }; class Hiew::LineMerger { public: LineMerger( Hiew& outer) : _(outer), m_collapsed(0) {} bool skip( const std::vector<char>& line) { if ( !_.m_mergeLines) return false; if ( line == m_lastLine) { m_collapsed++; return true /*skip line*/; } else { if ( m_collapsed > 0) { _.m_out << "* " << std::setw(6) << std::hex << std::setfill(' ') << m_collapsed << " "; m_collapsed = 0; for (int i = 0; i < line.size(); ++i) { _.m_out << "-- "; } _.m_out << std::endl; } m_lastLine = line; } return false; } private: Hiew& _; std::vector<char> m_lastLine; size_t m_collapsed; }; void Hiew::hex( std::istream& in) { using std::hex; using std::uppercase; using std::setfill; using std::setw; using std::endl; std::vector<char> line(m_width); std::vector<char> pLine; size_t offset = 0; size_t collapsed = 0; LineMerger merger( *this); while ( in.read(line.data(), line.size()) || in.gcount()) { if ( merger.skip( line)) continue; size_t n = in.gcount(); // hexadecimal output m_out << hex << setfill('0') << setw(8) << offset << ": "; for (int i = 0; i < line.size(); ++i) { if ( i < n) { uint8_t c = line[i]; m_out << setw(2) << setfill('0') << hex << uppercase << (int) c; } else { m_out << " "; } if ( i == line.size() - 1) m_out << " "; else if ( i % 4 == 3) m_out << '-'; else m_out << ' '; } // characters output for (int i = 0; i < n; ++i) { uint8_t c = line[i]; m_out << m_trans[ c]; } m_out << endl; offset += n; } } void Hiew::text( std::istream& in) { using std::endl; int n; char line[256]; while ( ( n = in.readsome(line, sizeof(line)))) { uint8_t c = 0; uint8_t lc = 0; for ( int i = 0; i < n; ++i) { lc = c; c = line[i]; switch ( m_lineFeed) { case CR: if ( c == '\n') { m_out << endl; continue; } break; case LF: if ( c == '\r') { m_out << endl; continue; } break; case NLL: if ( c == '\0') { m_out << endl; continue; } break; case CRLF: if ( c == '\n' && lc == '\r') { m_out << endl; continue;} else if ( lc == '\r') { m_out << m_trans['\r']; } if ( c == '\r') { continue; } break; } m_out << m_trans[ c]; } } }
true
c812b9ca91d7e92af174a39caf16e4d7ec83b3d7
C++
Reinsborg/ComplexNumbers
/KomplekseTal/KomplekseTal.h
UTF-8
506
2.671875
3
[]
no_license
#include <math.h> class ComplexNumber { public: ComplexNumber(); ComplexNumber(double Rez, double Imz); void setSum(double rez, double imz); void setPol(double mod, double arg); double getRez(); double getImz(); double getMod(); double getArg(); private: void setRez(double rez); void setImz(double imz); void setMod(double mod); void setArg(double arg); void calPol(double rez, double imz); void calSum(double mod, double arg); double reZ; double imZ; double moD; double arG; };
true
db387cd79e31dd92d125ac923257fec7f05eb0e8
C++
Itamarled/Streaming-service-system
/include/Action.h
UTF-8
2,754
2.890625
3
[]
no_license
#ifndef ACTION_H_ #define ACTION_H_ #include <string> #include <iostream> #include "User.h" class Session; enum ActionStatus{ PENDING, COMPLETED, ERROR }; class BaseAction{ public: BaseAction();///Constructor BaseAction(const BaseAction& other);///Copy Constructor virtual BaseAction* clone()=0; virtual ~BaseAction()= default;///default destructor ActionStatus getStatus() const; virtual void act(Session& sess)=0; virtual std::string toString() const=0; bool Isfound(std::string name,std::unordered_map<std::string,User*> user); protected: void complete(); void error(const std::string& errorMsg); std::string getErrorMsg() const; private: std::string errorMsg; ActionStatus status; }; class CreateUser : public BaseAction { public: virtual void act(Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~CreateUser()= default; }; class ChangeActiveUser : public BaseAction { public: virtual void act(Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~ChangeActiveUser()= default;///default destructor }; class DeleteUser : public BaseAction { public: virtual void act(Session & sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~DeleteUser()= default;///default destructor }; class DuplicateUser : public BaseAction { public: virtual void act(Session & sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~DuplicateUser()= default;///default destructor }; class PrintContentList : public BaseAction { public: virtual void act (Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~PrintContentList()= default;///default destructor }; class PrintWatchHistory : public BaseAction { public: virtual void act (Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~PrintWatchHistory()= default;///default destructor }; class Watch : public BaseAction { public: virtual void act(Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~Watch()= default;///default destructor }; class PrintActionsLog : public BaseAction { public: virtual void act(Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~PrintActionsLog()= default;///default destructor }; class Exit : public BaseAction { public: virtual void act(Session& sess); virtual std::string toString() const; virtual BaseAction* clone(); virtual ~Exit()= default;///default destructor }; #endif
true
6584ffec099ba472daf2f306dd5e207293815541
C++
fsps60312/old-C-code
/C++ code/HSNU Online Judge/15(6).cpp
UTF-8
935
2.546875
3
[]
no_license
#include<cstdio> #include<vector> #include<algorithm> using namespace std; const int INF=2147483647; int N,M,MAT[100][100]; void Expand(int s,int &ans) { for(int i=s+1;i<N;i++) { for(int j=i+1;j<N;j++) { int &a=MAT[s][i],&b=MAT[s][j]; if(a==INF||b==INF)continue; int &l=MAT[i][j]; if(l!=INF&&a+b+l<ans) { printf("(%d<->%d<->%d)ans=%d\n",i+1,s+1,j+1,a+b+l); ans=a+b+l; } if(l>a+b)printf("%d:(%d,%d):%d->%d\n",s+1,i+1,j+1,l,a+b); l=MAT[j][i]=min(l,a+b); } } // printf("%d:ans=%d\n",s+1,ans); } int main() { freopen("in.txt","r",stdin); while(scanf("%d%d",&N,&M)==2) { for(int i=0;i<N;i++)for(int j=0;j<N;j++)MAT[i][j]=INF; for(int i=0,a,b,c;i<M;i++) { scanf("%d%d%d",&a,&b,&c); a--,b--; if(c<MAT[a][b]&&a!=b)MAT[a][b]=MAT[b][a]=c; } int ans=INF; for(int i=0;i<N;i++) { Expand(i,ans); } if(ans==INF)puts("No solution."); else printf("%d\n",ans); } return 0; }
true
2bf5afc628c3efb4c1380caaff63d21601b5d537
C++
Bhaskar-Dutt/Project-Euler
/src/Divisibility_Of_Factorials.cpp
UTF-8
3,562
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <unordered_map> #include <algorithm> // odd prime numbers are marked as "true" in a bitvector std::vector<bool> sieve; // return true, if x is a prime number bool isPrime(unsigned int x) { // handle even numbers if ((x & 1) == 0) return x == 2; // lookup for odd numbers return sieve[x >> 1]; } // find all prime numbers from 2 to size void fillSieve(unsigned int size) { // store only odd numbers const unsigned int half = (size >> 1) + 1; // allocate memory sieve.resize(half, true); // 1 is not a prime number sieve[0] = false; // process all relevant prime factors for (unsigned int i = 1; 2*i*i < half; i++) // do we have a prime factor ? if (sieve[i]) { // mark all its multiples as false unsigned int current = 3*i+1; while (current < half) { sieve[current] = false; current += 2*i+1; } } } // compute all factorials until factorial % n == 0 unsigned int naive(unsigned int n) { unsigned long long factorial = 1; unsigned int result = 0; while (factorial % n != 0) { result++; factorial *= result; factorial %= n; } return result; } // all prime numbers < 10^8 std::vector<unsigned int> primes; // cache for i^2, i^3, i^4, ... where i is prime std::unordered_map<unsigned int, unsigned int> cache; // compute s(n) unsigned int getSmallestFactorial(unsigned int n) { // will be the result unsigned int best = 0; // split off all prime factors for (auto p : primes) { // p is not a prime factor of the current number ? if (n % p != 0) continue; // extract the current prime factor as often as possible // e.g. => 24 => 2^3 * 3 => primePower will be 8 and reduced = 3 unsigned int primePower = 1; do { n /= p; primePower *= p; } while (n % p == 0); // higher result ? best = std::max(best, cache[primePower]); // no further factorization possible ? if (n == 1) return best; if (isPrime(n)) // s(prime) = prime return std::max(best, n); } return best; } int main() { unsigned int limit = 100000000; std::cin >> limit; unsigned long long sum = 0; // simple algorithm, too slow //for (unsigned int i = 2; i <= 100; i++) // sum += naive(i); // and now the more sophisticated approach // find all primes below 10^8 fillSieve(limit); // copy those 5761455 primes to a dense array for faster access for (unsigned int i = 2; i < limit; i++) if (isPrime(i)) primes.push_back(i); // find result for numbers with are powers of a single prime for (unsigned int i = 2; i <= limit; i++) { if (isPrime(i)) { // pre-compute all values of i^2, i^3, ... where i is prime and store in cache[] unsigned long long power = i * (unsigned long long) i; for (unsigned int exponent = 2; power <= limit; exponent++) { // optimized version of naive(), skip i numbers in each iteration unsigned long long factorial = i; unsigned int result = i; do { result += i; factorial *= result; factorial %= power; } while (factorial % power != 0); cache[power] = result; // next exponent power *= i; } // s(prime) = prime sum += i; } else { // compute s(non prime) sum += getSmallestFactorial(i); } } // and display the result std::cout << sum << std::endl; return 0; }
true
d391228aba80803894b7f550ca937183b5767f84
C++
shraddhanahar/FindingMaxMin
/StraightMaxMin0.cpp
UTF-8
590
2.859375
3
[]
no_license
#include<iostream> using namespace std; /*BestAlgorithmToFindMaxMinInAccordanceToTimeComplexity*/ int main() { int a[100],i,n,min,max; cout<<"Enter size of array :\t"; cin>>n; /* #####AcceptArray##### */ for(i = 1 ;i<=n;i++) { cin>>a[i]; } /* #####StraightMaxMinLogic##### */ min=max=a[1]; for(i=2;i<=n;i++) { if(max<a[i]) max=a[i]; else if(min>a[i]) min=a[i]; } cout<<"MIN :\t"<<min; cout<<"\nMAX :\t"<<max; }
true
9e0b180bd21e61e96a31b3d3bab0dcdfbadb6bbe
C++
dexfire/ccode
/ACM/long_long_ago/cable_master_copy.cpp
UTF-8
723
2.609375
3
[]
no_license
#include <cmath> #include <cstdio> #include <iostream> using namespace std; const int INF = 10005; const int MAX_N = 10005; int N, K; double Len[MAX_N]; bool C(double x) { int num = 0; for (int i = 0; i < N; i++) { num += (int)(Len[i] / x); } return num >= K; } void solve() { double lb = 0.0, ub = (double)INF * 10.0, mid; for (int i = 0; i < 100; i++) { mid = (lb + ub) / 2; if (C(mid)) lb = mid; else ub = mid; } printf("%.2f\n", floor(ub * 100) / 100); } int main() { int i; while (scanf("%d %d", &N, &K) != EOF) { for (i = 0; i < N; i++) scanf("%lf", &Len[i]); solve(); } return 0; }
true
ef702d8a7d1c8ac956de60b63fe49add86c69d51
C++
cycasmi/proyectos-VS
/Segundo semestre orientada a objetos/Libreria/Libreria/Heroe.h
UTF-8
310
3.28125
3
[]
no_license
#pragma once #include "Personaje.h" #include <string> class Heroe : public Personaje { private: Heroe(){} public: Heroe(string nombre, int popularidad) : Personaje(nombre, popularidad){} void imprimir() { cout << "Soy el heroe " << nombre << " y mi popularidad es de: " << *popularidad << endl; } };
true
fb7ff23cd17a93234347a95723e06eeac8d0f942
C++
Bode2222/DeepQ
/DeepQ/main.cpp
UTF-8
1,916
2.5625
3
[]
no_license
#include "QLearn.h" #include "LizardGame.h" #include "CarGame.h" #include "NeuralNet.h" //NOTE: MAKING THE NUMBER OF STEPS BEFORE TARGET NET UPDATE TOO SMALL OR TOO LARGE (RELATIVE TO THE GAME WERE PLAYING) CREATES \ INSTABILITY IN THE NETWORK!!! //implement dynamic replay memory and compare performance //Time taken 58*30 reps, about 58 mins 3780 secs I think, replay mem size: 500k //Complete counter disabled. Let's see just how good We can get int main() { //Should the rate at which the targetnet updates be related to the exploration decay rate? srand(time(0)); //LizardGame env; sf::RenderWindow wd(sf::VideoMode(512, 512), "Car Game"); CarGame env(&wd); //Instantiate network template vector<Layer> layout; layout.push_back(Layer(DENSE, env.getStateSize(), NONE)); layout.push_back(Layer(DENSE, 21, TANH, 2, 2)); layout.push_back(Layer(DENSE, env.getActionSize(), NONE)); //Instantiate DQN NeuralNet temp(layout); NeuralNet temp2(temp); QLearn DeepQ(env, temp, temp2); int duration; //Train char ans = 'M', an = 'M'; int trainingReps = 4000; while (ans != 'Y' && ans != 'N') { system("cls"); cout << "Load trained network? Y/N" << endl; cin >> ans; if (ans == 'Y') { if (!DeepQ.load("CarGameSaveHash.hnn")) { cout << "No found file, Hit enter to train" << endl; cin.get(); ans = 'N'; } else { while (an != 'Y' && an != 'N') { system("cls"); cout << "Train loaded Network? Y/N" << endl; cin >> an; } } } if (ans == 'N' || an == 'Y') { auto start = time(0); DeepQ.trainNetwork(trainingReps); auto end = time(0); cout << "Time: " << end - start << endl; DeepQ.save("CarGameSaveHash.hnn"); } } cout << "Finished training. Hit enter to continue" << endl; cin.get(); cin.get(); wd.requestFocus(); //Play game with trained DQN DeepQ.Play(); cout << "Program Ended" << endl; cin.get(); return 0; }
true
179cd23302f3745b41b654f0101cfe86ace8a745
C++
Sunakarus/SFMLParticleEngine
/SFMLParticleEngine/Controller.cpp
UTF-8
898
3.015625
3
[]
no_license
#include "stdafx.h" #include "Controller.h" #include <random> Controller::Controller(sf::RenderWindow* window) { font.loadFromFile("OpenSans-Regular.ttf"); this->window = window; emitterList.push_back(new ParticleEmitter(this)); std::random_device rd; std::mt19937 rng(rd()); text.setFont(font); text.setColor(sf::Color::White); text.setCharacterSize(16); text.setString(""); } int Controller::getRandomNumber(int min, int max) { std::uniform_int_distribution<int> uni(min, max); return uni(rng); } void Controller::update() { if (!emitterList.empty()){ for (int i = 0; i < emitterList.size(); i++) { emitterList[i]->update(); } } } void Controller::setText(std::string str) { text.setString(str); } void Controller::draw() { if (!emitterList.empty()){ for (int i = 0; i < emitterList.size(); i++) { emitterList[i]->draw(window); } } window->draw(text); }
true
ac1608f8075c02e1887512c9ffe1bc58c4a0a231
C++
james47/acm
/oj/hdoj/hdoj_1285.cpp
UTF-8
886
2.625
3
[]
no_license
#include<cstring> #include<cstdio> #include<queue> using namespace std; int en[510], in[510]; int n, m, x, y, esize; struct edge{ int n, v; } e[30000]; void insert(int u, int v) { esize ++; e[esize].v = v; e[esize].n = en[u]; en[u] = esize; } int main() { while(scanf("%d %d", &n, &m) != EOF) { memset(en, -1, sizeof(en)); memset(in, 0, sizeof(in)); esize = -1; for(int i = 0; i < m; i++){ scanf("%d %d", &x, &y); insert(x, y); in[y]++; } priority_queue<int, vector<int>, greater<int> > q; for (int i = 1; i <= n; i++){ if (!in[i]) q.push(i); } bool flag = true; while(!q.empty()){ int t = q.top(); q.pop(); if (flag){ flag = false; printf("%d", t); } else printf(" %d", t); for (int tt = en[t]; tt != -1; tt = e[tt].n){ int v = e[tt].v; in[v]--; if (!in[v]) q.push(v); } } printf("\n"); } return 0; }
true
6f6c9cbf70bd8edb1fab36e53cb4be2b5901d7e4
C++
baozhiyu0212/Leetcode
/842. Split Array into Fibonacci Sequence.cpp
UTF-8
932
3.15625
3
[]
no_license
class Solution { vector<vector<int>> res; public: vector<int> splitIntoFibonacci(string s) { dfs(s,vector<int>(),0); if(res.size()==0) return {}; return res[0]; } void dfs(string s, vector<int> temp, int index){ if(temp.size()>=3 && !valid(temp)) return; else if(temp.size()>=3 && index>=s.size()){ res.push_back(temp); return; } for(int i=index;i<s.size();i++){ string cur = s.substr(index,i-index+1); if((cur[0]=='0' && cur.size()>1) || stol(cur)>INT_MAX) break; temp.push_back(stol(cur)); dfs(s,temp,i+1); temp.pop_back(); } } bool valid(vector<int> temp){ if(temp.size()<3) return false; for(int i=2;i<temp.size();i++){ if(temp[i]!=temp[i-1]+temp[i-2]) return false; } return true; } };
true
2c537c90fd0afa240a6beb4a3425f6fc39769fcd
C++
teamneem/Cplusplusclass
/proj06/proj06.driver.cpp
UTF-8
4,510
3.125
3
[]
no_license
/**************************************************************************** Tasneem Pierce Section 8 Computer Project #6 ****************************************************************************/ using namespace std; #include <iostream> #include "/user/cse232/Projects/project06.word.h" int main() { Word A; Word B; Word C; Word D; Word E; Word F; Word G; Word H; Word I; std::cout.setf(std::ios::boolalpha); cout << "this shows off what happens when two similar words are compared" << endl; cin >> A; cout << "A (apple): " << A << endl; cin >> B; cout << "B (apples): " << B << endl; cout << "A equal to B: " << (A==B) << endl; cout << "A is not equal to B: " << (A!=B) << endl; cout << "A is less than B: " << (A<B) << endl; cout << "A is less than or equal to B: " << (A<=B) << endl; cout << "A is more than B: " << (A>B) << endl; cout << "A is more than or equal to B: " << (A>=B) << endl; cout << "A+B: " << A+B << endl; A += B; cout << "A +=B: " << A << endl << endl; cout << "this shows off what happens when we call the = operator" << endl; I = A; cout << "A (appleapples): " << A << endl; cout << "I (appleapples): " << I << endl; cout << "A equal to I: " << (A==I) << endl; cout << "A is not equal to I: " << (A!=I) << endl; cout << "A is less than I: " << (A<I) << endl; cout << "A is less than or equal to I: " << (A<=I) << endl; cout << "A is more than I: " << (A>I) << endl; cout << "A is more than or equal to I: " << (A>=I) << endl; cout << "A+I: " << A+I << endl; A += I; cout << "A +=I: " << A << endl << endl; cin >> C; cout << "C (applesauce): " << C << endl; cin >> D; cout << "D (appl-e): " << D << endl; cout << "C equal to D: " << (C==D) << endl; cout << "C is not equal to D: " << (C!=D) << endl; cout << "C is less than D: " << (C<D) << endl; cout << "C is less than or equal to D: " << (C<=D) << endl; cout << "C is more than D: " << (C>D) << endl; cout << "C is more than or equal to D: " << (C>=D) << endl; cout << "C+D: " << C+D << endl; C +=D; cout << "C +=D: " << C << endl << endl; cout << "D (appl-e): " << D << endl; cin >> E; cout << "this shows off what happens when an input starts incorrectly" << endl; cout << "E ('apple): " << E << endl; cout << "D equal to E: " << (D==E) << endl; cout << "D is not equal to E: " << (D!=E) << endl; cout << "D is less than E: " << (D<E) << endl; cout << "D is less than or equal to E: " << (D<=E) << endl; cout << "D is more than E: " << (D>E) << endl; cout << "D is more than or equal to E: " << (D>=E) << endl; cout << "D+E: " << D+E << endl; D +=E; cout << "D +=E: " << D << endl << endl; cout << "this shows off what happens when an input starts incorrectly" << endl; cout << "E ('apple): " << E << endl; cin >> F; cout << "this shows off what happens when an input ends incorrectly" << endl; cout << "F (apple12): " << F << endl; cout << "E equal to F: " << (E==F) << endl; cout << "E is not equal to F: " << (E!=F) << endl; cout << "E is less than F: " << (E<F) << endl; cout << "E is less than or equal to F: " << (E<=F) << endl; cout << "E is more than F: " << (E>F) << endl; cout << "E is more than or equal to F: " << (E>=F) << endl; cout << "E+F: " << E+F << endl; E +=F; cout << "E +=F: " << E << endl << endl; cout << "this shows off what happens when input is too long" << endl; cout << "F (apple): " << F << endl; cin >> G; cout << "G (monkeymonkeymonkeymonkeymonkeymonkey): " << G << endl; cout << "F equal to G: " << (F==G) << endl; cout << "F is not equal to G: " << (F!=G) << endl; cout << "F is less than G: " << (F<G) << endl; cout << "F is less than or equal to G: " << (F<=G) << endl; cout << "F is more than G: " << (F>G) << endl; cout << "F is more than or equal to G: " << (F>=G) << endl; cout << "F+G: " << F+G << endl; F += G; cout << "F += G: " << F << endl << endl; cout << "this shows off what happens when input is too long as next input is the excess" << endl; cout << "G (monkeymonkeymonkeymonkeymonkeym): " << G << endl; cin >> H; cout << "H (onkey): " << H << endl; cout << "H equal to G: " << (H==G) << endl; cout << "H is not equal to G: " << (H!=G) << endl; cout << "H is less than G: " << (H<G) << endl; cout << "H is less than or equal to G: " << (H<=G) << endl; cout << "H is more than G: " << (H>G) << endl; cout << "H is more than or equal to G: " << (H>=G) << endl; cout << "H+G: " << H+G << endl; H +=G; cout << "H+=G: " << H << endl << endl; }
true
772c3ea4d44dab0a1af8a84e138a9cb4436c6e4b
C++
alychuk/Image_Processing
/proj3/exp2/exp2.cpp
UTF-8
1,559
2.9375
3
[]
no_license
// modified exp2 for exp3 this is the code for exp2 copied over in case needed later for (int i = 0; i < rows; ++i) { //add a new col for each row image_real[i + 1] = new float[cols + 1]; image_imag[i + 1] = new float[cols + 1]; for (int j = 0; j < cols; ++j) { //gets the value of the pixel from image image.getPixelVal(i, j, val); //insert value into real num array and have 0 on imaginary image_real[i + 1][j + 1] = val; image_imag[i + 1][j + 1] = 0; // image_real[i+1][j+1] *= pow(-1, ((i+1)+(j+1))); // if multiplied by -1, it is centered } // if multiplied by 1, then it isn't centered } int N = rows; int M = cols; //call 2D fft and passes the size of row,col, the 2d arrays for //real and imaginary numbers along with the isign, -1 = forward, //1 = Inverse fft2D(M, N, image_real, image_imag, -1); std::complex<float> complex_num; for (int i = 1; i < N + 1; ++i) { for (int j = 1; j < N + 1; ++j) { complex_num = std::complex<float>(image_real[i][j], image_imag[i][j]); complex_num /= N * N; image_real[i][j] = complex_num.real(); image_imag[i][j] = complex_num.imag(); } } float **image_out = new float *[rows]; for (int i = 0; i < rows; ++i) { image_out[i] = new float[cols]; for (int j = 0; j < cols; ++j) { image_out[i][j] = log(1. + sqrt(pow(image_real[i + 1][j + 1], 2.) + pow(image_imag[i + 1][j + 1], 2.))); } } for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { image.setPixelVal(i, j, image_out[i][j]); } } writeImage(argv[2], image);
true
0bcdb8003d0483fc02cbeee02e56a3206ae706c1
C++
BhuiyanMH/Uva
/11764 Jumping mario.cpp
UTF-8
577
2.890625
3
[]
no_license
#include <stdio.h> #include <math.h> #include <string.h> int main() { int tc, N; scanf("%d", &tc); for(int i =1; i<= tc; i++) { scanf("%d", &N); int arr[N]; for(int j =0; j<N; j++) { scanf("%d", &arr[j]); } int highJump = 0, lowJump =0; for(int k = 1; k<N; k++) { if( arr[k] < arr[k-1]) lowJump++; if( arr[k] > arr[k-1]) highJump++; } printf("Case %d: %d %d\n", i, highJump, lowJump); } return 0; }
true
4f320c884ddea623fe3abffd3a8f24666c2db2c4
C++
jshal001/R-Shell
/header/parser.hpp
UTF-8
1,018
3
3
[]
no_license
#ifndef PARSER_H #define PARSER_H #include <string> #include <iostream> #include <stack> #include <vector> #include <queue> #include "command.hpp" #include "executable.hpp" #include "or.hpp" #include "and.hpp" #include "semicolon.hpp" using std::string; using std::vector; using std::queue; class Parser { private: string input{}; // Holds user's command line input Connector* WhichConnector(string); // Return a connector object depending on which "&&" "||" or ";" string is passed in bool isOperator(string &); // True if argument is one of the "&&" "||" or ";" void ShuntingYard(vector<string>); void MakeTree(queue<string> ); bool escapeChar(); bool parenthesesMatch(); // returns true if there is a same number of left "(" and right ")" parentheses in input bool quotesMatch(); int bracketsMatch(); void printError(string); public: Parser(){}; void getInput(); // getline user input void parse(); // Takes the user input and tokenizes it by "&& || ;" delimiters }; #endif // END PARSER_H
true
03652103acf4580da09646a54282c42ba2556ce7
C++
jloxfo2/gb-emu
/cpu.h
UTF-8
5,462
3.0625
3
[]
no_license
#ifndef CPU_H_ #define CPU_H_ #include "mmu.h" #include <stdint.h> #include <iostream> #include <string> #define MAX_INT_4BIT 0x000F #define MAX_INT_8BIT 0x00FF #define MAX_INT_12BIT 0x0FFF #define MAX_INT_16BIT 0xFFFF #define C_FLAG 0x10 // carry flag #define H_FLAG 0x20 // half carry flag #define N_FLAG 0x40 // subtract flag #define Z_FLAG 0x80 // zero flag class CPU { public: CPU(MMU& mmu); void initialize(); int execute_next_opcode(); void cpu_dump(); private: union cpu_register { uint16_t highlow; struct { uint16_t low : 8; // Order is subject to system endianess uint16_t high : 8; }; }; // The 8-bit general registers have been paired to form four 16-bit registers // since the cpu frequently combines them for certain opcodes. cpu_register AF; cpu_register BC; cpu_register DE; cpu_register HL; uint16_t SP; uint16_t PC; int clock_cycles; // 4 clock cycles = 1 machine cycle MMU& gb_mmu; // ****** GameBoy Opcode Instructions ****** void JUMP(const uint16_t addr); // 8-Bit ALU void ADD_8BIT(const uint8_t val); void ADC_8BIT(const uint8_t val); void SUB(const uint8_t val); void SBC(const uint8_t val); void XOR(const uint8_t val); void AND(const uint8_t val); void OR(const uint8_t val); void CP(const uint8_t val); uint8_t INC_8BIT(uint8_t val); uint8_t DEC_8BIT(uint8_t val); // 8-Bit Loads void LD_reg_val_8BIT(const char reg, const uint8_t val); void LD_addr_val_8BIT(const uint16_t addr, const uint8_t val); // 16-Bit Loads void LD_reg_val_16BIT(const std::string reg, const uint16_t val); void LD_addr_val_16BIT(const uint16_t addr, const uint16_t val); void LDHL_SP_n(const uint8_t val); // 16-Bit Stack Operations void PUSH_nn(const std::string reg); void POP_nn(const std::string reg); // ********** End of Instructions ********** }; // Jump to address designated by val. inline void CPU::JUMP(const uint16_t addr) { PC = addr; } // Add val to register A. inline void CPU::ADD_8BIT(const uint8_t val) { // set flags if (AF.high + val == 0) AF.low |= Z_FLAG; if ((AF.high & 0xF) > (MAX_INT_4BIT - (val & 0xF))) AF.low |= H_FLAG; if (AF.high > (MAX_INT_8BIT - val)) AF.low |= C_FLAG; AF.low &= ~(N_FLAG); AF.high += val; clock_cycles += 4; } // Add val + Carry Flag to A. inline void CPU::ADC_8BIT(const uint8_t val) { // set flags if (AF.high + val == 0) AF.low |= Z_FLAG; if ((AF.high & 0xF) > (MAX_INT_4BIT - (val & 0xF))) AF.low |= H_FLAG; if (AF.high > (MAX_INT_8BIT - val)) AF.low |= C_FLAG; AF.low &= ~(N_FLAG); AF.high = AF.high + val + ((AF.low & C_FLAG) >> 4); clock_cycles += 4; } // Subtract val from A. inline void CPU::SUB(const uint8_t val) { // set flags if (AF.high - val == 0) AF.low |= Z_FLAG; if ((AF.high & 0xF) > (val & 0xF)) // Set if no borrow AF.low |= H_FLAG; if (AF.high > val) // Set if no borrow AF.low |= C_FLAG; AF.low |= N_FLAG; AF.high -= val; clock_cycles += 4; } // Subtract A + Carry Flag from A. inline void CPU::SBC(const uint8_t val) { // set flags if (AF.high - val == 0) AF.low |= Z_FLAG; if ((AF.high & 0xF) > (val & 0xF)) // Set if no borrow AF.low |= H_FLAG; if (AF.high > val) // Set if no borrow AF.low |= C_FLAG; AF.low |= N_FLAG; AF.high = AF.high - val - ((AF.low & C_FLAG) >> 4); clock_cycles += 4; } // Logical exclusive OR register A with val. inline void CPU::XOR(const uint8_t val) { // set flags AF.low = 0; if ((AF.high ^ val) == 0) AF.low |= Z_FLAG; AF.high ^= val; clock_cycles += 4; } // Logical AND register A with val. inline void CPU::AND(const uint8_t val) { // set flags AF.low = 0; AF.low |= H_FLAG; if ((AF.high & val) == 0) AF.low |= Z_FLAG; AF.high &= val; clock_cycles += 4; } // Logical OR register A with val. inline void CPU::OR(const uint8_t val) { // set flags AF.low = 0; if ((AF.high | val) == 0) AF.low |= Z_FLAG; AF.high |= val; clock_cycles += 4; } // Compare register A with val. inline void CPU::CP(const uint8_t val) { // set flags AF.low |= N_FLAG; if (AF.high - val == 0) AF.low |= Z_FLAG; if ((AF.high & 0xF) > (val & 0xF)) // Set if no borrow AF.low |= H_FLAG; if (AF.high > val) // Set if no borrow AF.low |= C_FLAG; clock_cycles += 4; } // Increment val by 1. inline uint8_t CPU::INC_8BIT(uint8_t val) { // set flags AF.low &= ~(N_FLAG); if (val + 1 == 0) AF.low |= Z_FLAG; if (((val & 0xF) + 1) > MAX_INT_4BIT) AF.low |= H_FLAG; val++; clock_cycles += 4; return val; } // Decrement val by 1. inline uint8_t CPU::DEC_8BIT(uint8_t val) { // set flags AF.low |= N_FLAG; if (val - 1 == 0) AF.low |= Z_FLAG; if ((val & 0xF) > 1) // Set if no borrow AF.low |= H_FLAG; val--; clock_cycles += 4; return val; } // Load 8-bit val into the specified 16-bit address inline void CPU::LD_addr_val_8BIT(const uint16_t addr, const uint8_t val) { gb_mmu.write_byte(addr, val); clock_cycles += 8; } // Load 16-bit val into the specified 16-bit address inline void CPU::LD_addr_val_16BIT(const uint16_t addr, const uint16_t val) { gb_mmu.write_word(addr, val); clock_cycles += 12; } // Load (SP + n) effective address into HL inline void CPU::LDHL_SP_n(const uint8_t val) { // set flags AF.low &= ~(Z_FLAG); AF.low &= ~(N_FLAG); if ((HL.low & 0x0F) > (MAX_INT_4BIT - (val & 0x0F))) AF.low |= H_FLAG; if (HL.low > (MAX_INT_8BIT - val)) AF.low |= C_FLAG; HL.highlow = SP + val; clock_cycles += 12; } #endif // CPU_H_
true
9f9b35625480c14ea66ce2592d14638007d79453
C++
dskuang/Randomized-Search-Tree
/PA2/benchtree.cpp
UTF-8
4,413
3.28125
3
[]
no_license
/**************************************************************************** Dominic Kuang CSE 100, Winter 2015 cs100wdy 2/5/15 Assignment Two File Name: benchtree.cpp Description: The program benchmarks the performance of a RST implementation, an ordinary BST implementation, and the C++ STL std::set structure (red-black tree). It shows how many comparisons were required to do a successful find operation, in the average case". ****************************************************************************/ #include "RST.hpp" #include "countint.hpp" #include "BST.hpp" #include <set> #include <random> #include <algorithm> using namespace std; /*************************************************************************** % Routine Name : dataStructTester(string tester, int num, string orderType) % File : benchtree.cpp % % Description : This function an insert and find into either a rst, bst, or set. It keeps track of the count and returns that as a double type to the main method % Parameters descriptions : % % name description % ------------------ ------------------------------------------------------ % tester a string of the data structure being tested % num an int to the current amount of N % orderType a string determining shuffled or sorted % <return> a double type ***************************************************************************/ double dataStructTester(string tester, int num, string orderType) { int N = num; string order = orderType; string test = tester; std::vector<countint> v; v.clear(); for (int i = 0; i < N ; ++i) { v.push_back(i); } //checks if order is shuffled if (order == "shuffled") { random_shuffle(v.begin(), v.end()); } std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); //checks if tester is rst if(test == "rst"){ RST<countint> r; for(vit = v.begin(); vit != ven; ++vit){ r.insert(*vit); } countint::clearcount(); for(vit = v.begin(); vit != ven; ++vit) { r.find(*vit); } } //checks if tester is bst else if(test == "bst"){ BST<countint> b; for(vit = v.begin(); vit != ven; ++vit){ b.insert(*vit); } countint::clearcount(); for(vit = v.begin(); vit != ven; ++vit) { b.find(*vit); } } //checks if tester is set else if(test == "set"){ set<countint> s; for(vit = v.begin(); vit != ven; ++vit){ s.insert(*vit); } countint::clearcount(); for(vit = v.begin(); vit != ven; ++vit) { s.find(*vit); } } return countint::getcount(); } int main(int argc, char**argv){ if(argc != 5){ cout<<"Incorrect # of arguments"<<endl; return 1; } string test = argv[1]; string order = argv[2]; int maxSize = atoi(argv[3]); double numRuns = atoi(argv[4]); srand(static_cast<unsigned int>(time(NULL))); cout << "# Benchmarking average number of comparisons for successful find"<< endl; cout << "# Data structure: "<< test << endl; cout << "# Data: "<< order<< endl; cout << "# N is powers of 2, minus 1, from 1 to "<<maxSize<< endl; cout << "# Averaging over "<< numRuns<<" for each N"<<endl; cout << "# "<<endl; cout << setw(6) << right << "# N" << "\t" << setw(16) << right << "avgComps" << setw(16) << right << setiosflags(ios::fixed) << setprecision(6) << "stdev" << endl; //loops through maxsize for (int k = 1, N = 1; N <= maxSize; N = pow(2,++k)-1) { double avgComps = 0; double totalAvg = 0; double stdev = 0; double variance = 0; for (int z = 0; z < numRuns; z++) { double compare = dataStructTester(test,N,order); avgComps += compare/(double)N; totalAvg += pow(compare/(double)N,2); } //calculates stdev avgComps = avgComps/numRuns; totalAvg = totalAvg/numRuns; variance = abs(totalAvg - pow(avgComps,2)); stdev = sqrt(variance); cout << setw(6) << right << N << "\t" << setw(16) << right << avgComps << setw(16) << right << setiosflags(ios::fixed) << setprecision(6) << stdev << endl; } return 0; }
true
c10b7984cfca4c92ed4eb81289279474e5657f06
C++
freesamael/wolf
/include/CTcpConnectionListener.h
UTF-8
1,409
2.96875
3
[]
no_license
/** * \file CTcpConnectionListener.h * \date Apr 27, 2010 * \author samael */ #ifndef CTCPCONNECTIONLISENTER_H_ #define CTCPCONNECTIONLISENTER_H_ #include "AObservable.h" #include "IRunnable.h" #include "CTcpSocket.h" #include "CTcpServer.h" #include "CMutex.h" #include "HelperMacros.h" namespace wolf { /** * A listener that continuously accept incoming connections on given * server socket until setDown() is called. It notifies all observers each * time a new connection is accepted, and clients can use lastAcceptedSocket() * to get the last socket accepted. */ class CTcpConnectionListener: public AObservable, public IRunnable { public: CTcpConnectionListener(CTcpServer *server): _mx(), _done(false), _server(server), _ssock(NULL) {} inline CTcpSocket* lastAcceptedSocket() { _mx.lock(); CTcpSocket *s = _ssock; _mx.unlock(); return s; } inline bool isDone() { _mx.lock(); bool d = _done; _mx.unlock(); return d; } inline void setDone(bool d = true) { _mx.lock(); _done = d; _mx.unlock(); } void run(); private: CTcpConnectionListener(const CTcpConnectionListener &UNUSED(o)): AObservable(), IRunnable(), _mx(), _done(false), _server(NULL), _ssock(NULL) {} CTcpConnectionListener& operator=(const CTcpConnectionListener &UNUSED(o)) { return *this; } CMutex _mx; bool _done; CTcpServer *_server; CTcpSocket *_ssock; }; } #endif /* CTCPCONNECTIONLISENTER_H_ */
true
5b1e13c8135132994e81f72e93c718f5219e5e30
C++
DanielBatesJ/Problem-Solving-Code
/Three Algorithmic Assignments/sticks.cpp
UTF-8
2,813
3.859375
4
[]
no_license
#include <iostream> #include <stdio.h> #include <string> using namespace std; void findLargest(int stickNum) { int i = 0; cout << "Largest Number:"; // The pattern for largest is just ones and sevens based on odd and even number of sticks while(stickNum > 0) { if((stickNum%2 == 1) && (stickNum >= 3)) { stickNum -= 3; cout << "7"; i++; } else { stickNum -= 2; cout << "1"; i++; } } } // The smallest case has a pattern of additions of 7 to numbers, where, past the first case or two, the remaining numbers are just eights void findSmallest(int sticksNum) { int i = 0; cout << "Smallest Number:"; // Special Cases that don't fit any pattern. if(sticksNum == 3) { cout << "7"; return; } if(sticksNum == 4) { cout << "4"; return; } if(sticksNum == 10) { cout << "22"; return; } // Repeating cases based off of mod 7. if(sticksNum % 7 == 2) { cout << "1"; sticksNum = sticksNum-7; while(sticksNum >= 2) { cout << "8"; sticksNum = sticksNum-7; }; return; } // Three and 10 don't follow the pattern so this only effects 17+7x if(sticksNum % 7 == 3) { cout << "200"; sticksNum -= 7; while(sticksNum >= 10) { cout << "8"; sticksNum -= 7; } return; } if(sticksNum % 7 == 4) { cout << "20"; sticksNum = sticksNum-7; while(sticksNum >= 11) { cout << "8"; sticksNum = sticksNum-7; }; return; } if(sticksNum % 7 == 5) { cout << "2"; sticksNum = sticksNum-7; while(sticksNum >= 5) { cout << "8"; sticksNum = sticksNum-7; }; } if(sticksNum % 7 == 6) { cout << "6"; sticksNum = sticksNum-7; while(sticksNum >= 6) { cout << "8"; sticksNum = sticksNum-7; }; } if(sticksNum % 7 == 0) { cout << "8"; sticksNum = sticksNum-7; while(sticksNum >= 7) { cout << "8"; sticksNum = sticksNum-7; }; } if(sticksNum % 7 == 1) { cout << "10"; sticksNum = sticksNum-7; while(sticksNum >= 8) { cout << "8"; sticksNum = sticksNum-7; }; } } int main() { int stickNum = 0; bool check; do{ cout << "This program generates the largest and smallest numbers that can be created given a user-inputed number of \"sticks\".\n" << endl; cout << "\"Sticks\" referes to the line segments that make up numbers on a digital clock.\nFor example...\nThe number \"1\" is made up of two sticks, and the number \"8\" is made up of seven sticks.\n"; cout << "Enter a number of sticks (2 <= x <= 100):"; cin >> stickNum; if((stickNum > 100) && (stickNum < 2)) { cout << "Invalid Input: Make sure to use a number greater than or eqaul to 2, and less than or equal to 100.\n"; check = false; } else { check = true; } }while(!check); findLargest(stickNum); cout << endl; findSmallest(stickNum); cout << endl; return 0; }
true
088dcc25faad8644046cda28fe2e7f2e415b0ab8
C++
AkiraHero/OpenRoadEd
/src/Osg/OSGCameraControls.cpp
UTF-8
6,653
2.625
3
[]
no_license
#include "OSGCameraControls.h" //// Constructor and Destructor //OSGCameraControls::OSGCameraControls() //{ // mSpaceIsPressed=false; //} //OSGCameraControls::~OSGCameraControls() //{} // ///** //* Sets the target node //*/ //void OSGCameraControls::setNode(osg::Node* node) //{ // mNode = node; // if (mNode.get()) // { // const osg::BoundingSphere& boundingSphere=mNode->getBound(); // mModelScale = boundingSphere._radius; // } // if (getAutoComputeHomePosition()) computeHomePosition(); //} // ///** //* Gets the constant target node //*/ //const osg::Node* OSGCameraControls::getNode() const //{ // return mNode.get(); //} // ///** //* Gets the target node //*/ //osg::Node* OSGCameraControls::getNode() //{ // return mNode.get(); //} // ///** //* Goes to the home position //*/ //void OSGCameraControls::home(double /*currentTime*/) //{ // if (getAutoComputeHomePosition()) computeHomePosition(); // computePosition(_homeEye, _homeCenter, _homeUp); //} // ///** //* Goes to the home position //*/ //void OSGCameraControls::home(const osgGA::GUIEventAdapter& ea ,osgGA::GUIActionAdapter& aa) //{ // home(ea.getTime()); // aa.requestRedraw(); // aa.requestContinuousUpdate(false); //} // ///** //* Event handler //*/ //bool OSGCameraControls::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa) //{ // switch(ea.getEventType()) // { // case(osgGA::GUIEventAdapter::KEYDOWN): // // Listens for space key down to set the mSpaceIsDown flag // if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Space) // { // mSpaceIsPressed=true; // } // // If H or h key is pressed while space is down - reset position to home position // if ((ea.getKey()== 'h' || ea.getKey()== 'H') && mSpaceIsPressed) // { // home(ea,aa); // return true; // } // return false; // case(osgGA::GUIEventAdapter::KEYUP): // // Resets the mSpaceIsDown flag // if (ea.getKey()== osgGA::GUIEventAdapter::KEY_Space) // { // mSpaceIsPressed=false; // } // return false; // case(osgGA::GUIEventAdapter::PUSH): // { // flushMouseEvents(); // addMouseEvent(ea); // // if (calcMovement()) us.requestRedraw(); // aa.requestContinuousUpdate(false); // return true; // } // case(osgGA::GUIEventAdapter::DRAG): // { // addMouseEvent(ea); // if (calculateMovement()) aa.requestRedraw(); // aa.requestContinuousUpdate(false); // return true; // } // default: // return false; // } //} // ///** //* Computes the position given eye,center and up vectors //*/ //void OSGCameraControls::computePosition(const osg::Vec3& eye,const osg::Vec3& center,const osg::Vec3& up) //{ // osg::Vec3 lv(center-eye); // // osg::Matrix rotation_matrix = osg::Matrixd::lookAt(eye,center,up); // // mCenter = center; // mDistance = lv.length(); // mRotation = rotation_matrix.getRotate().inverse(); //} // ///** //* Flushh mouse event history //*/ //void OSGCameraControls::flushMouseEvents() //{ // mMouseEvent1=NULL; // mMouseEvent2=NULL; //} ///** //* Add event to mouse event history //*/ //void OSGCameraControls::addMouseEvent(const osgGA::GUIEventAdapter &ea) //{ // mMouseEvent1=mMouseEvent2; // mMouseEvent2=&ea; //} ///** //* Calculate mouse movement //*/ //bool OSGCameraControls::calculateMovement() //{ // // return if less then two events have been added. // if (mMouseEvent1.get()==NULL || mMouseEvent2.get()==NULL) return false; // // double dx = mMouseEvent1->getXnormalized()-mMouseEvent2->getXnormalized(); // double dy = mMouseEvent1->getYnormalized()-mMouseEvent2->getYnormalized(); // // // // return if there is no movement. // if (dx==0 && dy==0) return false; // // unsigned int buttonMask = mMouseEvent2->getButtonMask(); // if (mSpaceIsPressed && ((buttonMask==osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON) || (buttonMask==(osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON|osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)))) // { // // // pan model. // double scale = 0.3f*mDistance; // // osg::Matrixd rotation_matrix; // rotation_matrix.makeRotate(mRotation); // osg::Vec3d sideVector = getSideVector(rotation_matrix); // // // Var1 // //osg::CoordinateFrame coordinateFrame = getCoordinateFrame(mCenter); // //osg::Vec3d localUp = getUpVector(coordinateFrame); // // Var2 // //osg::Matrix position_matrix; // //position_matrix.makeTranslate(mCenter); // //osg::Vec3d localUp = getUpVector(position_matrix); // // Var3 // osg::Vec3d localUp(0,0,1); // // osg::Vec3d forwardVector =localUp^sideVector; // //sideVector = forwardVector^localUp; // // //forwardVector.normalize(); // //sideVector.normalize(); // // osg::Vec3d dv = forwardVector * (dy*scale) + sideVector * (dx*scale); // // mCenter += dv; // // return true; // } // else if (mSpaceIsPressed && buttonMask==osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) // { // // // zoom model. // double scale = 1.0f+dy; // mDistance *= scale; // return true; // // } // else if (mSpaceIsPressed && buttonMask==osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) // { // // osg::Matrix rotation_matrix; // rotation_matrix.makeRotate(mRotation); // osg::Vec3d sideVector = getSideVector(rotation_matrix); // // // Var1 // //osg::CoordinateFrame coordinateFrame = getCoordinateFrame(mCenter); // //osg::Vec3d localUp = getUpVector(coordinateFrame); // // Var2 // //osg::Matrix position_matrix; // //position_matrix.makeTranslate(mCenter); // //osg::Vec3d localUp = getUpVector(position_matrix); // // Var3 // osg::Vec3d localUp(0,0,1); // // //osg::Vec3d forwardVector = localUp^sideVector; // //sideVector = forwardVector^localUp; // // //forwardVector.normalize(); // //sideVector.normalize(); // // osg::Quat rotate_elevation; // rotate_elevation.makeRotate(-dy,sideVector); // // osg::Quat rotate_azim; // rotate_azim.makeRotate(-dx,localUp); // // mRotation = mRotation * rotate_elevation * rotate_azim; // // return true; // // } // // return false; //} // ///** //* Sets the position given a matrix //*/ //void OSGCameraControls::setByMatrix(const osg::Matrixd& matrix) //{ // mCenter = osg::Vec3(0.0f,0.0f,-mDistance)*matrix; // mRotation = matrix.getRotate(); //} ///** //* Sets the position given an inverse matrix //*/ //void OSGCameraControls::setByInverseMatrix(const osg::Matrixd& matrix) //{ // //} ///** //* Gets the matrix //*/ //osg::Matrixd OSGCameraControls::getMatrix() const //{ // return osg::Matrixd::translate(0.0,0.0,mDistance)*osg::Matrixd::rotate(mRotation)*osg::Matrixd::translate(mCenter); //} ///** //* Gets the inverse matrix //*/ //osg::Matrixd OSGCameraControls::getInverseMatrix() const //{ // return osg::Matrixd::translate(-mCenter)*osg::Matrixd::rotate(mRotation.inverse())*osg::Matrixd::translate(0.0,0.0,-mDistance); //}
true
63e4c79124b9a6cd72b7bdb226252d2eb0cb6ebe
C++
liulin2012/myLeetcode
/NextPermutation.cpp
UTF-8
398
2.765625
3
[]
no_license
class Solution { public: void nextPermutation(vector<int>& nums) { int n = nums.size() - 1; while (n != 0 && nums[n] <= nums[n - 1]) n--; if (n != 0) { int val = nums[n - 1]; int m = nums.size() - 1; while (nums[m] <= val) m--; swap(nums[n - 1], nums[m]); } reverse(nums.begin() + n, nums.end()); } };
true
c946a3915363890b7df65aad6bae00e59a62c781
C++
elphastori/pca
/test.cpp
UTF-8
1,353
2.859375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <fstream> #include <sstream> #define CATCH_CONFIG_MAIN //So that catch will define a main method #include "catch.hpp" #include "pca_math.h" using namespace std; using namespace TRNELP001; TEST_CASE("dimension mean") { vector<vector<double>> values = {{1.5, 2.5}, {2.5, 3.5}, {3.5, 4.5}}; SECTION("first dimension") { double expected_mean = 2.5; double calculated_mean = dimension_mean(values, 0); REQUIRE(expected_mean==calculated_mean); } SECTION("second dimension") { double expected_mean = 3.5; double calculated_mean = dimension_mean(values, 1); REQUIRE(expected_mean==calculated_mean); } } TEST_CASE("covariance") { vector<vector<double>> values = {{1.5, 2.5}, {2.5, 3.5}, {3.5, 4.5}}; SECTION("two dimensions (covariance)") { double expected_covariance = 1.0; REQUIRE(expected_covariance==covariance(values, 0, 1)); REQUIRE(expected_covariance==covariance(values, 1, 0)); } SECTION("one dimension (variance)") { double expected_variance_0 = 1.0; double expected_variance_1 = 1.0; REQUIRE(expected_variance_0==covariance(values, 0, 0)); REQUIRE(expected_variance_1==covariance(values, 1, 1)); } }
true
f3da710d3b65ca76e93267a4e91130c73c0e841f
C++
meshell/KataTournamentRunner
/src/kataround_scores.cpp
UTF-8
1,381
2.859375
3
[ "MIT" ]
permissive
#include "tournament_runner/kataround_scores.h" #include <algorithm> #include <numeric> #include <cmath> namespace TournamentRunner { void KataRoundScores::add_kata_score (float score) { if (current_score_ < number_of_kata_scores_per_round) { kata_scores_[current_score_++] = score; } else { throw std::length_error("max number of scores per round reached"); } } float KataRoundScores::get_overall_score () const { const auto init_value = 0.0F; return std::accumulate(std::begin(kata_scores_), std::end(kata_scores_), init_value) - get_maximum_score() - get_minimum_score() - deduction_; } float KataRoundScores::get_maximum_score () const { return (*std::max_element(std::begin(kata_scores_), std::end(kata_scores_))); } float KataRoundScores::get_minimum_score () const { const auto first_zero_entry = std::find_if_not(std::begin(kata_scores_), std::end(kata_scores_), [](float v){return v > 0.0; }); return (*std::min_element(std::begin(kata_scores_), first_zero_entry)); } KataRoundScores::ScoreVectorType KataRoundScores::get_scores() const { ScoreVectorType scores; scores.assign(std::begin(kata_scores_), std::end(kata_scores_)); return scores; } } // namespace
true
6328756622827203b84cda55ac26df4ffc6775e3
C++
15831944/TMS
/GetRouteQuery.cpp
UTF-8
16,389
2.90625
3
[]
no_license
#include "CIS.h" #include <set> void getPathifyConnections( PathifyConnections &pc, CISlocationMapSet &fromTo ) { pc.clear(); register size_t cTotal = 0; register CISlocationMapSet::iterator from, fromEnd; for( from = fromTo.begin(), fromEnd = fromTo.end(); from != fromEnd; ++from ) cTotal += from->second.size(); // Organize the connections reasonably. pc.reserve( cTotal ); for( from = fromTo.begin(), fromEnd = fromTo.end(); from != fromEnd; ++from ) { register std::set<ident_t>::iterator to, toEnd; for( to = from->second.begin(), toEnd = from->second.end(); to != toEnd; ++to ) pc.push_back( std::make_pair(from->first, *to) ); } pathify( pc ); } class IDGraph { public: IDGraph() : hasCycle(false) {} enum VisitedState { White, // Unseen. Grey, // On the current path (used to detect cycles). Black // Fully fathomed previously. }; protected: struct Node; friend struct Node; typedef HashFI<ident_t, Node *> Nodes; struct Node { Node( const ident_t aID ) : id(aID) { reset(); } void reset() { visitedState = White; parent = NULL; } const ident_t id; Node *parent; // Used for backtracking in DFS. Nodes::iterator child; // Current child in DFS. VisitedState visitedState; Nodes out; // Out "arcs" to connecting nodes. }; Nodes nodes; bool hasCycle; // Will be set true after topoSort if the graph has a cycle. public: void connect( const ident_t fromID, const ident_t toID ) { Nodes::iterator from = nodes.find(fromID); if( from == nodes.end() ) from = nodes.insert( fromID, new Node(fromID) ); Nodes::iterator to = nodes.find(toID); if( to == nodes.end() ) to = nodes.insert( toID, new Node(toID ) ); from.data()->out.insert( toID, to.data() ); } void newNode( const ident_t id ) { if( !contains(id) ) nodes.insert( id, new Node(id) ); } bool contains( const ident_t id ) const { return nodes.contains(id); } VisitedState getVisitedState( const ident_t id ) { Nodes::iterator n = nodes.find(id); return n == nodes.end() ? White : n.data()->visitedState; } void setVisitedState( const ident_t id, const VisitedState vs ) { Nodes::iterator n = nodes.find(id); n.data()->visitedState = vs; } void getOutConnections( IDVector &out, const ident_t id ) { out.clear(); Nodes::iterator n = nodes.find(id); if( n != nodes.end() ) { out.reserve( n.data()->out.size() ); for( register Nodes::iterator o = n.data()->out.begin(), oEnd = n.data()->out.end(); o != oEnd; ++o ) out.push_back( *o ); } } void topoSort( IDVector &s, ident_t suggestedStart = 0 ) { s.clear(); s.reserve( nodes.size() ); hasCycle = false; Nodes::iterator n, nEnd; for( n = nodes.begin(), nEnd = nodes.end(); n != nEnd; ++n ) n.data()->reset(); if( !nodes.contains(suggestedStart) ) suggestedStart = *nodes.begin(); bool firstTime = true; for( n = nodes.find(suggestedStart), nEnd = nodes.end(); n != nEnd; ++n ) { if( n.data()->visitedState != White ) continue; // Start the depth-first search. register Node *nCur = n.data(); nCur->parent = NULL; nCur->visitedState = Grey; nCur->child = nCur->out.begin(); do { // Try to extend the path. while( nCur->child != nCur->out.end() ) { register Node *nChild = nCur->child.data(); ++nCur->child; switch( nChild->visitedState ) { case White: break; case Grey: hasCycle = true; // Cycle can be recovered with as follows: // // IDVector idv; // for( Node *nCycle = nCur; nCycle != nChild; nCycle = nCycle->parent ) // idv.push_back( nCycle ); // idv.push_back( nChild ); // // Fallthrough. case Black: continue; } // Found an unvisited child. Extend the DFS path. nChild->parent = nCur; nChild->visitedState = Grey; nChild->child = nChild->out.begin(); nCur = nChild; } // All the children of this node have been visited. // Record its position in the topological sort. s.push_back( nCur->id ); // Backtrack up the path. nCur->visitedState = Black; } while( nCur = nCur->parent ); if( firstTime ) { n = nodes.begin(); firstTime = false; } } // In the DFS, the furthest nodes will be added first. // Reverse the order so that tha furthest nodes are last. std::reverse( s.begin(), s.end() ); } void clear() { register Nodes::iterator n, nEnd; for( n = nodes.begin(), nEnd = nodes.end(); n != nEnd; ++n ) delete n.data(); nodes.clear(); } bool isCyclic() const { return hasCycle; } ~IDGraph() { clear(); } }; typedef HashFI<CISarc *, CISarc *> CISarcCollection; typedef HashObj<IdentHash, TimeVector> LocIDTimes; typedef std::vector< std::vector<size_t> > IndexVectorVector; CISrouteTimesReply *CIS::getRouteTimesReply( const ident_t serviceID, const ident_t routeDirectionID ) { CISserviceCollection::iterator sItr = services.find( serviceID ); if( sItr == services.end() ) return NULL; CISservice *service = sItr.data(); CISrouteCollection::iterator rItr = service->routes.find( routeDirectionID ); if( rItr == service->routes.end() ) return NULL; CISroute *route = rItr.data(); // Check if the timetable is already cached. This sames a lot of processing. if( route->stripes.empty() ) { // Collect all the leave events for this route at each location. LocIDTimes locIDTimes; IDGraph idGraph; ident_t earliestLocID = 0; tod_t tEarliest = 24*60*60*3; CISlocationCollection::iterator loc, locEnd; for( loc = service->locations.begin(), locEnd = service->locations.end(); loc != locEnd; ++loc ) { CISlocation *location = loc.data(); CIScRouteIDEventSet::iterator resItr = location->routeCurb.find(routeDirectionID); if( resItr == location->routeCurb.end() ) continue; const ident_t fromLocID = location->getID(); CIScEventSet::const_iterator event, eventEnd; for( event = resItr->second.begin(), eventEnd = resItr->second.end(); event != eventEnd; ++event ) { register CISarc *a = (*event)->findTravelOutArc(); if( !a ) continue; if( (*event)->t < tEarliest ) { tEarliest = (*event)->t; earliestLocID = fromLocID; } // Add this link to the graph so we can figure out the location sequence with toposort. const ident_t toLocID = a->to->location->getID(); idGraph.connect( fromLocID, toLocID ); // Add the time this route left the location. LocIDTimes::iterator lid; if( (lid = locIDTimes.find(fromLocID)) == locIDTimes.end() ) lid = locIDTimes.insert( fromLocID, TimeVector() ); lid.data().push_back( a->from->t ); // Ensure that the 'to' location and its time is recorded. if( (lid = locIDTimes.find(toLocID)) == locIDTimes.end() ) lid = locIDTimes.insert( toLocID, TimeVector() ); lid.data().push_back( a->to->t ); } } // Topologically sort the location graph to get the stop sequence for this route. IDVector idLocations; idGraph.topoSort( idLocations, earliestLocID ); // Create a link between the location ids and its position in the route. IDVector::const_iterator i, iEnd; HashFI<ident_t, size_t> idIndex; for( i = idLocations.begin(), iEnd = idLocations.end(); i != iEnd; ++i ) idIndex.insert( *i, (unsigned int)(i - idLocations.begin()) ); // Populate the paths of single vehicles through the route. StripeVector stripes; CISarcCollection visitedArcs; for( i = idLocations.begin(), iEnd = idLocations.end(); i != iEnd; ++i ) { const ident_t fromLocID = *i; CISlocation *fromLoc = service->locations[fromLocID]; CIScEventSet &es = fromLoc->routeCurb[routeDirectionID]; CIScEventSet::const_iterator event, eventEnd; for( event = es.begin(), eventEnd = es.end(); event != eventEnd; ++event ) { register CISarc *a = (*event)->findTravelOutArc(); if( !a || visitedArcs.contains(a) ) continue; visitedArcs.insertKey( a ); // Start a new stripe. stripes.push_back( Stripe() ); Stripe &stripe = stripes.back(); stripe.push( i - idLocations.begin(), (*event)->t ); // Create a path following the closest connection times. tod_t tFrom = a->to->t; const ident_t toID = a->to->location->getID(); const size_t iTo = idIndex[toID]; CISlocation *curLoc = service->locations[toID]; if( iTo <= stripe.getLastILoc() ) { // We have a loop of one stop. Ignore the stripe? Better than crashing... stripes.erase( stripes.end()-1, stripes.end() ); continue; } stripe.push( iTo, a->to->t ); bool pathExtended; do { pathExtended = false; // Only search for a leave connection up to the next arrive time. // Find the next arrival time for this route. tod_t tNextArrival = 2 * 24 * 60 * 60; CIScEvent eSearch(tFrom, curLoc, route, service); CIScEventSet &esCur = curLoc->routeCurb[routeDirectionID]; CIScEventSet::const_iterator eventBegin = esCur.lower_bound(&eSearch), eventEnd = esCur.end(); CIScEventSet::const_iterator event; for( event = eventBegin; event != eventEnd; ++event ) { if( (*event)->t <= tFrom ) continue; register CISarc *a = (*event)->findTravelInArc(); if( !a || visitedArcs.contains(a) ) continue; tNextArrival = (*event)->t; break; } // Find the next leave connection. Do not search past the next arrival time. for( event = eventBegin; event != eventEnd; ++event ) { register CISarc *a = (*event)->findTravelOutArc(); if( !a || a->to->t < tFrom || visitedArcs.contains(a) ) continue; if( (*event)->t >= tNextArrival ) // Do not steal the the next vehicle's leave connection. break; visitedArcs.insertKey( a ); const ident_t toID = a->to->location->getID(); const size_t iTo = idIndex[toID]; if( iTo <= stripe.getLastILoc() ) // We have a loop - don't know what to do with this - start a new stripe? break; stripe.push( iTo, a->to->t ); curLoc = service->locations[toID]; tFrom = a->to->t; pathExtended = true; break; } } while( pathExtended ); } } // Sequence the stripes into increasing time by location. std::sort( stripes.begin(), stripes.end() ); // Check if consecutive stripes can be merged. register size_t c; for( c = 0; c < stripes.size() - 1; ++c ) { bool merged = false; const size_t cNext = c + 1; Stripe &sCur = stripes[c], &sNext = stripes[cNext]; if( !merged ) { if( sCur.getLastILoc() == sNext.getFirstILoc() && sCur.getLastTime() < sNext.getFirstTime() ) { sCur.appendAllButFirst( sNext ); merged = true; } } if( !merged ) { if( sNext.iLocTimes[1].t >= sCur.getLastTime() && sCur.onlyFirstLocInCommon(sNext) ) { sCur.appendAllButFirst( sNext ); merged = true; } } if( merged ) stripes.erase( stripes.begin() + cNext ); } // Cache the timetable in the route so we can access it faster later. route->stripes.swap( stripes ); route->idLocations.swap( idLocations ); // Get all the connections in the route. getFromToStops( route->fromTo, serviceID, routeDirectionID ); } // Build the return structure. const StripeVector &stripes = route->stripes; const IDVector &idLocations = route->idLocations; CISrouteTimesReply *rq = new CISrouteTimesReply(); rq->route = route; rq->service = service; const size_t rows = idLocations.size(); const size_t cols = stripes.size(); rq->locationTimes.reserve( rows ); // Initialize everything to invalid times. for( register size_t r = 0; r < rows; ++r ) { rq->locationTimes.push_back( CISlocationTimes(service->locations[idLocations[r]]) ); TimeVector &tv = rq->locationTimes.back().times; tv.resize( cols ); std::fill( tv.begin(), tv.end(), -1 ); } // Fill in the times for each path. for( register size_t c = 0; c < cols; ++c ) { register Stripe::ILocTimeVector::const_iterator il, ilEnd; for( il = stripes[c].iLocTimes.begin(), ilEnd = stripes[c].iLocTimes.end(); il != ilEnd; ++il ) rq->locationTimes[il->iLoc][c] = il->t; } // Transform the connections into a reasonable list of arcs. PathifyConnections connections; getPathifyConnections( connections, route->fromTo ); rq->fromToConnections.reserve( connections.size() ); { for( PathifyConnections::const_iterator c = connections.begin(), cEnd = connections.end(); c != cEnd; ++c ) rq->fromToConnections.push_back( std::make_pair(service->locations[c->first], service->locations[c->second]) ); } return rq; } void CIS::getRouteStopTimes( TripPlanRequestReply::TimeOfDayVector &todv, const ident_t serviceID, const ident_t routeDirectionID, const ident_t locationID ) { todv.clear(); CISserviceCollection::iterator sItr = services.find( serviceID ); if( sItr == services.end() ) return; CISservice *service = sItr.data(); CISrouteCollection::iterator rItr = service->routes.find( routeDirectionID ); if( rItr == service->routes.end() ) return; CISroute *route = rItr.data(); CISlocationCollection::iterator locItr = service->locations.find( locationID ); if( locItr == service->locations.end() ) return; CISlocation *location = locItr.data(); CIScRouteIDEventSet::iterator resItr = location->routeCurb.find(routeDirectionID); if( resItr == location->routeCurb.end() ) return; register CIScEventSet::const_iterator event, eventEnd; for( event = resItr->second.begin(), eventEnd = resItr->second.end(); event != eventEnd; ++event ) { if( (*event)->findTravelOutArc() ) todv.push_back( (*event)->t ); } } void CIS::getRouteStops( CISlocationVector &locv, const ident_t serviceID, const ident_t routeDirectionID ) { locv.clear(); CISserviceCollection::iterator sItr = services.find( serviceID ); if( sItr == services.end() ) return; CISservice *service = sItr.data(); CISrouteCollection::iterator rItr = service->routes.find( routeDirectionID ); if( rItr == service->routes.end() ) return; CISroute *route = rItr.data(); IDGraph idGraph; // Add all the locations to the graph so we can figure out the location sequence. { CISlocationCollection::iterator loc, locEnd; for( loc = service->locations.begin(), locEnd = service->locations.end(); loc != locEnd; ++loc ) { CIScRouteIDEventSet::iterator resItr = loc.data()->routeCurb.find(routeDirectionID); if( resItr == loc.data()->routeCurb.end() ) continue; CIScEventSet::const_iterator event, eventEnd; for( event = resItr->second.begin(), eventEnd = resItr->second.end(); event != eventEnd; ++event ) { register const CISarc *a = (*event)->findTravelOutArc(); if( a ) idGraph.connect( a->from->location->getID(), a->to->location->getID() ); } } } IDVector idLocations; idGraph.topoSort( idLocations ); locv.reserve( idLocations.size() ); for( register IDVector::const_iterator loc = idLocations.begin(), locEnd = idLocations.end(); loc != locEnd; ++loc ) locv.push_back( service->locations.find(*loc).data() ); } void CIS::getFromToStops( CISlocationMapSet &fromToMapSet, const ident_t serviceID, const ident_t routeDirectionID ) { fromToMapSet.clear(); CISserviceCollection::iterator sItr = services.find( serviceID ); if( sItr == services.end() ) return; CISservice *service = sItr.data(); CISrouteCollection::iterator rItr = service->routes.find( routeDirectionID ); if( rItr == service->routes.end() ) return; CISroute *route = rItr.data(); CISlocationCollection::iterator loc, locEnd; for( loc = service->locations.begin(), locEnd = service->locations.end(); loc != locEnd; ++loc ) { CIScRouteIDEventSet::iterator resItr = loc.data()->routeCurb.find(routeDirectionID); if( resItr == loc.data()->routeCurb.end() ) continue; register CIScEventSet::const_iterator event, eventEnd; for( event = resItr->second.begin(), eventEnd = resItr->second.end(); event != eventEnd; ++event ) { register const CISarc *a = (*event)->findTravelOutArc(); if( a ) { CISlocationMapSet::iterator ft = fromToMapSet.find(a->from->location->getID()); if( ft == fromToMapSet.end() ) ft = fromToMapSet.insert( std::make_pair(a->from->location->getID(), std::set<ident_t>() ) ).first; ft->second.insert( a->to->location->getID() ); } } } }
true
0633417b5deeca340185400d456f83e4ef6065f0
C++
SinghVikram97/DP-and-Trees
/DP/A_10. RodCutting.cpp
UTF-8
1,842
3.5625
4
[]
no_license
// http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ // https://hack.codingblocks.com/contests/c/141/1090 // Basic recursion #include <bits/stdc++.h> using namespace std; int maximum_cost(int length_of_rod, vector<int> prices) { if (length_of_rod == 0) { return 0; } int maximum = -1; /// At each step we can take portion of 1 to length of rod part from rod and sell it. /// We can take piece of length=1,2,3,....length_of_rod and calculate for remaining length for (int i = 1; i <= length_of_rod; i++) { maximum = max(maximum, maximum_cost(length_of_rod - i, prices) + prices[i]); } return maximum; } int main() { int length_of_rod; cin >> length_of_rod; vector<int> prices(length_of_rod + 1); /// 1 based indexing for (int i = 1; i <= length_of_rod; i++) { cin >> prices[i]; } cout << maximum_cost(length_of_rod, prices); } // Recursion + memo #include <bits/stdc++.h> using namespace std; int dp[100005]; int maximum_cost(int length_of_rod, vector<int> prices) { if (length_of_rod == 0) { return 0; } if (dp[length_of_rod] == -1) { int maximum = -1; /// At each step we can take portion of 1 to length of rod part from rod and sell it. /// We can take piece of length=1,2,3,....length_of_rod and calculate for remaining length for (int i = 1; i <= length_of_rod; i++) { maximum = max(maximum, maximum_cost(length_of_rod - i, prices) + prices[i]); } dp[length_of_rod] = maximum; } return dp[length_of_rod]; } int main() { int length_of_rod; cin >> length_of_rod; for (int i = 0; i <= length_of_rod; i++) { dp[i] = -1; } vector<int> prices(length_of_rod + 1); /// 1 based indexing for (int i = 1; i <= length_of_rod; i++) { cin >> prices[i]; } cout << maximum_cost(length_of_rod, prices); }
true
7346e55dc060d3027ed29785aab55bfe78da797e
C++
dolphingarlic/CompetitiveProgramming
/Baltic/Baltic 12-brackets.cpp
UTF-8
1,260
3.125
3
[]
no_license
/* Baltic 2012 Brackets - Notice how we basically only care about changing '(' to ')' - Let the "height" of a bracket sequence be the number of unpaired '(' - dp[i][j] = The number of ways to change several '(' in the first i brackets such that the height is never negative and the final height is j = dp[i - 1][j + 1] + (s[i] == '(' ? dp[i - 1][j - 1] : 0) - Notice how dp[i] only depends on 2 values in dp[i - 1], so we don't have to store the first dimension in our DP array - Also, we can use a stack to store our DP, since we know which index the maximum non-zero value is at - This is somehow fast enough to pass - Complexity: O(N^2) */ #include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 9; int dp[30001], tail = 1; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; string s; cin >> n >> s; dp[0] = 1; for (char c : s) { if (c == ')') tail--; else { dp[tail] = (tail > 1 ? dp[tail - 2] : 0); for (int i = tail - 1; i > 1; i--) { dp[i] += dp[i - 2]; if (dp[i] >= MOD) dp[i] -= MOD; } tail++; } } cout << dp[tail - 1]; return 0; }
true
b44b673449ad58c9acc408840d40031818fc902e
C++
tangodown1934/Algorithm-judge
/20150802/4번_기타리스트.cpp
UHC
912
2.546875
3
[]
no_license
#pragma warning(disable:4996) #include <stdio.h> #define SIZE 111 int N, S, M; int vol[SIZE]; int cache[SIZE][111111]; int ans; int max(int a, int b) { if (a < b) return b; return a; } int sol(int idx, int sum) { int i; // if (sum<0 || sum>M) return -1111111; // ʰѴٸ if (idx == N) return sum; // հ int& ret = cache[idx][sum]; if (ret != -1) return ret; ret = max(sol(idx + 1, sum - vol[idx]), sol(idx + 1, sum + vol[idx])); return ret; } int main() { int i, j; scanf("%d %d %d", &N, &S, &M); // input , init for (i = 0; i < N; i++){ scanf("%d", &vol[i]); } for (i = 0; i < SIZE; i++) for (j = 0; j < 111111; j++) cache[i][j] = -1; ans = sol(0, S); if (ans < 0) ans = -1; printf("%d\n", ans); return 0; }
true
3a04db06ee88c016b491350f7d942278a4364973
C++
bryanlov/python_compiler
/src/ast.h
UTF-8
21,129
2.890625
3
[]
no_license
/* -*- mode: C++; c-file-style: "stroustrup"; indent-tabs-mode: nil; -*- */ /* ast.h: Top-level definitions for abstract syntax trees. */ /* Authors: */ #ifndef _AST_H_ #define _AST_H_ #include <string> #include <vector> #include <unordered_set> #include <unordered_map> /** A type representing source locations. Source locations are * represented as artificial line numbers. For locations in the first * source file processed, the Location values correspond to the * actual line numbers, starting from 1. Line numbers then continue * increasing in subsequent files, so that line 1 of the second file * is one greater than the last line of the first. The functions * locationFileName and locationLine convert Locations back to actual * line numbers and file locations. */ typedef long Location; /** An enumeration type giving symbolic names of integer indices * representing all AST types. Used for the node factories. */ enum AST_Index { #define AST_INFO(SYM, NAME) SYM, #include "ast-types.i" #undef AST_INFO }; /** The base type of all nodes in the abstract syntax tree. */ class AST { friend AST_Ptr NODE (AST_Index typeIndex); friend AST_Ptr LEAF (AST_Index typeIndex, const std::string& text, Location loc); friend class AST_Tree; friend class subseq<AST>; public: virtual bool isLeaf() { return false; } /** The encoded location associated with this AST. */ virtual Location location () const; /** Set location () to LOC. */ virtual void setLoc (Location loc); /** Return the identifying syntactic category associated with this * node. This category is used by AST node factories to select * the subtype of AST to use and to access other information * about the node. */ virtual AST_Index typeIndex () const; /** Set typeIndex() to SYN. */ virtual void setTypeIndex (AST_Index syn); /** External name of this node's type, as printed by print. */ virtual const char* astTypeName () const; /** My text content. Generally applicable to leaf nodes only. */ virtual std::string text () const; /** Set text () to TEXT. */ virtual void setText (const std::string& text); /** Append S to the value of text (), if allowed. */ virtual void appendText (const std::string& s); /** The text denoted by THIS, if it is a string literal. This may * differ from text () in that escape sequences have been replaced * with the actual characters they denote. */ virtual std::string denotedText () const; /** Print my representation as an AST on OUT. Use INDENT as the * indentation for subsequent lines if my representation takes up * multiple lines. */ void print (std::ostream& out, int indent); /** True if this node represents a type. */ virtual bool isType (); /** True iff this node represents something that has a type (as * opposed to something that represents a type or module). */ virtual bool hasType (); /** For nodes that represent types, return the node with a static * type that reveals its Type operations. An error on node types * that do not represent types. */ virtual Type_Ptr asType (); /** The number of my children. */ virtual int arity () const; /** My Kth child, numbering from 0. */ virtual AST_Ptr child (int k) const; /** Set my Kth child to C, returning me. */ virtual AST_Ptr setChild (int k, AST_Ptr c); /** My children, as a vector. */ virtual AST_Vect& children (); /** Add C as a new rightmost child, returning me. */ virtual AST_Ptr add (AST_Ptr c); /** Add the elements of V as new rightmost children, returning me. */ virtual AST_Ptr add (const AST_Vect& v); /* Methods and types to make ASTs look like STL containers whose * contents are the child nodes. */ typedef AST_Vect::iterator iterator; typedef AST_Vect::reverse_iterator reverse_iterator; /** A forward iterator through my children. */ virtual iterator begin (); /** A forward iterator to the end of my children. */ virtual iterator end (); /** A reverse iterator through my children. */ virtual reverse_iterator rbegin (); /** A reverse iterator to the beginning of my children. */ virtual reverse_iterator rend (); /* End of container definitions. */ /** Set NODE's type index to TYPEINDEX and register it as an * exemplar. Returns an arbitrary integer so that it may be used * in an initializer. */ static int registerExemplar (AST_Ptr node, AST_Index typeIndex); /* Static Semantics */ /** For nodes representing formal parameters, ids, or attribute * references, the id part. For types, the class id. */ virtual AST_Ptr getId (); /** Returns my currently selected Decl, or nullptr if there is none yet * assigned. */ virtual Decl* getDecl (); /** The type of this entity. */ virtual Type_Ptr getType (); /** Unify my type with TYPE in SUBST, if possible, and return true * iff successful. */ virtual bool setType (Type_Ptr type, Unifier& subst); /** Returns a view of all of Decls. */ virtual const Decl_Vect& getDecls (); /** Returns the number of Decls I currently have. */ virtual int getNumDecls (); /** Add DECL to my set of Decls. */ virtual void addDecl (Decl* decl); /** Set getDecl () to getDecls ()[k]. */ virtual void setDecl (int k); /** Remove my Kth Decl. */ virtual void removeDecl (int k); /** The set of all declarations reachable from me. */ Decl_Set reachableDecls (); /** Add all declarations reachable from me to DECLS. */ virtual void reachableDecls (Decl_Set& decls); /** Set the "freeze" state of everything defined by a "def" in me to * FROZEN. The types of these entities will not be freshened if * they are frozen. */ virtual void freezeDecls (bool frozen); /** Replace all type-variable bindings reachable from me according * to SUBST, returning the result. */ virtual AST_Ptr replaceBindings (const Unifier& subst); /** Do outer-level semantic analysis on me---all scope and type * analysis that applies to definitions and statements that are * not nested inside classes or function definitions. Modifies * the global environment with any definitions I represent. * Returns the modified tree. */ virtual AST_Ptr doOuterSemantics (); /** Add any declarations that I represent to ENCLOSING, the * environment in which I am nested. This does not add * declarations for declarative regions nested within me. */ virtual void collectDecls (Decl* enclosing); /** Add declarations that result from occurrences of type * variables in type attributions to ENCLOSING. */ virtual void collectTypeVarDecls (Decl* enclosing); /** Assuming I am a target of an assignment, add any local * declarations that would result from assignments to me to * ENCLOSING, my enclosing construct. (Used by overridings of * collectDecls.) */ virtual void addTargetDecls (Decl* enclosing); /** Resolve all simple (non-qualified) identifiers in me, assuming * that ENV defines declarations visible at my outer level. * Returns the resolved node. This will differ from THIS when it * denotes a type. */ virtual AST_Ptr resolveSimpleIds (const Environ* env); /** Replace any allocators in me with appropriate NEW nodes, * returning the modified node. */ virtual AST_Ptr resolveAllocators (const Environ* env); /** Resolve all selections of the form CLASS.ID by replacing them * with ID, appropriately decorated, assuming that ENV defines * all visible classes. Returns the modified tree. */ virtual AST_Ptr resolveStaticSelections (const Environ* env); /** Resolve the types of me and my outer-level subcomponents, and resolve * the meanings of unresolved attribute references (OBJ.ID, where * OBJ is not a class, so that the possible meanings of ID depends * on the type of OBJ). When finished, all type variables will have * been removed, save those needed for the types of polymorphic * definitions, and all relevant identifiers will have exactly * one declaration attached. */ virtual void resolveTypesOuter(Decl* context); /** Add all overloaded identifier instances in me to RESOLVER. */ virtual void getOverloadings (Resolver& resolver); /** Extend SUBST to resolve all types in me. CONTEXT denotes my * container. */ virtual void resolveTypes (Decl* context, Unifier& subst); /** If DOMETHODS, resolve all types in my methods (only). Otherwise, * resolve types in all other statements. CONTEXT denotes the * enclosing class. */ virtual void resolveClassStmtTypes (Decl* context, Unifier& subst, bool doMethods); /** Miscellaneous checks, after types are fully resolved. Use LOC * as the construct to "blame" in case of error. */ virtual void typeSpecificChecks (AST_Ptr loc); /** Add all Decls used in me to USED. */ virtual void findUsedDecls (Decl_Set& used); /** Check for an outer-level variable whose type still contains * type variables that are not in ALLOWED. */ virtual void freeTypeVarCheck (const Type_Set& allowed); /** Generate code for me. CONTEXT carries information needed to * perform code generation aside from the AST itself. */ /* local: 1-local variables, 2-method param list */ virtual std::string codeGen (Code_Context& context, int local, std::string enclosing); virtual std::string getInst (Code_Context& context, int local, std::string enclosing); virtual std::string sliceAssign (Code_Context& context, std::string value, int local, std::string enclosing); virtual std::string subscriptAssign(Code_Context& context, std::string value, int local, std::string enclosing); virtual std::pair<std::string, std::string> getParams(Code_Context& context, int local, std::string enclosing); protected: /** Normally, leave node creation to the factory methods Node and * Leaf. */ AST (); /* The following definition is for implementing a "node factory" * function. The idea is to create one "exemplar" object * of each subclass of AST, and to place them in an array indexed * by a syntactic category index, unique to each type. The allows one to * write general functions (see Node and Leaf) that, given a * syntactic category and sequence of child nodes, can produce a * node of the appropriate type by simply looking up the * appropriate exemplar by the syntactic category and then calling * these methods. * * See also the macros FACTORY and EXEMPLAR below. */ /** Create a node of my type with no children. Must be overridden * in each subtype that wants to have an exemplar. The intent is * that the bodies of such an overriding in class T return new T. */ virtual AST_Ptr make () const; struct AST_Printer { AST_Printer (std::ostream& os, int indent); std::ostream& os; int indent; std::unordered_map<AST_Ptr, int> nodeNums; std::unordered_set<AST_Ptr> seen; }; /** Finds circular structures in me and numbers them in PRINTER. */ void findCircular (AST_Printer& printer); /** Print my representation as an AST on OUT according to the parameters * in PRINTER. * * This is an internal printing method that handles general, * potentially circular graph structures, using standard Common * Lisp notation. The first time a node beginning a circular path is * encountered, it is prefixed with #N=. On subsequent * appearances, it is replaced entirely by #N#. */ virtual void print (AST_Printer& printer); /** Used by replaceBindings(SUBST). Replace all type-variable bindings * reachable from me with their referents, except for those * needed to break cycles. Assumes that the traversal started by * replaceBindings() is currently visiting nodes in VISITING. * Returns the modified tree. */ virtual AST_Ptr replaceBindings (const Unifier& subst, AST_Set& visiting); /** Computes my type, which is then cached by getType(). */ virtual Type_Ptr computeType (); private: /** My source location. */ Location loc; /** My syntactic index. */ AST_Index index; /** My type, or nullptr if I have none or it has not been determined. */ Type_Ptr _type; }; /* Factory macros. See the definition of Module_AST in stmts.cc, for * example, for how to use FACTORY and EXEMPLAR to "register" a class * with the system so that an instance of the class may be created by * referring to its AST_Index. */ /** Use this in the class declaration of TYPE to define an appropriate make() * function. */ #define FACTORY(TYPE) TYPE* make () const override { return new TYPE; } /** Use this to create an exemplar for node type TYPE with the given TYPEINDEX. * It creates a dummy static variable and initializes it in a way that * creates the exemplar. */ #define EXEMPLAR(TYPE, TYPEINDEX) \ static int TYPEINDEX ## _EXEMPLAR = AST::registerExemplar(new TYPE, TYPEINDEX) typedef subseq<AST> trimmedAST; class AST_Leaf : public AST { public: bool isLeaf() override; std::string text () const override; void setText (const std::string& text) override; void appendText (const std::string& text) override; protected: void print (AST_Printer& printer) override; private: std::string value; }; class AST_Tree : public AST { public: int arity () const override { return kids.size(); } AST_Ptr child (int k) const override { return kids.at(k); } AST_Ptr setChild (int k, AST_Ptr c) override { kids.at(k) = c; return this; } AST_Vect& children () override { return kids; } AST_Ptr add (AST_Ptr c) override { kids.push_back (c); if (location () == 0) setLoc (c->location ()); return this; } AST_Ptr add (const AST_Vect& v) override { for (auto c : v) add (c); return this; } iterator begin() override { return kids.begin(); } iterator end() override { return kids.end(); } reverse_iterator rbegin() override { return kids.rbegin(); } reverse_iterator rend() override { return kids.rend(); } AST_Ptr make () const override { return new AST_Tree; } private: AST_Vect kids; }; /* TYPES */ /** The supertype of non-leaf nodes representing expressions that have * types. */ class Typed_Tree : public AST_Tree { protected: Type_Ptr computeType () override; bool hasType () override; }; /** The supertype of all tree nodes that represent types. We could * instead define type-specific operations in AST, but that clutters * ASTs with operations that apply only to certain subtypes. This * class is intended to factor out the operations specific to types. */ class Type : public AST_Tree { public: bool isType () override { return true; } /** Overrides AST::asType. Effectively reveals the Type-specific * operations on this node. */ Type_Ptr asType () override { return this; } virtual bool isFunctionType () { return false; } /** Reports an erroneous type reference, since types do not have types. */ Type_Ptr getType () override; /** The id_node representing my class. For function types, * returns a special dedicated ID. nullptr for unbound type * variables and for types that as yet have no Decl node. For * two instances of the same class type, this returns the same * ("canonical") id_node. */ virtual AST_Ptr getId () override; /** My arity, if I am a function type. Otherwise -1. */ virtual int numParams (); /** The type of my Kth parameter, 0 <= K < numParams(). */ virtual Type_Ptr paramType (int k); /** My return type, if I am a function type. Otherwise nullptr. */ virtual Type_Ptr returnType (); /** My number of type parameters. */ virtual int numTypeParams (); /** My Kth type parameter, 0 <= K < numTypeParams(), For a * function type, numTypeParams() == numParams() + 1; the 0th * type parameter is the return type, and the K+1st is * paramType(K). */ virtual Type_Ptr typeParam (int k); /** Set typeParam(K) to TYPE, for 0 <= K < numTypeParams(). * Returns this. */ virtual Type_Ptr setTypeParam (int k, Type_Ptr type); /** For function types, the type of the closure on the first * argument. If THIS is (t1, t2, ..., tn)->t0, then the result is * (t2,...,tn)->t0. Returns nullptr if applied to other kinds of type * or to parameterless function types. If f is a method, then * this is the type of x.f. */ virtual Type_Ptr boundFunctionType (); /** an environment defining all my attributes. */ virtual const Environ* getEnviron (); /** True iff I am a type variable. */ virtual bool isTypeVariable (); /** Add all type variables in me to TYPEVARS. Assumes that * VISITED contains nodes that are already processed, and adds * this node and all descendents to VISITED as needed. */ virtual void getTypeVariables (Type_Set& typeVars, Type_Set& visited); /** Replace all type-variable bindings reachable from me according * to SUBST, returning the result. */ AST_Ptr replaceBindings (const Unifier& subst) override; /** Miscellaneous checks of this type. Use LOC as the location of * any errors. */ void typeSpecificChecks (AST_Ptr loc) override; /** True if I am valid as the first type parameter of a dictionary * type. */ virtual bool isValidAsKey (); protected: AST_Ptr replaceBindings (const Unifier& subst, AST_Set& visiting) override; }; /** Create a type variable named NAME (which should start with $). */ extern Type_Ptr newTypeVar (const std::string& name); /** Create a previously unused type variable, decorated with a unique * Decl. */ extern Type_Ptr newTypeVar (); extern bool unify (Type_Ptr t0, Type_Ptr t1, Unifier& subst); /** Unify a most-general function type having N formals with TYPE, * returning true iff successful. */ extern bool makeFuncType (int n, Type_Ptr type, Unifier& subst); /** Return a most-general function type having N formals. */ extern Type_Ptr makeFuncType (int n); /** Return a most-general method type for a method of class CLAS * having N>=1 formals. */ extern Type_Ptr makeMethodType (int n, Decl* clas); /** Return a copy of TYPE such that all unbound type variables are * replaced by fresh unbound variables. */ extern Type_Ptr freshen (Type_Ptr type); /** Simultaneously freshen all unbound type variables in TYPES, * replacing each with a freshened version. */ extern void freshen (Type_Vect& types); /** ADD(NODE, CHILD1, ...) appends CHILD1, ... to the children of * AST_Ptr NODE, where each CHILDi is either an AST_Ptr or a vector * of AST_Ptr, or a pointer to a vector of AST_Ptr. */ inline AST_Ptr ADD (AST_Ptr node) { return node; } template<typename... Args> AST_Ptr ADD (AST_Ptr node, AST_Ptr c0, Args... rest) { node->add (c0); return ADD(node, rest...); } template<typename... Args> AST_Ptr ADD (AST_Ptr node, const AST_Vect& c0, Args... rest) { node->add (c0); return ADD(node, rest...); } template<typename... Args> AST_Ptr ADD (AST_Ptr node, const AST_Vect* c0, Args... rest) { node->add (*c0); return ADD(node, rest...); } /** NODE(TYPEINDEX, CHILD1, ...) returns an AST_Ptr whose type index is * TYPEINDEX and whose children are CHILD1, ..., where each CHILDi is * either an AST_Ptr or a vector of AST_Ptr, or a pointer to a * vector of AST_Ptr. */ extern AST_Ptr NODE(AST_Index typeIndex); template<typename... Args> AST_Ptr NODE(AST_Index typeIndex, Args... rest) { AST* r = NODE (typeIndex); return ADD (r, rest...); } /** A new AST leaf node, whose type is identified by TYPEINDEX. TEXT * is the semantic content of the node. LOC is its source location. */ extern AST_Ptr LEAF (AST_Index typeIndex, const std::string& text, Location loc = 0); /* Other functions. */ /** Create a new ID token whose text is TEXT, and whose location is LOC. */ extern AST_Ptr makeId (const char* text, Location loc); extern AST_Ptr makeId (const std::string& text, Location loc); /** Used below. */ template<class T> struct unref { typedef T type; }; template<class T> struct unref<T&> { typedef T type; }; #endif
true
54271d6f6964ad69b3c1c95baf2d91656b90da47
C++
furkankaysudu/stack
/stack/main.cpp
UTF-8
1,221
3.390625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <cstdlib> struct stackExmpl{ int sp; unsigned capacity; int *arr; }; struct stackExmpl* createStack(unsigned capacity){ struct stackExmpl* stck = (struct stackExmpl*)malloc(sizeof(struct stackExmpl)); stck->capacity = capacity; stck->sp = -1; stck->arr = (int*)malloc(stck->capacity*sizeof(int)); return stck; }; int overflow(struct stackExmpl*stck){ return stck->sp == stck->capacity-1; } int underflow(struct stackExmpl*stck){ return stck->sp==-1; } void top(stackExmpl*stck,int veri){ if (overflow(stck)) return; stck->arr[++stck->sp]=veri; printf("%d verisi eklendi",veri); } int pop(stackExmpl*stck){ if (underflow(stck)) return -500; return stck->arr[stck->sp--]; } int main(){ struct stackExmpl*stck = createStack(100); top(stck,10); printf(" %d \n",stck->sp); top(stck,20); printf(" %d \n",stck->sp); top(stck,30); printf(" %d \n",stck->sp); printf("%d verisi yigindan alindi.\n",pop(stck)); printf("%d verisi yigindan alindi.\n",pop(stck)); printf("%d verisi yigindan alindi.\n",pop(stck)); return 0; }
true
5c491520ff0e3d2a259d5f78a09415fb994b9cbd
C++
niamrouzwest/11_lab
/lab_11.cpp
UTF-8
3,283
3.265625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <conio.h> #include "lab_11.h" int Priority(char c) { switch (c) { case '+': case '-': return 1; case '*': case '/': return 2; } return 100; } PNode_t MakeTree(char Expr[], int first, int last) { int MinPrt, i, k, prt; int nest = 0; PNode_t Tree = new Node; MinPrt = 100; for (i = first; i <= last; i++) { if (Expr[i] == '(') { nest++; continue; } if (Expr[i] == ')') { nest--; continue; } if (nest > 0) continue; prt = Priority(Expr[i]); if (prt <= MinPrt) { MinPrt = prt; k = i; } } if (MinPrt == 100) if (Expr[first] == '(' && Expr[last] == ')') { free(Tree); return MakeTree(Expr, first + 1, last - 1); } else { k = last - first + 1; strncpy(Tree->data, Expr + first, k); Tree->data[k] = '\0'; Tree->left = NULL; Tree->right = NULL; return Tree; } Tree->data[0] = Expr[k]; Tree->data[1] = '\0'; Tree->left = MakeTree(Expr, first, k - 1); Tree->right = MakeTree(Expr, k + 1, last); return Tree; } float CalcTree(PNode_t Tree) { float num1, num2; if (!Tree->left) return atof(Tree->data); num1 = CalcTree(Tree->left); num2 = CalcTree(Tree->right); switch (Tree->data[0]) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; } return 0; } void LPK(PNode_t Tree) { if (Tree) { LPK(Tree->left); LPK(Tree->right); printf("%s ", Tree->data); } } void KLP(PNode_t Tree) { if (Tree) { printf("%s ", Tree->data); KLP(Tree->left); KLP(Tree->right); } } void LKP(PNode_t Tree) { if (Tree) { LKP(Tree->left); printf("%s ", Tree->data); LKP(Tree->right); } } int maxDepth(struct Node* Tree) { if (Tree == NULL) return 0; else { int lDepth = maxDepth(Tree->left); int rDepth = maxDepth(Tree->right); if (lDepth > rDepth) return(lDepth + 1); else return(rDepth + 1); } } int NodeCount(struct Node* Tree) { if (Tree->left == NULL && Tree->right == NULL) return 1; int left, right; if (Tree->left != NULL) left = NodeCount(Tree->left); else left = 0; if (Tree->right != NULL) right = NodeCount(Tree->right); else right = 0; return left + right + 1; } void print_Tree(PNode_t tree, int level) { if (tree) { print_Tree(tree->left, level + 1); for (int i = 0; i < level; i++) std::cout << " "; std::cout << tree->data << std::endl; print_Tree(tree->right, level + 1); } } void DeleteTree(struct Node* Tree) { DeleteTree(Tree->left); DeleteTree(Tree->right); delete Tree; }
true
b340569d75885d04d19db1eac84b67bfdcf07b86
C++
drake200120xx/ConStorm
/ConStorm/src/input/input_function.cpp
UTF-8
602
2.890625
3
[ "Apache-2.0" ]
permissive
/* Code by Drake Johnson */ #include "../../include/cons/input/input_function.hpp" namespace cons { template <> std::string input<std::basic_string<char>>( std::function<bool(std::string)> valid_func, const std::string& invalid_msg) { std::string user_input; bool first_loop = true; do { if (first_loop) { // Suppresses error msg on loop's first iteration first_loop = false; } else { // Error msg for invalid input. prompt(invalid_msg); } std::getline(std::cin, user_input); } while (!valid_func(user_input)); return user_input; } } // namespace cons
true
e6fd43b7b2951159ea7b8cd8123941157fdd777f
C++
crazycracker/Competitive-Programming-Codes
/change_the_signs2.cpp
UTF-8
2,195
3.03125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void changeTheSigns(long long int arr[], int n, map<int,bool> m){ long long int temp; long long int prefixSum[n+2]; prefixSum[0] = prefixSum[n+1] = 0; if(m[1]) prefixSum[1] = -arr[1]; else prefixSum[1] = arr[1]; for(int i = 2; i <= n; i++){ if(m[i]) prefixSum[i] = prefixSum[i-1] - arr[i]; else prefixSum[i] = prefixSum[i-1] + arr[i]; } for(int i = 3; i <= n; i++){ for(int j = i; j <= n; j++){ temp = prefixSum[j] - prefixSum[j-i]; //cout<<j-i<<" "<<j<<" "<<"Sum = "<<temp<<endl; if(temp > 0) continue; else{ long long int index = -1, temp1 = INT_MIN; for(int k = j-i+1; k <= j; k++){ if(m[k] && arr[k] > temp1 && arr[k] >= (1-temp)) { temp1 = arr[k]; index = k; } } if(index != -1){ m[index] = false; //cout<<index<<endl; for(int k = index; k <= n; k++){ prefixSum[k] += (2*arr[index]); } } } } } //unsigned long long int sum = 0; for(int i = 1; i <= n; i++) { if(m[i]){ //sum -= arr[i]; //arr[i] = -arr[i]; cout<<"-"<<arr[i]<<" "; }else{ //sum += arr[i]; cout<<arr[i]<<" "; } } cout<<endl; //cout<<sum<<" "<<prefixSum[n]<<endl; return; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; long long int arr[n+2],sum = 0, temp = 0; arr[0] = arr[n+1] = INT_MAX; for(int i = 1; i <= n; i++){ cin>>arr[i]; } map<int,bool> m; for(int i = 1; i <= n; i++){ if((arr[i] < arr[i-1]) && (arr[i] < arr[i+1])){ m[i] = true; }else{ m[i] = false; } } changeTheSigns(arr,n,m); } }
true
4eb60a4db4d6405079ebcd2de8053c0ac4e58365
C++
jakebills1/cpp_practice
/chapter_4/questions/4.19/lib/question_4.19.cpp
UTF-8
877
4.09375
4
[]
no_license
#include <iostream> using namespace std; int main() { int counter = 1; // keeps track of loop repeats int largest; // stores largest inputted number int second_largest; // stores second largest inputted number int input; // stores user input each loop while (counter < 11) { cout << "Enter a number: "; cin >> input; if (counter != 1) { // do comparisons if (input > largest) { largest = input; } else if (input > second_largest) { second_largest = input; } } else { // the first time the loop runs, initialize variables as user input, because no comparison largest = input; second_largest = input; } counter++; } cout << "The largest number you entered was " << largest << "\nthe second largest was " << second_largest << endl; }
true
4ef0e51ddae458c4a1c3f09e2262602de1903f82
C++
natallem-ITMO/Algo-labs
/Semester2/Lab3/J_mine.cpp
UTF-8
3,068
2.640625
3
[]
no_license
/* #pragma GCC optimize("Ofast,no-stack-protector") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("fast-math") #pragma GCC optimize("section-anchors") #pragma GCC optimize("profile-values,profile-reorder-functions,tracer") #pragma GCC optimize("vpt") #pragma GCC optimize("rename-registers") #pragma GCC optimize("move-loop-invariants") #pragma GCC optimize("unswitch-loops") #pragma GCC optimize("function-sections") #pragma GCC optimize("data-sections") #pragma GCC optimize("branch-target-load-optimize") #pragma GCC optimize("branch-target-load-optimize2") #pragma GCC optimize("btr-bb-exclusive") //#include <fstream> #include <iostream> #include <vector> #include <string> #include <stdio.h> #include <cmath> #include <iomanip> #include <set> #include <unordered_set> #include <unordered_map> using namespace std; //std::ifstream cin("a.in"); //std::ofstream cout("a.out"); int n; vector<bool> is_centroid; vector<vector<int>> sons; vector<int> father; vector<int> size_tree; vector<bool> visited; void get_size(int vertex){ visited[vertex] = true; size_tree[vertex] = 1; for (int x : sons[vertex]){ if (!is_centroid[x] && !visited[x]){ get_size(x); size_tree[vertex] += size_tree[x]; } } } int find_centroid(int vertex, int size_of_tree){ visited[vertex] = true; int max_son = -1; for (int x : sons[vertex]){ if (!is_centroid[x] && !visited[x]){ if (size_tree[x] > (size_of_tree/2)){ if (max_son == -1 || size_tree[max_son] < size_tree[x]) max_son = x; } } } if (max_son!=-1) return find_centroid(max_son, size_of_tree); return vertex; } int get_centroid_from_root(int vertex){ for (int i = 0; i <=n ; i++){ visited[i] = false; size_tree[i] = 1; } get_size(vertex);//vertex not centroid for (int i = 0; i <=n ; i++){ visited[i] = false; } int centroid = find_centroid(vertex, size_tree[vertex]); is_centroid[centroid] = true; return centroid; } int centroid_decompose(int vertex){ int cur_centoid = get_centroid_from_root(vertex); for (int x : sons[cur_centoid]){ if (!is_centroid[x]){ int child = centroid_decompose(x); father[child] = cur_centoid; } } return cur_centoid; } int main123(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n; vector<int> sample; for (int i = 0; i <=n; i++){ is_centroid.push_back(false); sons.push_back(sample); father.push_back(0); visited.push_back(false); size_tree.push_back(1); } for (int i = 1; i < n; i++){ int u, v; cin >> u >> v; sons[u].push_back(v); sons[v].push_back(u); } //int res = get_centroid_from_root(1, sons); centroid_decompose(1); for (int i = 1; i <= n; i ++){ cout << father[i] << " "; } }*/
true
20a75df643e18834fcb177e7f4054b5a79352ce8
C++
farabiahmed/MachineLearningFramework
/src/Miscellaneous/SmartVector.cpp
UTF-8
5,336
3.5
4
[]
no_license
/* * Vector.cpp * * Created on: Mar 8, 2017 * Author: farabiahmed */ #include "Miscellaneous/SmartVector.hpp" SmartVector::SmartVector(int N) { // TODO Auto-generated constructor stub dimension = N; elements = new double[dimension]; index = -1; // initially undefined. } SmartVector::SmartVector() { // TODO Auto-generated constructor stub dimension = 0; elements = nullptr; index = -1; // initially undefined. } // Copy Constructor (Rule Of Three #2) SmartVector::SmartVector(const SmartVector& other) : elements(new double[other.dimension]),dimension(other.dimension),index(other.index) { // copy element by element for (int var = 0; var < dimension; ++var) { elements[var] = other.elements[var]; } } // Assignment Operator (Rule Of Three #3) SmartVector& SmartVector::operator=(const SmartVector& other) { // Check for self-assignment if (this != &other) { // release memory first delete[] elements; elements = nullptr; // Start To Copy this->dimension = other.dimension; this->index = other.index; elements = new double[dimension]; // copy element by element for (int var = 0; var < dimension; ++var) { elements[var] = other.elements[var]; } } return *this; } const bool SmartVector::operator==(const SmartVector& other) const { // This operator just consider elements, not the index // that indicates the sequence number its set that is belonging to. if(dimension!=other.dimension) { throw std::invalid_argument( "SmartVector operator== vector dimensions mismatched." ); } for (int i = 0; i < dimension; ++i) { if(elements[i]!=other.elements[i]) return false; } return true; } const SmartVector SmartVector::operator+(const SmartVector& other) const { if(dimension!=other.dimension) { throw std::invalid_argument( "vector dimensions mismatched." ); } SmartVector vec(dimension); for (int i = 0; i < dimension; ++i) { vec.elements[i] = elements[i] + other.elements[i]; } return vec; } const SmartVector SmartVector::operator-(const SmartVector& other) const { if(dimension!=other.dimension) { throw std::invalid_argument( "vector dimensions mismatched." ); } SmartVector vec(dimension); for (int i = 0; i < dimension; ++i) { vec.elements[i] = elements[i] - other.elements[i]; } return vec; } const SmartVector SmartVector::operator*(double scalar) const { SmartVector result(dimension); for (int i = 0; i < dimension; ++i) { result.elements[i] = elements[i] * scalar; } return result; } // Non-Member Function to handle left-hand-side multiplication SmartVector operator*(double scalar, const SmartVector& vec) { SmartVector result(vec.dimension); for (int i = 0; i < vec.dimension; ++i) { result.elements[i] = vec.elements[i] * scalar; } return result; } void SmartVector::Initialize(void) { for (int i = 0; i < dimension; ++i) { elements[i] = 0; } } void SmartVector::Initialize(double val) { for (int i = 0; i < dimension; ++i) { elements[i] = val; } } int SmartVector::size() const { return dimension; } double SmartVector::Magnitude() const { double sum; for (int i = 0; i < dimension; i++) { sum += elements[i]*elements[i]; } return sqrt(sum); } void SmartVector::Print() const { // Inform user that it is the begining. cout<< endl <<"Printing Elements of The Vector:"<<endl; // Print Index of vector in its own space cout<<" Index in its space: " << index << endl; // Print each element of the vector for (int var = 0; var < dimension; ++var) { cout<<" Element " << var << " :" << elements[var] << endl; } // Inform user that it is the end. cout<<" End of vector."<<endl<<endl; } // Destructor (Rule Of Three #1) SmartVector::~SmartVector() { // matching pair of allocators // + malloc/free // + new/delete // + new[]/delete[] // release memory delete[] elements; } double SmartVector::InnerProduct(const SmartVector& v1, const SmartVector& v2) { double sum=0.0; if(v1.dimension!=v2.dimension) { throw std::invalid_argument( "vector dimensions mismatched." ); } for (int i = 0; i < v1.dimension; ++i) { sum += v1.elements[i] * v2.elements[i]; } return sum; } SmartVector SmartVector::Plus(const SmartVector& v1, const SmartVector& v2) { SmartVector sumVec(v1.dimension); if(v1.dimension!=v2.dimension) { throw std::invalid_argument( "vector dimensions mismatched." ); } for (int i = 0; i < v1.dimension; ++i) { sumVec.elements[i] = v1.elements[i] + v2.elements[i]; } return sumVec; } SmartVector SmartVector::Combine(const SmartVector& v1, const SmartVector& v2) { SmartVector comVec(v1.size()+v2.size()); for (int i = 0; i < v1.size(); ++i) { comVec.elements[i] = v1.elements[i]; } for (int i = 0; i < v2.size(); ++i) { comVec.elements[i+v1.size()] = v2.elements[i]; } return comVec; } vector<SmartVector> SmartVector::Split(const SmartVector& vec, const int n) { if(vec.dimension % n != 0) { throw std::invalid_argument( "SmartVector split: vector dimensions mismatched." ); } // Get the size of the vectors that will be produced. int new_size = vec.dimension / n; vector<SmartVector> ret; for (int i = 0; i < vec.size(); i+=new_size) { SmartVector s(new_size); for (int j = 0; j < new_size; ++j) { s.elements[j] = vec.elements[i+j]; } ret.push_back(s); } return ret; }
true
40f8fb7753414cf28b460b479834fb94f2c9307c
C++
haowenz/chromap
/src/index_utils.h
UTF-8
3,780
2.671875
3
[ "MIT" ]
permissive
#ifndef INDEX_UTILS_H_ #define INDEX_UTILS_H_ #include "khash.h" // Note that the max kmer size is 28 and its hash value is always saved in the // lowest 56 bits of an unsigned 64-bit integer. When an element is inserted // into the hash table, its hash value is left shifted by 1 bit and the lowest // bit of the key value is set to 1 when the minimizer only occurs once. So // right shift by one bit is lossless and safe. #define KHashFunctionForIndex(a) ((a) >> 1) #define KHashEqForIndex(a, b) ((a) >> 1 == (b) >> 1) KHASH_INIT(/*name=*/k64, /*khkey_t=*/uint64_t, /*khval_t=*/uint64_t, /*kh_is_map=*/1, /*__hash_func=*/KHashFunctionForIndex, /*__hash_equal=*/KHashEqForIndex); namespace chromap { struct RepetitiveSeedStats { uint32_t repetitive_seed_length = 0; uint32_t previous_repetitive_seed_position = std::numeric_limits<uint32_t>::max(); int repetitive_seed_count = 0; }; inline static uint64_t GenerateHashInLookupTable(uint64_t minimizer_hash) { return minimizer_hash << 1; } inline static uint64_t GenerateEntryValueInLookupTable( uint64_t occurrence_table_offset, uint32_t num_occurrences) { return (occurrence_table_offset << 32) | num_occurrences; } inline static uint32_t GenerateOffsetInOccurrenceTable(uint64_t lookup_value) { return lookup_value >> 32; } inline static uint32_t GenerateNumOccurrenceInOccurrenceTable( uint64_t lookup_table_entry_value) { return static_cast<uint32_t>(lookup_table_entry_value); } inline static uint64_t SequenceIndexAndPositionToCandidatePosition( uint64_t sequence_id, uint32_t sequence_position) { return (sequence_id << 32) | sequence_position; } inline static uint64_t GenerateCandidatePositionFromOccurrenceTableEntry( uint64_t entry) { return entry >> 1; } inline static bool IsSingletonLookupKey(uint64_t lookup_key) { return (lookup_key & 1) > 0; } // Only used in Index to merge sorted candidate position lists using heap. struct CandidatePositionWithListIndex { uint32_t list_index; uint64_t position; CandidatePositionWithListIndex(uint32_t list_index, uint64_t position) : list_index(list_index), position(position) {} bool operator<(const CandidatePositionWithListIndex &h) const { // The inversed direction is to make a min-heap. return position > h.position; } }; inline static void HeapMergeCandidatePositionLists( const std::vector<std::vector<uint64_t>> sorted_candidate_position_lists, std::vector<uint64_t> &candidate_positions) { std::priority_queue<CandidatePositionWithListIndex> heap; std::vector<uint32_t> candidate_position_list_indices( sorted_candidate_position_lists.size(), 0); for (uint32_t li = 0; li < sorted_candidate_position_lists.size(); ++li) { if (sorted_candidate_position_lists[li].size() == 0) { continue; } heap.emplace(li, sorted_candidate_position_lists[li][0]); } while (!heap.empty()) { const CandidatePositionWithListIndex min_candidate_position = heap.top(); heap.pop(); candidate_positions.push_back(min_candidate_position.position); ++candidate_position_list_indices[min_candidate_position.list_index]; const uint32_t min_candidate_position_list_index = candidate_position_list_indices[min_candidate_position.list_index]; const std::vector<uint64_t> &min_sorted_candidate_position_list = sorted_candidate_position_lists[min_candidate_position.list_index]; if (min_candidate_position_list_index < min_sorted_candidate_position_list.size()) { heap.emplace(min_candidate_position.list_index, min_sorted_candidate_position_list [min_candidate_position_list_index]); } } } } // namespace chromap #endif // INDEX_UTILS_H_
true
bb6745374e05a76f29477106b56ef40a83464599
C++
atupal/oj
/poj/2409_Let_it_Bead_置换群_伯恩赛德定理.cpp
UTF-8
1,734
3.078125
3
[ "MIT" ]
permissive
/* 对于旋转置换群,群内置换的总个数显而易见是n个(转n次就返回到自己了嘛),第i个置换中循环节的个数可以用dfs搜索出来,不过有直接的结论,循环节个数应该是gcd(n,i)个,这个结论所有博客都给出了,但是几乎都没给证明(大神都觉得太显而易见了吧)。 对于翻转置换,看上面的那个图,它已经给了你很大提示,找循环节的关键是找对称轴。这里n要分奇偶性。 当n为奇数,那么对称轴就是每个点和圆心的连线,共n条(观察第二个图),那么显然除了这个点没变,其他的点都跟对称的那个点置换了,所以循环节的个数是(n-1)/2+1。 当n为偶数,那么对称轴有每个点和对面的点的连线,共n/2条,显然除了对称轴上的两个点,其余点都跟对面的点置换了循环节的个数是(n-2)/2+2,两个相邻点中点和圆心的连线也是n/2条,显然每个点都跟对面的点置换了,循环节的个数是n/2,n为偶也是n条对称轴, */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int n, c; typedef long long int64; int64 gcd(int64 a, int64 b) { if (b == 0) return a; return gcd(b, a%b); } void solve () { if (n == 0) { printf("0\n"); return; } int64 sum = 0; for (int i = 0; i < n; ++ i) { sum += (int64) pow(c, gcd(n, i) * 1.0); } if (n&1) sum += (int64) pow(c, (n+1)/2*1.0) * n; else sum += (int64) pow(c, (n-2)/2+2.0) * n/2 + (int64) pow(c, n/2.0) * n/2; sum /= n*2; printf("%lld\n", sum); } int main() { for (;;) { scanf("%d %d", &c, &n); if (n+c==0) break; solve(); } return 0; }
true
f45e7cc562be969d09a901dc172abe0a0b231197
C++
phhusson/STpp
/lib/RPC.cpp
UTF-8
1,728
2.65625
3
[]
no_license
#include "RPC.h" #include <Tasks.h> #include <Log.h> RPC::RPC(): in(NULL), out(NULL) { } RPC& RPC::setStream(IStream* in, OStream* out) { this->in = in; this->out = out; return *this; } void RPC::waitIngoing() { log << "Ingoing thread started" << endl; while(true) { do { in->wait(); log << "Received something" << endl; } while(!running.tryTake()); log << "Notify main thread" << endl; ingoing = true; signalIncoming.give(); } } void RPC::handleIncoming() { unsigned char c; unsigned char id; log << "Received packet" << endl; *in >> c; //Not a start of frame if(c != 0xa5) return; *in >> id; if(id>sizeof(cbs)/sizeof(cbs[0])) return; unsigned char checksum = 0; char buf[128]; unsigned char len; *in >> len; if(len > sizeof(buf)) { return; } for(int i=0; i<len; ++i) { *in >> buf[i]; checksum+=buf[i]; } *in >> c; #if 0 if(c != (unsigned char)(~checksum)) { //NACK bad checksum *out << (char) 0xa5 << (char) 0xf2; return; } #endif if(cbs[id]) { cbs[id](len, buf); //ACK *out << (char) 0xa5 << (char) 0xf0; } else { //NACK not found *out << (char) 0xa5 << (char) 0xf1; } } void RPC::handleOutgoing() { } void RPC::runLogic() { signalIncoming.tryTake(); while(true) { running.give(); ingoing = false; log << "Waiting for signal" << endl; signalIncoming.take(); log << "Got a signal" << endl; if(ingoing) { log << "Incoming signal" << endl; handleIncoming(); } else { log << "Outgoing signal" << endl; handleOutgoing(); } } } void RPC::run() { Task Ingoing([this]() { waitIngoing();}, "Ingoing RPC", 128); runLogic(); } RPC& RPC::registerClass(int id, Callback cb) { cbs[id] = cb; return *this; }
true
3af092e2a0c9d34c2fd172c935dcf2318ecc3416
C++
wagulu/cocos2dx_sanguo_heroes
/SanguoClient/frameworks/runtime-src/Classes/battle/system/hero/States/StateHeroDizzy.h
UTF-8
2,837
2.609375
3
[]
no_license
// // StateHeroDizzy.h // Game // // Created by fu.chenhao on 3/16/15. // // #ifndef __STATE_HERO_DIZZY_H__ #define __STATE_HERO_DIZZY_H__ #include "IState.h" #include "BattleConfig.h" #include "BattleComponent.h" #include "DizzyAction.h" #include "DizzyCondition.h" class DizzyActionBuilderBase; class DizzyConditionBuilderBase; class StateHeroDizzy : public IState { public: enum RESULT { WORKING, OVER, }; RESULT m_result = WORKING; StateHeroDizzy(const BattleConfig::HeroDizzyData& dizzyData, const BattleConfig::HeroDizzyConfig& dizzyConfig); virtual ~StateHeroDizzy(); virtual int getStateCode() { return BattleConfig::GENERAL_DIZZY; } virtual void enter(entityx::Entity& entity); virtual void exit(entityx::Entity& entity); virtual int update(entityx::Entity& entity, double dt); virtual bool isDelegateState(); virtual bool isDelegateStateWorking(); inline bool allowBreakByAnotherDizzy() { return m_dizzyConfig.allowBreakByAnotherDizzy; } inline const std::vector<DizzyAction*>& getActions() { return m_actions; }; private: std::vector<DizzyAction*> m_actions; std::vector<DizzyCondition*> m_conditions; BattleConfig::HeroDizzyData m_dizzyData; BattleConfig::HeroDizzyConfig m_dizzyConfig; static std::map<std::string, DizzyConditionBuilderBase*> s_conditionMap; static std::map<std::string, DizzyActionBuilderBase*> s_actionMap; static bool s_inited; void clearAllActions(); void clearAllConditions(); void addCondition(BattleConfig::HeroDizzyConditionConfig* pConfig); void addAction(BattleConfig::HeroDizzyActionConfig* pConfig); bool checkConditionComplete(); static bool initConditionsAndActions(); template<typename DizzyConditionClass> static void registerDizzyCondition(const std::string& key); template<typename DizzyActionClass> static void registerDizzyAction(const std::string& key); }; class DizzyActionBuilderBase { public: virtual ~DizzyActionBuilderBase() {}; virtual DizzyAction* build() = 0; }; template<class DizzyActionClass> class DizzyActionBuilder : public DizzyActionBuilderBase { public: DizzyActionBuilder() {}; ~DizzyActionBuilder() {}; DizzyAction* build() override { return new DizzyActionClass(); } }; class DizzyConditionBuilderBase { public: virtual ~DizzyConditionBuilderBase() {}; virtual DizzyCondition* build() = 0; }; template<class DizzyConditionClass> class DizzyConditionBuilder : public DizzyConditionBuilderBase { public: DizzyConditionBuilder() {}; ~DizzyConditionBuilder() {}; DizzyCondition* build() override { return new DizzyConditionClass(); } }; #endif /* defined(__STATE_HERO_DIZZY_H__) */
true
f23d6ff5f02185817d3209a91ef9d86b154f51da
C++
mwharris/Accelerated-C-Exercises
/Chapter14/Chap14/Chap14/Str.h
UTF-8
2,453
3.8125
4
[]
no_license
#ifndef STR_H #define STR_H #include <iterator> #include "Vec.h" #include "Ptr.h" class Str { //Input operator overload friend std::istream& operator>> (std::istream& is, Str& str); public: typedef Vec<char>::size_type size_type; //Default empty constructor Str() : data(new Vec<char>) {} //Constructor: Initialize a string of n occurrences of c Str(size_type n, char c) : data(new Vec<char>(n, c)) {} //Constructor: Initialize a string given an array of char Str(const char* c) : data(new Vec<char>) { std::copy(c, c + std::strlen(c), std::back_inserter(*data)); } //Constructor: Initialize a string with the values given between two iterators template <class In> Str(In begin, In end) : data(new Vec<char>){ std::copy(begin, end, std::back_inserter(*data)); } //Index operator overloads char& operator[] (size_type n) { //Make unique since this function is not const and the value can be updated data.make_unique(); return (*data)[n]; } const char& operator[] (size_type n) const { return (*data)[n]; } //Concatenate operator overload Str& operator+= (const Str& s) { //Make sure we are a unique instance data.make_unique(); //Simply copy the data from the input Str to this Str std::copy(s.data->begin(), s.data->end(), std::back_inserter(*data)); return *this; } //Utility functions //Note: this should be const so const Str's can call this fine size_type size() const { return data->size(); } private: Ptr<Vec<char>> data; }; //Input operator overload std::istream& operator>> (std::istream& is, Str& str) { //Clear the Str's data str.data->clear(); //Skip over any whitespace in the istream char c; while (is.get(c) && isspace(c)) {} //If there are characters left to read if (is) { //Keep reading characters until we reach a space OR end-of-file do str.data->push_back(c); while (is.get(c) && !isspace(c)); //If we ended because we hit a space if (is) { //Undo the get() on the space is.unget(); } } return is; } //Output operator overload std::ostream& operator<< (std::ostream& os, const Str& s) { //Read every character of the Str into the output stream for (Str::size_type i = 0; i != s.size(); i++) { os << s[i]; } return os; } //Concatenation overload Str operator+ (const Str& left, const Str& right) { //Create a new Str Str ret = left; //Use the += copy operator to concatenate the two ret += right; return ret; } #endif // !STR_H
true
f131768203eeba6d63a3d25d2f73ed1596bda46b
C++
pmannil/my-arduino-codes
/sketch_jan26d.ino
UTF-8
479
2.875
3
[]
no_license
unsigned long previousMillis[3]; int led1=3; int led2=5; int led3=9; void setup() { pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); } void loop() { BlinkLed(led1, 10, 0); BlinkLed(led2, 100, 1); BlinkLed(led3, 1000, 2); } void BlinkLed (int led, int interval, int array){ if ((millis() - previousMillis[array]) >= interval){ previousMillis[array]= millis(); digitalWrite(led, !digitalRead(led)); } }
true
5c8f81134b2c7afbfee2957458d82898b511b36f
C++
useyourfeelings/POJ
/1543/1245003_AC_327MS_260K.cc
UTF-8
872
3.171875
3
[]
no_license
#include<iostream> #include<vector> #include<cmath> using namespace std; struct ct { ct(float aa, float bb, float cc, float dd):a(aa),b(bb),c(cc),d(dd){} float a; float b; float c; float d; }; int main() { float a, b, c, d, n; vector<ct> vct; for(a = 1; a <= 100; a++) { for(b = 2; b < a; b++) { for(c = b; c < a; c++) { for(d = c; d < a; d++) { if(pow(a, 3) == pow(b, 3) + pow(c, 3) + pow(d, 3)) vct.push_back(ct(a, b, c, d)); } } } } cin>>n; int s = vct.size(); for(int i = 0; i < s; i++) { if(vct[i].a > n) break; cout<<"Cube = "<<vct[i].a<<", Triple = (" <<vct[i].b<<","<<vct[i].c<<","<<vct[i].d<<")"<<endl; } return 0; }
true
646cc91dfc4780f60e60dadd72dd07bf16e4bde7
C++
96Asch/CG_OpenGL_Engine
/src/component/Motion.h
UTF-8
2,231
3.0625
3
[]
no_license
#ifndef MOTION_H_ #define MOTION_H_ #include "Component.h" #include <sstream> #include <glm/vec3.hpp> struct Motion : public IComponent<Motion> { Motion() : direction(glm::vec3(0.0f)), rotation(glm::vec3(0.0f)), movSpeed(1.0f), rotSpeed(0.5f) {}; Motion(const float &movSpeed, const float &rotSpeed) : direction(glm::vec3(0.0f)), rotation(glm::vec3(0.0f)), movSpeed(movSpeed), rotSpeed(rotSpeed) {}; Motion(std::ifstream &stream) : direction(glm::vec3(0.0f)), rotation(glm::vec3(0.0f)), movSpeed(1.0f), rotSpeed(0.5f) { if(!deserialize(stream)) std::cerr << "ERR: Deserializing Motion Component" << std::endl; }; virtual bool deserialize(std::ifstream &stream) override { bool firstAcc(false), lastAcc(false); do { std::string buffer; std::string comp; std::string var; stream >> std::ws; if(std::getline(stream, buffer)) { std::istringstream ss(buffer); if(!firstAcc && buffer == "{") firstAcc = true; else if (firstAcc && buffer == "}") lastAcc = true; else if(std::getline(ss, comp, '=')) { if (comp == "movSpeed") { if(std::getline(ss, var)) { float speed = std::stof(var); this->movSpeed = speed; } } else if (comp == "rotSpeed") { if(std::getline(ss, var)) { float speed = std::stof(var); this->rotSpeed = speed; } } } } else return false; } while(stream && firstAcc && !lastAcc); return true; }; virtual void serialize(std::ofstream &) override {}; glm::vec3 direction; glm::vec3 rotation; float movSpeed; float rotSpeed; }; #endif
true
f99e31eade3d744deec01249f12118cc0379ea65
C++
yuangu/project
/Classes/commonData/dictData/DictHeroQuality/DictHeroQualityManager.cpp
UTF-8
1,997
2.640625
3
[]
no_license
#include "DictHeroQualityManager.h" #include "../../../common/PublicShowUI.h" DictHeroQualityManager* DictHeroQualityManager::_instance = NULL; void DictHeroQualityManager::setConfigData(Json* json) { Json* node = json->child; node = node->next; while (node) { if(node->type == Json_Array) { Json* item = node->child; DictHeroQuality* data = new DictHeroQuality(); data->level = item->valueInt; item = item->next; data->nameDesp = item->valueString; item = item->next; data->name = item->valueString; item = item->next; data->ename = item->valueString; item = item->next; data->porpUpMultiple = item->valueFloat; item = item->next; data->levelUpLimit = item->valueInt; item = item->next; data->levelColour = item->valueString; item = item->next; data->levelColourResource = item->valueString; item = item->next; data->baseCost = item->valueInt; item = item->next; data->costLevelTenUp = item->valueInt; item = item->next; data->sellMultiple = item->valueInt; data_list.insert(PublicShowUI::numberToString(data->level), data); } node = node->next; } } DictHeroQuality* DictHeroQualityManager::getData(int id) { string key = PublicShowUI::numberToString(id); DictHeroQuality* data = (DictHeroQuality*)(data_list.at(key)); return data; } DictHeroQualityManager* DictHeroQualityManager::getInstance() { if(_instance == NULL) { _instance = new DictHeroQualityManager(); } return _instance; } Vector<DictHeroQuality*>* DictHeroQualityManager::getDataList() { Vector<DictHeroQuality*>* list = new Vector<DictHeroQuality*>(); for(auto value : data_list) { DictHeroQuality* data = ( DictHeroQuality* )value.second; list->pushBack(data); } return list; } DictHeroQualityManager::~DictHeroQualityManager() { destroyInstance(); } void DictHeroQualityManager::destroyInstance() { if(_instance) { data_list.clear(); delete _instance; _instance = NULL; } }
true
a7287137e537fbdde528c1032d3b210bafe5bb84
C++
chenshuyuhhh/acm
/9.14/Test3.cpp
UTF-8
3,314
2.625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <queue> #include <set> #include <cstring> #include <algorithm> using namespace std; // // Created by 陈姝宇 on 2020/9/13. // class Test3 { int nn; int mm; int **hen; int **shu; int **moneys; int **visit; int sum = 0; set<pair<int, int>> s; set<pair<int, int>> gc; void dfs(int i, int j, int m) { if (moneys[i][j] <= m) return; moneys[i][j] = m; if (gc.find(pair<int, int>(i, j)) != gc.end()) return; if (i - 1 >= 0) { dfs(i - 1, j, m + shu[i - 1][j]); } if (i + 1 < nn) { dfs(i + 1, j, m + shu[i][j]); } if (j - 1 >= 0) { dfs(i, j - 1, m + hen[i][j - 1]); } if (j + 1 < mm) { dfs(i, j + 1, m + hen[i][j]); } } //void findPath(int i, int j, int m) { // if (i - 1 >= 0 && !visit[i - 1][j] && m + shu[i - 1][j] == moneys[i - 1][j]) { // visit[i - 1][j] = 1; // sum += shu[i - 1][j]; // findPath(i - 1, j, m); // } // if (i + 1 < nn && !visit[i + 1][j] && m + shu[i][j] == moneys[i + 1][j]) { // visit[i + 1][j] = 1; // sum += shu[i][j]; // findPath(i + 1, j, m); // } // if (j - 1 >= 0 && !visit[i][j - 1] && m + hen[i][j - 1] == moneys[i][j - 1]) { // visit[i][j - 1] = 1; // sum += hen[i][j - 1]; // findPath(i, j - 1, m); // } // if (j + 1 < mm && !visit[i][j + 1] && m + hen[i][j] == moneys[i][j + 1]) { // visit[i][j + 1] = 1; // sum += hen[i][j]; // findPath(i, j + 1, m); // } //} int mainTest3() { int n, m; cin >> n >> m; nn = n; mm = m; int stations[n][m]; moneys = new int *[n]; for (int i = 0; i < n; ++i) { moneys[i] = new int[m]; for (int j = 0; j < m; ++j) { moneys[i][j] = INT32_MAX; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> stations[i][j]; if (stations[i][j] > 0) s.insert(pair<int, int>(i, j)); else if (stations[i][j] < 0) gc.insert(pair<int, int>(i, j)); } } hen = new int *[n]; for (int i = 0; i < n; ++i) { hen[i] = new int[m - 1]; for (int j = 0; j < m - 1; ++j) { cin >> hen[i][j]; } } shu = new int *[n - 1]; for (int i = 0; i < n - 1; ++i) { shu[i] = new int[m]; for (int j = 0; j < m; ++j) { cin >> shu[i][j]; } } for (const auto &it : s) { dfs(it.first, it.second, stations[it.first][it.second]); } // visit = new int *[n]; // for (int i = 0; i < n; ++i) { // visit[i] = new int[m]; // memset(visit[i], 0, sizeof(int) * m); // } for (const auto &it : gc) { int i = it.first; int j = it.second; sum += moneys[i][j]; // if (!visit[i][j] && moneys[i][j] == stations[i][j]) { // sum += stations[i][j]; // findPath(i, j, stations[i][j]); // } } cout << sum << endl; } };
true
9934a786da3fcacfb65488e63cf173029243cc83
C++
tianyaochou/antlr-generator
/include/Pass/ResolveRef.h
UTF-8
1,565
2.765625
3
[]
no_license
#include <map> #include "Rules/Rule.h" struct ResolveRef : public RuleVisitor { std::map<std::string, std::shared_ptr<Rule>> &parserRules; std::map<std::string, std::shared_ptr<Rule>> &lexerRules; ResolveRef(std::map<std::string, std::shared_ptr<Rule>> &parserRules, std::map<std::string, std::shared_ptr<Rule>> &lexerRules) : parserRules(parserRules), lexerRules(lexerRules) {} virtual std::any visitSeqRule(SeqRule *rule) { for (auto &child : rule->sequence) { child->accept(this); } return nullptr; } virtual std::any visitOrRule(OrRule *rule) { for (auto &child : rule->alternatives) { child->accept(this); } return nullptr; }; virtual std::any visitEbnfSuffixRule(EbnfSuffixRule *rule) { rule->child->accept(this); return nullptr; }; virtual std::any visitRuleRefRule(RuleRefRule *rule) { rule->ref = parserRules.at(rule->refName); return nullptr; }; virtual std::any visitNotSetRule(NotSetRule *rule) { return nullptr; }; virtual std::any visitDotRule(DotRule *rule) { return nullptr; }; virtual std::any visitTokenRefRule(TokenRefRule *rule) { rule->ref = lexerRules.at(rule->refName); return nullptr; }; virtual std::any visitStringLiteralRule(StringLiteralRule *rule) { return nullptr; }; virtual std::any visitCharSetRule(CharSetRule *rule) { return nullptr; }; };
true
9d4e443bdafaabbeb7a3f603028bc582c0fb43ce
C++
pcannon67/pocketkaldi
/test/list_test.cc
UTF-8
1,064
2.890625
3
[]
no_license
// Created at 2016-11-22 #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include "util.h" #include "list.h" PKLIST_DEFINE(int, int_list) void TestIntList() { int_list_t pklist_int; int_list_init(&pklist_int); assert(int_list_empty(&pklist_int)); std::vector<int> stdvector_int; int N = 1000000; for (int i = 0; i < N; ++i) { int random_num = rand(); stdvector_int.push_back(random_num); int_list_push_back(&pklist_int, random_num); } assert(!int_list_empty(&pklist_int)); for (int i = 0; i < N; ++i) { assert(stdvector_int[i] == pklist_int.data[i]); } assert(pklist_int.size == stdvector_int.size()); assert(int_list_back(&pklist_int) == stdvector_int.back()); // Test pop_back() int_list_pop_back(&pklist_int); stdvector_int.pop_back(); assert(int_list_back(&pklist_int) == stdvector_int.back()); assert(pklist_int.size == stdvector_int.size()); int_list_destroy(&pklist_int); } int main() { TestIntList(); return 0; }
true
840331b9675839329c849fd6ae901bf1ec79e037
C++
B2SIC/cpp_training
/Solution/Baekjoon/5101.cpp
UTF-8
791
3.125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v; int start = -1, sequence = -1, target = -1; while(true) { int count = 1; cin >> start >> sequence >> target; if (start == 0 && sequence == 0 && target == 0) break; for(start; start <= target; start += sequence) { if(start == target) { v.push_back(count); break; }else{ count++; } } if(start > target) v.push_back(-1); } for(int i = 0; i < v.size(); i++) { if(v[i] != -1) cout << v[i] << endl; else cout << 'X' << endl; } return 0; }
true
2775a6175cd52a162791fcb96bca797ad7ed6d3b
C++
aplesss/CrossingRoad
/Source/CPeople.cpp
UTF-8
2,938
2.8125
3
[]
no_license
#pragma once #include "CPeople.h" Character People::cha("Character\\People.txt"); People::People() {} People::~People() {} People::People(int x, int y) { X = x; Y = y; COORD temp = { -1,-1 }; oldPos.push_back(temp); oldPos.resize(3); } void People::Up() { int width = this->Width(); int height = this->Height(); oldPos.clear(); COORD pos = { 0, Y + height - 1 }; for (int i = 0; i < width; i++) { pos.X = X + i; pos.Y = Y + height - 1; oldPos.push_back(pos); } if (Y > BOARD_GAME_TOP + 1) { Y--; } } void People::Left() { int width = this->Width(); int height = this->Height(); oldPos.clear(); COORD pos = { X + width - 1 ,0}; for (int i = 0; i < height; i++) { pos.Y = Y + i; oldPos.push_back(pos); } if (X > BOARD_GAME_LEFT + 1) { X--; } } void People::Right() { int width = this->Width(); int height = this->Height(); oldPos.clear(); COORD pos = { X }; for (int i = 0; i < height; i++) { pos.Y = Y + i; oldPos.push_back(pos); } if (X + cha.Width() - 1 < BOARD_GAME_RIGHT - 1) { X++; } } void People::Down() { int width = this->Width(); int height = this->Height(); oldPos.clear(); COORD pos = { 0, Y }; for (int i = 0; i < width; i++) { pos.X = X + i; oldPos.push_back(pos); } if (Y + cha.Height() - 1 < BOARD_GAME_BOTTOM - 1) { Y++; } } void People::Move(char key) { if (key == LEFT || key == 'a' ) { this->Left(); } else if (key==RIGHT|| key == 'd' ) { this->Right(); } else if (key==DOWN||key == 's') { this->Down(); } else if (key==UP||key == 'w') { this->Up(); } } bool People::IsDied() { return Live == false; } void People::Draw(bool color) { if (oldPos[0].X > 0) { this->ClearPre(); } if(color) TextColor(6); cha.Draw(X, Y); TextColor(7); } void People::ClearPre() { int len = oldPos.size(); for (int i = 0; i < len; i++) { GotoXY(oldPos[i]); lock_guard<mutex> lock(theLock); cout<<" "; } } COORD People::GetPos() { COORD pos = { X,Y }; return pos; } Character& People::GetCharacter() { return cha; } int People::Width() { if (cha.width == 0) { Character f("Character\\people.txt"); return f.Width(); } return cha.Width(); } int People::Height() { if (cha.height == 0) { Character f("Character\\people.txt"); return f.Height(); } return cha.Height(); } void People::SetLive(bool live) { Live = live; } void People::Write(ostream& outDev) { outDev.write((char*)&X, sizeof(X)); outDev.write((char*)&Y, sizeof(Y)); outDev.write((char*)&Live, sizeof(Live)); int num = oldPos.size(); outDev.write((char*)&num, sizeof(num)); outDev.write((char*)&oldPos[0], num * sizeof(oldPos[0])); } void People::Read(istream& inDev) { inDev.read((char*)&X, sizeof(X)); inDev.read((char*)&Y, sizeof(Y)); inDev.read((char*)&Live, sizeof(Live)); int num; inDev.read((char*)&num, sizeof(num)); oldPos.resize(num); inDev.read((char*)&oldPos[0], num * sizeof(COORD)); }
true
f0e38ab9e93c5a8c9d10b5ed178bdacfc815fd35
C++
vpadi/ACAP
/P3/src/convolucion_2.0.cpp
UTF-8
3,147
3.109375
3
[]
no_license
#include <png.h> #include <chrono> #include "pngio.h" int main(int argc, char *argv[]) { if(argc != 3) abort(); const int conv[3][3] = {{-2,-1,0},{-1,1,1},{0,1,2}}; const int DIVISOR = 1; /* Lectura de la imagen en una matriz bytep */ dimension dim = read_png_file(argv[1]); /* Paso de la matriz original a 3 matrices para cada Canal */ int * R = new int[(dim.height+2)*(dim.width+2)], * G = new int[(dim.height+2)*(dim.width+2)], * B = new int[(dim.height+2)*(dim.width+2)]; conversion_a_RGBAMatrices(R, G, B); /* Creación de una matriz copia para no sobrescribir la original. */ int * R_cop = new int[(height+2)*(width+2)], * G_cop = new int[(height+2)*(width+2)], * B_cop = new int[(height+2)*(width+2)]; std::chrono::high_resolution_clock::time_point t_inicio = std::chrono::high_resolution_clock::now(); /* Realización del proceso de convolucion */ for(int i = 2; i < height; ++i){ for(int j = 2; j < width; ++j){ R_cop[(i*dim.width)+j] += R[((i-1)*dim.width)+(j-1)] * conv[0][0] + R[((i)*dim.width)+(j-1)] * conv[1][0] + R[((i+1)*dim.width)+(j-1)] * conv[2][0]; G_cop[(i*dim.width)+j] += G[((i-1)*dim.width)+(j-1)] * conv[0][0] + G[((i)*dim.width)+(j-1)] * conv[1][0] + G[((i+1)*dim.width)+(j-1)] * conv[2][0]; B_cop[(i*dim.width)+j] += B[((i-1)*dim.width)+(j-1)] * conv[0][0] + B[((i)*dim.width)+(j-1)] * conv[1][0] + B[((i+1)*dim.width)+(j-1)] * conv[2][0]; R_cop[(i*dim.width)+j] += R[((i-1)*dim.width)+(j)] * conv[0][1] + R[((i)*dim.width)+(j)] * conv[1][1] + R[((i+1)*dim.width)+(j)] * conv[2][1]; G_cop[(i*dim.width)+j] += G[((i-1)*dim.width)+(j)] * conv[0][1] + G[((i)*dim.width)+(j)] * conv[1][1] + G[((i+1)*dim.width)+(j)] * conv[2][1]; B_cop[(i*dim.width)+j] += B[((i-1)*dim.width)+(j)] * conv[0][1] + B[((i)*dim.width)+(j)] * conv[1][1] + B[((i+1)*dim.width)+(j)] * conv[2][1]; R_cop[(i*dim.width)+j] += R[((i-1)*dim.width)+(j+1)] * conv[0][2] + R[((i)*dim.width)+(j+1)] * conv[1][2] + R[((i+1)*dim.width)+(j+1)] * conv[2][2]; G_cop[(i*dim.width)+j] += G[((i-1)*dim.width)+(j+1)] * conv[0][2] + G[((i)*dim.width)+(j+1)] * conv[1][2] + G[((i+1)*dim.width)+(j+1)] * conv[2][2]; B_cop[(i*dim.width)+j] += B[((i-1)*dim.width)+(j+1)] * conv[0][2] + B[((i)*dim.width)+(j+1)] * conv[1][2] + B[((i+1)*dim.width)+(j+1)] * conv[2][2]; R_cop[(i*width)+j] /= DIVISOR; G_cop[(i*width)+j] /= DIVISOR; B_cop[(i*width)+j] /= DIVISOR; } } std::chrono::high_resolution_clock::time_point t_fin = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> total_time = std::chrono::duration_cast<std::chrono::duration<double> >(t_fin - t_inicio); /* Conversión de las 3 matrices de vuelta a una matriz de representación de imagenes */ conversion_a_Imagen(R_cop, G_cop, B_cop); /* Escritura de la matriz en un fichero .png */ write_png_file(argv[2]); printf("Problem size: %i x %i\tElapsed time: %f\n", dim.width, dim.height, total_time); return 0; }
true
791a8d8596e5f8cf57fa21d31becb863451448ca
C++
erik/blocks
/src/scene.cpp
UTF-8
6,349
2.59375
3
[]
no_license
#include "scene.hpp" #include <SFML/Graphics.hpp> #include <sstream> void MenuScene::Init(Context *c) { context = c; floor = world.CreateBox(200, 700, 400, 10, true); floor.SetColor(sf::Color(0x44, 0x44, 0x44, 255)); } void MenuScene::Step() { if(sf::Randomizer::Random(1, 20) == 5) { int w = sf::Randomizer::Random(1, 50); int h = sf::Randomizer::Random(1, 50); int x = sf::Randomizer::Random(1, 800); int r = sf::Randomizer::Random(1, 128); int g = sf::Randomizer::Random(1, 128); int b = sf::Randomizer::Random(1, 128); WorldShape ws = world.CreateBox(x, -50, w, h, false); ws.SetColor(sf::Color(r, g, b, 255)); blocks.push_back(ws); } // remove blocks that are off screen std::vector<WorldShape>::iterator iter = blocks.begin(); while(iter != blocks.end()) { if(iter->GetPosition().y >= 800) { iter->Destroy(world); iter = blocks.erase(iter); } else { ++iter; } } world.Step(); } void MenuScene::Render() { sf::Shape s; for(unsigned int i = 0; i < blocks.size(); ++i) { s = blocks[i].CreateRectangle(); context->window->Draw(s); } } void MenuScene::HandleInput(const sf::Input& in) { context->gui->HandleInput(in); } void MenuScene::HandleEvent(sf::Event e) { context->gui->HandleEvent(e); } // Game Scene // void GameScene::Init(Context* c) { context = c; platform = world.CreateBox(200, 700, 400, 10, true); platform.SetColor(sf::Color(0x44, 0x44, 0x44, 255)); x = 800.0 / 2; droppedBlocks = score = 0; GenerateShape(); gui = new GUIPage(context->window, context); { sf::Color gray(0x22, 0x22, 0x22, 128); sf::Rect<int> scoreButRect(50, 50, 170, 100); sf::Rect<int> timeButRect(800 - 170, 50, 800 - 50, 100); scoreBut = new GUIButton("SCORE: 0", scoreButRect, gray, gray); timeBut = new GUIButton("TIME:", timeButRect, gray, gray); scoreBut->SetFontSize(15.0f); timeBut->SetFontSize(15.0f); gui->AddElement(scoreBut); gui->AddElement(timeBut); } clock.Reset(); } void GameScene::Step() { score = 0.0f; // remove blocks that are off screen std::vector<WorldShape>::iterator iter = blocks.begin(); while(iter != blocks.end()) { if(iter->GetPosition().y >= 800) { iter->Destroy(world); iter = blocks.erase(iter); droppedBlocks++; } else { score += 700 - iter->GetPosition().y; ++iter; } } score -= 100 * droppedBlocks; std::ostringstream buff; buff.precision(1); buff.setf(std::ios::fixed, std::ios::floatfield); buff << "SCORE: "; buff << static_cast<int>(score); scoreBut->SetText(buff.str()); float timeLeft = 120 - clock.GetElapsedTime(); if(timeLeft <= 0) { context->gameState = State_Paused; return; } buff.str(""); buff << "TIME: "; buff << timeLeft; timeBut->SetText(buff.str()); world.Step(); } /*YO, ADD COMBOS, SUBTRACT SCORE EACH TIME SOMETHING FALLS OFF, POINTS DEPEND ON HEIGHT */ /* ALSO, LOTS OF HACKED STUFF IN HERE */ void GameScene::Render() { sf::Shape s; // Draw the alignment line for(int i = 50 + h / 2, col = 0x66; i < 700 / 1.25; i += 10, col += 6) { if (col <= 0) col = 0; s = sf::Shape::Line(x + w / 2, i, x + w / 2, i + 10, 1.0, sf::Color(col, col, col, 256 - col)); context->window->Draw(s); // To make a dashed line i += 10; } // Draw the held shape s = sf::Shape::Rectangle(0, 0, w, h, sf::Color(0x66, 0x66, 0x66, 255)); s.SetCenter(w / 2, h / 2); s.SetPosition(x + w / 2, 50 + h / 2); s.SetRotation(rot); context->window->Draw(s); // Draw the blocks for(unsigned int i = 0; i < blocks.size(); ++i) { s = blocks[i].CreateRectangle(); context->window->Draw(s); } int highestIndex = -1; float highestPoint = -1; // Draw the lines and heights for(unsigned int i = 0; i < blocks.size(); ++i) { sf::Vector2<float> pos = blocks[i].GetPosition(); float w = blocks[i].GetWidth(); float h = blocks[i].GetHeight(); float midWidth = pos.x + w / 2; float midHeight = pos.y + h / 2; int mapped = 256 - map(pos.y, 0, 700, 0, 256); if((pos.y < highestPoint || highestIndex == -1)) { highestPoint = pos.y; highestIndex = i; } sf::Color color = (700 - pos.y) <= 0 ? sf::Color::Red : sf::Color(255, 256 - mapped, 256 - mapped, mapped); if(pos.y <= 700 - 50 || pos.y >= 700 - 0) { s = sf::Shape::Line(midWidth, midHeight, midWidth + 50, midHeight, 1.0, color); context->window->Draw(s); std::ostringstream buff; buff << 700 - pos.y; sf::String str = sf::String(buff.str(), sf::Font::GetDefaultFont(), 15.0); str.SetPosition(midWidth + 50, midHeight - str.GetSize() / 2); str.SetColor(color); context->window->Draw(str); } } // Draw the bracket if(blocks.size() > 1 && highestIndex != -1) { s = sf::Shape::Line(700.0 / 2 - 200, 700, 100, 700, 3.0, sf::Color::Red); context->window->Draw(s); s = sf::Shape::Line(700.0 / 2 - 200, highestPoint, 100, highestPoint, 3.0, sf::Color::Red); context->window->Draw(s); s = sf::Shape::Line(100, 700, 100, highestPoint, 3.0, sf::Color::Red); context->window->Draw(s); } gui->Render(); } void GameScene::HandleInput(const sf::Input& in) { context->gui->HandleInput(in); if(in.IsKeyDown(sf::Key::Left)) { x -= x ? 4 : 0; } if(in.IsKeyDown(sf::Key::Right)) { x += x >= 800 ? 0 : 4;; } if(in.IsKeyDown(sf::Key::Q)) { rot -= 2 % 360; } if(in.IsKeyDown(sf::Key::E)) { rot += 2 % 360; } } void GameScene::HandleEvent(sf::Event e) { context->gui->HandleEvent(e); if(e.Type == sf::Event::KeyReleased) { if(e.Key.Code == sf::Key::Space) { DropShape(); GenerateShape(); } } } void GameScene::GenerateShape() { w = sf::Randomizer::Random(20, 50); h = sf::Randomizer::Random(20, 50); rot = sf::Randomizer::Random(0, 360); } void GameScene::DropShape() { WorldShape ws = world.CreateBox(x, 50, w, h, false); int r = sf::Randomizer::Random(1, 256); int g = sf::Randomizer::Random(1, 256); int b = sf::Randomizer::Random(1, 256); ws.SetColor(sf::Color(r, g, b, 255)); ws.SetRotation(rot); blocks.push_back(ws); }
true
9d39012ec5dcc2daeb20efe14905ab67b9bfc100
C++
abhishekk781/matrix-session
/intro to programming/session 4/assignment_pattern4.cpp
UTF-8
296
2.984375
3
[]
no_license
#include <iostream> using namespace std; void print_c(int x,int& start){ for (int i = 0; i < x; ++i) { cout<<start<<" "; start++; } // return start; } int main(){ int n = 5,counter = 1; for (int i = 1; i <= n; ++i) { print_c(i,counter); // counter = counter+i; cout<<endl; } }
true
6aa51498c2be72561e0b87f96f96fa2e3acfaa2a
C++
UniversaBlockchain/U8
/crypto/HashId.cpp
UTF-8
3,310
2.84375
3
[]
no_license
/* * Copyright (c) 2018-present Sergey Chernov, iCodici S.n.C, All Rights Reserved. */ #include <tomcrypt.h> #include "HashId.h" #include "gost3411-2012.h" #include "base64.h" #include "../tools/tools.h" namespace crypto { HashId::HashId(const std::vector<unsigned char> &packedData) : HashId((void *) &packedData[0], packedData.size()) { } HashId::HashId(void *data, size_t size) { initWith(data, size); } HashId::HashId(const HashId &copyFrom) { digest = copyFrom.digest; } HashId::HashId(HashId &&moveFrom) { digest = std::move(moveFrom.digest); } HashId HashId::of(const std::vector<unsigned char> &packedData) { return HashId(packedData); } HashId HashId::of(void *data, size_t size) { return HashId(data, size); } HashId HashId::withDigest(const std::vector<unsigned char> &digestData) { return withDigest((void *) &digestData[0], digestData.size()); } HashId HashId::withDigest(void *digestData, size_t digestDataSize) { HashId res; res.digest.resize(digestDataSize); memcpy(&res.digest[0], digestData, digestDataSize); return res; } HashId HashId::createRandom() { byte_vector body(64); sprng_read(&body[0], 64, NULL); return HashId::of(body); } void HashId::initWith(void *data, size_t size) { if (digest.size() == 0) { const unsigned long gostSize = 256; digest.resize(sha512_256_desc.hashsize + sha3_256_desc.hashsize + gostSize / 8); hash_state md2; sha512_256_init(&md2); sha512_256_process(&md2, (unsigned char *) data, size); sha512_256_done(&md2, &digest[0]); hash_state md3; sha3_256_init(&md3); sha3_process(&md3, (unsigned char *) data, size); sha3_done(&md3, &digest[sha512_256_desc.hashsize]); size_t len = 0; gost3411_2012_get_digest(gostSize, (unsigned char *) data, size, &digest[sha512_256_desc.hashsize + sha3_256_desc.hashsize], &len); } else { throw std::runtime_error("HashId is already initialized"); } } std::string HashId::toBase64() const { return base64_encode(&digest[0], digest.size()); } std::vector<unsigned char> HashId::getDigest() { return digest; } bool HashId::operator<(const HashId &other) const { if (digest.size() != other.digest.size()) { //TODO: throw error return false; } for (int i = 0; i < digest.size(); i++) { if (digest[i] < other.digest[i]) return true; if (digest[i] > other.digest[i]) return false; } return false; } bool HashId::operator==(const HashId &other) const { if (digest.size() != other.digest.size()) return false; return std::equal(digest.begin(), digest.end(), other.digest.begin()); } size_t HashId::hashCode() const { return std::hash<std::string>()(std::string(digest.begin(), digest.end())); } size_t HashId::UnorderedHash::operator()(const HashId &val) const { return val.hashCode(); } };
true
379fe5e62fd7e9a0562b3b047847f3ec76291710
C++
Divyanshnigam/DS-ALGO
/QUEUES/QUEUES Linked List based implementation.cpp
UTF-8
658
3.421875
3
[]
no_license
#include<iostream> #include<list> using namespace std; class queue { int cs; list<int>qu; public: queue() { this->cs=0; } bool isempty() { return this->cs==0; } void enqueue(int data) { this->qu.push_back(data); this->cs+=1; } void deque() { if(!isempty()) { this->cs-=1; this->qu.pop_front(); } } int getfront() { return this->qu.front(); } }; int main(int argc,char const*agr[]) { queue qu; for(int i=0;i<=6;i++) { qu.enqueue(i); } qu.deque(); qu.enqueue(8); while(!qu.isempty()) { cout<<qu.getfront()<<endl; qu.deque(); } return 0; }
true
e25be7684ca1d40db9b1f87e4f0221f2350c5fc2
C++
bhushan23/competitive-programming
/LeetCode/algorithm/Medium_MinSizeSubArraySum_209.cpp
UTF-8
788
2.71875
3
[]
no_license
class Solution { public: int minSubArrayLen(int s, vector<int>& nums) { if (nums.size() <= 0) return 0; int low = 0; int hi = 0; int minD = nums.size()+2; int sum = nums[0]; while (low <= hi && hi < nums.size()) { // cout << sum << " " << hi << " " << low << endl; if (sum >= s) { if (minD > hi-low+1) { minD = hi-low+1; } sum -= nums[low++]; } else if (sum < s) { if (hi < nums.size()-1) sum += nums[++hi]; else sum -= nums[low++]; } } if (minD == nums.size()+2) return 0; return minD; } };
true
c1dad4cb150c194c50beb7854671e7bb5fe3df4f
C++
monarchshield/ProcedGenFinale
/Source/WindowStartup/WindowStartup/src/ObjLoader.cpp
UTF-8
6,728
2.671875
3
[]
no_license
#include "ObjLoader.h" ObjLoader::ObjLoader() {} ObjLoader::ObjLoader(const char *path, const char *textureloc, float Faces) { Facenum = Faces; m_vertexCount = 0; m_ModelIndexCount = 0; Initialise(path, textureloc); CreateBuffers(); } ObjLoader::~ObjLoader() { } void ObjLoader::Draw(unsigned int shader, mat4 &ProjectionView) { glUseProgram(shader); int loc = glGetUniformLocation(shader, "ProjectionView"); glUniformMatrix4fv(loc, 1, GL_FALSE, &(ProjectionView[0][0])); loc = glGetUniformLocation(shader, "diffuse"); glUniform1i(loc, 0); glBindVertexArray(m_VAO); glDrawElements(GL_TRIANGLES, m_ModelIndexCount, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void ObjLoader::Initialise(const char *path, const char *textureloc) { if(textureloc != NULL) { data = stbi_load(textureloc,&imageWidth,&imageHeight,&imageFormat, STBI_default); glGenTextures(1, &m_texture); glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_texture); stbi_image_free(data); } std::ifstream in(path, std::ios::in); if(!in) { std::cerr << "Cannot open" << "Path" << std::endl; exit(1); } std::string line; while(std::getline(in, line)) { if(line.substr(0,2) == "v ") { std::istringstream s(line.substr(2)); Vertex v; s >> v.position.x; s >> v.position.y; s >> v.position.z; v.position.w = 1.0f; v.colour = vec4(1,1,1,1); Vertices.push_back(v); m_vertexCount++; } else if(line.substr(0,2) == "vt") { std::istringstream s(line.substr(2)); vec2 uv; s >> uv.x; s >> uv.y; uv.y = uv.y * -1; ModelUV.push_back(uv); } else if(line.substr(0,2) == "f " && Facenum == 2.1) { char dummychar; int dummyint; std::istringstream s(line.substr(2)); unsigned int a,b,c; s >> a; s >> dummychar; s >> dummychar; s >> dummyint; s >> b; s >> dummychar; s >> dummychar; s >> dummyint; s >> c; s >> dummychar; s >> dummychar; s >> dummyint; a--; b--; c--; Elements.push_back(a); Elements.push_back(b); Elements.push_back(c); } else if(line.substr(0,2) == "f " && Facenum == 2) { char dummychar; std::istringstream s(line.substr(2)); unsigned int a,b,c,aTex,bTex,cTex; s >> a; s >> dummychar; s >> aTex; s >> b; s >> dummychar; s >> bTex; s >> c; s >> dummychar; s >> cTex; a--; b--; c--; aTex--; bTex--; cTex--; Elements.push_back(a); Elements.push_back(b); Elements.push_back(c); Vertices[a].UV = ModelUV[aTex]; Vertices[b].UV = ModelUV[bTex]; Vertices[c].UV = ModelUV[cTex]; //uv .Y *-1 } #pragma region FaceCondition3 else if(line.substr(0,2) == "f " && Facenum == 3) { char dummychar; int dummyint; std::istringstream s(line.substr(2)); unsigned int a,b,c; s >> a; s >> dummychar; s >> dummyint; s >> dummychar; s >> dummyint; s >> b; s >> dummychar; s >> dummyint; s >> dummychar; s >> dummyint; s >> c; s >> dummychar; s >> dummyint; s >> dummychar; s >> dummyint; a--; b--; c--; Elements.push_back(a); Elements.push_back(b); Elements.push_back(c); } #pragma endregion else if (line.substr(0, 2) == "f " && Facenum == 3.1f) { char dummychar; std::istringstream s(line.substr(2)); unsigned int a, b, c, aTex, bTex, cTex, aNormal, bNormal, cNormal; s >> a; s >> dummychar; s >> aNormal; s >> dummychar; s >> aTex; s >> b; s >> dummychar; s >> bNormal; s >> dummychar; s >> bTex; s >> c; s >> dummychar; s >> cNormal; s >> dummychar; s >> cTex; a--; b--; c--; aTex--; bTex--; cTex--; Elements.push_back(a); Elements.push_back(b); Elements.push_back(c); Vertices[a].UV = ModelUV[aTex]; Vertices[b].UV = ModelUV[bTex]; Vertices[c].UV = ModelUV[cTex]; } else if( line[0] == '#') { // Do nothing } else {/* Also ignore */} } m_ModelIndexCount = Elements.size(); normals.resize(Vertices.size(), vec3(0,0,0)); for (unsigned int i = 0; i < Elements.size(); i+=3) { GLushort ia = Elements[i]; GLushort ib = Elements[i+1]; GLushort ic = Elements[i+2]; vec3 normal = glm::normalize(glm::cross(vec3(Vertices[ib].position) - vec3(Vertices[ia].position),vec3(Vertices[ic].position) - vec3(Vertices[ia].position))); normals[ia] = normals[ib] = normals[ic] = normal; Vertices[ia].colour = Vertices[ib].colour = Vertices[ic].colour = vec4(normal, 1.0f); } } int ObjLoader::loadShader(unsigned int type, const char* path) { FILE* file = fopen(path, "rb"); if(file == nullptr) { std::cout << "Failed to Find Shader:" << path << "\n"; return 0; } //Read the shader source fseek(file,0,SEEK_END); unsigned int length = ftell(file); fseek(file,0,SEEK_SET); char* source = new char[length + 1]; memset(source, 0 , length + 1); fread(source,sizeof(char),length,file); fclose(file); unsigned int shader = glCreateShader(type); glShaderSource(shader,1, &source, 0); glCompileShader(shader); delete[] source; return shader; } void ObjLoader::CreateBuffers() { // Create VAO, VBO and IBO glGenVertexArrays(1, &m_VAO); glGenBuffers(1, &m_VBO); glGenBuffers(1, &m_IBO); // Bind buffers glBindVertexArray( m_VAO ); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); // send data to the buffers glBufferData(GL_ARRAY_BUFFER, Vertices.size() * sizeof(Vertex), &Vertices[0], GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, Elements.size() * sizeof(unsigned int), &Elements[0], GL_STATIC_DRAW); // describe how the vertices are setup so they can be sent to the shader glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(vec4))); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(vec4)*2)); //Setting textur slots glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_texture); //tell the shader where it is loc = glGetUniformLocation(m_programID, "diffuse"); glUniform1i(loc, 0); // m_VAO hold all our ARRAY_BUFFER and ARRAY_ELEMENT_BUFFER settings // so just rebind it later before using glDrawElements glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
true
57fbb683e73859213440c35dddb63c477e5db8b6
C++
loganharbour/meen644
/hwk5/Problem_coefficients.cpp
UTF-8
5,291
2.59375
3
[]
no_license
#include "Problem.h" namespace Flow2D { void Problem::fillCoefficients(const Variable & var) { if (var.name == Variables::pc) pcCoefficients(); else if (var.name == Variables::T) TCoefficients(); else if (var.name == Variables::u) uCoefficients(); else if (var.name == Variables::v) vCoefficients(); if (debug) { cout << var.string << " coefficients: " << endl; var.printCoefficients(var.string, true); } } void Problem::pcCoefficients() { for (unsigned int i = 1; i < pc.Mx; ++i) for (unsigned int j = 1; j < pc.My; ++j) { Coefficients & a = pc.a(i, j); if (i != 1) a.w = rho * dy * dy / u.a(i - 1, j).p; if (i != pc.Mx - 1) a.e = rho * dy * dy / u.a(i, j).p; if (j != 1) a.s = rho * dx * dx / v.a(i, j - 1).p; if (j != pc.My - 1) a.n = rho * dx * dx / v.a(i, j).p; a.p = a.n + a.e + a.s + a.w; a.b = rho * (dy * (u(i - 1, j) - u(i, j)) + dx * (v(i, j - 1) - v(i, j))); } } void Problem::TCoefficients() { Coefficients D, F; for (unsigned int i = 1; i < T.Mx; ++i) for (unsigned int j = 1; j < T.My; ++j) { // Diffusion coefficient D.n = (j == T.My - 1 ? 2 * dx * k / dy : dx * k / dy); D.e = (i == T.Mx - 1 ? 2 * dy * k / dx : dy * k / dx); D.s = (j == 1 ? 2 * dx * k / dy : dx * k / dy); D.w = (i == 1 ? 2 * dy * k / dx : dy * k / dx); // Heat flows F.n = dx * cp * rho * v(i, j); F.e = dy * cp * rho * u(i, j); F.s = dx * cp * rho * v(i, j - 1); F.w = dy * cp * rho * u(i - 1, j); // Compute and store power law coefficients fillPowerLaw(T.a(i, j), D, F); } } void Problem::uCoefficients() { Coefficients D, F; double W, dy_pn, dy_ps, b; for (unsigned int i = 1; i < u.Mx; ++i) for (unsigned int j = 1; j < u.My; ++j) { // Width of the cell W = (i == 1 || i == u.Mx - 1 ? 3 * dx / 2 : dx); // North/south distances to pressure nodes dy_pn = (j == u.My - 1 ? dy / 2 : dy); dy_ps = (j == 1 ? dy / 2 : dy); // Diffusion coefficients D.n = mu * W / dy_pn; D.e = mu * dy / dx; D.s = mu * W / dy_ps; D.w = mu * dy / dx; // East and west flows F.e = (i == u.Mx - 1 ? rho * dy * u(u.Mx, j) : rho * dy * (u(i + 1, j) + u(i, j)) / 2); F.w = (i == 1 ? rho * dy * u(0, j) : rho * dy * (u(i - 1, j) + u(i, j)) / 2); // North and south flows if (i == 1) // Left boundary { F.n = rho * W * (v(0, j) + 3 * v(1, j) + 2 * v(2, j)) / 6; F.s = rho * W * (v(0, j - 1) + 3 * v(1, j - 1) + 2 * v(2, j - 1)) / 6; } else if (i == u.Mx - 1) // Right boundary { F.n = rho * W * (2 * v(i, j) + 3 * v(i + 1, j) + v(i + 2, j)) / 6; F.s = rho * W * (2 * v(i, j - 1) + 3 * v(i + 1, j - 1) + v(i + 2, j - 1)) / 6; } else // Interior (not left or right boundary) { F.n = rho * W * (v(i, j) + v(i + 1, j)) / 2; F.s = rho * W * (v(i, j - 1) + v(i + 1, j - 1)) / 2; } // Pressure RHS b = dy * (p(i, j) - p(i + 1, j)); // Compute and store power law coefficients fillPowerLaw(u.a(i, j), D, F, b); } } void Problem::vCoefficients() { Coefficients D, F; double H, dx_pe, dx_pw, b; for (unsigned int i = 1; i < v.Mx; ++i) for (unsigned int j = 1; j < v.My; ++j) { // Height of the cell H = (j == 1 || j == v.My - 1 ? 3 * dy / 2 : dy); // East/west distances to pressure nodes dx_pe = (i == v.Mx - 1 ? dx / 2 : dx); dx_pw = (i == 1 ? dx / 2 : dx); // Diffusion coefficient D.n = mu * dx / dy; D.e = mu * H / dx_pe; D.s = mu * dx / dy; D.w = mu * H / dx_pw; // North and east flows F.n = (j == v.My - 1 ? rho * dx * v(i, v.My) : rho * dx * (v(i, j + 1) + v(i, j)) / 2); F.s = (j == 1 ? rho * dx * v(i, 0) : rho * dx * (v(i, j - 1) + v(i, j)) / 2); // East and west flows if (j == 1) // Bottom boundary { F.e = rho * H * (u(i, 0) + 3 * u(i, 1) + 2 * u(i, 2)) / 6; F.w = rho * H * (u(i - 1, 0) + 3 * u(i - 1, 1) + 2 * u(i - 1, 2)) / 6; } else if (j == v.My - 1) // Top boundary { F.e = rho * H * (2 * u(i, j) + 3 * u(i, j + 1) + u(i, j + 2)) / 6; F.w = rho * H * (2 * u(i - 1, j) + 3 * u(i - 1, j + 1) + u(i - 1, j + 2)) / 6; } else // Interior (not top or bottom boundary) { F.e = rho * H * (u(i, j) + u(i, j + 1)) / 2; F.w = rho * H * (u(i - 1, j) + u(i - 1, j + 1)) / 2; } // Pressure RHS b = dx * (p(i, j) - p(i, j + 1)); // Compute and store power law coefficients fillPowerLaw(v.a(i, j), D, F, b); } } void Problem::fillPowerLaw(Coefficients & a, const Coefficients & D, const Coefficients & F, const double & b) { a.n = D.n * fmax(0, pow5(1 - 0.1 * fabs(F.n / D.n))) + fmax(-F.n, 0); a.e = D.e * fmax(0, pow5(1 - 0.1 * fabs(F.e / D.e))) + fmax(-F.e, 0); a.s = D.s * fmax(0, pow5(1 - 0.1 * fabs(F.s / D.s))) + fmax(F.s, 0); a.w = D.w * fmax(0, pow5(1 - 0.1 * fabs(F.w / D.w))) + fmax(F.w, 0); a.p = a.n + a.e + a.s + a.w; a.b = b; } } // namespace Flow2D
true
3978ce0fea055baf98fadff393f823f2d0f32829
C++
Kingcom/armips
/Core/Allocations.h
UTF-8
1,969
3.03125
3
[ "MIT" ]
permissive
#pragma once #include <cstdint> #include <map> struct AllocationStats { int64_t largestPosition; int64_t largestSize; int64_t largestUsage; int64_t largestFreePosition; int64_t largestFreeSize; int64_t largestFreeUsage; int64_t sharedFreePosition; int64_t sharedFreeSize; int64_t sharedFreeUsage; int64_t totalSize; int64_t totalUsage; int64_t sharedSize; int64_t sharedUsage; int64_t largestPoolPosition; int64_t largestPoolSize; int64_t totalPoolSize; }; class Allocations { public: static void clear(); static void setArea(int64_t fileID, int64_t position, int64_t space, int64_t usage, bool usesFill, bool shared); static void forgetArea(int64_t fileID, int64_t position, int64_t space); static void setPool(int64_t fileID, int64_t position, int64_t size); static void forgetPool(int64_t fileID, int64_t position, int64_t size); static void clearSubAreas(); static bool allocateSubArea(int64_t fileID, int64_t& position, int64_t minRange, int64_t maxRange, int64_t size); static int64_t getSubAreaUsage(int64_t fileID, int64_t position); static bool canTrimSpace(); static void validateOverlap(); static AllocationStats collectStats(); private: struct Key { int64_t fileID; int64_t position; inline bool operator <(const Allocations::Key &other) const { return std::tie(fileID, position) < std::tie(other.fileID, other.position); } }; struct Usage { int64_t space; int64_t usage; bool usesFill; bool shared; }; struct SubArea { int64_t offset; int64_t size; }; static void collectAreaStats(AllocationStats &stats); static void collectPoolStats(AllocationStats &stats); static int64_t getSubAreaUsage(Key key) { return getSubAreaUsage(key.fileID, key.position); } static std::map<Key, Usage> allocations; static std::map<Key, int64_t> pools; static std::multimap<Key, SubArea> subAreas; static bool keepPositions; static bool nextKeepPositions; static bool keptPositions; };
true
16cbba561bc05742ebce08bc6e89ba721e6a52f7
C++
bhavinnirmal29/C_CPP_Programs
/TOKEN2.CPP
UTF-8
893
2.703125
3
[]
no_license
#include<iostream.h> #include<conio.h> #include<string.h> void main() { char a[50]; int i,n,token=1,beg=0,end,loc; int y; clrscr(); printf("enter the string\n"); gets(a); n=strlen(a); printf("string lenght is %d\n",n); printf("token=1\n"); for(i=0;i<n;i++) { loc=i; if(a[i]!=' ') { printf("%c",a[i]); } if(a[i]==' '|| a[i+1]=='\0') { if((a[beg]>=65 && a[beg]<=91) || (a[beg]>=97 && a[loc]<=122)) { printf("\tvariable"); printf("\n"); } if(a[beg]>='0' && a[beg]<='9' || a[beg]>=33 &&a[beg]<=47) { if(a[loc-1]>='0' && a[loc-1]<='9') { printf("\tliteral\n"); } else if(a[loc-1]>=33 && a[loc-1]<=47) { printf("Symbols"); } else { printf("Invalid\n"); } } beg=loc+1; loc=i+1; if(i+1==n) { break; } token++; printf("\ntoken=%d\n",token); } } getch(); }
true
c6162ae81d750992a42fddfaae301f5f8d0ac589
C++
free5fall5/uni
/sum_and_avg.cpp
UTF-8
648
3.484375
3
[]
no_license
#include <iostream> #include <cmath> #include <math.h> using namespace std; int main () { cout << "This program will calculate the sum and avg of the negative numbers entered by you. " << endl; cout << "The program will termiante if you end if you fail to enter a negative number." << endl<<endl; int input = 0; double sum = 0; int num_of_entries = 0; while ( input <= 0 ) { cout << "Please enter a negative number: " << endl; cin >> input; if ( input < 0 ) { sum = sum + input; num_of_entries = num_of_entries + 1; cout << "The sum is " << sum <<"." <<endl; cout << "The avg is " << sum / num_of_entries << endl; } else break; } return 0; }
true
6e70d269b36c15ab70a2b485a00833b330a2ed8b
C++
evelio521/Books
/cplusplus/More Effective c++/貳/7.cpp
GB18030
2,012
3.84375
4
[]
no_license
/*ItemM7Ҫء&&,||, ,*/ //˲&&˵ģ if (expression1 && expression2) ... //ڱ˵֮ͬһ if (expression1.operator&&(expression2)) ... // when operator&& is a // member function if (operator&&(expression1, expression2)) ... // when operator&& is a // global function /* * ϵÿԵµĽ: * ȵʱҪвԵú * functions operator&& operator||ʱ * Ҫ㣬֮ûвö·㷨ڶC++ * Թ淶ûж庯ļ˳ûа취֪ * ʽ1ʽ2һȼ㡣ȫд * Ҳ˳Ķ·㷨෴ */ /* * ڽ&&||C++һЩ㡣 * ͬҲй嶺Ųļ㷽һ * ŵıʽȼ㶺ߵıʽȻ㶺 * ұߵıʽʽĽǶұ߱ʽֵ * ѭ󲿷ȼ++iȻ * jűʽĽ--j * ضűʽ޷ṩЧ * / /* * 㲻IJ * . .* :: ?: * new delete sizeof typeid * static_cast dynamic_cast const_cast reinterpret_cast */ /* * IJ * operator new operator delete * operator new[] operator delete[] * + - * / % ^ & | ~ * ! = < > += -= *= /= %= * ^= &= |= << >> >>= <<= == != * <= >= && || ++ -- , ->* -> * () [] */ */
true
f52431ff4067aaa1f304f849b413fca8fee1aa51
C++
Hirosvk/sdf_3d
/open_gl/shader.cpp
UTF-8
1,706
2.78125
3
[]
no_license
#include <iostream> #include "shader.h" using namespace OpenGL; Shader::Shader(std::string vertexSource, std::string fragmentSource) { GLuint vertexShader = initShader(GL_VERTEX_SHADER, vertexSource); GLuint fragmentShader = initShader(GL_FRAGMENT_SHADER, fragmentSource); id = glCreateProgram(); glAttachShader(id, vertexShader); glAttachShader(id, fragmentShader); glLinkProgram(id); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } GLuint Shader::getAttribLocation(const GLchar *attribute) { return glGetAttribLocation(id, attribute); } void Shader::setRGBA(std::string attribute, GLfloat r, GLfloat g, GLfloat b, GLfloat a) { const GLchar* c_attr = attribute.c_str(); int location = glGetUniformLocation(id, c_attr); glUniform4f(location, r, g, b, a); } void Shader::setMatrix4(std::string attribute, const glm::mat4 &transform) { const GLchar* c_attr = attribute.c_str(); int location = glGetUniformLocation(id, c_attr); glUniformMatrix4fv(location, 1, GL_FALSE, &transform[0][0]); } void Shader::use() { glUseProgram(id); } void Shader::reset() { glUseProgram(0); } GLuint Shader::initShader (GLenum type, std::string &source) { GLuint shaderId = glCreateShader(type); const GLchar* c_source = source.c_str(); glShaderSource(shaderId, 1, &c_source, NULL); glCompileShader(shaderId); GLint status; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &status); if (status != GL_TRUE) { char infoLog[512]; glGetShaderInfoLog(shaderId, 521, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; throw std::runtime_error("shader compile failed"); } return shaderId; }
true
5c8f4bd0a58993b5f6a8ce037d6555b5f9c16764
C++
astephens4/bide
/common/test/TestAssert.hpp
UTF-8
3,258
3.546875
4
[]
no_license
#ifndef TEST_ASSERT_H #define TEST_ASSERT_H 1 #include <iostream> #include <cinttypes> #include <cmath> #define MAX_ULP_DIFFERENCE 5 #include <cassert> // Macro to assert that two values relate to each other in the manner specified by the operation parameter // This macro should not be used directly, instead, use the Assert... functions below // Example Usage: MAKE_ASSERTION(2, <=, 1); // This fails the test. For example purposes, this is on line #210 in file Class.cpp // Example Output: Assertion Failed @ Class.cpp:210 - var1 <= var2 // (2 <= 1) #define MAKE_ASSERTION(op1, operation, op2) \ assert(((op1) operation (op2)) \ || !(std::cout << "Assertion Failed @ " << __FILE__ << ":" << __LINE__ << " - " << #op1 << " " << #operation << " " << #op2 \ << "\n(" << op1 << #operation << op2 << ")\n")) // Please don't use this union. It should only be used internally by tests union Float_t { Float_t(float val) : f(val) { } bool negative() { return f < 0.0f; } int32_t i; float f; }; // Please don't use this union. It should only be used internally by tests union Double_t { Double_t(double val) : d(val) { } bool negative() { return d < 0.0f; } int64_t i; double d; }; /** * METHOD NAME: clid::AssertEquals * * @FullDescription * Assert that two different things are equal, and halt, logging the error, if the assertion * fails. * * @tparam T Type of things to be compared. Must provide an operator== * * @param arg1 First thing to check for equality * @param arg2 Second thing to check for equality */ template<typename T> void AssertEquals( T arg1, T arg2 ) { MAKE_ASSERTION( arg1, ==, arg2 ); } /** * Assert that two floating point values are equivalent. This checks equivalency using the * difference in the least significant bits of the float method * @param [in] arg1 First value to check for equivalence * @param [in] arg2 Value to check against arg1 */ template<> void AssertEquals(float arg1, float arg2) { Float_t f1(arg1); Float_t f2(arg2); if(f1.negative() != f2.negative()) { if(std::fabs(f1.f) == std::fabs(f2.f)) return; MAKE_ASSERTION(f1.f, ==, f2.f); } int ulpDiff = std::abs(f1.i - f2.i); MAKE_ASSERTION(ulpDiff, <=, MAX_ULP_DIFFERENCE); } /** * Assert that two floating point values are equivalent. This checks equivalency using the * difference in the least significant bits of the float method * @param [in] arg1 First value to check for equivalence * @param [in] arg2 Value to check against arg1 */ template<> void AssertEquals(double arg1, double arg2) { Double_t d1(arg1); Double_t d2(arg2); if(d1.negative() != d2.negative()) { // If they have different signs, but are equal (?) then don't assert if(std::fabs(d1.d) == std::fabs(d2.d)) return; // Values have different signedness, test fails, use MAKE_ASSERTION to print the message MAKE_ASSERTION(d1.d, ==, d2.d); } // Get the difference between the float representations in ints to check units of least precisions int ulpDiff = std::abs(d1.i - d2.i); MAKE_ASSERTION(ulpDiff, <=, MAX_ULP_DIFFERENCE); } #endif // TEST_ASSERT_H
true
067e2d1b75cd52b147bc82b3fc813c0c5498706f
C++
denaas/msup_online_audio
/registr.cpp
WINDOWS-1251
1,415
3.078125
3
[]
no_license
#pragma once #include <initializer_list> #include <algorithm> #include <tuple> #include <memory> #include <iostream> #include <string> #include <type_traits> class identification { public: string login; // string password; // bool registration() { bool flag; // , // // ( Ms SQL) // // // flag = True // // flag = False return flag; } bool autorization() { bool flag; // , // // flag = False // // ( ) // //flag = True // //flag = False return flag; } }
true
7f088d05482f3271a052572c0606d986d78e9165
C++
khleexv/kmucs
/2019-spring/cpp/algolab/22_유리수.cpp
UTF-8
7,123
3.5
4
[]
no_license
#include <iostream> #include <vector> using namespace std; typedef long long ll; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a%b); } ll lcm(ll a, ll b) { return a * b / gcd(a,b); } class myRational { public: // Member Field ll _num; ll _den; // Constructor myRational(ll num=0, ll den=1) { if (den == 0) { num = 0; den = 1; } _num = num; _den = den; reduce(); } myRational(const myRational &rat) { // Assume a is prefect. _num = rat._num; _den = rat._den; } // Accessor ll getNumerator() const { return _num; } ll getDenominator() const { return _den; } // Member Function myRational reciprocal() const { return myRational(_den, _num); } void reduce() { bool negative = false; if (_num < 0) { _num = -_num; negative = true; } ll divisor = gcd(_num, _den); _num /= divisor; _den /= divisor; if (negative) _num = -_num; } // Overloaded Operator myRational operator +(const myRational &rat) { ll den = lcm(_den, rat._den); ll num = _num * (den / _den) + rat._num * (den / rat._den); return myRational(num, den); } myRational operator +(int value) { return *this + myRational(value); } myRational operator -(const myRational &rat) { myRational you = rat; return *this + -you; } myRational operator -(int value) { return *this - myRational(value); } myRational operator *(const myRational &rat) { return myRational(_num * rat._num, _den * rat._den); } myRational operator *(int value) { return *this * myRational(value); } myRational operator /(const myRational &rat) { return *this * rat.reciprocal(); } myRational operator /(int value) { return *this / myRational(value); } // Unary Operator myRational operator -() { return myRational(-_num, _den); } myRational& operator ++() { *this += 1; return *this; } myRational operator ++(int) { myRational ret(_num, _den); ++(*this); return ret; } myRational& operator --() { *this -= 1; return *this; } myRational operator --(int) { myRational ret(_num, _den); --(*this); return ret; } // Comparison Operator bool operator <(const myRational &rat) { return (*this - rat)._num < 0; } bool operator <=(const myRational &rat) { return (*this - rat)._num <= 0; } bool operator >(const myRational &rat) { return (*this - rat)._num > 0; } bool operator >=(const myRational &rat) { return (*this - rat)._num >= 0; } bool operator ==(const myRational &rat) { return (_num == rat._num && _den == rat._den); } bool operator !=(const myRational &rat) { return !(*this == rat); } // Assignment Operator myRational& operator =(const myRational &rat) { _num = rat._num; _den = rat._den; return *this; } myRational& operator =(int value) { _num = value; _den = 1; return *this; } myRational& operator +=(const myRational &rat) { *this = *this + rat; return *this; } myRational& operator +=(int value) { *this = *this + myRational(value); return *this; } myRational& operator -=(const myRational &rat) { *this = *this - rat; return *this; } myRational& operator -=(int value) { *this = *this - myRational(value); return *this; } myRational& operator *=(const myRational &rat) { *this = *this * rat; return *this; } myRational& operator *=(int value) { *this = *this * myRational(value); return *this; } myRational& operator /=(const myRational &rat) { *this = *this / rat; return *this; } myRational& operator /=(int value) { *this = *this / myRational(value); return *this; } }; ostream &operator <<(ostream &outStream, const myRational& r) { if (r._num == 0) outStream << 0; else if (r._den == 1) outStream << r._num; else outStream << r._num << '/' << r._den; return outStream; } istream &operator >>(istream &inStream, myRational& r) { inStream >> r._num >> r._den; if (r._den == 0) { r._num = 0; r._den = 1; } if (r._den < 0) { r._num = -r._num; r._den = -r._den; } r.reduce(); return inStream; } myRational operator +(int value, const myRational &rat) { return myRational(value) + rat; } myRational operator -(int value, const myRational &rat) { return myRational(value) - rat; } myRational operator *(int value, const myRational &rat) { return myRational(value) * rat; } myRational operator /(int value, const myRational &rat) { return myRational(value) / rat; } void testSimpleCase(); void swap(myRational *a, myRational *b) { myRational temp = *a; *a = *b; *b = temp; } int main() { testSimpleCase(); int t; cin >> t; while (t--) { int n; cin >> n; vector<myRational> a(n); for (int i=0;i<n;++i) cin >> a[i]; for (int i=0;i<n;++i) { for (int j=i+1;j<n;++j) { if (a[i] > a[j]) swap(a[i], a[j]); } } for (int i=0;i<a.size();++i) cout << a[i] << ' '; cout << '\n'; } } void testSimpleCase() { myRational frac1(2), frac2(3, 2), frac3(6, 4), frac4(12, 8), frac5, frac6, frac7; cout << frac1 << " " << frac2 << " " << frac3 << " " << frac4 << " " << frac5 << endl; cout << frac1.getNumerator() << " " << frac1.getDenominator() << endl; // Check arithmetic operators cout << frac1 * frac2 << " " << frac1 + frac3 << " " << frac2 - frac1 << " " << frac3 / frac2 << endl; // Check comparison operators cout << ((frac1 < frac2) ? 1 : 0) << " " << ((frac1 <= frac2) ? 1 : 0) << " " << ((frac1 > frac2) ? 1 : 0) << " " << ((frac1 >= frac2) ? 1 : 0) << " " << ((frac1 == frac2) ? 1 : 0) << " " << ((frac1 != frac2) ? 1 : 0) << " " << ((frac2 < frac3) ? 1 : 0) << " " << ((frac2 <= frac3) ? 1 : 0) << " " << ((frac2 > frac3) ? 1 : 0) << " " << ((frac2 >= frac3) ? 1 : 0) << " " << ((frac2 == frac3) ? 1 : 0) << " " << ((frac2 != frac3) ? 1 : 0) << endl; cout << (frac6 = frac3) << " "; cout << (frac6 += frac3) << " "; cout << (frac6 -= frac3) << " "; cout << (frac6 *= frac3) << " "; cout << (frac6 /= frac3) << endl; cout << -frac6 << endl; frac6 = (++frac4) + 2; frac7 = 2 + (frac4++); cout << frac4 << " " << frac6 << " " << frac7 << endl; frac6 = (--frac4) - 2; frac7 = 2 - (frac4--); cout << frac4 << " " << frac6 << " " << frac7 << endl; cout << 2 * frac3 << " " << frac3 * 2 << " " << 2 / frac3 << " " << frac3 / 2 << endl; }
true
cd51c762b79d181b4670d337cd2764ad55199a6e
C++
yanqiniu/CowByte
/src/CowByteEngine 0.2/Utils/CBVector.h
UTF-8
6,073
3.5
4
[]
no_license
#ifndef _CBVECTOR_H #define _CBVECTOR_H #include <cstring> #include "../Memory/CBMemory.h" // Unlike CBQueue who implement a block based linked list, // CBVector implement a contiguous array in a single block. template <typename T> class CBVector { public: CBMEM_OVERLOAD_NEW_DELETE(CBVector) CBVector(); CBVector(const CBVector &toCopy); CBVector(size_t size); // Initialize the container to a size. ~CBVector(); CBVector<T> & operator=(const CBVector<T> &rhs); size_t Size() const { return m_Size; } size_t Capacity() const { return m_Capacity; } void Resize(size_t newCapacity); /* Change capacity of container. */ bool IsEmpty() const { return m_Size == 0; } const T& peekat(size_t index) const { return m_Data[index]; } // const version of at(). T& at(size_t index) { return m_Data[index]; } T& operator[](size_t index) { return m_Data[index]; } T* Back(); // This is always a copy construct. T* Push_back(const T &toPush); bool Pop_back(); T* Insert(size_t index, const T &value); bool Erase(size_t index); void Clear(); // TODO: what is wrong with these that range-based for loop don't work? T* begin() const { return &m_Data[0]; } T* end() const { return &m_Data[m_Size - 1]; } private: // Make array larger. void Grow_capacity(); bool IsValidIndex(size_t index); T* m_Data; size_t m_Capacity; size_t m_Size; }; template <typename T> CBVector<T>::CBVector() : m_Size(0), m_Capacity(0), m_Data(nullptr) { } // Custom copy constructor that doesn't just do a shallow copy. template <typename T> CBVector<T>::CBVector(const CBVector &toCopy) : m_Size(0), m_Capacity(0), m_Data(nullptr) { Resize(toCopy.m_Capacity); memcpy(m_Data, toCopy.m_Data, m_Size * sizeof(T)); m_Size = toCopy.m_Size; } template <typename T> CBVector<T>::CBVector(size_t size) : CBVector() { Resize(size); } template <typename T> CBVector<T>::~CBVector() { Clear(); if (m_Data != nullptr) { CBMemArena::Get().Free(m_Data, m_Capacity * sizeof(T)); m_Data = nullptr; } } template <typename T> CBVector<T> & CBVector<T>::operator=(const CBVector<T> &rhs) { /* Ok, here's the problem. To assign a CBVector to a new value, we'd want to destruct stuff already in it, if there happens to be any. Since assignment operator is used to initialize objects, it means that when we run into this func, the class can be either uninitialized or filled with stuff that needs to be destructed. And there isn't really a reliable way of knowing which case it is. And if it happens to be uninitialized, we are gonna get an error trying to Clear() it. So we can only assume that this is an empty/uninitialized vector, and explicitly clean it up before the assignment operator is called. */ // Reset counts. m_Size = 0; m_Capacity = 0; // Copy data Resize(rhs.m_Capacity); memcpy(m_Data, rhs.m_Data, rhs.m_Size * sizeof(T)); m_Size = rhs.m_Size; return *this; } template <typename T> T* CBVector<T>::Back() { if (m_Size == 0) return nullptr; else return &m_Data[m_Size - 1]; } template <typename T> void CBVector<T>::Clear() { // Please note that this does not set capacity to 0. // The idea is that when you clear an array, it's // possible you are going to put new stuff in. while(!IsEmpty()) Pop_back(); } template <typename T> bool CBVector<T>::IsValidIndex(size_t index) { return index >= 0 && index < m_Size; } // Insert a copy. And return ptr to the inserted copy. // Notice that insert in the middle is very costly as it // needs to destruct elements being shifted when shifting // them. template <typename T> T* CBVector<T>::Insert(size_t index, const T &value) { if (index < 0 || index > m_Size) // can insert at mSize (push_back) return nullptr; if (m_Size + 1 > m_Capacity) Grow_capacity(); // Shift. Make some space. if(m_Size > 0) for (size_t i = m_Size - 1; i >= index; --i) { m_Data[i + 1] = m_Data[i]; m_Data[i].~T(); if(i == 0) break; // underflow guard. } m_Data[index] = value; ++m_Size; return &m_Data[index]; } template <typename T> bool CBVector<T>::Erase(size_t index) { if (!IsValidIndex(index)) return false; // shift for (size_t i = index + 1; i < m_Size; ++i) { m_Data[i - 1] = m_Data[i]; } m_Data[m_Size - 1].~T(); memset(&m_Data[m_Size - 1], 0, sizeof(T)); --m_Size; return true; } template <typename T> bool CBVector<T>::Pop_back() { return Erase(m_Size - 1); } template <typename T> void CBVector<T>::Resize(size_t newCapacity) { if (newCapacity == m_Capacity) // "wtf?" return; else if (newCapacity < m_Size) // shrink { // No need to shrink the actual array, // since that introduces performance // overhead. Just destroy elements out // of bound and update bookkeepings. for (size_t i = newCapacity; i < m_Size; ++i) { m_Data[i].~T(); memset(&m_Data[i], 0, sizeof(T)); } m_Capacity = newCapacity; m_Size = newCapacity; } else // grow { // Create new array T *newData = (T*)CBMemArena::Get().Allocate(newCapacity * sizeof(T)); if (!IsEmpty()) { memcpy(newData, m_Data, m_Size * sizeof(T)); CBMemArena::Get().Free(m_Data, m_Capacity * sizeof(T)); m_Data = nullptr; } m_Capacity = newCapacity; m_Data = newData; } } template <typename T> T* CBVector<T>::Push_back(const T &toPush) { return Insert(m_Size, toPush); } template <typename T> void CBVector<T>::Grow_capacity() { if (m_Capacity == 0) { Resize(1); } else Resize(m_Capacity * 2); } #endif
true
253d845f2d4a2714583f7354115123455e3c3933
C++
osama-afifi/Online-Judges-Solutions
/UVA Problems/UVA/UVA/Above Average.cpp
UTF-8
569
2.546875
3
[]
no_license
#include <iostream> #include<iomanip> using namespace std; int main () { freopen("input.in", "r", stdin); double t,n,x[1500],avg; cin>>t; while (t>0) { cin>>n; if (n==0) {cout << setprecision(3) << fixed << n <<"%"<< endl; continue;} int i=0; for(i=0;i<n;i++) cin>>x[i]; int sum=0; for(i=0;i<n;i++) sum=sum+x[i]; avg=sum/n; int above=0; for(i=0;i<n;i++) {if (x[i]>avg) above++;} double per; per=(above/n)*100; //cout<<per<<"%"<<endl; cout << setprecision(3) << fixed << per <<"%"<< endl; t--; } return 0; }
true
8b6bcbaf736fc559f654fd1480a113543d7ca9d0
C++
AparnaChinya/100DaysOfCode
/BinarySearchTreeIterator.cpp
UTF-8
1,611
4.0625
4
[]
no_license
/* Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. Credits: Special thanks to @ts for adding this problem and creating all test cases. From <https://leetcode.com/explore/interview/card/amazon/81/design/895/> */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: //Stack for all nodes in increasing order always stack<TreeNode *> myStack; BSTIterator(TreeNode *root) { pushAll(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !myStack.empty(); } /** @return the next smallest number */ int next() { auto temp = myStack.top(); myStack.pop(); //Remember to call this here pushAll(temp->right); return temp->val; } void pushAll(TreeNode *root) { //Push all the leftmost nodes from the root the first time and after each next(), push the right nodes left nodes. while(root != NULL) { myStack.push(root); root = root->left; } } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
true
6b88ae4263eebed928020cc251bf56499b160324
C++
donaldrshade/Columbot2017
/serialcommander/serialcommander.ino
UTF-8
1,081
2.90625
3
[]
no_license
#include "Servo.h" Servo lshoulder; Servo lelbow; Servo lclaw; Servo rshoulder; Servo relbow; Servo rclaw; int toDigit(int character) { return character - 48; } void setup() { lshoulder.attach(6); lelbow.attach(9); lclaw.attach(10); // // // rshoulder.attach(6); // relbow.attach(9); // rclaw.attach(10); Serial.begin(115200); Serial.write("Hello from Robot1!"); } int byteCount = 0; int digits[11]; void loop() { if (true) { int number = Serial.read(); if (number == 13) { int shoulder = 100 * toDigit(digits[0]) + 10 * toDigit(digits[1]) + toDigit(digits[2]); int elbow = 100 * toDigit(digits[4]) + 10 * toDigit(digits[5]) + toDigit(digits[6]); int claw = 100 * toDigit(digits[8]) + 10 * toDigit(digits[9]) + toDigit(digits[10]); Serial.print(shoulder); Serial.print(elbow); Serial.println(claw); lshoulder.write(shoulder); lelbow.write(elbow); lclaw.write(claw); byteCount = 0; } else if (byteCount < 11) { digits[byteCount] = number; byteCount++; } } }
true
b3719f3570d629048d44312306a2461ce674f8a3
C++
asyzruffz/ProjectPhronesis
/Phronesis/Sources/Phronesis/FileIO/BinaryFile.cpp
UTF-8
709
3.046875
3
[]
no_license
#include "StdAfx.hpp" #include "BinaryFile.hpp" using namespace Phronesis; std::vector<char> BinaryFile::read(const std::string& filename) { // std::ios::ate is for reading at the end of the file std::ifstream file(filename, std::ios::ate | std::ios::binary); if(!file.is_open()) { throw std::runtime_error("[ERROR] [FileIO] Failed to open file " + filename); } // so we can use the read position to determine the size of the file and allocate a buffer size_t fileSize = (size_t)file.tellg(); std::vector<char> buffer(fileSize); // seek back to the beginning of the file and read all of the bytes at once file.seekg(0); file.read(buffer.data(), fileSize); file.close(); return buffer; }
true