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
3b49a44fac5f7aa1f47b734116e2296f75140b08
C++
wang-y-z/leetcode-algorithm
/290.单词规律.cpp
UTF-8
1,030
3.0625
3
[]
no_license
/* * @lc app=leetcode.cn id=290 lang=cpp * * [290] 单词规律 */ // @lc code=start class Solution { public: bool wordPattern(string pattern, string s) { vector<string> str; string buf; stringstream is(s); while( is>> buf) str.push_back(buf); if(str.size() != pattern.length()) return false; // for(auto i : str) // cout<< i << ","; unordered_map<char,string> c2s; unordered_map<string,char> s2c; for(int i = 0 ; i < str.size() ; i++){ char c = pattern[i]; string s = str[i]; if(c2s.find(c) != c2s.end()){ string tempS = (c2s.find(c))->second; if(tempS != s) return false; }else if(s2c.find(s)!=s2c.end()){ char tempC = (s2c.find(s))->second; if(tempC != c) return false; } c2s[c] = s; s2c[s] = c; } return true; } }; // @lc code=end
true
1584afc933c01c2fe68ca6fa1d8714c308038944
C++
bayuajik2403/observer-pattern-simple-example-c-
/src/statusObserver1.cpp
UTF-8
456
2.90625
3
[]
no_license
#include "../include/statusObserver1.h" using namespace std; //this function will be called when there is status change void statusObserver1::status(bool status){ if (status == false) { //you can do anything here cout<<"-statusObserver1 got status false, so I will say goodbye"<<endl; } else { //you can do anything here cout<<"-statusObserver1 got status true, so I will say hello"<<endl; } }
true
fc10c7264dc3f34d3ea60dab66d2499fe98712fa
C++
songkey7/leetcode
/283.move_zeroes/MoveZeroes.cpp
UTF-8
426
3.234375
3
[]
no_license
// // Created by Qi Song on 2/7/18. // #include "MoveZeroes.h" void MoveZeroes::move_zeroes(vector<int> &nums) { int b = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] != 0) { swap(nums[i], nums[b]); b++; } } } void MoveZeroes::run() { vector<int> nums = {0, 1, 0, 3, 12}; vector<int> ret = {1, 3, 12, 0, 0}; move_zeroes(nums); assert(nums == ret); }
true
1fcd00ca593b1666490341e7d38ff35aadf49180
C++
krejgo/game-eater
/player.h
UTF-8
3,129
3.09375
3
[]
no_license
#pragma once //MEMORY int cKey; //Last key pressed; class player { public: player(int L) { //Initialize Parameters phase1 = ph1L; phase2 = ph1L + ph2L; phase3 = ph1L + ph2L + 1; length = L; dir = 0; dirB = 0; deltaDir = 0; phase = 0; //Initialize Entity Position x = border/2; pos.assign(L,x); } void updatePos() { for (int i=length-1; i>0; i--) pos[i] = pos[i-1]; x += calcMovement(); pos[0] = x; } int pLength() { return length; } int pPos(int x) { return pos[x]; } void showPos() { cout << "["; for (int i = 0; i < pos.size(); ++i) { cout << pos[i] << " "; } cout << "]" << endl; } void debug() { cout << "PH1 " << phase1 << endl; cout << "PH2 " << phase2 << endl; cout << "PH3 " << phase3 << endl; cout << "PHS " << phase << endl; cout << "DIR " << dir << endl; cout << "DRB " << dirB << endl; cout << "DDR " << deltaDir << endl; cout << "POS " << x << endl; showPos(); } private: vector <int> pos; //CURRENT position of whole body int x; //Head position (bottom part) int dir; //Current movement direction int dirB; //Last movement direction int deltaDir; //Where to translate (left or right), to satisfy current movement int phase; //Transition between moving left, down, right int velX; //X velocity, the variable depended by X int phase1; int phase2; int phase3; int length; int calcMovement() { //Reset parameters velX = 0; //Check last movement dirB = dir; //Check key input dir = cKey; //Check if there any change in direction if (dir != dirB) { if (dir > dirB) { deltaDir = 1; } else if (dir < dirB) { deltaDir = -1; } } //*Changing direction if ((phase == phase3 || phase == -phase3) && deltaDir != 0) { phase += deltaDir; } //*Fixing direction else if (phase == 0 && dir == 0){ deltaDir = 0; } //Check phase //POSITIVE PHASE else if (phase > 0){ if (phase < phase3) { phase += deltaDir; } if (phase == phase1 || phase == phase2) { velX = 1; } else if (phase == phase3){ deltaDir = 0; velX = 1; } } //NEGATIVE PHASE else if (phase < 0){ if (phase > -phase3) { phase += deltaDir; } if (phase == -phase1 || phase == -phase2) { velX = -1; } else if (phase == -phase3){ deltaDir = 0; velX = -1; } } else if (phase == 0 && deltaDir != 0) { phase += deltaDir; velX = deltaDir; } //IF PHASE ERROR //couldnt find out why sometimes phase passing the limit //this is used to correct the phase if that happens if (phase < -phase3) { phase = -phase3; //cout << "error detected"; } else if (phase > phase3) { phase = phase3; //cout << "error detected"; } //Check border collision if ((x==0 && velX==-1) || (x==border && velX==1)) { velX = 0; phase = 0; dir = 0; } //DEBUGGING //cout << phase << " | " << deltaDir << " | " << dir << endl; return velX; } };
true
77f4b4e704108716083dbcfffe5b7595a50fe7a7
C++
lqcfcjx/ExampleQt
/TcpServer/server.cpp
UTF-8
1,134
2.546875
3
[ "Apache-2.0" ]
permissive
#include "server.h" Server::Server(QObject *parent, int port) : QTcpServer(parent) { listen(QHostAddress::Any,port); } void Server::incomingConnection(int socketDescriptor){ TcpClientSocket *tcpClientSocket = new TcpClientSocket(this); connect(tcpClientSocket,&TcpClientSocket::updateClients,this,&Server::updateClients); connect(tcpClientSocket,&TcpClientSocket::disconnected,this,&Server::slotDisconnected); tcpClientSocket->setSocketDescriptor(socketDescriptor); tcpClientSocketList.append(tcpClientSocket); } void Server::updateClients(QString msg,int length){ emit updateServer(msg,length); for(int i=0; i<tcpClientSocketList.size(); i++){ QTcpSocket *item = tcpClientSocketList.at(i); if(item->write(msg.toLatin1(),length)!=length){ continue; } } } void Server::slotDisconnected(int descriptor){ for(int i=0; i<tcpClientSocketList.size();i++){ QTcpSocket *item = tcpClientSocketList.at(i); if(item->socketDescriptor() == descriptor){ tcpClientSocketList.removeAt(i); return; } } return; }
true
4e7fa3d3dfcd30d5453a3bd9e04fbc90a4f28479
C++
tom-code/bluepill
/opencm3-cppcomp/led.h
UTF-8
1,192
2.703125
3
[]
no_license
class status_led : public component_t { int status = 0; int state = 0; int state_last_time = 0; int pin = -1; int port = -1; public: void set(int s) { status = s; state_last_time = 0; state = 1000; } void setup(int _port, int _pin) { port = _port; pin = _pin; gpio_set_mode(port, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, pin); gpio_set(port, pin); } void loop() override { int time_now = millis(); if ((time_now - state_last_time) < 200) return; state_last_time = time_now; state = state + 1; if (state < status*2 + 2) { int current = (state%2) ? 0 : 1; if (current) gpio_set(port, pin); else gpio_clear(port, pin); return; } if (state > status*4) state = 0; } }; class blinking_led : public component_t { int pin = -1; int port = -1; int last_switch = 0; public: void setup(int _port, int _pin) { port = _port; pin = _pin; gpio_set_mode(port, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, pin); } void loop() override { int now = millis(); if ((now - last_switch) > 100) { last_switch = now; gpio_toggle(port, pin); } } };
true
1396b1ea5479df2336512308ed755ee3fef14dc1
C++
flashpoint493/AyaRay
/src/Core/TriangleMesh.h
UTF-8
2,017
2.5625
3
[ "MIT" ]
permissive
#ifndef AYA_CORE_TRIANGLEMESH_H #define AYA_CORE_TRIANGLEMESH_H #include "../Math/Vector2.h" #include "../Math/Vector3.h" #include "../Math/Transform.h" #include "../Core/Memory.h" #include "../Loaders/ObjMesh.h" #include "../Core/Ray.h" #include "../Core/Intersection.h" #include "../Core/BSDF.h" namespace Aya { class TriangleMesh { UniquePtr<Transform> w2o, o2w; uint32_t m_tris, m_verts; uint32_t *mp_vert_idx; MeshVertex *mp_vertices; public: TriangleMesh() : m_tris(0), m_verts(0), mp_vert_idx(nullptr), mp_vertices(nullptr) {} ~TriangleMesh() { release(); } void release() { SafeDeleteArray(mp_vertices); m_tris = 0; m_verts = 0; } void loadMesh(const Transform &o2w, const ObjMesh *obj_mesh); void loadSphere(const Transform &o2w, const float radius, const uint32_t slices = 64, const uint32_t stacks = 64); void loadPlane(const Transform &o2w, const float length); void postIntersect(const Ray &ray, SurfaceIntersection *intersection) const; // Data Interface __forceinline const Point3& getPositionAt(uint32_t idx) const { assert(idx < 3 * m_tris); assert(mp_vertices); assert(mp_vert_idx); return mp_vertices[mp_vert_idx[idx]].p; } __forceinline const Normal3& getNormalAt(uint32_t idx) const { assert(idx < 3 * m_tris); assert(mp_vertices); assert(mp_vert_idx); return mp_vertices[mp_vert_idx[idx]].n; } __forceinline const Vector2f& getUVAt(uint32_t idx) const { assert(idx < 3 * m_tris); assert(mp_vertices); assert(mp_vert_idx); return mp_vertices[mp_vert_idx[idx]].uv; } __forceinline const uint32_t *getIndexAt(uint32_t idx) const { assert(idx < 3 * m_tris); assert(mp_vertices); assert(mp_vert_idx); return &mp_vert_idx[3 * idx]; } __forceinline const uint32_t* getIndexBuffer() const { return mp_vert_idx; } __forceinline uint32_t getTriangleCount() const { return m_tris; } __forceinline uint32_t getVertexCount() const { return m_verts; } }; } #endif
true
e806e240b4ce8c5c036f2cdcc55d3bb6c95a3fd9
C++
srfunksensei/OS2
/source/pokusajOS/pokusajOS/fs.cpp
UTF-8
1,048
2.8125
3
[ "Apache-2.0" ]
permissive
#include "fs.h" #include "kernelfs.h" FS::FS(){ myImpl = new KernelFS(); } FS::~FS(){ delete myImpl; } char FS::mount(Partition* partition){ return KernelFS::mount(partition); } char FS::unmount(char part){ return KernelFS::unmount(part); } char FS::format(char part){ return KernelFS::format(part); } BytesCnt FS::freeSpace(char part){ return KernelFS::freeSpace(part); } BytesCnt FS::partitionSize(char part){ return KernelFS::partitionSize(part); } char FS::doesExist(char* fname){ return myImpl->doesExist(fname); } File* FS::open(char* fname, char mode){ return myImpl->open(fname, mode); } char FS::deleteFile(char* fname){ return myImpl->deleteFile(fname); } char FS::createDir(char* dirname){ return myImpl->createDir(dirname); } char FS::readDir(char* dirname, EntryNum num, Directory &dir){ return myImpl->readDir(dirname, num, dir); } char FS::deleteDir(char* dirname){ return myImpl->deleteDir(dirname); } char* FS::pwd(){ return myImpl->pwd(); } char FS::cd(char* dirname){ return myImpl->cd(dirname); }
true
e19943810c127c092afaa314765e3e09cfb7d44b
C++
shriki001/Pacman
/Project_Pacman/StaticObject.h
UTF-8
503
2.53125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include "Settings.h" class StaticObject { public: virtual void draw(sf::RenderWindow&)const = 0; // draw object on the window virtual sf::Vector2f getCenter() const = 0;// get object center virtual sf::Vector2f getPosition() const=0; // get object position sf::Color getColor() const; // get object color sf::Sprite getObject() const; // return object protected: sf::Sprite m_body; sf::Texture m_texture; sf::Color m_color; };
true
d8484355be7e19243180a89129ee74ec2c4964a4
C++
Stevensishernandez/ACE2_2S21_G16
/Practica 1/Arduino/sketch_feb08a/sketch_feb08a.ino
UTF-8
3,279
2.71875
3
[]
no_license
//Sensor de ritmo cardiaco variables int PulseSensor = A0 ; int PulseSensorAux = 0 ; // Conecte el cable rojo del sensor en pin analogico cero int Signal = 0; //Valor del sensor de pulso int Threshold = 520; //Dato analogico considerado como un pulso //Sensor de temperatura variables int sensor; float temperatura; float suma; float suma1; void setup() { Serial.begin(9600); // Velocidad de comunicacion del arduino //Serial1.begin(57600); // Velocidad de comunicacion con el modulo Bluetooth HC-05 //Serial1.begin(38400); // Velocidad de comunicacion con el modulo Bluetooth HC-05 Serial1.begin(9600); // Velocidad de comunicacion con el modulo Bluetooth HC-05 pinMode(LED_BUILTIN, OUTPUT); } int i = 0; void loop(){ /*********Prueba de temperatura con bluetooth*********/ if(i < 40){ sensor = analogRead(A1); temperatura = ((sensor*5000.0)/1023)/10; suma1 += temperatura - 3; i++; }else{ i = 0; suma = suma1; suma1 = 0; } /*suma = 0; for(int i=0; i<5; i++){ sensor = analogRead(A1); temperatura = ((sensor*5000.0)/1023)/10; suma += temperatura; delay(100); }*/ //Serial.println(suma/5.0, 1); //Serial1.print("T: "+String(suma/40.0,1)); //delay(1000); /*********Prueba sensor cardiaco con bluetooth*********/ Signal = analogRead(PulseSensor); //Lectura de datos del sensor de ritmo cardiaco //Serial.write(Signal); if(Signal > 520){ PulseSensorAux = Signal; } Serial.println("T:"+String(suma/40.0,1)+",P:"+String(PulseSensorAux)); //Serial1.print("T:"+String(suma/5.0,1)+",P:"+String(Signal)); //Serial1.print("hola "+String(Signal)); //jala de ahuevo //delay(500); //Envio para app Serial1.print("*G"); Serial1.print(String(Signal)); Serial1.print("*"); //Serial.println(Signal); delay(100); //Pulso y envio por blue //digitalWrite(LED_BUILTIN, LOW); //Uso de led arduino para latidos /*if(Signal > Threshold){ Serial1.print("hola "+String(Signal)); //jala de ahuevo //digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second } if(Signal <= Threshold){ Serial1.print("hola nada"); //jala de ahuevo //digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); }*/ //Recepcion de datos bluetooth /*if(Serial1.available()){ c = Serial1.read(); //Serial.write(c); digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW }*/ //Envio de datos bluetooth /*int state = 0; digitalWrite(LED_BUILTIN, LOW); if(Serial1.available()){//Envio de datos bluetooth state = Serial1.read(); if (state == 'E') { //Bluetooth desactiva leds de salida digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(5000); } }else{ Serial1.print("hola "+String(i)); //jala de ahuevo //Serial1.write("hola "+String(i)); i = i+1; delay(1000); }*/ }
true
af7ce9065136cabe0a63e91415a5f1b85e08ddec
C++
NordicArts/NordicEngine
/NordicEngine/Color/Color.cpp
UTF-8
3,642
2.875
3
[]
no_license
#include <NordicEngine/Color/Color.hpp> namespace NordicArts { namespace NordicEngine { const Color Color::Black(0, 0, 0); const Color Color::White(255, 255, 255); const Color Color::Red(255, 0, 0); const Color Color::Green(0, 255, 0); const Color Color::Blue(0, 0, 255); const Color Color::Yellow(255, 255, 0); const Color Color::Magenta(255, 0, 255); const Color Color::Cyan(0, 255, 255); const Color Color::Transparent(0, 0, 0, 0); Color::Color() : m_iRed(0), m_iGreen(0), m_iBlue(0), m_iAlpha(255) { } Color::Color(uint8_t iRed, uint8_t iGreen, uint8_t iBlue, uint8_t iAlpha) : m_iRed(iRed), m_iGreen(iGreen), m_iBlue(iBlue), m_iAlpha(iAlpha) { } Color::Color(std::string cHex) { // Remove the hash size_t nFound = cHex.find("#"); if (nFound != std::string::npos) { cHex = cHex.erase(0, 1); } int iColor = (int)std::strtol(cHex.c_str(), NULL, 16); m_iRed = (iColor >> 16); m_iGreen = (iColor >> (8 & 0xFF)); m_iBlue = (iColor & 0xFF); m_iAlpha = 255; } float Color::getRed() const { return (float)m_iRed; } float Color::getGreen() const { return (float)m_iGreen; } float Color::getBlue() const { return (float)m_iBlue; } float Color::getAlpha() const { return (float)m_iAlpha; } bool operator ==(const Color &oLeft, const Color &oRight) { return ( (oLeft.m_iRed == oRight.m_iRed) && (oLeft.m_iGreen == oRight.m_iGreen) && (oLeft.m_iBlue == oRight.m_iBlue) && (oLeft.m_iAlpha == oRight.m_iAlpha) ); } bool operator !=(const Color &oLeft, const Color &oRight) { return !(oLeft == oRight); } Color operator +(const Color &oLeft, const Color &oRight) { return Color( NA_UINT8(std::min(int(oLeft.m_iRed) + oRight.m_iRed, 255)), NA_UINT8(std::min(int(oLeft.m_iGreen) + oRight.m_iGreen, 255)), NA_UINT8(std::min(int(oLeft.m_iBlue) + oRight.m_iBlue, 255)), NA_UINT8(std::min(int(oLeft.m_iAlpha) + oRight.m_iAlpha, 255)) ); } Color operator -(const Color &oLeft, const Color &oRight) { return Color( NA_UINT8(std::max(int(oLeft.m_iRed) - oRight.m_iRed, 0)), NA_UINT8(std::max(int(oLeft.m_iGreen) - oRight.m_iGreen, 0)), NA_UINT8(std::max(int(oLeft.m_iBlue) - oRight.m_iBlue, 0)), NA_UINT8(std::max(int(oLeft.m_iAlpha) - oRight.m_iAlpha, 0)) ); } Color operator *(const Color &oLeft, const Color &oRight) { return Color( NA_UINT8((int(oLeft.m_iRed) * oRight.m_iRed) / 255), NA_UINT8((int(oLeft.m_iGreen) * oRight.m_iGreen) / 255), NA_UINT8((int(oLeft.m_iBlue) * oRight.m_iBlue) / 255), NA_UINT8((int(oLeft.m_iAlpha) * oRight.m_iAlpha) / 255) ); } Color &operator +=(Color &oLeft, const Color &oRight) { return oLeft = (oLeft + oRight); } Color &operator -=(Color &oLeft, const Color &oRight) { return oLeft = (oLeft - oRight); } Color &operator *=(Color &oLeft, const Color &oRight) { return oLeft = (oLeft * oRight); } }; };
true
fa891c5be1fa52861cc1254c122ed4ba11f27df3
C++
HargovindArora/Programming
/Problems/countSubSequences.cpp
UTF-8
694
2.546875
3
[]
no_license
#include<bits/stdc++.h> #define MOD 1000000007 #define ll long long int using namespace std; const int MAX_CHAR = 256; ll distinctSubSeqDP(string s){ vector<int> last(MAX_CHAR, -1); // (size, intial value) int n = s.size(); ll dp[n+1] = {0}; dp[0] = 1; for(int i=1; i<=n; i++){ dp[i] = (dp[i-1]*2)%MOD; if(last[s[i-1]]!=-1){ dp[i] = dp[i] = (dp[i] - dp[last[s[i-1]]]+MOD)%MOD; } last[s[i-1]] = (i-1); } return (dp[n]); } void solve(){ string s; cin >> s; cout << distinctSubSeqDP(s) << endl; return; } int main(){ int t; cin >> t; while(t--){ solve(); } return 0; }
true
8f30aab12b9ea24a324d4280506ecc2c40fbf095
C++
Vijaydurga/c-assignments
/assignment-1/sum-of-digits/Source.cpp
UTF-8
226
2.546875
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; int main() { int n, r = 0, s = 0; cin >> n; getchar(); while (n > 0) { r = n % 10; s = s + r; n = n / 10; } cout << s; getchar(); }
true
8ab68ef8f8b8b3eb3d31d6a7d2f4b9505ea892cd
C++
Twinklebear/crafting-interpreters
/antlr4-interpreter/main.cpp
UTF-8
2,519
2.8125
3
[ "MIT" ]
permissive
#include <fstream> #include <iostream> #include <string> #include <vector> #include "LoxLexer.h" #include "LoxParser.h" #include "antlr4-runtime.h" #include "ast_builder.h" #include "ast_printer.h" #include "interpreter.h" #include "resolver.h" #include "util.h" using namespace loxgrammar; void run_file(const std::string &file); void run_prompt(); void run(antlr4::ANTLRInputStream &input, Interpreter &interpreter); int main(int argc, char **argv) { if (argc > 2) { std::cerr << "Usage: interpreter [script]\n"; return 1; } if (argc == 2) { run_file(argv[1]); } else { run_prompt(); } return 0; } void run_file(const std::string &file) { antlr4::ANTLRFileStream input; input.loadFromFile(file); try { Interpreter interpreter; run(input, interpreter); } catch (const InterpreterError &e) { if (e.token) { // This seems to still crash with the file input stream? std::cerr << "[error] at " << e.token->getLine() << ":" << e.token->getCharPositionInLine() << ": " << e.message << "\n"; } else { std::cerr << "[error] " << e.message << "\n"; } throw e; } catch (const std::runtime_error &e) { std::cerr << "interpreter error: " << e.what() << "\n"; std::exit(1); } } void run_prompt() { std::cout << "> "; std::string line; Interpreter interpreter; while (std::getline(std::cin, line)) { antlr4::ANTLRInputStream input(line); try { run(input, interpreter); } catch (const InterpreterError &e) { // Prompt doesn't quit on errors, just prints them (in run) } std::cout << "> "; } } void run(antlr4::ANTLRInputStream &input, Interpreter &interpreter) { LoxLexer lexer(&input); antlr4::CommonTokenStream tokens(&lexer); tokens.fill(); for (const auto &t : tokens.getTokens()) { std::cerr << t->toString() << "\n"; } // TODO: handle errors in parser LoxParser parser(&tokens); antlr4::tree::ParseTree *tree = parser.file(); std::cerr << tree->toStringTree(&parser) << "\n"; ASTBuilder ast_builder; ast_builder.visit(tree); Resolver resolver(interpreter); resolver.resolve(ast_builder.statements); ProgramPrinter printer; std::cerr << "Program:\n" << printer.print(ast_builder.statements) << "------\n"; interpreter.evaluate(ast_builder.statements); }
true
41610ae303ea60219b43ce9b8d086c11d4f14ecc
C++
gnulnx/dynamol
/old_complete/dynamol/trunk/Main_Build/dynacomp/angle.h
UTF-8
1,058
2.640625
3
[]
no_license
/***************************************** * Copyright (C) 2004 by Dynamol * * email: john.furr@dynamol.com * * *************************************/ #ifndef DYNACOMPANGLE_H #define DYNACOMPANGLE_H namespace dynacomp { class atom; /** \brief A Molecular Mechanis/Dynamics Angle class * * Most (all) Modern Molecular Mechanics Force Fields have an angle term * This class provides the necassary equilibrium angles and force constants * that are used in these calculations @author jfurr */ class angle { public: angle(atom *front, atom *mid, atom *back); ~angle(); /** \brief The Degree of the Angle * * This function returns the angle in Degrees */ float degree(); protected: /** \brief The Angle assignment operator * * This is the angle assignment operator */ angle &operator=(const angle &ang); public: atom *front, *mid, *back; float refAngle; float actualAngle; float K; float stepSize; float prevEnergy; }; }//End Namespace #endif
true
6ae4341ea0d4814dd19f4fb732baf98576b39565
C++
RishabhDevbanshi/C-Codes
/Bit-Manipulation/unique-element-in-array.cpp
UTF-8
130
2.828125
3
[]
no_license
void unique(vec(int) arr) { int xorsum = 0; loop(i, 0, arr.size()) { xorsum = xorsum ^ arr[i]; } cout << xorsum << endl; }
true
5f10b76d66e5a6c2b61b6197e71e5596132af5e1
C++
gabrielegenovese/Esercizi-Programmazione-2020
/Esercizi/Stringhe/Parametri/main.cpp
UTF-8
865
3.40625
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; void parola(char str[], char c, char dest[]) { int j = 0, i = 1; // trovo la parola (per trovare la prima parola bisogna mettere prima uno spazio) while (str[i] != '\0' && (str[i] != c || str[i-1] != ' ')) i++; // la inserisco in dest while (str[i] != '\0' && str[i] != ' ') { dest[j] = str[i]; i++; j++; } dest[j] = '\0'; } void stampa(char arr[]) { int i = 0; while (arr[i] != '\0') { cout << arr[i] << ' '; i++; } cout << endl; } int main() { int length = 30; char str[] = " ciao mi chiamo gabriele e sono un informatico\0"; char dest[length], find; cout << str << endl; cout << "Inserire un carattere: "; cin >> find; parola(str, find, dest); stampa(dest); return(0); }
true
7f3ed4a5101dd166023ff9fe7a22046e1f1263ac
C++
signalcompose/libSimpleControl
/example/macOS/01_Serialized_test/Serialized_test/main.cpp
UTF-8
2,264
3.25
3
[]
no_license
// // main.cpp // Serializer_test // // Created by leico_studio on 2019/08/17. // Copyright © 2019 leico_studio. All rights reserved. // #include <iostream> #include <vector> #include <array> #include <list> #include "Serialized.hpp" /** * @brief dummy class to check copy function */ class dummy{ std :: size_t size( void ){ return 10; } }; using SimpleControl :: Serialized; /** * @brief a function for output function result */ void print( const Serialized :: value_type value ){ std :: cout << static_cast< int >( value ) << std :: endl; } /** * @brief a function for output boolean result */ void bool_print( const bool value ){ std :: cout << std :: boolalpha << value << std :: endl; } int main( void ) { { Serialized default_constructor_test; print(default_constructor_test[ 2 ]); Serialized copy_constructor_test( default_constructor_test ); print(copy_constructor_test[ 4 ]); Serialized :: value_type array[ Serialized :: SIZE ] = { 1, 2, 3, 4, 5 }; Serialized array_constructor_test( array ); print(array_constructor_test[ 1 ]); std :: vector< Serialized :: value_type > vec{ 1, 2, 3, 4, 5, 6, 7 }; Serialized vec_constructor_test( vec ); print(vec_constructor_test[ 4 ]); std :: array< Serialized :: value_type, Serialized :: SIZE > arr{ 1, 2, 3, 4, 5 }; Serialized arr_constructor_test( arr ); print(array_constructor_test[ 0 ]); std :: list< Serialized :: value_type > list{ 1, 2, 3, 4, 5, 6 }; Serialized list_constructor_test( list ); print(list_constructor_test[ 3 ]); //dummy d; //Serialized custom_class_test( d ); } Serialized arr = { 1, 2, 3, 4, 5 }; try{ for( int i = 0 ; i != Serialized :: SIZE + 1 ; ++ i ) print( arr.at( i ) ); } catch( std :: out_of_range& e ){ std :: cout << e.what() << std :: endl; } Serialized address_test{ 128, 134, 158, 128, 0b11110110 }; bool_print( address_test.is_correct() ); bool_print( address_test.is_address() ); bool_print( address_test.is_data () ); Serialized data_test{ 100, 127, 50, 79, 0b01110010 }; bool_print( data_test.is_correct() ); bool_print( data_test.is_address() ); bool_print( data_test.is_data () ); return 0; }
true
2f4998c4e0202c3273fbd1111ed6fa063d89b20f
C++
adityanjr/code-DS-ALGO
/CodeForces/Complete/1-99/17B-Hierarchy.cpp
UTF-8
612
2.8125
3
[ "MIT" ]
permissive
#include <cstdio> #include <map> int main(){ long n; scanf("%ld", &n); for(long p = 0; p < n; p++){long x; scanf("%ld", &x);} //Irrelevant long m; scanf("%ld", &m); std::map<long, long> cost; while(m--){ long x, y, c; scanf("%ld %ld %ld", &x, &y, &c); if(cost.count(y) > 0){cost[y] = (cost[y] < c) ? cost[y] : c;} else{cost[y] = c;} } if(cost.size() < n - 1){puts("-1"); return 0;} long long total(0); for(std::map<long, long>::iterator it = cost.begin(); it != cost.end(); it++){total += it->second;} printf("%lld\n", total); return 0; }
true
277d90645417db87f0246f5f0c13e5ffd3a57f78
C++
DEAKSoftware/Panoramic-Rendering
/source/system/systimer.cpp
UTF-8
4,512
2.703125
3
[ "MIT" ]
permissive
/*============================================================================*/ /* Cosmic Ray [Tau] - Dominik Deak */ /* */ /* System Timer Functions (at this stage Windows 9x and NT only) */ /*============================================================================*/ /*---------------------------------------------------------------------------- Don't include this file if it's already defined. ----------------------------------------------------------------------------*/ #ifndef __SYSTIMER_CPP__ #define __SYSTIMER_CPP__ /*---------------------------------------------------------------------------- Include libraries and other source files needed in this file. ----------------------------------------------------------------------------*/ #include "../_common/std_inc.h" /*---------------------------------------------------------------------------- System timer class. ----------------------------------------------------------------------------*/ class SystemTimerClass { /*==== Private Declarations ===============================================*/ private: bool TS_Valid; qword LastCount; qword Frequency; float FreqInv; /*==== Public Declarations ================================================*/ public: /*---- Constructor --------------------------------------------------------*/ SystemTimerClass(void) { //==== Win32 specific ==== #if defined (WIN32) || defined (WIN32_NT) if ((QueryPerformanceFrequency((LARGE_INTEGER*)&Frequency) != 0) && (QueryPerformanceCounter((LARGE_INTEGER*)&LastCount) != 0)) { FreqInv = 1.0f / (float)Frequency; TS_Valid = true; } else { TS_Valid = false; LastCount = 0; Frequency = 0; FreqInv = 0.0f; } //==== Other OS ==== #else TS_Valid = false; LastCount = 0; Frequency = 0; FreqInv = 0.0f; #endif } /*---- Destructor ---------------------------------------------------------*/ ~SystemTimerClass(void) {} /*------------------------------------------------------------------------- Returns the current time stamp. -------------------------------------------------------------------------*/ inline qword ReadTS(void) { if (!TS_Valid) {return 0;} qword Count; //==== Win32 specific ==== #if defined (WIN32) || defined (WIN32_NT) if (QueryPerformanceCounter((LARGE_INTEGER*)&Count) == 0) {return 0;} //==== Other OS ==== #else Count = 0; #endif return Count; } /*------------------------------------------------------------------------- Sets up the delay measurement by initializing the LastCount register. -------------------------------------------------------------------------*/ inline void TS_DiffStart(void) { if (!TS_Valid) {return;} LastCount = ReadTS(); } /*------------------------------------------------------------------------- Returns the delay in time stamp counts. -------------------------------------------------------------------------*/ inline qword ReadTS_Diff(void) { if (!TS_Valid) {return 0;} qword Count = ReadTS(); qword Diff = Count - LastCount; LastCount = Count; return Diff; } /*------------------------------------------------------------------------- Returns the delay in seconds. -------------------------------------------------------------------------*/ inline float ReadTS_DiffSec(void) { if (!TS_Valid) {return 0.0f;} qword Diff = ReadTS_Diff(); return (float)Diff * FreqInv; } /*==== End Class ==========================================================*/ }; /*---------------------------------------------------------------------------- Global Declarations. ----------------------------------------------------------------------------*/ SystemTimerClass SystemTimer; /*==== End of file ===========================================================*/ #endif
true
b14f5ebbc8caee91d7c9f6c36a9a44a7087636b5
C++
ChankiWu/parallel-computing
/hw2_matrix_thread.cpp
UTF-8
2,512
3.453125
3
[]
no_license
#include<iostream> #include<time.h> #include<vector> #include<mutex> using namespace std; using matrix = vector<vector<int> >; // maximum size of matrix #define MAX 256 // maximum number of threads #define MAX_THREAD 256 matrix matA(MAX, vector<int>(MAX, 0)); matrix matB(MAX, vector<int>(MAX, 0)); matrix matC(MAX, vector<int>(MAX, 0)); int step = 0; mutex m; void* multi(void* arg) { m.lock(); int core = step++; m.unlock(); // Each thread computes 1/MAX th of matrix multiplication for (int i = core * MAX / MAX_THREAD; i < (core + 1) * MAX / MAX_THREAD; i++) for (int j = 0; j < MAX; j++) for (int k = 0; k < MAX; k++) matC[i][j] += matA[i][k] * matB[k][j]; } // Driver Code int main() { struct timespec start, finish; double elapsed; // Generating random values in matA and matB for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { matA[i][j] = rand() % 100; matB[i][j] = rand() % 100; } } /* // Displaying matA cout << endl << "Matrix A" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matA[i][j] << " "; cout << endl; } // Displaying matB cout << endl << "Matrix B" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matB[i][j] << " "; cout << endl; } */ clock_gettime(CLOCK_MONOTONIC, &start); // declaring four threads pthread_t threads[MAX_THREAD]; // Creating four threads, each evaluating its own part for (int i = 0; i < MAX_THREAD; i++) { int* p; pthread_create(&threads[i], NULL, multi, (void*)(p)); } // joining and waiting for all threads to complete for (int i = 0; i < MAX_THREAD; i++) pthread_join(threads[i], NULL); clock_gettime(CLOCK_MONOTONIC, &finish); elapsed = (finish.tv_sec - start.tv_sec); elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; /* // Displaying the result matrix cout << endl << "Multiplication of A and B" << endl; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) cout << matC[i][j] << " "; cout << endl; } */ cout << "\nTotal Time : " << elapsed << " s" << endl; return 0; }
true
a5d988b4817b0125b3929a1cf02831d9a8200941
C++
abdullah-abwisk/C-Plus-Plus
/021_Pascal_Triangle.cpp
UTF-8
2,309
3.78125
4
[]
no_license
/* Programming Fundamentals : Assignment 03 : Q4 Abdullah Khan : DS-N : 20i-0894 : Pascal's Triangle */ #include <iostream> using namespace std; int main() { int row, ans = 1, space = 0, display_num, i, j, k; cout << "Input number of rows : "; cin >> row; cout << "Enter the display number: "; cin >> display_num; switch(display_num) { case 1: space = row; i = 0; while (i < row) { k = 0; while (k < space) { cout << " "; k++; } j = 0; while (j <= i) { if (j == 0) { ans = 1; } else { ans = ans * (i - j + 1) / j; } cout << ans << " "; j++; } cout << endl; space--; i++; } break; case 3: i = row; while (i > -1) { k = 0; while (k <= space) { cout << " "; k++; } j = 0; while (j <= i) { if (j == 0) { ans = 1; } else { ans = ans * (i - j + 1) / j; } cout << ans << " "; j++; } cout << endl; space++; i--; } space = 0; space = row; i = 1; while (i < row + 1) { k = 0; while (k < space) { cout << " "; k++; } j = 0; while (j <= i) { if (j == 0) { ans = 1; } else { ans = ans * (i - j + 1) / j; } cout << ans << " "; j++; } cout << endl; space--; i++; } break; case 2: space = row - 1; i = 0; while (i < row) { k = 0; while (k <= space) { cout << " "; k++; } j = 0; while (j <= i) { if (j == 0) { ans = 1; } else { ans = ans * (i - j + 1) / j; } cout << ans << " "; j++; } cout << endl; space--; i++; } i = row; while (i > -1) { k = 0; while (k <= space) { cout << " "; k++; } j = 0; while (j <= i) { if (j == 0) { ans = 1; } else { ans = ans * (i - j + 1) / j; } cout << ans << " "; j++; } cout << endl; space++; i--; } break; default: cout << "Invalid number."; } return 0; }
true
3b5dc86c750640aa5b76bc90240ea9c781377cc4
C++
ZephyrZhng/code_ub
/cpp/pda2cfg/number.cpp
UTF-8
806
3.390625
3
[]
no_license
#include "number.h" Number::Number() { } Number::Number(int _r): r(_r) { num.push_back(0); } void operator ++(Number& n) { int carry = 0; n.num[n.num.size() - 1] += 1; if(n.num[n.num.size() - 1] >= n.r) { n.num[n.num.size() - 1] -= n.r; carry = 1; } for(int i = n.num.size() - 2; i >= 0 && carry != 0; --i) { n.num[i] += carry; carry = 0; if(n.num[i] >= n.r) { n.num[i] -= n.r; carry = 1; } } if(carry != 0) { n.num.insert(n.num.begin(), 1); } } void Number::setLen(int len) { while(num.size() < len) { num.insert(num.begin(), 0); } } bool Number::isMax() { for(int i = 0; i < num.size(); ++i) { if(num[i] != r - 1) { return false; } } return true; } void Number::display() { for_each(num.begin(), num.end(), [](const int& i){ cout << i; }); }
true
1a06a9a321e507b376ff93c104a6411a14a59315
C++
Delicious-Goat/Groups
/Groups.cpp
UTF-8
1,762
2.53125
3
[]
no_license
#include "stdafx.h" #include "Groups.h" Groups::Groups(QWidget *parent) : QMainWindow(parent), screenHeight(0), screenWidth(0), windowHeight(0), windowWidth(0) { ui.setupUi(this); } //Extend show method of base class void Groups::show() { centerAndResize(); setBackgroundColor(255,255,255); OutputDebugStringA("Here"); //run show of base class QMainWindow::show(); } // get the dimension available on this screen void Groups::centerAndResize() { QSize availableSize = qApp->desktop()->availableGeometry().size(); screenWidth = availableSize.width(); screenHeight = availableSize.height(); //Control how large window is relative to screen dimensions windowWidth = screenWidth * 0.75; windowHeight = screenHeight * 0.75; QSize newSize(windowWidth, windowHeight); setGeometry( QStyle::alignedRect( Qt::LeftToRight, Qt::AlignCenter, newSize, qApp->desktop()->availableGeometry() ) ); } void Groups::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setPen(QPen(Qt::black, 4, Qt::SolidLine, Qt::FlatCap)); painter.drawLine(windowWidth*.4,windowHeight*.111, windowWidth* .4, windowHeight*.889); } void Groups::resizeEvent(QResizeEvent* event) { //Reset window size QSize availableSize = qApp->desktop()->availableGeometry().size(); windowWidth = size().width(); windowHeight = size().height(); //Update widget update(); } void Groups::setBackgroundColor(int r, int g, int b) { QPalette pal = palette(); // set black background pal.setColor(QPalette::Background, QColor(r,g,b)); setAutoFillBackground(true); setPalette(pal); }
true
0e841e4bc0acd1beab4926145e45e6447af6223e
C++
togekk/togekk.github.io
/wasm/array_index_of_object_array/string.cpp
UTF-8
757
3.265625
3
[]
no_license
#include <stdio.h> // for 'printf' function #include <string.h> // for 'strtok' & 'strcmp' #include <stdlib.h> // for 'free' function using namespace std; extern "C" { // get object array from javascript int arrayIndexOf(char* arr, char* value_selected, int arr_length, int key_length) { char* a; int id = 0; int id_found = -1; strtok(arr, "\""); do { a = strtok(NULL, "{,\"}"); if (strcmp(a, value_selected) == 0) { id_found = id; } id++; } while (strcmp(a, value_selected) != 0 && id < arr_length * key_length * 3); if (id_found >= 0) { return (id_found / key_length) / 3; } else { return -1; } free(value_selected); free(arr); } }
true
3ca1ec1ca42b10b582ddf4582829d597849bc3ba
C++
thedeepestreality/diods
/Observer.cpp
UTF-8
5,217
2.65625
3
[]
no_license
//#include "Observer.h" #include <cstdio> #include <sstream> #include <cmath> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> //#include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; #define pi 3.141593 class Observer { private: double x; double y; double phi; public: void FindCoords(cv::Mat &img); void SetCoords(double x, double y, double phi); double GetX() {return x;} double GetY() {return y;} double GetPhi() {return phi;} }; void Observer::FindCoords(Mat &img) { vector<vector<Point> > contours; vector<Vec4i> hierarchy; vector<Point> approx; double square_side = 0.0; //in pixels (измеренная в ходе работы алгоритма) double square_side_cm = 12.2; //сторона квадарата в реале, в сантиметрах, измеренная заранее double square_side_max = 0.0; // максимальная сторона квадрата - скорее все искомая не "деформированная" проекцией double square_side_min = 0.0; // минимальная сторона - та, которая поернулась double distance = 0.0; //перпендикуляр до плоскости, параллельной плоскости изображения, проходящей через центр маячка double sides[4] = {0.0, 0.0, 0.0, 0.0}; // стороны квадрата - маячка double angle = 0.0; //угол поворота робота вокруг своей оси - фи double focal_length = 700.0; double from_mayat_center_to_image_center_in_px = 0.0; double x_coord = 0.0; double x_min = 100000.0, x_max = 0.0; double a1=0, a2=0, b1=0, b2=0; Point diag_intersection; Mat gray(img.size(),CV_8UC1); cvtColor(img,gray,CV_BGR2GRAY); threshold(gray,gray,150,255,THRESH_BINARY); findContours(gray,contours,hierarchy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE); for (int i=0;i<contours.size();++i) { approxPolyDP(contours[i],approx,arcLength(contours[i],true)*0.02,true); if (approx.size()==4 && contourArea(approx,0)>100 && isContourConvex(approx)) { if (hierarchy[i][2]>=0) { //Оцениваем сторону квадрата circle(img, approx[0], 6, Scalar(0,0,255),3); circle(img, approx[1], 6, Scalar(0,255,0),3); circle(img, approx[2], 6, Scalar(255,0,0),3); circle(img, approx[3], 6, Scalar(0,0,0),3); circle(img, approx[4], 6, Scalar(0,100,20),3); // я думал все четыре точки в контуре, ан нет. //красный - зеленый = сторона square_side = sqrt(pow(approx[0].x-approx[1].x,2)+pow(approx[0].y-approx[1].y,2)); distance = (focal_length*square_side_cm)/square_side; printf("distance is %f\n", distance); for (int ii=0; ii<4; ii++){ if(approx[ii].x > x_max){ x_max = approx[ii].x; } if(approx[ii].x < x_min){ x_min = approx[ii].x; } } square_side_min = x_max - x_min; //наибольшая сторона "квадрата" for (int ii=0, max=0, min=100000; ii<4; ii++){ if (ii!=3){ sides[ii] = sqrt(pow(approx[ii].x-approx[ii+1].x,2)+pow(approx[ii].y-approx[ii+1].y,2)); } else { sides[ii] = sqrt(pow(approx[ii].x-approx[0].x,2)+pow(approx[ii].y-approx[0].y,2)); } if (sides[ii]>max){ max = sides[ii]; } square_side_max = max; } angle = acos(square_side_min/square_side_max) * 180 / pi; //нахождение центра маячка: это точка пересечения диагоналей //находим сначала уравнения прямых: коэффициенты a,b (ax+b=y) //потом находим точку пересечения (x,y) a1*x+b1=a2*x+b2 diag_intersection.x = (approx[0].x+approx[1].x+approx[2].x+approx[3].x)/4; diag_intersection.y = (approx[0].y+approx[1].y+approx[2].y+approx[3].y)/4; //считаем расстояние в пикселях от центра изображения до точки пересечения from_mayat_center_to_image_center_in_px = sqrt(pow(img.cols/2-diag_intersection.x,2)+pow(img.rows/2-diag_intersection.y,2)); x_coord = (distance * from_mayat_center_to_image_center_in_px) / focal_length; line(img, diag_intersection, Point(img.cols/2, img.rows/2), Scalar(255,0,0), 2); SetCoords(x_coord, distance, angle); printf("mat.cols(x): %d, Mat.rows(y): %d\n", img.cols, img.rows); printf("y(distance): %f, x: %f, angle: %f || from_mayat_to_center: %f\n", distance, x_coord, angle, from_mayat_center_to_image_center_in_px); vector<Point> child_approx; approxPolyDP(contours[hierarchy[i][2]],child_approx,arcLength(contours[hierarchy[i][2]],1)*0.02,1); if (child_approx.size()==4 && contourArea(child_approx,0)>100 && isContourConvex(child_approx)) { drawContours(img,contours,i,Scalar(0,255,0),3); drawContours(img,contours,hierarchy[i][2],Scalar(0,0,255),3); } } else { } } } } void Observer::SetCoords(double iks, double igrek, double fi) { x = iks; y = igrek; phi = fi; }
true
9f8528317ee1fe9de4a0d6fb630653ea056d3bdb
C++
BSU2015gr09/Khmelnikova
/firstSemester/Sum_do_0.cpp
WINDOWS-1251
460
3.109375
3
[]
no_license
/* */ #include <iostream> #include <clocale> #include <stdlib.h> using std::cout; using std::cin; int main() { setlocale(LC_ALL, "Russian"); long int a = 0, y=0,s=0; cout << " :" << "\n"; cin >> a ; while (a % 10!= 0) { y = a % 10; s = s+y; a = a / 10; } cout << " : " << s << "\n"; return 0; }
true
82d758c1d46b9562efc359386030c266651387db
C++
JosvanGoor/bbm
/old_code/engine/Font.hpp
UTF-8
2,892
3
3
[]
no_license
#ifndef ENGINE_FONT_HPP #define ENGINE_FONT_HPP #include <string> #include "../math/Vector3.hpp" #include "../math/Matrix4x4.hpp" #include "../extern/gl_core_4_4.h" namespace engine { class RenderableString; /* This class describes a Spritesheet font (v1), such a font consists of 2 files. the spritesheet (image), and a ,info file organized as follows: <file start> sheet_width sheet_height sprite_width sprite_height first_ascii_character advance_between_characters advance_between_newlines <for each character> width <file end> # denotes a comment and should be ignored. */ class Font { public: Font(const std::string &fontname); //searches for *.png & .info itsself. Font(const Font&) = delete; Font(const Font&&) = delete; ~Font(); bool contains(char c) const; //returns whether this char can be drawn. bool valid(const std::string &str); //returns whether string can be drawn. RenderableString* renderable_string(const std::string &str); void renderable_string(RenderableString *old, const std::string &str); //reuses old buffer for new string. protected: GLuint m_texture; char m_first; int m_advance; int m_newline_advance; int *widths; size_t m_sheet_width; size_t m_sheet_height; size_t m_sprite_width; size_t m_sprite_height; void parse_info(const std::string &file); }; class RenderableString { public: RenderableString(const RenderableString&) = delete; RenderableString(const RenderableString&&) = delete; ~RenderableString(); void draw() const; //setters/getters size_t width() const; size_t height() const; GLuint texture() const; GLuint vertex_buffer() const; std::string string() const; math::Vector3<float> color() const; void color(const math::Vector3<float> &color); math::Matrix4x4<float> transform() const; void transform(const math::Matrix4x4<float> &transform); protected: friend class Font; RenderableString() : m_height(0), m_width(0), m_triangles(0), m_texture(0), m_vertex_buffer(0), m_string(""), m_color(), m_transform() { }; size_t m_height; size_t m_width; size_t m_triangles; GLuint m_texture; GLuint m_vertex_array; GLuint m_vertex_buffer; std::string m_string; math::Vector3<float> m_color; math::Matrix4x4<float> m_transform; }; } #endif
true
59672948270f3f92bd72634524fe8994b6438aea
C++
symanli/just-p2p-live-p2pcommon2
/base/ppl/data/buffer.h
GB18030
6,485
3.015625
3
[]
no_license
#ifndef _LIVE_P2PCOMMON2_BASE_PPL_DATA_BUFFER_H_ #define _LIVE_P2PCOMMON2_BASE_PPL_DATA_BUFFER_H_ #include <ppl/config.h> #include <ppl/data/alloc.h> #include <boost/noncopyable.hpp> #include <algorithm> template <typename T, typename AllocT> class basic_buffer : private boost::noncopyable { public: typedef T element_type; typedef AllocT alloc_type; typedef basic_buffer<T, AllocT> this_type; typedef element_type* iterator; typedef element_type* const_iterator; enum { max_buffer_size = 32 * 1024 * 1024 + 1 }; basic_buffer() : m_data(NULL), m_capacity(0), m_size(0) { } explicit basic_buffer(const T* data, size_t size) : m_capacity(size), m_size(size) { if ( size > 0 ) { m_data = static_cast<element_type*>(AllocT::allocate(size * sizeof(element_type))); memcpy( m_data, data, size ); } else { m_data = NULL; } } explicit basic_buffer(size_t size) : m_capacity(size), m_size(size) { if ( size > 0 ) { m_data = static_cast<element_type*>(AllocT::allocate(size * sizeof(element_type))); } else { m_data = NULL; } } explicit basic_buffer(size_t size, const T& initialVal) : m_capacity(size), m_size(size) { if ( m_size > 0 ) { m_data = static_cast<element_type*>(AllocT::allocate(m_size * sizeof(element_type))); std::fill_n( m_data, m_size, initialVal ); } else { m_data = NULL; } } ~basic_buffer() { if (m_data != NULL) { AllocT::deallocate(m_data); m_data = NULL; m_capacity = 0; m_size = 0; } else { LIVE_ASSERT(m_capacity == 0 && m_size == 0); } } /// Ԥռ(ԭݱ) void reserve(size_t size) { LIVE_ASSERT(size < max_buffer_size); LIVE_ASSERT(m_size <= m_capacity); if (m_capacity >= size) return; this_type newBuffer(size); newBuffer.resize(m_size); if (m_size > 0) { memcpy(newBuffer.m_data, m_data, m_size); } this->swap(newBuffer); } /// Сԭݱδ֪ void resize(size_t size) { reserve(size); LIVE_ASSERT(m_capacity >= size); m_size = size; } /// ֤СΪָȣ֤Ч(ԭݿܶʧ) void ensure_size(size_t size) { resize(0); resize(size); } void assign( const element_type& elem ) { if ( m_data && m_size > 0 ) { std::fill_n( m_data, m_size, elem ); } } void assign( const this_type& src ) { this->assign( src.data(), src.size() ); } /// void assign(const element_type* src, size_t size) { if (size == 0) { this->resize(0); return; } LIVE_ASSERT(src != NULL && size > 0); LIVE_ASSERT(!::IsBadReadPtr(src, size)); resize(size); memcpy(m_data, src, size); LIVE_ASSERT(m_size == size); LIVE_ASSERT(m_capacity >= size); } void append(const element_type* src, size_t size) { size_t oldSize = m_size; resize(oldSize + size); memcpy(m_data + oldSize, src, size * sizeof(element_type)); } void append(size_t size, const element_type& elem) { size_t oldSize = m_size; resize(oldSize + size); std::fill_n(m_data + oldSize, elem, size); } void append(const this_type& src) { this->append(src.data(), src.size()); } /// ͷԴ void clear() { this_type buf; this->swap(buf); } void swap(this_type& b) { std::swap(m_data, b.m_data); std::swap(m_capacity, b.m_capacity); std::swap(m_size, b.m_size); } /// ȡݴС size_t size() const { return m_size; } /// ȡС size_t capacity() const { return m_capacity; } /// ǷΪ bool empty() const { return m_data == 0; } /// ȡдĻ element_type* data() { return m_data; } /// ȡֻĻ const element_type* data() const { return m_data; } element_type* begin() { return m_data; } const element_type* begin() const { return m_data; } element_type* end() { return m_data + m_size; } const element_type* end() const { return m_data + m_size; } /// element_type operator[](size_t index) const { LIVE_ASSERT(!empty()); LIVE_ASSERT(index < m_size); return m_data[index]; } /// element_type& operator[](size_t index) { LIVE_ASSERT(!empty()); LIVE_ASSERT(index < m_size); return m_data[index]; } private: /// element_type* m_data; /// С size_t m_capacity; /// ЧݴС size_t m_size; }; template<typename T, typename AllocT> inline void swap(basic_buffer<T, AllocT> & a, basic_buffer<T, AllocT> & b) // never throws { a.swap(b); } //typedef basic_buffer<char, pool_alloc> dynamic_buffer; typedef basic_buffer<char, malloc_alloc> char_buffer; typedef basic_buffer<unsigned char, malloc_alloc> byte_buffer; /* #ifdef _PPL_RUN_TEST class DynamicBufferTestCase : public TestCase { public: virtual void DoRun() { dynamic_buffer buf; LIVE_ASSERT(buf.empty()); CheckBuffer(buf, 0, 0, true); buf.reserve(1); CheckBuffer(buf, 1, 0); buf.resize(1); CheckBuffer(buf, 1, 1); buf.reserve(2); CheckBuffer(buf, 2, 1); buf.resize(2); CheckBuffer(buf, 2, 2); buf.resize(3); CheckBuffer(buf, 3, 3); buf.resize(19); CheckBuffer(buf, 19, 19); string str("Hello"); buf.assign(str.data(), str.size()); CheckBuffer(buf, 19, str.size()); LIVE_ASSERT(0 == memcmp(buf.data(), str.data(), str.size())); str = "111222333444555666777888999abcdefghijklmnopq"; buf.assign(str.data(), str.size()); CheckBuffer(buf, str.size(), str.size()); LIVE_ASSERT(0 == memcmp(buf.data(), str.data(), str.size())); buf.resize(64 * 1000); CheckBuffer(buf, 64 * 1000, 64 * 1000); dynamic_buffer buf2(110); LIVE_ASSERT(!buf2.empty()); LIVE_ASSERT(buf2.data() != NULL); LIVE_ASSERT(buf2.capacity() == 110); LIVE_ASSERT(buf2.size() == 110); } void CheckBuffer(const dynamic_buffer& buf, size_t capacity, size_t size, bool isNull = false) { LIVE_ASSERT(buf.capacity() == capacity); if (buf.size() != size) { LIVE_ASSERT(false); } LIVE_ASSERT(buf.size() == size); if (isNull) { LIVE_ASSERT(buf.data() == NULL); } else { LIVE_ASSERT(buf.data() != NULL); } } }; CPPUNIT_TEST_SUITE_REGISTRATION(DynamicBufferTestCase); #endif */ #endif
true
e1728b8d51654eb1d4bc096ce31495c6c6ac0272
C++
jainans/My-Leetcode-Solution-In-CPP
/CPP, C++ Solutions/1027. Longest Arithmetic Subsequence.cpp
UTF-8
1,399
3.140625
3
[ "MIT" ]
permissive
/************ Method-1 (TLE because of map, TC-O(N^2), SC-O(N^2)) ************ class Solution { public: int longestArithSeqLength(vector<int>& nums) { int n = nums.size(), cd, res = 0; vector<unordered_map<int, int>> dp(n); for(int i = 0; i < n; i++) { for(int j = i-1; j >= 0; j--) { cd = nums[i] - nums[j]; if(dp[j].find(cd) == dp[j].end()) dp[i][cd] = max(dp[i][cd], 2); else dp[i][cd] = max(dp[i][cd], 1 + dp[j][cd]); res = max(res, dp[i][cd]); } } return res; } }; ********************************************************************************/ /*************** Method-2 (Use 2D-vector, TC-O(N^2), SC-O(N*1001)) ***************/ class Solution { public: int longestArithSeqLength(vector<int>& nums) { int n = nums.size(), cd, res = 0; // We can pass nums array and find min and max elt to do more space optimization vector<vector<int>> dp(n, vector<int>(1001, 0)); for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { cd = nums[i] - nums[j]; dp[i][cd+500] = max(2, 1+dp[j][cd+500]); res = max(res, dp[i][cd+500]); } } return res; } };
true
2fbd11cd14ab5bf43c439c129f12d5a1f3601bc3
C++
h8liu/usaco
/starry/starry.cpp
UTF-8
6,342
2.859375
3
[]
no_license
/* ID: liulonn1 PROG: starry LANG: C++ */ #include <cstdio> #include <cassert> #include <cstring> #include <cstdlib> #include <vector> using std::vector; inline int _ind(int x, int y) { return (x << 7) | (y & 0x7f); } struct Bound { int minRow, maxRow; int minCol, maxCol; int _w, _h; int count; int code; void init(int r, int c) { count = 0; minRow = maxRow = r; minCol = maxCol = c; } int w() { return maxCol - minCol + 1; } int h() { return maxRow - minRow + 1; } int isDot() { return maxCol == minCol && maxRow == minRow; } void add(int r, int c) { count++; if (r < minRow) { minRow = r; } if (r > maxRow) { maxRow = r; } if (c < minCol) { minCol = c; } if (c > maxCol) { maxCol = c; } } int ind(int r, int c) { return _ind(minRow + r, minCol + c); } int ind1(int m, int r, int c) { switch (m) { case 1: return _ind(maxRow - r, minCol + c); case 2: return _ind(minRow + r, maxCol - c); case 3: return _ind(maxRow - r, maxCol - c); case 0: default: return _ind(minRow + r, minCol + c); } } int ind2(int m, int r, int c) { return ind1(m, c, r); } void calcSize() { _w = w(); _h = h(); } }; struct Prob { FILE * fin; FILE * fout; int w, h; int pic[128 * 128]; Bound bounds[512]; int outputChar[512]; int ind(int x, int y) { return _ind(x, y); } void indr(int ind, int & x, int & y) { x = (ind >> 7) & 0x7f; y = ind & 0x7f; } bool validCord(int x, int y) { return x >= 0 && x < h && y >= 0 && y < w; } int get(int x, int y) { return pic[ind(x, y)]; } void set(int x, int y, int v) { pic[ind(x, y)] = v; } void readIn() { fin = fopen("starry.in", "r"); assert(fin); int ret = fscanf(fin, "%d", &w); assert(ret == 1); ret = fscanf(fin, "%d", &h); assert(ret == 1); char buf[128]; for (int i = 0; i < h; i++) { ret = fscanf(fin, "%s", buf); assert(ret == 1); for (int j = 0; j < w; j++) { if (buf[j] == '0') { set(i, j, 0); } else { set(i, j, -1); } } } fclose(fin); } void pour(int i, int j, int code) { Bound & bd = bounds[code]; set(i, j, code); vector<int> stack; stack.push_back(ind(i, j)); bd.init(i, j); bd.code = code; while (!stack.empty()) { int cur = stack.back(); stack.pop_back(); int row, col; indr(cur, row, col); // printf("- %d %d\n", row, col); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if (x == 0 && y == 0) continue; int _r = row + x; int _c = col + y; if (!validCord(_r, _c)) continue; int next = ind(_r, _c); assert(next >= 0); int px = pic[next]; if (px >= 0) continue; bd.add(_r, _c); pic[next] = code; // color this pixel stack.push_back(next); } } } } void color() { int code = 1; char ch = 'a'; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int c = get(i, j); if (c >= 0) continue; // blank or colored // printf("new code: (%d, %d), %d, %d \n", i, j, c, code); pour(i, j, code); outputChar[code] = ch; ch++; for (int k = 1; k < code; k++) { if (sameShape(code, k)) { outputChar[code] = outputChar[k]; ch--; break; } } code++; } } } bool same1(Bound & b1, Bound & b2, int m) { int w = b1._w; int h = b1._h; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (pic[b1.ind(i, j)] != b1.code) { continue; } if (pic[b2.ind1(m, i, j)] != b2.code) { return false; } } } return true; } bool same2(Bound & b1, Bound & b2, int m) { int w = b1._w; int h = b1._h; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (pic[b1.ind(i, j)] != b1.code) { continue; } if (pic[b2.ind2(m, i, j)] != b2.code) { return false; } } } return true; } bool sameShape(int c1, int c2) { Bound & b1 = bounds[c1]; Bound & b2 = bounds[c2]; if (b1.isDot() && b2.isDot()) return true; if (b1.count != b2.count) return false; b1.calcSize(); b2.calcSize(); if (b1._w == b2._w && b1._h == b2._h) { for (int m = 0; m < 4; m++) { if (same1(b1, b2, m)) return true; } } if (b1._w == b2._h && b1._h == b2._w) { for (int m = 0; m < 4; m++) { if (same2(b1, b2, m)) return true; } } return false; } void writeOut() { color(); fout = fopen("starry.out", "w"); assert(fout); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int px = get(i, j); assert(px >= 0); char c = '0'; if (px > 0) { c = outputChar[px]; } fprintf(fout, "%c", c); } fprintf(fout, "\n"); } fclose(fout); } }; Prob prob; int main() { prob.readIn(); prob.writeOut(); return 0; }
true
79f3bf8009ad7f8b4af08629a19b936fcc28416e
C++
gershGit/IceCaps
/Source/Core/AnimationSystem.cpp
UTF-8
5,563
2.75
3
[]
no_license
#include "Core/AnimationSystem.h" #include "Core/GameTimer.h" #include "glm/gtx/matrix_decompose.hpp" void AnimationSystem::start() { for (int id : *entities) { animation * anim = getCManager<animation>(*managers, ANIMATION_COMPONENT)->getComponentAddress(id); if (anim->playOnStartup) { anim->startTime = GameTimer::getCurrentTime(); anim->lastFrameEnd = &(anim->frames[0]); anim->lastFrameStart = &(anim->frames[0]); anim->lastCalulatedFrame = anim->frames[0]; anim->state = ANIMATION_PLAYING; } } } //Returns the closest frame before the current time key_frame* AnimationSystem::getFramePrior(animation *anim, double time) { for (unsigned int i = 0; i < anim->frameCount; i++) { if (anim->frames[i].t > time) { return &anim->frames[i - 1]; } } return &anim->frames[anim->frameCount - 1]; } //Returns the closest frame after the current time key_frame* AnimationSystem::getFramePost(animation *anim, double time) { for (unsigned int i = 0; i < anim->frameCount; i++) { if (anim->frames[i].t > time) { return &anim->frames[i]; } } return &anim->frames[anim->frameCount - 1]; } //Interpolates a vector linearly glm::vec3 AnimationSystem::linearInterpolation(glm::vec3 start, glm::vec3 end, double time) { return start + (end * (float) time); } //Interpolates a vector by converting a quaternion and slerping glm::vec3 AnimationSystem::quaternionInterpolation(glm::vec3 start, glm::vec3 end, double time) { glm::quat startQuat = glm::quat(start); glm::quat endQuat = glm::quat(end); glm::quat intermediateQuat = glm::slerp(startQuat, endQuat, (float) time); return glm::eulerAngles(intermediateQuat); } //Calculates the left over deltas key_frame getLeftOver(double t, animation *anim, key_frame* leftOverStart, key_frame* thisFrameStart) { key_frame leftOverFrame; leftOverFrame.deltaPosition = leftOverStart->deltaPosition - anim->lastCalulatedFrame.deltaPosition; leftOverFrame.deltaRotation = leftOverStart->deltaRotation - anim->lastCalulatedFrame.deltaRotation; leftOverFrame.deltaScale = leftOverStart->deltaScale - anim->lastCalulatedFrame.deltaScale; unsigned int nextIndex = leftOverStart->index + 1; while (nextIndex <= thisFrameStart->index) { leftOverFrame.deltaPosition += anim->frames[nextIndex].deltaPosition; leftOverFrame.deltaRotation += anim->frames[nextIndex].deltaRotation; leftOverFrame.deltaScale += anim->frames[nextIndex].deltaScale; nextIndex++; } return leftOverFrame; } //Applies an animation to an entity void AnimationSystem::applyAnimation(animation *anim, int entityID, ArrayManager<transform>* tManager) { if (anim->state == ANIMATION_PLAYING) { double currentTime = GameTimer::getCurrentTime(); if (!anim->repeat && currentTime - anim->startTime > anim->length) { anim->state = ANIMATION_OVER; return; } transform * t = tManager->getComponentAddress(entities->at(entityID)); glm::vec3 newDeltaPos; glm::vec3 newDeltaRot; glm::vec3 newDeltaScale; if (currentTime - anim->startTime < anim->lastFrameEnd->t) { //Still between the same 2 keyframes double timePercentage = (currentTime - (anim->startTime + anim->lastFrameStart->t)) / (anim->lastFrameEnd->t - anim->lastFrameStart->t); newDeltaPos = linearInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaPosition, timePercentage) * anim->animationWeight; newDeltaRot = quaternionInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaRotation, timePercentage) * anim->animationWeight; newDeltaScale = linearInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaScale, timePercentage) * anim->animationWeight; t->pos += (newDeltaPos - anim->lastCalulatedFrame.deltaPosition); t->rot += (newDeltaRot - anim->lastCalulatedFrame.deltaRotation); t->scale += (newDeltaScale - anim->lastCalulatedFrame.deltaScale); } else { //Skipped frame or moved to next frame key_frame* leftOverStartFrame = anim->lastFrameEnd; anim->lastFrameStart = getFramePrior(anim, currentTime - anim->startTime); anim->lastFrameEnd = getFramePost(anim, anim->lastFrameStart->t); double timePercentage = (currentTime - (anim->startTime + anim->lastFrameStart->t)) / (anim->lastFrameEnd->t - anim->lastFrameStart->t); newDeltaPos = linearInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaPosition, timePercentage) * anim->animationWeight; newDeltaRot = quaternionInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaRotation, timePercentage) * anim->animationWeight; newDeltaScale = linearInterpolation(glm::vec3(0), anim->lastFrameEnd->deltaScale, timePercentage) * anim->animationWeight; key_frame leftOverFrame = getLeftOver(currentTime - anim->startTime, anim, leftOverStartFrame, anim->lastFrameStart); t->pos += newDeltaPos + leftOverFrame.deltaPosition; t->rot += newDeltaRot + leftOverFrame.deltaRotation; t->scale += newDeltaScale + leftOverFrame.deltaScale; } //Update the last delta anim->lastCalulatedFrame.deltaPosition = newDeltaPos; anim->lastCalulatedFrame.deltaRotation = newDeltaRot; anim->lastCalulatedFrame.deltaScale = newDeltaScale; } } //Applies animations to all entities void AnimationSystem::onUpdate() { ArrayManager<transform>* tManager = dynamic_cast<ArrayManager<transform>*>(getCManager<transform>(*managers, TRANSFORM)); MappedManager<animation>* aManager = dynamic_cast<MappedManager<animation>*>( getCManager<animation>(*managers, ANIMATION_COMPONENT)); for (int i = 0; i < entities->size(); i++) { applyAnimation( aManager->getComponentAddress(entities->at(i)), entities->at(i), tManager ); } }
true
27f110ec53196af25215dfa4c21e60d7d10c91dd
C++
vishalpolley/Algorithms
/Greedy Algorithms/Job Sequencing With Deadlines.cpp
UTF-8
1,880
3.640625
4
[]
no_license
// Author:- Jatin Kumar // Job Sequencing with deadlines:- given n jobs with their deadlines and profits // task is to maximize the profit and job should be completed before its deadline // greedy approach is used // pick the job with maximum profit and place it as near as to it's deadline so that // jobs having less deadline than it can also fit inside the array // time complexity= O(n^2) #include<bits/stdc++.h> using namespace std; // define the structure for the job struct object { char jobid; int deadline; int profit; }; // as usual compare function bool compare(struct object *x,struct object *y) { return x->profit>y->profit; } int main() { int n,size,max,totalprofit=0; cout<<"enter the no. of jobs="; cin>>n; struct object *obj[n]; // user input and finding maximum deadline for(int i=0;i<n;i++) { obj[i]=(struct object*)malloc(sizeof(struct object)); cout<<"enter jobid,deadline and profit of job "<<i+1<<":"; cin>>obj[i]->jobid>>obj[i]->deadline>>obj[i]->profit; if(i==0) { max=obj[i]->deadline; } else { if(obj[i]->deadline>max) max=obj[i]->deadline; } } // sort them according to their profit size=sizeof(obj)/sizeof(obj[0]); sort(obj,obj+size,compare); // create array of max deadline size char array[max]={'\0'}; // null indicates that cell is empty for(int i=0;i<n;i++) { // now pick the job with max deadline and // from that deadline traverse array back // to find an empty slot for(int j=(obj[i]->deadline)-1;j>=0;j--) { if(array[j]=='\0') // cell is empty { // count the total profit totalprofit=totalprofit+obj[i]->profit; array[j]=obj[i]->jobid; break; } } } // here will be the desired output cout<<"jobs selectd are:"<<"\t"; for(int i=0;i<max;i++) { if(array[i]=='\0') continue; cout<<array[i]<<"\t"; } cout<<"\ntotal profit is "<<totalprofit<<"\n"; }
true
2214444001f83bcb0d51bf2275483c2e43dbb66c
C++
icce-top/compiler
/codegen/flextest/stack-machine.cpp
UTF-8
3,639
2.890625
3
[]
no_license
#include "stdafx.h" #include "stack-machine.h" ///////////////////////////////////// // instructions void Stack_Instr_print(Stack_Instr_t s) { switch (s->kind){ case STACK_INSTR_PUSH:{ Stack_Instr_Push p = (Stack_Instr_Push)s; printf("push %d", p->n); break; } case STACK_INSTR_LOAD:{ Stack_Instr_Load p = (Stack_Instr_Load)s; printf("load %s", p->x); break; } case STACK_INSTR_STORE:{ Stack_Instr_Store p = (Stack_Instr_Store)s; printf("store %s", p->x); break; } case STACK_INSTR_ADD:{ printf("add"); break; } case STACK_INSTR_MINUS:{ printf("minus"); break; } case STACK_INSTR_TIMES:{ printf("times\n"); break; } case STACK_INSTR_DIV:{ printf("div"); break; } case STACK_INSTR_AND:{ printf("and"); break; } case STACK_INSTR_OR:{ printf("or"); break; } case STACK_INSTR_PRINTI:{ printf("printi"); break; } case STACK_INSTR_PRINTB:{ printf("printb"); break; } default: break; } } // push Stack_Instr_t Stack_Instr_Push_new(int n) { Stack_Instr_Push p = (Stack_Instr_Push)malloc(sizeof(*p)); p->kind = STACK_INSTR_PUSH; p->n = n; return (Stack_Instr_t)p; } // load x Stack_Instr_t Stack_Instr_Load_new(char *x) { Stack_Instr_Load p = (Stack_Instr_Load)malloc(sizeof(*p)); p->kind = STACK_INSTR_LOAD; p->x = x; return (Stack_Instr_t)p; } // store x Stack_Instr_t Stack_Instr_Store_new(char *x) { Stack_Instr_Store p = (Stack_Instr_Store)malloc(sizeof(*p)); p->kind = STACK_INSTR_STORE; p->x = x; return (Stack_Instr_t)p; } // add Stack_Instr_t Stack_Instr_Add_new() { Stack_Instr_Add p = (Stack_Instr_Add)malloc(sizeof(*p)); p->kind = STACK_INSTR_ADD; return (Stack_Instr_t)p; } // Minus Stack_Instr_t Stack_Instr_Minus_new() { Stack_Instr_Minus p = (Stack_Instr_Minus)malloc(sizeof(*p)); p->kind = STACK_INSTR_MINUS; return (Stack_Instr_t)p; } // times Stack_Instr_t Stack_Instr_Times_new() { Stack_Instr_Times p = (Stack_Instr_Times)malloc(sizeof(*p)); p->kind = STACK_INSTR_TIMES; return (Stack_Instr_t)p; } // divide Stack_Instr_t Stack_Instr_Divide_new() { Stack_Instr_Divide p = (Stack_Instr_Divide)malloc(sizeof(*p)); p->kind = STACK_INSTR_DIV; return (Stack_Instr_t)p; } // and Stack_Instr_t Stack_Instr_And_new() { Stack_Instr_And p = (Stack_Instr_And)malloc(sizeof(*p)); p->kind = STACK_INSTR_AND; return (Stack_Instr_t)p; } // or Stack_Instr_t Stack_Instr_Or_new() { Stack_Instr_Or p = (Stack_Instr_Or)malloc(sizeof(*p)); p->kind = STACK_INSTR_OR; return (Stack_Instr_t)p; } // printi Stack_Instr_t Stack_Instr_Printi_new() { Stack_Instr_Printi p = (Stack_Instr_Printi)malloc(sizeof(*p)); p->kind = STACK_INSTR_PRINTI; return (Stack_Instr_t)p; } // printb Stack_Instr_t Stack_Instr_Printb_new() { Stack_Instr_Printb p = (Stack_Instr_Printb)malloc(sizeof(*p)); p->kind = STACK_INSTR_PRINTB; return (Stack_Instr_t)p; } /////////////////////////////////////// // prog Stack_Prog_t Stack_Prog_new(List_t ids, List_t instrs) { Stack_Prog_t p = (Stack_Prog_t)malloc(sizeof (*p)); p->ids = ids; p->instrs = instrs; return p; } void Stack_Prog_print(Stack_Prog_t prog) { List_t ids = prog->ids; printf("{\n"); while (ids){ char *id = (char *)ids->data; printf(" .int %s\n", id); ids = ids->next; } printf("\n"); List_t instrs = prog->instrs; while (instrs){ Stack_Instr_t s = (Stack_Instr_t)instrs->data; printf(" "); Stack_Instr_print(s); printf("\n"); instrs = instrs->next; } printf("}\n"); return; }
true
cb0476940bb9bb531f91e49cd2eeef1366b6408f
C++
derklausberger/klausberger
/src/server/manager.cpp
UTF-8
2,024
3.484375
3
[]
no_license
#include "manager.h" #include <string> #include <iostream> using namespace std; void Manager::print() { for (auto& user : users) { user.print(); } } User* Manager::get_user(string name) { for (auto& user : users) { if (user.get_name().compare(name) == 0) { return &user; } } return nullptr; } bool Manager::contains(string name) { return (get_user(name) != nullptr); } bool Manager::add(string name, string pw) { if (!contains(name)) { users.push_back(User{name, pw}); return true; } return false; } bool Manager::mod_pw(string name, string pw_) { User* user = get_user(name); if (user != nullptr) { user->set_pw(pw_); return true; } return false; } bool Manager::mod_name(string name, string new_name) { User* user = get_user(name); if (user != nullptr) { user->set_name(new_name); return true; } return false; } bool Manager::del(string name) { User* user = get_user(name); if (user != nullptr) { users.remove(*user); return true; } return false; } bool Manager::set_right(string name, string object, string right) { User* user = get_user(name); if (user != nullptr) { return user->set_right(object, right); } return false; } bool Manager::rem_right(string name, string object) { User* user = get_user(name); if (user != nullptr) { return user->rem_right(object); } return false; } bool Manager::print_rights(string name, string object) { User* user = get_user(name); if (user != nullptr) { if (!object.empty()) { user->print_rights(object); } else { user->print_rights(); } return true; } return false; } bool Manager::login(string name, string pw) { User* user = get_user(name); if (user != nullptr) { return (user->get_pw().compare(pw) == 0); } return false; }
true
579a1e3fe0c847e6834ae670b9ea80f10e21e689
C++
vinaykumargb/Algorithms
/Quick sort.cpp
UTF-8
1,634
3.890625
4
[ "MIT" ]
permissive
#include <iostream> // std::cout #include <algorithm> // std::swap, std::generate #include <ctime> // time() #include <cstdlib> // srand(), rand() using namespace std; int rnd() {return (rand()%101+1);} int partition(int arr[], int first, int last){ // To swap values. int i = first + 1; // Pick the first element as pivot. int pivot = first, k = first; // Start loop from first value to last value while(k++<=last){ // Check if any element between first // and last is lesser than pivot value. if(arr[k] < arr[pivot]) // If condition true, swap them. swap(arr[i++], arr[k]); } // Swap pivot to proper index. swap(arr[pivot], arr[i - 1]); // Return index of pivot. return (i - 1); } void quick_sort(int arr[], int first, int last){ if(first < last){ // Swap if pivot value is greater than any value till last. // Also, get the index of pivot. int pivot = partition(arr, first, last); // Sort pivot left side values. quick_sort(arr, first, pivot - 1); // Sort pivot right side values. quick_sort(arr, pivot + 1, last); } } void print_elements(int arr[], int s){ for(int i = 0; i < s; i++) cout<<arr[i]<<" "; } int main(){ srand(time(nullptr)); int arr[10]; generate(begin(arr), end(arr), rnd); cout<<"Unsorted array..\n"; print_elements(arr, size(arr));cout<<endl; cout<<"Calling quick sort function..\n"; quick_sort(arr, 0, (size(arr) - 1)); cout<<"Sorted array..\n"; print_elements(arr, size(arr)); return 0; }
true
d178a3f5b53c5cb437ed6189e7a450a835e845a2
C++
andrewrong/kvstore
/src/storage/impl/IteratorImpl.cpp
UTF-8
961
2.53125
3
[]
no_license
// // Created by fenglin on 2018/12/29. // #include "IteratorImpl.h" storage::IteratorImpl::IteratorImpl(rocksdb::Iterator* iter) : Iterator() { assert(iter); iter_ = iter; } storage::IteratorImpl::~IteratorImpl() { if(iter_) { delete iter_; } } bool storage::IteratorImpl::IsValid() { assert(iter_); return iter_->Valid(); } //todo 优化copy std::string storage::IteratorImpl::GetKey() { assert(iter_); return iter_->key().ToString(); } std::string storage::IteratorImpl::GetValue() { assert(iter_); return iter_->value().ToString(); } void storage::IteratorImpl::Next() { assert(iter_); iter_->Next(); } void storage::IteratorImpl::Seek(const std::string &target) { assert(iter_); iter_->Seek(target); } void storage::IteratorImpl::SeekToFirst() { assert(iter_); iter_->SeekToFirst(); } void storage::IteratorImpl::SeekToLast() { assert(iter_); iter_->SeekToLast(); }
true
bcf3879ad1870805d21397cce569173bdca72d3d
C++
pkmital/NSCARPE
/src/ofxFbo.cpp
UTF-8
4,940
2.59375
3
[]
no_license
#include "ofxFbo.h" void ofxFbo::push() { if(levels == 0) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboId); levels++; } void ofxFbo::pop() { levels--; if(levels == 0) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } ofTexture* ofxFbo::getAttachment() { for(unsigned int i = 0; i < attachments.size(); i++) if(attachments[i] != NULL) return attachments[i]; return NULL; } void ofxFbo::checkAttachment() { if(getAttachment() == NULL) { // change this to only allocate if not already allocated internalColor.allocate(width, height, GL_RGBA); attach(internalColor); } } void ofxFbo::setupScreenForFbo() { float eyeX = (float) width / 2; float eyeY = (float) height / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float nearDist = dist / 10; float farDist = dist * 10; float aspect = (float) width / height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, aspect, nearDist, farDist); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0); glViewport(0, 0, width, height); } void ofxFbo::setupScreenForWindow() { width = screenWidth; height = screenHeight; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); float viewW = viewport[2]; float viewH = viewport[3]; float eyeX = viewW / 2; float eyeY = viewH / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float aspect = (float) viewW / viewH; float nearDist = dist / 10.0f; float farDist = dist * 10.0f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, aspect, nearDist, farDist); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0); glScalef(1, -1, 1); glTranslatef(0, -screenHeight, 0); glViewport(0, 0, screenWidth, screenHeight); } ofxFbo::ofxFbo() : levels(0), fov(60), fboId(0), depthId(0), stencilId(0) { } void ofxFbo::setup(int width, int height, int screenWidth, int screenHeight, bool useDepth, bool useStencil) { this->width = width; this->height = height; this->screenWidth = screenWidth; this->screenHeight = screenHeight; glGenFramebuffersEXT(1, &fboId); if(useDepth) glGenRenderbuffersEXT(1, &depthId); if(useStencil) glGenRenderbuffersEXT(1, &stencilId); push(); if(useDepth) { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthId); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, width, height); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthId); } if(useStencil) { glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthId); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX, width, height); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthId); } pop(); int maxAttachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &maxAttachments); cout << "[ofxFBO]: Max color attachments: " << maxAttachments << endl; attachments.assign(maxAttachments, (ofTexture*) NULL); } ofxFbo::~ofxFbo() { if(fboId != 0) glDeleteFramebuffersEXT(1, &fboId); if(depthId != 0) glDeleteRenderbuffersEXT(1, &depthId); if(stencilId != 0) glDeleteRenderbuffersEXT(1, &stencilId); } void ofxFbo::setFov(float fov) { this->fov = fov; } void ofxFbo::attach(ofTexture& target, int position) { push(); detach(position); attachments[position] = &target; ofTextureData& texData = target.texData; glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + position, texData.textureTarget, texData.textureID, 0); pop(); } void ofxFbo::detach(int position) { push(); ofTexture* target = attachments[position]; if(target != NULL) { ofTextureData& texData = target->texData; glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + position, texData.textureTarget, 0, 0); target = NULL; } pop(); } void ofxFbo::setBackground(float r, float g, float b, float a) { push(); checkAttachment(); glClearColor(r / 255, g / 255, b / 255, a / 255); glClear(GL_COLOR_BUFFER_BIT | (depthId != 0 ? GL_DEPTH_BUFFER_BIT : 0) | (stencilId != 0 ? GL_STENCIL_BUFFER_BIT : 0)); pop(); } void ofxFbo::clearAlpha() { push(); glColorMask(0, 0, 0, 1); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColorMask(1, 1, 1, 1); pop(); } void ofxFbo::begin() { checkAttachment(); glPushMatrix(); setupScreenForFbo(); push(); } void ofxFbo::end() { pop(); setupScreenForWindow(); glPopMatrix(); } void ofxFbo::draw(float x, float y) { draw(x, y, width, height); } void ofxFbo::draw(float x, float y, float width, float height) { checkAttachment(); getAttachment()->draw(x, y, width, height); } int ofxFbo::getWidth() { return width; } int ofxFbo::getHeight() { return height; }
true
4d2a8bf80e0d18e7d71cc8c82e2b55689064f389
C++
paulot/uva
/10681.cpp
UTF-8
873
2.6875
3
[]
no_license
#include <iostream> using namespace std; int s, e, d, n, m; bool dp[102][202], g[102][102]; // Still getting WA, but the recurrence is correct, probably some small bug int main() { while (cin >> m >> n and m and n) { for (int i = 0; i <= m; i++) for (int j = 0; j <= m; j++) g[i][j] = false; for (int i = 1; i <= n; i++) { int a, b; cin >> a >> b; g[a][b] = g[b][a] = true; } cin >> s >> e >> d; for (int i = 0; i <= m; i++) for (int j = 0; j <= d; j++) dp[i][j] = false; dp[s][0] = true; for (int day = 0; day < d; day++) for (int to = 1; to <= m; to++) for (int from = 1; from <= m; from++) if (g[from][to] and dp[from][day]) dp[to][day+1] = true; if (dp[e][d]) cout << "Yes, Teobaldo can travel." << endl; else cout << "No, Teobaldo can not travel." << endl; } return 0; }
true
c63913036d59f6205b368cffc65fe74476efb392
C++
iynaur/solarsystem
/camera.h
UTF-8
1,408
2.796875
3
[ "MIT" ]
permissive
/*Published under The MIT License (MIT) See LICENSE.TXT*/ // Ryan Pridgeon COM2032 rp00091 #ifndef RYAN_CAMERA_H #define RYAN_CAMERA_H class Camera { private: // a vector pointing in the directio nyoure facing float forwardVec[3]; // a vector pointing to the right of where your facing (to describe orientation float rightVec[3]; // a vector pointing upwards from where youre facing float upVec[3]; // a vector describing the position of the camera float position[3]; // the camera speed float cameraSpeed; float cameraTurnSpeed; public: Camera(void); // transform the opengl view matrix for the orientation void transformOrientation(void); // transform the opoengl view matrix for the translation void transformTranslation(void); // points the camera at the given point in 3d space void pointAt(float* targetVec); // speed up the camera speed void speedUp(void); // slow down the camera speed void slowDown(void); // move the camera forward void forward(void); // strafe left void left(void); // strafe right void right(void); // move the camera backward void backward(void); // roll the camera to the right void rollRight(void); // roll the camera to the left void rollLeft(void); // pitch the camera up void pitchUp(void); // pitch the camera down void pitchDown(void); // yaw left void yawLeft(void); // yaw right void yawRight(void); }; #endif
true
a9b22e2f908387c00b7975a910eaf4a80b25a629
C++
seppestas/arduino-client
/libraries/allthingstalk_arduino_gateway_lib/allthingstalk_arduino_gateway_lib.cpp
UTF-8
9,067
2.734375
3
[]
no_license
/* Not yet supported allthingstalk_arduino_gateway_lib.cpp - SmartLiving.io Arduino library provides a way to create devices & assets + send & receives asset values to/from the cloud. Author: Jan Bogaerts first version: october 2014 */ #define DEBUG //turns on debugging in the IOT library. comment out this line to save memory. #include "allthingstalk_arduino_gateway_lib.h" #define RETRYDELAY 5000 //the nr of milliseconds that we pause before retrying to create the connection #define ETHERNETDELAY 1000 //the nr of milliseconds that we pause to give the ethernet board time to start #define MQTTPORT 1883 #ifdef DEBUG char HTTPSERVTEXT[] = "connection HTTP Server"; char MQTTSERVTEXT[] = "connection MQTT Server"; char FAILED_RETRY[] = " failed,retry"; char SUCCESTXT[] = " established"; #endif //create the object ATTGateway::ATTGateway(String clientId, String clientKey) { _clientId = clientId; _clientKey = clientKey; } //connect with the http server bool ATTGateway::Connect(byte mac[], char httpServer[]) { _serverName = httpServer; //keep track of this value while working with the http server. if (Ethernet.begin(mac) == 0) // Initialize the Ethernet connection: { Serial.println(F("DHCP failed,end")); return false; //we failed to connect } delay(ETHERNETDELAY); // give the Ethernet shield a second to initialize: #ifdef DEBUG Serial.println(F("Connecting")); #endif while (!_client.connect(httpServer, 80)) // if you get a connection, report back via serial: { #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(HTTPSERVTEXT); Serial.println(SUCCESTXT); #endif delay(ETHERNETDELAY); // another small delay: sometimes the card is not yet ready to send the asset info. return true; //we have created a connection succesfully. } void ATTGateway::AddDevice(String deviceId, String name, String description) { // Make a HTTP request: _client.println("POST /api/device HTTP/1.1"); _client.print(F("Host: ")); _client.println(_serverName); _client.println(F("Content-Type: application/json")); _client.print(F("Auth-ClientKey: "));_client.println(_clientKey); _client.print(F("Auth-ClientId: "));_client.println(_clientId); _client.print(F("Content-Length: ")); { //make every mem op local, so it is unloaded asap int length = name.length() + description.length() + deviceId.length() + 43; _client.println(length); } _client.println(); _client.print(F("{\"id\":\"xbee_")); //12 _client.print(deviceId); _client.print(F("\", \"name\":\"")); //11 _client.print(name); _client.print(F("\",\"description\":\"")); //17 _client.print(description); _client.print(F("\" }")); //3 _client.println(); delay(ETHERNETDELAY); if(CheckHTTPResult('2', '0','1')){ Serial.println("Device created"); MqttSubscribe(deviceId); } else Serial.println("Failed to create device"); delay(ETHERNETDELAY); // another small delay: sometimes the card is not yet ready to send the asset info. } //check if the device already exists or not bool ATTGateway::DeviceExists(String deviceId) { // Make a HTTP request: _client.println("GET /api/device/xbee_" + deviceId + " HTTP/1.1"); _client.print(F("Host: ")); _client.println(_serverName); _client.println(F("Content-Type: application/json")); _client.print(F("Auth-ClientKey: "));_client.println(_clientKey); _client.print(F("Auth-ClientId: "));_client.println(_clientId); _client.println(); delay(ETHERNETDELAY); return CheckHTTPResult('2', '0','0'); } //checks the result of the http request by comparing the characters at pos 9,10 & 11 //ex: CheckHTTPResult('2','0','0') will check if the http server returned 200 OK bool ATTGateway::CheckHTTPResult(char a, char b, char c) { if(_client.available()){ //check the result int count = 0; while (_client.available()) { count++; char c = _client.read(); if((count == 10 && c != a) || (count == 11 && c != b) || (count == 12 && c != c) ){ //if the result starting at pos 10 is 200, then the device exists, otherwise it doesn't _client.flush(); //make certain that there is nothing left in the ethernet buffer, cause this can screw up the other actions. return false; } else if(count > 12) //when we have read more then 11 bytes, we know the result, so discard anything else that came in _client.flush(); } return count > 12; //if the count > 11, and we get here, then the http result contained '200', so the device exists. } return false; } //create or update the specified asset. void ATTGateway::AddAsset(String deviceId, char id, String name, String description, bool isActuator, String type) { // Make a HTTP request: _client.print(F("PUT /api/asset/xbee_")); _client.print(deviceId); _client.print(F("_")); _client.print(id); _client.println(" HTTP/1.1"); _client.print(F("Host: ")); _client.println(_serverName); _client.println(F("Content-Type: application/json")); _client.print(F("Auth-ClientKey: "));_client.println(_clientKey); _client.print(F("Auth-ClientId: "));_client.println(_clientId); _client.print(F("Content-Length: ")); { //make every mem op local, so it is unloaded asap int length = name.length() + description.length() + type.length() + deviceId.length() + 82; if(isActuator) length += 8; else length += 6; _client.println(length); } _client.println(); _client.print(F("{\"name\":\"")); //9 _client.print(name); _client.print(F("\",\"description\":\"")); //17 _client.print(description); _client.print(F("\",\"is\":\"")); //8 if(isActuator) _client.print(F("actuator")); else _client.print(F("sensor")); _client.print(F("\",\"profile\": { \"type\":\"")); //23 _client.print(type); _client.print(F("\" }, \"deviceId\":\"xbee_")); //22 _client.print(deviceId); _client.print(F("\" }")); //3 _client.println(); delay(ETHERNETDELAY); if(CheckHTTPResult('2', '0','1')) Serial.println("Asset created"); else Serial.println("Failed to create asset"); delay(ETHERNETDELAY); // another small delay: sometimes the card is not yet ready to send the asset info. } //connect with the http server and broker void ATTGateway::Subscribe(PubSubClient& mqttclient) { _mqttclient = &mqttclient; MqttConnect(); } //tries to create a connection with the mqtt broker. also used to try and reconnect. void ATTGateway::MqttConnect() { char mqttId[23]; // Or something long enough to hold the longest file name you will ever use. int length = _clientId.length(); length = length > 22 ? 22 : length; _clientId.toCharArray(mqttId, length); mqttId[length] = 0; String brokerId = _clientId + ":" + _clientId; while (!_mqttclient->connect(mqttId, (char*)brokerId.c_str(), (char*)_clientKey.c_str())) { #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(FAILED_RETRY); #endif delay(RETRYDELAY); } #ifdef DEBUG Serial.print(MQTTSERVTEXT); Serial.println(SUCCESTXT); #endif } //check for any new mqtt messages. void ATTGateway::Process() { _mqttclient->loop(); } //send a data value to the cloud server for the sensor with the specified id. void ATTGateway::Send(String deviceId, char sensorId, String value) { if(_mqttclient->connected() == false) { Serial.println(F("Lost broker connection,restarting")); MqttConnect(); } char* message_buff; { //put in a sub block so 'length' can be freed asap. int length = value.length() + 3; message_buff = new char[length]; sprintf(message_buff, "0|%s", value.c_str()); message_buff[length-1] = 0; } #ifdef DEBUG //don't need to write all of this if not debugging. Serial.print(F("Publish to ")); Serial.print(sensorId); Serial.print(" : "); Serial.println(message_buff); #endif char* Mqttstring_buff; { int length = _clientId.length() + deviceId.length() + (int)log(float(sensorId)) + 30; Mqttstring_buff = new char[length]; sprintf(Mqttstring_buff, "client/%s/out/asset/xbee_%s_%c/state", _clientId.c_str(), deviceId.c_str(), sensorId); Mqttstring_buff[length-1] = 0; } _mqttclient->publish(Mqttstring_buff, message_buff); delay(100); //give some time to the ethernet shield so it can process everything. delete(message_buff); delete(Mqttstring_buff); } //subscribe to the mqtt topic so we can receive data from the server. void ATTGateway::MqttSubscribe(String deviceId) { String MqttString = "client/" + _clientId + "/in/device/xbee_" + deviceId + "/asset/+/command"; //arduinos are only intersted in actuator command, no management commands char Mqttstring_buff[MqttString.length()+1]; MqttString.toCharArray(Mqttstring_buff, MqttString.length()+1); _mqttclient->subscribe(Mqttstring_buff); #ifdef DEBUG Serial.println(F("MQTT Client subscribed")); #endif }
true
ff6ffb29916a3dbc375fb6121120a280f0380328
C++
Formation-C/SA_MediaPlayer
/State.h
UTF-8
334
2.578125
3
[]
no_license
#pragma once class Player; #include "Player.h" class State { protected: Player* player; public: State() { player = nullptr; }; State(Player* _player); virtual ~State(); Player* GetPlayer() { return player; }; void SetPlayer(Player *_player) { player = _player; }; virtual void onPlay() = 0; virtual void onStop() = 0; };
true
d5ca45b85f6524b2215bc55234eef62d657ced7f
C++
tomy0000000/YZU-Computer-Programming-I
/Midterm Exam 1/Midterm 1.cpp
UTF-8
9,114
3.296875
3
[ "MIT" ]
permissive
// Huge integer division #include <iostream> using std::cin; using std::cout; using std::endl; #include <fstream> using std::ifstream; using std::ios; using std::istream; using std::ofstream; using std::ostream; // enable user to input two positive huge integers from user void inputTwoHugeInts(istream &inFile, unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int &size1, unsigned int &size2); // perform addition, subtraction, multiplication and division void perform(ostream &outFile, unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int hugeInt3[], unsigned int hugeInt4[], unsigned int size1, unsigned int size2, unsigned int size3, unsigned int size4); // output the specified huge integer void output(ostream &outFile, unsigned int hugeInt[], unsigned int size); // returns true if and only if the specified huge integer is zero bool isZero(unsigned int hugeInt[], unsigned int size); // returns true if and only if hugeInt1 < hugeInt2 bool less(unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int size1, unsigned int size2); // quotient = dividend / divisor; remainder = dividend % divisor void division(unsigned int dividend[], unsigned int divisor[], unsigned int quotient[], unsigned int remainder[], unsigned int dividendSize, unsigned int divisorSize, unsigned int &quotientSize, unsigned int &remainderSize); // product = multiplicand * multiplier * ( 10 ^ multiplierPos ) void multiplication(unsigned int multiplicand[], unsigned int multiplier, unsigned int product[], unsigned int multiplicandSize, unsigned int multiplierPos, unsigned int &productSize); // minuend -= subtrahend void subtraction(unsigned int minuend[], unsigned int subtrahend[], unsigned int &minuendSize, unsigned int subtrahendSize); const unsigned int numTestCases = 22; // the number of test cases const unsigned int arraySize = 200; unsigned int main() { system("mode con cols=122"); ifstream inFile("Test cases.txt", ios::in); // exit program if ofstream could not open file if (!inFile) { cout << "File could not be opened" << endl; system("pause"); exit(1); } ofstream outFile("Result.txt", ios::out); // exit program if ofstream could not open file if (!outFile) { cout << "File could not be opened" << endl; system("pause"); exit(1); } for (unsigned int i = 0; i < numTestCases; i++) { unsigned int hugeInt1[arraySize] = {}; unsigned int hugeInt2[arraySize] = {}; unsigned int hugeInt3[arraySize] = {}; unsigned int hugeInt4[arraySize] = {}; unsigned int size1 = 0; unsigned int size2 = 0; unsigned int size3 = 0; unsigned int size4 = 0; inputTwoHugeInts(inFile, hugeInt1, hugeInt2, size1, size2); perform(cout, hugeInt1, hugeInt2, hugeInt3, hugeInt4, size1, size2, size3, size4); perform(outFile, hugeInt1, hugeInt2, hugeInt3, hugeInt4, size1, size2, size3, size4); } inFile.close(); outFile.close(); system("pause"); } // enable user to input two positive huge integers from user void inputTwoHugeInts(istream &inFile, unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int &size1, unsigned int &size2) { char numericString1[arraySize]; char numericString2[arraySize]; inFile >> numericString1 >> numericString2; size1 = strlen(numericString1); for (unsigned int i = 0; i < size1; ++i) hugeInt1[i] = numericString1[size1 - i - 1] - '0'; size2 = strlen(numericString2); for (unsigned int i = 0; i < size2; ++i) hugeInt2[i] = numericString2[size2 - i - 1] - '0'; } // perform addition, subtraction and multiplication void perform(ostream &outFile, unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int hugeInt3[], unsigned int hugeInt4[], unsigned int size1, unsigned int size2, unsigned int size3, unsigned int size4) { output(outFile, hugeInt1, size1); output(outFile, hugeInt2, size2); if (isZero(hugeInt2, size2)) { outFile << "DivideByZero!\n"; outFile << "DivideByZero!\n"; } else { division(hugeInt1, hugeInt2, hugeInt3, hugeInt4, size1, size2, size3, size4); output(outFile, hugeInt3, size3); // outputs n1 / n2 output(outFile, hugeInt4, size4); // outputs n1 % n2 } outFile << endl; } // output the specified huge integer void output(ostream &outFile, unsigned int hugeInt[], unsigned int size) { if (isZero(hugeInt, size)) outFile << 0; else for (int i = size - 1; i >= 0; i--) outFile << hugeInt[i]; outFile << endl; } // returns true if and only if the specified huge integer is zero bool isZero(unsigned int hugeInt[], unsigned int size) { for (unsigned int i = 0; i < size; i++) if (hugeInt[i] != 0) return false; return true; } // returns true if and only if hugeInt1 < hugeInt2 bool less(unsigned int hugeInt1[], unsigned int hugeInt2[], unsigned int size1, unsigned int size2) { if (size1 > size2) { return false; } if (size1 < size2) { return true; } if (size1 == size2) { for (int i = size1 - 1; i >= 0; i--) { if (hugeInt1[i] < hugeInt2[i]) { return true; } if (hugeInt1[i] > hugeInt2[i]) { return false; } } return false; } } void division(unsigned int dividend[], unsigned int divisor[], unsigned int quotient[], unsigned int remainder[], unsigned int dividendSize, unsigned int divisorSize, unsigned int &quotientSize, unsigned int &remainderSize) { if (isZero(dividend, dividendSize)) { quotientSize = 1; quotient[0] = 0; remainderSize = 1; remainder[0] = 0; return; } remainderSize = dividendSize; for (int i = 0; i < dividendSize; i++) { remainder[i] = dividend[i]; } if (less(remainder, divisor, remainderSize, divisorSize)) { quotientSize = 1; quotient = 0; } else { // Make Buffer int n = dividendSize - divisorSize; unsigned int buffer[200]; for (int i = 0; i < divisorSize; i++) { buffer[i + n] = divisor[i]; } for (int i = 0; i < n; i++) { buffer[i] = 0; } unsigned int bufferSize = divisorSize + n; // Cal quotientSize = dividendSize - divisorSize; if (!less(dividend, buffer, dividendSize, bufferSize)) { quotientSize++; } for (int i = 0; i < quotientSize; i++) { quotient[i] = 0; } int a = divisor[divisorSize - 1]; int j = dividendSize - 1; for (int i = dividendSize - divisorSize; i >= 0; i--, j--) { int b = 10 * remainder[j + 1] + remainder[j]; if (a <= b) { quotient[i] = b / a; multiplication(divisor, quotient[i], buffer, divisorSize, i, bufferSize); while (less(remainder, buffer, remainderSize, bufferSize)) { quotient[i]--; multiplication(divisor, quotient[i], buffer, divisorSize, i, bufferSize); } subtraction(remainder, buffer, remainderSize, bufferSize); // system("pause"); } } } } void multiplication(unsigned int multiplicand[], unsigned int multiplier, unsigned int product[], unsigned int multiplicandSize, unsigned int multiplierPos, unsigned int &productSize) { for (int i = 0; i < productSize; i++) { product[i] = 0; } productSize = multiplicandSize; for (int i = 0; i < productSize; i++) { product[i] = 0; } for (unsigned int i = 0; i < multiplicandSize; i++) { product[i] = multiplicand[i] * multiplier; } if (product[productSize - 1] >= 10) { product[productSize] = 0; productSize++; } for (unsigned int i = 0; i < productSize; i++) { while (product[i] >= 10) { product[i] -= 10; product[i + 1]++; } } for (unsigned int i = productSize - 1; i > 0; i--) { product[i + multiplierPos] = product[i]; } product[multiplierPos] = product[0]; for (unsigned int i = 0; i < multiplierPos; i++) { product[i] = 0; productSize++; } } void subtraction(unsigned int minuend[], unsigned int subtrahend[], unsigned int &minuendSize, unsigned int subtrahendSize) { if (minuendSize != subtrahendSize) { for (unsigned int k = subtrahendSize; k < minuendSize; k++) { subtrahend[k] == 0; } subtrahendSize = minuendSize; } for (unsigned int i = 0; i < minuendSize; i++) { if (minuend[i] < subtrahend[i]) { minuend[i] += 10; for (int j = 1; j < minuendSize; j++) { if (minuend[i + j] > 0) { minuend[i + j]--; break; } else { minuend[i + j] = 9; } } } } for (unsigned int i = 0; i < minuendSize; i++) { minuend[i] -= subtrahend[i]; } while (!isZero(minuend, minuendSize) && minuend[minuendSize - 1] == 0) { minuendSize--; } }
true
e65dc675a0ac1261504ec3077e49f04dcb6746c8
C++
pvarouktsis/HooliGame
/src/Menu.h
UTF-8
1,027
3.0625
3
[]
no_license
#pragma once #include <functional> #include <vector> #include "glm/vec2.hpp" #include "graphics.h" struct MenuElement { // Selectable element. Draw function is called when drawing it, on_select when selected. // pos is the position the last element was drawn on. You can use it to draw this element below the last. // sel is whether the cursor is above this element. MenuElement(std::function<glm::vec2(glm::vec2 pos, bool sel)> draw, std::function<void()> on_select); // Non-selectable element. The cursor will skip this element. MenuElement(std::function<glm::vec2(glm::vec2 pos)> draw); MenuElement() = default; std::function<glm::vec2(glm::vec2, bool)> draw; std::function<void()> on_select; }; class Menu { public: Menu(std::vector<MenuElement*> &&options, glm::vec2 &&start_coord); Menu() = default; virtual ~Menu(); void Update(); void Draw(); void MoveCursor(bool up); private: int curr_option; std::vector<MenuElement*> options; glm::vec2 start_coord; graphics::Brush br; float last_movement; };
true
24f06487541666dd23eaab75f80bb6fc6ec5a844
C++
EasternEmperor/PokemonCS
/问题二/thread-service.cpp
GB18030
55,123
2.65625
3
[]
no_license
#include <stdio.h> #include <iomanip> #include <cmath> #include <stdlib.h> #include <iostream> #include <string> #include <cstring> #include <WS2tcpip.h> #include <Winsock2.h> #include <Windows.h> #pragma comment(lib, "ws2_32.lib") #define USERNUM 50 //ܱû ûӵе #define NAMELENGTH 50 //û󳤶 #define EXMAX 4 // = 4 * ȼ #define NPI 10 // = 10 #define PI 20 // = 20 #define LMAX 15 //ȼ15 #define VEX 2 //ʤþ = 2 * зȼ #define FEX 1 //ʧܻþ = 1 * зȼ #define AIR 0.9 //;ʱ10% #define NAIR 0.96 //;ʱ4% #define MAI 1.0 //;鹥Сֵ0.4s #define NMAI 1.5 //;鹥Сֵ1s #define LVG 50 //;ʱֵɳ #define NLVG 25 //;ʱֵɳ #define CAT 50 * level + aggressivity * 2 //սèĹ˺ #define OX 40 * level + aggressivity * 1.2 + HP * 0.08 //ҰţĹ˺ #define LUOYIN 30 * level + HPMAX * 0.08 + defense * 0.8 //Ĺ˺ #define ODIN 30 * level + HPMAX * 0.12 //¶Ĺ˺ #define DRAGON 25 * level + defense * 0.8 //ϹսĹ˺ #define ABU 25 * level + defense * 0.4 + aggressivity * 0.8 //ܰĹ˺ #define LION 40 * level + aggressivity * 0.4 + HPMAX * 0.04 //ʨĹ˺ #define ORIOLE 40 * level + aggressivity * 0.8 + defense * 0.4 //ɻĹ˺ using namespace std; const int PORT = 1234; #define MaxClient 10 #define MaxBufSize 1024 #define _CRT_SECURE_NO_WARINGS //- class Spirit { public: string type; //࣬־ Spirit() {}; //ĬϹ캯 Spirit(string type); //캯 ~Spirit() {}; // //麯-ʽʱ virtual int attack() = 0; //麯-˺ʾʱ virtual void injury(int damage) = 0; //ӡ virtual void show() = 0; }; Spirit::Spirit(string type) { this -> type = type; } //1 class Type : public Spirit { public: string name; // int aggressivity; // int defense; // int HPMAX; //״ֵ̬ int HP; //սʱֵ仯 double cooldown; // int level; //ȼ int EX; //ֵ Type() {}; //ĬϹ캯 Type(string type, string name); //캯 ~Type() {}; // //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); }; Type::Type(string type, string name) : Spirit(type) { this -> level = 1; //ʼȼ1 this -> EX = 0; //ʼ0 this -> name = name; //ͻ if ((name == "սè") || (name == "Ұţ")) { this -> aggressivity = 30; this -> defense = 10; this -> HPMAX = 65; this -> HP = this -> HPMAX; this -> cooldown = 6; } // if ((name == "") || (name == "¶")) { this -> aggressivity = 20; this -> defense = 13; this -> HPMAX = 105; this -> HP = this -> HPMAX; this -> cooldown = 8; } // if ((name == "Ϲս") || (name == "ܰ")) { this -> aggressivity = 20; this -> defense = 20; this -> HPMAX = 90; this -> HP = this -> HPMAX; this -> cooldown = 8; } // if ((name == "ʨ") || (name == "ɻ")) { this -> aggressivity = 30; this -> defense = 5; this -> HPMAX = 55; this -> HP = this -> HPMAX; this -> cooldown = 4; } } int Type::attack() { cout << this -> name << "" << endl; return 0; } //˺ʾܵ˺ʱ void Type::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << this -> name << "ܵ" << damage << "˺"; cout << this -> name << "ֵΪ" << HP << endl; cout << endl; } void Type::show() { cout << "**************************************************************" << endl; cout << "* " << this -> name << '\t' << "ȼ" << this -> level; cout << " *" << endl; cout << "* " << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown; cout << " *" << endl; cout << "**************************************************************" << endl; cout << endl; } // void Type::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "************************************************" << endl; cout << this -> name << "ȼ" << this -> level << "!" << endl; // cout << "Ա仯" << endl; if (type == "") { cout << "" << aggressivity; aggressivity += PI; //仯 cout << " -> " << aggressivity << endl; } else { cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; } if (type == "") { cout << "" << defense; defense += PI; //仯 cout << " -> " << defense << endl; } else { cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; } if (type == "") { cout << "ֵ" << HPMAX; HPMAX += LVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX << endl; } else { cout << "ֵ" << HPMAX; HPMAX += LVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX << endl; } if (type == "") { cout << "" << setprecision(2) << cooldown; cooldown *= AIR; if (cooldown <= MAI) //;鹥ΪNMAI cooldown = MAI; cout << " -> " << setprecision(2) << cooldown << endl; } else { cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown << endl; } cout << "************************************************" << endl; cout << endl; } } //ս㺯 void Type::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "************************************************" << endl; cout << " սʤӣ" << VEX * enemyLv << endl; cout << "************************************************" << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "************************************************" << endl; cout << " սʧܣӣ" << FEX * enemyLv << endl; cout << "************************************************" << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //2徫 //1.1-ͣսè class Cat : public Type { public: Cat(string type, string name); //캯 ~Cat() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int prelevel); }; Cat::Cat(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Cat::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "սèȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += PI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += NLVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Cat::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Cat::attack() { //ʾ cout << "սèĹ" << endl; cout << "սèʹ<ͻ>" << endl; //˺ int damage = 0; damage = CAT; //˺ return damage; } //˺ʾܵ˺ʱ void Cat::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "սèܵ" << damage << "˺"; cout << "սèֵΪ" << HP << endl; cout << endl; } //ӡ void Cat::show() { cout << "սè" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Cat::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += PI * gradeDif; defense += NPI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //1.2-ͣҰţ class Ox : public Type { private: int level; //ȼ int EX; //ֵ public: Ox(string type, string name); //캯 ~Ox() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int prelevel); }; Ox::Ox(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Ox::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "Ұţȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += PI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += NLVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Ox::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Ox::attack() { //ʾ cout << "ҰţĹ" << endl; cout << "Ұţʹ<;>" << endl; //˺ int damage = 0; damage = OX; //˺ return damage; } //˺ʾܵ˺ʱ void Ox::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "Ұţܵ" << damage << "˺"; cout << "ҰţֵΪ" << HP << endl; cout << endl; } //ӡ void Ox::show() { cout << "Ұţ" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Ox::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += PI * gradeDif; defense += NPI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //2.1-ͣ class Luoyin : public Type { private: int level; //ȼ int EX; //ֵ public: Luoyin(string type, string name); //캯 ~Luoyin() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Luoyin::Luoyin(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Luoyin::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "ȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += LVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Luoyin::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Luoyin::attack() { //ʾ cout << "Ĺ" << endl; cout << "ʹ<>" << endl; //˺ int damage = 0; damage = LUOYIN; //˺ return damage; } //˺ʾܵ˺ʱ void Luoyin::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "ܵ" << damage << "˺"; cout << "ֵΪ" << HP << endl; cout << endl; } //ӡ void Luoyin::show() { cout << "" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Luoyin::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += NPI * gradeDif; HPMAX += LVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //2.2-ͣ¶ class Odin : public Type { private: int level; //ȼ int EX; //ֵ public: Odin(string type, string name); //캯 ~Odin() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Odin::Odin(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Odin::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "¶ȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += LVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Odin::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Odin::attack() { //ʾ cout << "¶Ĺ" << endl; cout << "¶ʹ<>" << endl; //˺ int damage = 0; damage = ODIN; //˺ return damage; } //˺ʾܵ˺ʱ void Odin::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "¶ܵ" << damage << "˺"; cout << "¶ֵΪ" << HP << endl; cout << endl; } //ӡ void Odin::show() { cout << "¶" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Odin::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += NPI * gradeDif; HPMAX += LVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //3.1-ͣϹս class Dragon : public Type { private: int level; //ȼ int EX; //ֵ public: Dragon(string type, string name); //캯 ~Dragon() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Dragon::Dragon(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Dragon::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "Ϲսȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += PI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += LVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Dragon::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Dragon::attack() { //ʾ cout << "ϹսĹ" << endl; cout << "Ϲսʹ<˵>" << endl; //˺ int damage = 0; damage = DRAGON; //˺ return damage; } //˺ʾܵ˺ʱ void Dragon::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "Ϲսܵ" << damage << "˺"; cout << "ϹսֵΪ" << HP << endl; cout << endl; } //ӡ void Dragon::show() { cout << "Ϲս" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Dragon::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += PI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //3.2-ͣܰ class Abu : public Type { private: int level; //ȼ int EX; //ֵ public: Abu(string type, string name); //캯 ~Abu() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Abu::Abu(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Abu::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "ܰȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += PI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += NLVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= NAIR; if (cooldown <= NMAI) //;鹥ΪNMAI cooldown = NMAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Abu::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Abu::attack() { //ʾ cout << "ܰĹ" << endl; cout << "ܰʹ<֮צ>" << endl; //˺ int damage = 0; damage = ABU; //˺ return damage; } //˺ʾܵ˺ʱ void Abu::injury(int damage) { // cout << ((double)defense / (double)(100 + defense)) << endl; damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "ܰܵ" << damage << "˺"; cout << "ֵܰΪ" << HP << endl; cout << endl; } //ӡ void Abu::show() { cout << "ܰ" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Abu::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += PI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= NMAI) cooldown = NMAI; } //4.1-ͣʨ class Lion : public Type { private: int level; //ȼ int EX; //ֵ public: Lion(string type, string name); //캯 ~Lion() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Lion::Lion(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Lion::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "ʨȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += NLVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX; cout << "" << setprecision(2) << cooldown; cooldown *= AIR; if (cooldown <= MAI) //;鹥ΪMAI cooldown = MAI; cout << " -> " << setprecision(2) << cooldown; cout << endl; } } //ս㺯 void Lion::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ cout << endl; } } //ʽ int Lion::attack() { //ʾ cout << "ʨĹ" << endl; cout << "ʨʹ<ɳ>" << endl; //˺ int damage = 0; damage = LION; //˺ return damage; } //˺ʾܵ˺ʱ void Lion::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "ʨܵ" << damage << "˺"; cout << "ʨֵΪ" << HP << endl; cout << endl; } //ӡ void Lion::show() { cout << "ʨ" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Lion::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += NPI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= MAI) cooldown = MAI; } //4.2-ͣɻ class Oriole : public Type { private: int level; //ȼ int EX; //ֵ public: Oriole(string type, string name); //캯 ~Oriole() {}; // // virtual void levelUp(); //սжӮӾֵ virtual void battleOver(int enemyLv, int enemyHP); //麯-ʽʱ virtual int attack(); //麯-˺ʾʱ virtual void injury(int damage); //ӡ virtual void show(); //öӦȼ void setLevel(int preLevel); }; Oriole::Oriole(string type, string name) : Type(type, name){ this -> level = 1; //ʼȼΪ1 this -> EX = 0; //ʼֵΪ0 } // void Oriole::levelUp() { if (EX >= EXMAX * level) { level += EX / (EXMAX * level); //ȼ EX %= (EXMAX * level); // cout << "ɻȼ" << level << "!" << endl; // cout << "Ա仯" << endl; cout << "" << aggressivity; aggressivity += NPI; //仯 cout << " -> " << aggressivity << endl; cout << "" << defense; defense += NPI; //仯 cout << " -> " << defense << endl; cout << "ֵ" << HPMAX; HPMAX += NLVG; //ֵ仯 HP = HPMAX; cout << " -> " << HPMAX << endl; cout << "" << setprecision(2) << cooldown; cooldown *= AIR; if (cooldown <= MAI) //;鹥ΪMAI cooldown = MAI; cout << " -> " << setprecision(2) << cooldown; } } //ս㺯 void Oriole::battleOver(int enemyLv, int enemyHP) { if (HP != 0 && enemyHP == 0) { //ʤ cout << "սʤ" << VEX * enemyLv << endl; EX += VEX * enemyLv; HP = HPMAX; //սֵظ } else if (HP == 0 && enemyHP != 0) { //ʧ cout << "սʧܣ" << FEX * enemyLv << endl; EX += FEX * enemyLv; HP = HPMAX; //սֵظ } } //ʽ int Oriole::attack() { //ʾ cout << "ɻĹ" << endl; cout << "ɻʹ<ħ>" << endl; //˺ int damage = 0; damage = ORIOLE; //˺ return damage; } //˺ʾܵ˺ʱ void Oriole::injury(int damage) { damage = damage * ((double)defense / (double)(50 + defense)); //˺ HP = HP - damage; //˺Ѫ仯 if (HP < 0) HP = 0; //Ѫܵ0 //ʾ˺ cout << "ɻܵ" << damage << "˺"; cout << "ɻֵΪ" << HP << endl; cout << endl; } //ӡ void Oriole::show() { cout << "ɻ" << '\t' << "ȼ" << level << endl; cout << "" << aggressivity << '\t'; cout << "" << defense << '\t'; cout << "ֵ" << HPMAX << '\t'; cout << "" << setprecision(2) << cooldown << endl; cout << endl; } //õȼ void Oriole::setLevel(int preLevel) { int gradeDif = preLevel - level; level = preLevel; //ֱӳɳ aggressivity += NPI * gradeDif; defense += NPI * gradeDif; HPMAX += NLVG * gradeDif; HP = HPMAX; // if (gradeDif >= 0) cooldown = cooldown * pow(NAIR, gradeDif); //ǽ if (gradeDif < 0) cooldown = cooldown / pow(NAIR, (-gradeDif)); //ע⹥ if (cooldown <= MAI) cooldown = MAI; } //û˺ typedef struct accout { char username[NAMELENGTH]; //û char password[NAMELENGTH]; // int logCnt; //¼¼ int onlineOrNot; //1 0 Type my_spirit[USERNUM]; //ûľ }accout; accout users[USERNUM]; //ûṹ int usercnt = 0; //¼û //߳ DWORD WINAPI ServerThread(LPVOID lpParameter){ SOCKET *ClientSocket=(SOCKET*)lpParameter; int receByt=0; char RecvBuf[MaxBufSize]; char SendBuf[MaxBufSize]; //¼ûע int logSrNo = 0; while(1){ /*¼˵*/ LOGMENU: char recvBuf[4024] = {}; char logMenu[4024] = {"\n************************************\n\ * 1ע *\n\ * 2¼ *\n\ * 3ע *\n\ * 4˳ *\n\ ************************************\n\ ѡ\n"}; int sLen = send(*ClientSocket, logMenu, strlen(logMenu), 0); cout << logMenu << endl; //ûѡ int reLen = recv(*ClientSocket, recvBuf, 4024, 0); //ȴ if (SOCKET_ERROR == sLen) { cout << "ʧܣ" << endl; } else { cout << recvBuf << endl; //1ע if (recvBuf[0] == '1') { strcpy(recvBuf, "***************ע*****************\nҪעû"); send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf; recv(*ClientSocket, recvBuf, 4024, 0); //յͻ˷û cout << recvBuf << endl; //û int username_flag = 0; //0δעᣬ1ѱע for (int i = 0; i < usercnt; i++) { if (strcmp(recvBuf, users[i].username) == 0) username_flag = 1; } //߿ͻ˸ûע char flagBuf[4]; if (username_flag == 1) { strcpy(flagBuf, "1"); } else { strcpy(flagBuf, "0"); } send(*ClientSocket, flagBuf, 4, 0); //δעע if (username_flag == 0) { strcpy(users[usercnt].username, recvBuf); //û strcpy(recvBuf, "룺"); send(*ClientSocket, recvBuf, 4024, 0); //ʾ cout << recvBuf; //յͻ˷ recv(*ClientSocket, recvBuf, 4024, 0); strcpy(users[usercnt++].password, recvBuf); // // for (int i = 0; i < usercnt; i++) { // cout << users[i].username; // cout << "" << users[i].password; // } cout << recvBuf << endl; // strcpy(recvBuf, "עɹ\n"); users[usercnt].logCnt = 0; //¼0 users[usercnt].onlineOrNot = 0; // send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; goto LOGMENU; } //ѱע򷵻ز˵ʾ else { strcpy(recvBuf, "dzǸûѱעᣬѡ"); send(*ClientSocket, recvBuf, 4024, 0); //ʾ cout << recvBuf << endl; goto LOGMENU; } } //2¼ if (recvBuf[0] == '2') { strcpy(recvBuf, "***************¼*****************\nû"); send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf; recv(*ClientSocket, recvBuf, 4024, 0); //յͻ˷û cout << recvBuf << endl; //û int username_flag = 0; //0δעᣬ1ѱע for (int i = 0; i < usercnt; i++) { if (strcmp(recvBuf, users[i].username) == 0) { username_flag = 1; logSrNo = i; //¼û break; } } //Ƿɵ¼͸ͻ char flagBuf[4]; if (username_flag == 1) { strcpy(flagBuf, "1"); } else { strcpy(flagBuf, "0"); } send(*ClientSocket, flagBuf, 4, 0); if (username_flag == 1) { strcpy(recvBuf, "룺"); send(*ClientSocket, recvBuf, 4024, 0); //ʾ cout << recvBuf; //յͻ˷ recv(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; //ȷ if (strcmp(recvBuf, users[logSrNo].password) == 0) { //Ŀǰ¼ɹ if (users[logSrNo].onlineOrNot == 0) { strcpy(recvBuf, "¼ɹ\n"); users[logSrNo].onlineOrNot = 1; //1ʾ cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); //¼+1 users[logSrNo].logCnt++; } //¼ʧ else { strcpy(recvBuf, "ǰ˺ѱ¼Ժٳԣ\n"); cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); goto LOGMENU; } } // else { strcpy(recvBuf, "ûѡ\n"); cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); goto LOGMENU; } } //δע򷵻ز˵ʾ else { strcpy(recvBuf, "dzǸûδעᣬѡ"); send(*ClientSocket, recvBuf, 4024, 0); //ʾ cout << recvBuf << endl; goto LOGMENU; } } //3ע if (recvBuf[0] == '3') { strcpy(recvBuf, "Ҫעû"); send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; recv(*ClientSocket, recvBuf, 4024, 0); //յû cout << recvBuf << endl; //û int username_flag = 0; //0δעᣬ1ѱע int srNo = 0; for (int i = 0; i < usercnt; i++) { if (strcmp(recvBuf, users[i].username) == 0) { username_flag = 1; srNo = i; //¼û break; } } //Ƿע͸ͻ char flagBuf[4]; if (username_flag == 1) { strcpy(flagBuf, "1"); } else { strcpy(flagBuf, "0"); } send(*ClientSocket, flagBuf, 4, 0); if (username_flag == 1) { strcpy(recvBuf, "¼룺"); send(*ClientSocket, recvBuf, 4024, 0); //ʾ cout << recvBuf; //յͻ˷ recv(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; //ȷ if (strcmp(recvBuf, users[srNo].password) == 0) { //ע˺ if (srNo != usercnt) { for (int i = srNo; i < usercnt - 1; i++) { strcpy(users[srNo].password, users[srNo + 1].password); strcpy(users[srNo].username, users[srNo + 1].username); } usercnt--; } else usercnt--; strcpy(recvBuf, "עɹ\n"); cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); goto LOGMENU; //ص¼˵ } // else { strcpy(recvBuf, "ûѡ\n"); cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); goto LOGMENU; } } //ûδע else { strcpy(recvBuf, "dzǸûδעᣬѡ"); cout << recvBuf << endl; send(*ClientSocket, recvBuf, 4024, 0); goto LOGMENU; } } //4˳ if (recvBuf[0] == '4') { break; } /*û¼*/ //˸֪ͻ˸ûΪڼε½ char logCnt[4]; if (users[logSrNo].logCnt == 1) strcpy(logCnt, "1"); else strcpy(logCnt, "0"); send(*ClientSocket, logCnt, 4, 0); //ûעһε½û侫 if (users[logSrNo].logCnt == 1) { srand((int)time(0)); // //ֶӦ־飬Դ˷ int flag[8] = {0, 0, 0, 0, 0, 0, 0, 0}; //Ϊֹظû飬жǷظ for (int i = 0; i < 3; i++) { switch ((rand() % 8 + 1)) { case 1: { if (flag[0] == 0) { Type s1("", "սè"); users[logSrNo].my_spirit[i] = s1; flag[0] = 1; break; } else { i--; //ѡi1 break; } } // mine.my_spirit.show(); case 2: { if (flag[1] == 0) { Type s2("", "Ұţ"); users[logSrNo].my_spirit[i] = s2; flag[1] = 1; break; } else { i--; //ѡi1 break; } } // mine.my_spirit.show(); case 3: { if (flag[2] == 0) { Type s3("", ""); users[logSrNo].my_spirit[i] = s3; break; } else { i--; //ѡi1 break; } } case 4: { if (flag[3] == 0) { Type s4("", "¶"); users[logSrNo].my_spirit[i] = s4; flag[3] = 1; break; } else { i--; //ѡi1 break; } } case 5: { if (flag[4] == 0) { Type s5("", "Ϲս"); users[logSrNo].my_spirit[i] = s5; flag[4] = 1; break; } else { i--; break; } } case 6: { if (flag[5] == 0) { Type s6("", "ܰ"); users[logSrNo].my_spirit[i] = s6; flag[5] = 1; break; } else { i--; break; } } case 7: { if (flag[6] == 0) { Type s7("", "ʨ"); users[logSrNo].my_spirit[i] = s7; flag[6] = 1; break; } else { i--; break; } } case 8: { if (flag[7] == 0) { Type s8("", "ɻ"); users[logSrNo].my_spirit[i] = s8; flag[7] = 1; break; } else { i--; break; } } } } //־鵽ͻ for (int i = 0; i < 3; i++) { strcpy(recvBuf, users[logSrNo].my_spirit[i].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); // char type_flag[4]; recv(*ClientSocket, type_flag, 4, 0); //յͻ˷ while (type_flag[0] != '1') { strcpy(recvBuf, users[logSrNo].my_spirit[i].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); recv(*ClientSocket, type_flag, 4, 0); } strcpy(recvBuf, users[logSrNo].my_spirit[i].name.c_str()); send(*ClientSocket, recvBuf, 4024, 0); } //ӡ users[logSrNo].my_spirit[0].show(); users[logSrNo].my_spirit[1].show(); users[logSrNo].my_spirit[2].show(); } //û˵ USERMENU: char userMenu[4024] = {"\n************************************\n\ * 1鿴ҵľ *\n\ * 2鿴û״̬ *\n\ * 3û *\n\ * 4˳¼ *\n\ ************************************\n\ ѡ\n"}; send(*ClientSocket, userMenu, 4024, 0); cout << userMenu << endl; //ûѡ recv(*ClientSocket, recvBuf, 4024, 0); //ȴ cout << recvBuf << endl; //ûѡ //1鿴ҵľ if (recvBuf[0] == '1') { //־鵽ͻ for (int i = 0; i < 3; i++) { strcpy(recvBuf, users[logSrNo].my_spirit[i].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); // char type_flag[4]; recv(*ClientSocket, type_flag, 4, 0); //յͻ˷ while (type_flag[0] != '1') { strcpy(recvBuf, users[logSrNo].my_spirit[i].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); recv(*ClientSocket, type_flag, 4, 0); } strcpy(recvBuf, users[logSrNo].my_spirit[i].name.c_str()); send(*ClientSocket, recvBuf, 4024, 0); } //ӡ users[logSrNo].my_spirit[0].show(); users[logSrNo].my_spirit[1].show(); users[logSrNo].my_spirit[2].show(); goto USERMENU; } //2鿴û״̬ if (recvBuf[0] == '2') { strcpy(recvBuf, "ûб\n"); send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf; for (int i = 0; i < usercnt; i++) { strcpy(recvBuf, users[i].username); //û send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << ""; strcpy(recvBuf, ""); send(*ClientSocket, recvBuf, 4024, 0); //״̬ if (users[i].onlineOrNot == 1) { strcpy(recvBuf, ""); // send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; } else { strcpy(recvBuf, ""); // send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; } } strcpy(recvBuf, ""); send(*ClientSocket, recvBuf, 4024, 0); cout << endl; goto USERMENU; } //3û if (recvBuf[0] == '3') { strcpy(recvBuf, "Ҫû"); int found_flag = 0; //1ҵ0δҵ send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf; recv(*ClientSocket, recvBuf, 4024, 0); //տͻû cout << recvBuf << endl; //Ҹû for (int i = 0; i < usercnt; i++) { if (strcmp(recvBuf, users[i].username) == 0) { //ƥ found_flag = 1; strcpy(recvBuf, "1"); send(*ClientSocket, recvBuf, 4024, 0); //ҵ֪ͻ cout << recvBuf << endl; /*û״̬*/ strcpy(recvBuf, users[i].username); //û send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << ""; strcpy(recvBuf, ""); send(*ClientSocket, recvBuf, 4024, 0); //״̬ if (users[i].onlineOrNot == 1) { strcpy(recvBuf, ""); // send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; } else { strcpy(recvBuf, ""); // send(*ClientSocket, recvBuf, 4024, 0); cout << recvBuf << endl; } /*ûӵеľ*/ //ûעδ½ûȡϵͳ͵ֻ if (users[i].logCnt == 0) { strcpy(recvBuf, "0"); send(*ClientSocket, recvBuf, 4024, 0); //֪ͻ޾ } //ûӵо else { strcpy(recvBuf, "1"); send(*ClientSocket, recvBuf, 4024, 0); //֪ͻо //־鵽ͻ for (int j = 0; j < 3; j++) { strcpy(recvBuf, users[i].my_spirit[j].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); // char type_flag[4]; recv(*ClientSocket, type_flag, 4, 0); //յͻ˷ while (type_flag[0] != '1') { strcpy(recvBuf, users[i].my_spirit[j].type.c_str()); send(*ClientSocket, recvBuf, 4024, 0); recv(*ClientSocket, type_flag, 4, 0); } strcpy(recvBuf, users[i].my_spirit[j].name.c_str()); send(*ClientSocket, recvBuf, 4024, 0); } //ӡ users[i].my_spirit[0].show(); users[i].my_spirit[1].show(); users[i].my_spirit[2].show(); } } } //δҵ if (found_flag == 0) { strcpy(recvBuf, "0"); send(*ClientSocket, recvBuf, 4024, 0); //δҵ֪ͻ } cout << endl; goto USERMENU; } //4˳¼ if (recvBuf[0] == '4') { cout << "˳¼" << endl; users[logSrNo].onlineOrNot = 0; goto LOGMENU; } // cout << " " << endl; // if (strcmp("cls", recvBuf) == 0) { // //ִ // system(recvBuf); // } // else if (strcmp("ȡ汾Ϣ", recvBuf) == 0) { // // // string verData = "Version: 1.0.1\nAuthor: Primer\nReleaseData: 2020-9-3"; // int sLen = send(recvClientSocket, (char*)verData.c_str(), verData.length(), 0); // } // else if (strcmp("exit", recvBuf) == 0) { // cout << endl << "˳" << endl; // break; // } // else { // cout << "\tȷ..." << endl; // } // cout << endl; } }//while closesocket(*ClientSocket); free(ClientSocket); return 0; } int main(){ WORD myVersionRequest; WSAData wsd; myVersionRequest=MAKEWORD(2,2); int err; err=WSAStartup(myVersionRequest,&wsd); if (!err) { printf("Ѵ׽\n"); } else { //һ׽ printf("Ƕδ!"); }//׽֣socketǰһЩ鹤,ͨWSACleanupķֵȷsocketЭǷ SOCKET ListenSocket = socket(AF_INET,SOCK_STREAM,0);//˿ʶ׽ SOCKADDR_IN ListenAddr; ListenAddr.sin_family=AF_INET; ListenAddr.sin_addr.S_un.S_addr=INADDR_ANY;//ʾ뱾ipַ ListenAddr.sin_port=htons(PORT);//󶨶˿ //Ҫ󶨵IJ int n; n=bind(ListenSocket,(LPSOCKADDR)&ListenAddr,sizeof(ListenAddr));// if(n==SOCKET_ERROR){ printf("˿ڰʧܣ\n"); return -1; } else{ printf("˿ڰ󶨳ɹ%d\n",PORT); } int l =listen(ListenSocket,20);//еڶܹյ printf("׼ȴ\n"); while(1){ //ѭտͻ󲢴߳ SOCKET *ClientSocket = new SOCKET; ClientSocket=(SOCKET*)malloc(sizeof(SOCKET)); //տͻ int SockAddrlen = sizeof(sockaddr); *ClientSocket = accept(ListenSocket,0,0); printf("һͻӵsocketǣ%d\n",*ClientSocket); CreateThread(NULL,0,&ServerThread,ClientSocket,0,NULL); }//while closesocket(ListenSocket); WSACleanup(); return(0); }//main
true
c5023ab4ce462bf3736a4391d5c94492ea67c32b
C++
hexagonal-sun/mace
/testsuite/zobrist-tester.cpp
UTF-8
1,867
2.84375
3
[ "MIT" ]
permissive
#include <iostream> #include "board.h" static void checkZobrist(std::string fen) { Board b = Board::constructFromFEN(fen); ZobristHash initialHash = b.getHash(); std::cout << "Initial hash: " << std::hex << initialHash << std::endl; for (int i : {1,2,3,4}) { std::cout << "Checking perft " << i << ": "; b.perft(i, false, [&](Move m) { if (zobHash.getHash(b) != b.getHash()) { std::cout << "ERROR: hash mismatch detected after making move " << m << std::endl; b.printBoard(std::cout); exit(1); } }, [&](Move m) { if (zobHash.getHash(b) != b.getHash()) { std::cout << "ERROR: hash mismatch detected after unmaking move " << m << std::endl; b.printBoard(std::cout); exit(1); } }); ZobristHash newHash = b.getHash(); if (newHash != initialHash) { std::cout << newHash << " != " << initialHash << std::endl; exit(1); } std::cout << newHash << " == " << initialHash << std::endl; } } int main() { for (std::string fen : {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1;", "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10"}) { std::cout << "Testing position: " << fen << std::endl; checkZobrist(fen); } return 0; }
true
5034f402f12e8938904f7a68927a9d22c5bbb0b3
C++
reyhanlioglu/ITU-Courses
/Analysis of Algorithm ll/Homework 1/usecases/BreadthFirstSearch.h
ISO-8859-9
5,281
3.296875
3
[]
no_license
/***************************** * (C) 2020 Emre Reyhanlolu * * All rights reserved. * * * * BLG 336E * * HOMEWORK 1 * * EMRE REYHANLIOGLU * * 150140126 * * * *****************************/ // Breadth First Search algorithm #ifndef BREADTHFIRSTSEARCH_H #define BREADTHFIRSTSEARCH_H #include "CreateGraph.h" #include <queue> #include <stack> using namespace std; class BreadthFirstSearch{ private: queue<GameStatus*> nodeQueue; int numberOfNodes; bool isItFirst; char* expectedWinner; bool canSomebodyWin; GameStatus* root; GameStatus* nodeWhichHasEasiestPath; void addChildrenNodes(GameStatus* node); void checkWhetherGameIsFinishedOrNot(GameStatus* node); public: BreadthFirstSearch(GameStatus* root); void traverse(); int getNumberOfNodes(); void printEasiestPath(); void setExpectedWinner(char winner); }; BreadthFirstSearch::BreadthFirstSearch(GameStatus* root){ this->root = root; this->numberOfNodes = 0; this->nodeWhichHasEasiestPath = NULL; this->isItFirst = true; this->expectedWinner = new char[1]; this->canSomebodyWin = false; } // Helper method which adds given node's children into queue // and increments the total number of nodes // Also there is a control methods which checks whether game is finished or not // This control mechanism is needed for PART 4 // NOTE: This additional control MAY SLOW part 3 DOWN a little bit void BreadthFirstSearch::addChildrenNodes(GameStatus* node){ if(node == NULL) return; // Control for PART 4 // If node has not any children, probably game is finished // but it may be null because of the graph's level limit if(node->children == NULL){ checkWhetherGameIsFinishedOrNot(node); return; } int numberOfChildren = node->numberOfChildren; // Add children into queue for(int i=0; i<numberOfChildren; i++){ this->nodeQueue.push(node->children[i]); this->numberOfNodes++; } } // Traverse method void BreadthFirstSearch::traverse(){ // Add children into queue (also this method counts the number of nodes) if(root == NULL) return; // Add the root node this->nodeQueue.push(root); this->numberOfNodes++; // Add other nodes for(int i=0; nodeQueue.size() > 0; i++){ // Add front node's children addChildrenNodes(nodeQueue.front()); // Pop the front node nodeQueue.pop(); } } // Getter int BreadthFirstSearch::getNumberOfNodes(){ return this->numberOfNodes; } // PART 4 Helper Method void BreadthFirstSearch::checkWhetherGameIsFinishedOrNot(GameStatus* node){ if(node->pikachu->isDead || node->blastoise->isDead){ this->canSomebodyWin = true; // Expected winner did not initilized, Part 3 is not working, so skip this method if( expectedWinner == NULL || (expectedWinner[0] != 'B' && expectedWinner[0] != 'P')) return; // Check whether expected winner is alive or not if( (this->expectedWinner[0] == 'B' && node->blastoise->isDead) // If blastoise should be won, then blastoise must be alive || (this->expectedWinner[0] == 'P' && node->pikachu->isDead) ) // If pikachu should be won, then pikachu must be alive return; // This block should run only once to get first easiest path if(isItFirst){ this->nodeWhichHasEasiestPath = node; isItFirst = false; } } } void BreadthFirstSearch::setExpectedWinner(char winner){ this->expectedWinner[0] = winner; } void BreadthFirstSearch::printEasiestPath(){ if(this->nodeWhichHasEasiestPath == NULL){ // Somebody is won but its not expected if(canSomebodyWin){ if(expectedWinner[0] == 'B'){ printf("I'm sorry. There is not any possible action sequence for Blastoise to win this game :(\n"); } else if(expectedWinner[0] == 'P'){ printf("I'm sorry. There is not any possible action sequence for Pikachu to win this game :(\n"); } } // Game is going on else{ printf("There is not any easiest path in this graph\nNobody is dead. Game is going on!\n"); } return; } // TEST: PRINTING THE NODE WHICH HAS EASIEST PATH //nodeWhichHasEasiestPath->printStatus(); // Getting the probability and level count float probability = nodeWhichHasEasiestPath->stats->probability; int levelCount = 0; // Stack is needed to reverse the order from current node to the head node while printing stack <GameStatus*> easiestPath; GameStatus* iterator = nodeWhichHasEasiestPath; while(iterator->parent != NULL){ easiestPath.push(iterator); iterator = iterator->parent; levelCount++; } // Now we can print the easiest path in order int pathSize = easiestPath.size(); for(int i=0; i<pathSize; i++){ GameStatus* currentNode = easiestPath.top(); if(currentNode->stats->turn == 'B') printf("\tPikachu "); else if(currentNode->stats->turn == 'P') printf("\tBlastoise "); printf("used %s.", currentNode->usedSkillName); if(currentNode->isSkillEffective) printf("It's effective.\n"); else printf("It's noneffective.\n"); easiestPath.pop(); } printf("\tLevel count : %d\n", levelCount); printf("\tProbability : %f\n", probability); } #endif
true
d48aee31e4cad502e79596fe5e1e5727fb535fd7
C++
vineetmidha/GFG
/CheckKthBitSet.cpp
UTF-8
284
2.78125
3
[]
no_license
// https://practice.geeksforgeeks.org/problems/check-whether-k-th-bit-is-set-or-not-1587115620/1/?track=dsa-workshop-1-bit-magic&batchId=308 // Function to check if Kth bit is set or not bool checkKthBit(int n, int k){ int mask = (1<<k); return (n & mask); }
true
d828f942b450fc20702684a0c0b4f6cda1175ad4
C++
markowanga/OI-OIG
/OIG/Obwarzanki.cpp
UTF-8
1,292
3.015625
3
[]
no_license
/** * V Olimpiada Informatyczna Gimnazjalistów * Zadanie: Obwarzanki * Wynik 100/100 * Wykonał: Marcin Wątroba * http://main.edu.pl/pl/archive/oig/5/obw */ #include <iostream> #include <cstdio> #include <utility> using namespace std; int min(int a, int b) { if (a > b) return b; return a; } int max(int a, int b) { if (a < b) return b; return a; } int main() { int n, m; scanf("%d%d", &n, &m); m--; pair<int, int> *tab = new pair<int, int>[n]; for (int a = 0; a < n; a++) scanf("%d%d", &tab[a].first, &tab[a].second); //sprawdzanie od obwarzaka m do 0 int lewo = 0; pair<int, int> pom = tab[m]; for (int a = m - 1; a >= 0; a--) if (!(tab[a].second <= pom.first || tab[a].first >= pom.second)) { lewo++; pom.first = min(pom.first, tab[a].first); pom.second = max(pom.second, tab[a].second); } //sprawdzenie prawo int prawo = 0; pom = tab[m]; for (int a = m + 1; a < n; a++) if (!(tab[a].second <= pom.first || tab[a].first >= pom.second)) { prawo++; pom.first = min(pom.first, tab[a].first); pom.second = max(pom.second, tab[a].second); } printf("%d", min(lewo, prawo)); return 0; }
true
ca98cf2885f3141bd8fa0a2a24742877eb83ddd1
C++
liuyehcf/Reflect
/Reflect/pattern2/demo.h
GB18030
1,311
2.859375
3
[]
no_license
#pragma once #include"object.h" #include<vector> #include<string> #include<iostream> class demo2; class demo1 :public object { /* * Ҫʵַע */ REGISTE_MEMBER_HEAD(demo1) private: int age; long time; float woman; double man; void set_age(std::string age) { this->age = stoi(age); } void print_age() { std::cout << "demo1's age: " << this->age << std::endl; } void set_time(std::string time) { this->time = stol(time); } void print_time() { std::cout << "demo1's time: " << this->time << std::endl; } void set_woman(std::string woman) { this->woman = stof(woman); } void print_woman() { std::cout << "demo1's woman: " << this->woman << std::endl; } void set_man(std::string man) { this->man = stod(man); } void print_man() { std::cout << "demo1's man: " << this->man << std::endl; } private: demo2* _demo2 = nullptr; void set_demo2(object* t_demo2) { _demo2 = (demo2*)t_demo2; } private: void init() { std::cout << "demo1's init" << std::endl; } }; class demo2 :public object { /* * Ҫʵַע */ REGISTE_MEMBER_HEAD(demo2) private: demo1* _demo1 = nullptr; void set_demo1(object* t_demo1) { _demo1 = (demo1*)t_demo1; } private: void init() { std::cout << "demo2's init" << std::endl; } };
true
caaf336255ec53fbbacd6071a8bf61a68be33432
C++
parksangwooyeahyeah/lab05
/Lab05-DSLinkedList_HT/DoublyIterator.h
UTF-8
1,167
2.984375
3
[]
no_license
#pragma once #ifndef _DOUBLYITERATOR_H #define _DOUBLYITERATOR_H #include "DoublySortedLinkedList.h" template<typename T> struct DoublyNodeType; template<typename T> class DoublySortedLinkedList; /** * ���Ḯ��Ʈ���� ���̴� Iterator�� Ŭ����. */ template <typename T> class DoublyIterator { friend class DoublySortedLinkedList<T>; public: DoublyIterator(const DoublySortedLinkedList<T> &list) : m_List(list), m_pCurPointer(list.m_pFirst) // 엠피퍼스트는 헤더 {}; // set the current pointer to the first node 헤드다음. 헤드와 트레일러에는 데이터 저장안됨 void Begin() { m_pCurPointer = m_List.m_pFirst->next; } // move current pointer to next void Next() { m_pCurPointer = m_pCurPointer->next; } // current node�� data �����͸� ���� T* GetCurrentNode() { return &m_pCurPointer->data; } // not end? bool NotEnd() { if (m_pCurPointer->next == NULL) return false; else return true; } private: const DoublySortedLinkedList<T> &m_List; DoublyNodeType<T>* m_pCurPointer; }; #endif _DOUBLYITERATOR_H
true
d7598016e9418c6fa475d4fae79e25aa94216344
C++
mikeypatt/IP_Address_Cache
/IP_Address_Tests.cpp
UTF-8
692
3.234375
3
[]
no_license
// // Created by Michael Patterson on 18/10/2020. // #include <gtest/gtest.h> #include "IP_Address.h" using testing::Eq; struct IPAddressTests : public testing::Test { IP_Address* Address1; IP_Address* Address2; IPAddressTests() { Address1 = new IP_Address(192,168,0,1); Address2 = new IP_Address(194,168,0,1); } ~IPAddressTests() override{ delete Address1; delete Address2; } }; TEST_F (IPAddressTests, displayIPAddressTest) { ASSERT_STREQ(Address1->format().c_str(),"192.168.0.1"); ASSERT_STREQ(Address2->format().c_str(),"194.168.0.1"); } TEST_F (IPAddressTests, ComparingTwoAddressTest) { ASSERT_TRUE(Address1<Address2); }
true
1bb6f2546c413f4ca2bdbb8832e7ab6dd1987723
C++
faemiyah/faemiyah-demoscene_2015-04_64k-intro_junamatkailuintro
/src/verbatim_vertex_buffer.cpp
UTF-8
1,796
2.734375
3
[ "BSD-3-Clause" ]
permissive
#include "verbatim_vertex_buffer.hpp" const VertexBuffer* VertexBuffer::g_bound_vertex_buffer = NULL; const VertexBuffer* VertexBuffer::g_programmed_vertex_buffer = NULL; VertexBuffer::VertexBuffer() { dnload_glGenBuffers(2, m_id_data); } void VertexBuffer::bind() const { if(this == g_bound_vertex_buffer) { return; } dnload_glBindBuffer(GL_ARRAY_BUFFER, getVertexId()); dnload_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, getIndexId()); g_bound_vertex_buffer = this; reset_programmed_vertex_buffer(); } void VertexBuffer::update(bool indicesEnabled) { if(!indicesEnabled) { dnload_glDeleteBuffers(1, &(m_id_data[1])); m_id_data[1] = 0; } this->bind(); #if 0 for(unsigned ii = 0; (ii < m_vertex_count); ++ii) { std::cout << m_vertex_data[ii] << std::endl; } for(unsigned ii = 0; (ii < m_index_count); ii += 3) { std::cout << m_index_data[ii] << ", " << m_index_data[ii + 1] << ", " << m_index_data[ii + 2] << std::endl; } #endif dnload_glBufferData(GL_ARRAY_BUFFER, m_vertices.getSizeBytes(), m_vertices.getData(), GL_STATIC_DRAW); if(indicesEnabled) { dnload_glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indices.getSizeBytes(), m_indices.getData(), GL_STATIC_DRAW); } } void VertexBuffer::use(const Program *op) const { this->bind(); if(this == g_programmed_vertex_buffer) { return; } op->attribPointer('P', 3, GL_FLOAT, false, sizeof(Vertex), static_cast<const uint8_t*>(NULL) + Vertex::POSITION_OFFSET); op->attribPointer('N', 4, GL_BYTE, true, sizeof(Vertex), static_cast<const uint8_t*>(NULL) + Vertex::NORMAL_OFFSET); op->attribPointer('C', 2, GL_UNSIGNED_BYTE, true, sizeof(Vertex), static_cast<const uint8_t*>(NULL) + Vertex::COLOR_OFFSET); g_programmed_vertex_buffer = this; }
true
e616251bf7821d4cba7c73c95398492db2f3ac6d
C++
ritik99/comp_code
/10004.cpp
UTF-8
1,636
2.671875
3
[]
no_license
#include<iostream> #include<map> #include<vector> #include<queue> #include<algorithm> #include<cstdio> using namespace std; int func(std::map<int, std::vector<int> > mp, int a){ //bool flag = true; queue<int> q; int color[100000] = {0}; bool discovered[100000] = {0}; vector<int> arr; q.push(); int layer = 1; while(!q.empty()){ int t = q.front(); if(discovered[t] == 0){ discovered[t] = 1; arr.push_back(t); if(layer%2 == 1) color[t] = 1; else color[t] = 2; } for(int i = 0; i < mp[t].size(); i++){ if(discovered[mp[t][i]] == 0){ if(layer%2 == 1) color[mp[t][i]] = 2; else color[mp[t][i]] = 1; discovered[mp[t][i]] = 1; arr.push_back(mp[t][i]); q.push(mp[t][i]); } } layer++; q.pop(); } bool flag = true; for(map<int, std::vector<int> >::iterator it = mp.begin(); it != mp.end(); it++){ for(int i = 0; i < (it->second).size(); i++){ if(color[it->first] == color[(it->second)[i]]){ cout << "NOT BICOLORABLE." << endl; flag = false; return 0; } } } if(flag == true) cout << "BICOLORABLE." << endl; /*for(int i = 0; i < arr.size(); i++){ cout << arr[i] << " "; }*/ return 0; } int main(){ //freopen ("uva10004.txt", "w", stdout); int a, b; cin >> a >> b; map<int, std::vector<int> > mp; for(int o = 0; o < b; o++){ //int ed; int m, n; cin >> m >> n; if(mp.find(m) != mp.end()){ vector<int>::iterator pos = find(mp[m].begin(), mp[m].end(), n); if(pos == mp[m].end()) mp[m].push_back(n); else mp[m].erase(pos); } else{ mp[m].push_back(n); } func(mp, a); //mp[b].push_back(a); //cin >> n; } return 0; }
true
3e80daa0f4627baf296ea4cf15804330c82d4f43
C++
sakshi-chauhan/DSCodes
/Stacks/AddNumbers.cpp
UTF-8
1,701
3.53125
4
[]
no_license
//http://ideone.com/kneolB //Add two numbers using stacks #include <iostream> #include<stack> int reverseNumber( int num ){ int rev = 0; while( num > 0 ){ rev = ( rev * 10 ) + ( num % 10 ) ; num /= 10; } return rev; } void printStack( std::stack<int> s ){ while( !s.empty() ){ std::cout<<s.top(); s.pop(); } std::cout<<'\n'; } int main() { // your code goes here std::stack<int> stk1; std::stack<int> stk2; std::stack<int> res; int num1,num2; int rev1,rev2; std::cin>>num1>>num2; rev1 = reverseNumber( num1 ); rev2 = reverseNumber( num2 ); //std::cout<<rev1<<" "<<rev2; while( rev1 > 0 ){ stk1.push( rev1%10 ); //std::cout<<stk1.top()<<" "; rev1 /= 10; } while( rev2 > 0 ){ stk2.push( rev2%10 ); //std::cout<<stk2.top()<<" "; rev2 /= 10; } int sum,carry=0; while( !stk1.empty() && !stk2.empty() ){ sum = stk1.top() + stk2.top() + carry; //std::cout<<sum; if( sum >= 10 ){ sum %= 10; carry = 1; } else carry = 0; res.push(sum); //std::cout<<res.top()<<" "; stk1.pop(); stk2.pop(); } //printStack( res ); if( !stk1.empty() ){ while( !stk1.empty() ){ if( carry ){ sum = stk1.top() + 1; res.push( sum ); stk1.pop(); carry = 0; } else{ res.push( stk1.top() ); stk1.pop(); } } } else if( !stk2.empty() ){ while( !stk2.empty() ){ if( carry ){ sum = stk2.top() + 1; res.push( sum ); stk2.pop(); carry = 0; } else{ res.push( stk2.top() ); stk2.pop(); } } } printStack( res ); return 0; }
true
b96b87e6b2279d62d4e31a6eaf9359267553d7b0
C++
coolsnowy/leetcode
/007.Reverse_Integer.cpp
GB18030
1,791
4.03125
4
[]
no_license
/* Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers. Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. */ #include <iostream> #include <vector> #include <string> #include <cmath> using namespace std; //my accepted answer int reverse1(int x) { int b = 0; /* while (x / 10) { int a = x % 10; if (abs(b) > (pow(2, 31)/10)) return 0;//עĿеnote32λҪעж b = b * 10 + a; x = x / 10; } if (abs(b) > (pow(2, 31) / 10)) return 0;//עĿеnote32λҪעж b = b * 10 + x; */ //Ľ ʽһѭһλԽwhileijx= 0 while (x != 0) { int a = x % 10; if (abs(b) > (pow(2, 31) / 10)) return 0;//עĿеnote32λҪעж b = b * 10 + a; x = x / 10; } return b; } // better answerҵĺ񣬸ĽڲҪжϣˣڽз㣬֮ǰֵ᲻ͬ // note Ϊ漰˳˳ֻмӼγɰȺʹҲõԭĽtest int reverse(int x) { int result = 0; while (x != 0) { int tail = x % 10; int newResult = result * 10 + tail; if ((newResult - tail) / 10 != result) { return 0; } result = newResult; x = x / 10; } return result; } int main() { int x = 0; cin >> x; cout << reverse(x) << endl; //test Ⱥ int a = 0, b = 0, c = 0; a = pow(2, 500); cout << a << endl; b = 123; c = a + b; b = c - a; cout << b; }
true
b325591f94d761e2145f78bc5599353d8c6cd8a3
C++
Baltoli/accsynt
/src/synth/src/affine_fragment.h
UTF-8
2,609
2.515625
3
[]
no_license
#pragma once #include "fragment.h" #include <support/llvm_utils.h> #include <support/random.h> namespace synth { class affine_fragment : public fragment { public: affine_fragment(std::vector<props::value> args, frag_ptr before); affine_fragment(std::vector<props::value> args); affine_fragment(affine_fragment const&) = default; affine_fragment& operator=(affine_fragment&) = default; affine_fragment(affine_fragment&&) = default; affine_fragment& operator=(affine_fragment&&) = default; bool operator==(affine_fragment const& other) const; bool operator!=(affine_fragment const& other) const; bool equal_to(frag_ptr const& other) const override; void splice(compile_context& ctx, llvm::BasicBlock* entry, llvm::BasicBlock* exit) override; bool add_child(frag_ptr f, size_t idx) override; std::string to_str(size_t indent = 0) override; int get_id() const override; std::vector<int> id_sequence() const override; size_t count_holes() const override; friend void swap(affine_fragment& a, affine_fragment& b); static char ID; protected: // Restrict this fragment to having things after it for simplicity - will help // to implement all the member functions that are awkward for multiple // children. fragment::frag_ptr after_; private: template <typename Builder> llvm::Value* create_affine(Builder& b, std::set<llvm::Value*> const& constants, std::set<llvm::Value*> const& indices) const; }; template <typename Builder> llvm::Value* affine_fragment::create_affine(Builder& b, std::set<llvm::Value*> const& constants, std::set<llvm::Value*> const& indices) const { constexpr auto is_int = [](auto v) { return v->getType()->isIntegerTy(); }; auto affine_len = std::min(indices.size(), constants.size() + 1); auto c_shuf = std::vector<llvm::Value*> {}; std::copy_if( constants.begin(), constants.end(), std::back_inserter(c_shuf), is_int); auto i_shuf = std::vector<llvm::Value*> {}; std::copy_if( indices.begin(), indices.end(), std::back_inserter(i_shuf), is_int); auto engine = support::get_random_engine(); std::shuffle(i_shuf.begin(), i_shuf.end(), engine); std::shuffle(c_shuf.begin(), c_shuf.end(), engine); auto summands = std::vector<llvm::Value*> {}; auto i_prod = i_shuf.begin(); auto c_prod = c_shuf.begin(); summands.push_back(*i_prod++); for (auto i = 1u; i < affine_len; ++i) { summands.push_back(b.CreateMul(*i_prod++, *c_prod++, "affine.mul")); } return support::create_sum(b, summands.begin(), summands.end(), "affine.sum"); } } // namespace synth
true
511f5aa4000f7c126b60ab04d60d1548aadc9519
C++
kapcom01/tcc2012-mlp-mpi-cuda
/src/mlp/mpi/RemoteOutLayer.cpp
UTF-8
3,213
2.578125
3
[]
no_license
#include "mlp/mpi/RemoteOutLayer.h" namespace ParallelMLP { //===========================================================================// RemoteOutLayer::RemoteOutLayer(uint inUnits, uint outUnits, uint hid, uint hosts) : Layer(inUnits, outUnits), OutLayer(inUnits, outUnits) { this->hid = hid; // Aloca os vetores if (hid == 0) { weights = new float[connUnits]; bias = new float[outUnits]; gradient = new float[outUnits]; funcSignal = new float[outUnits]; error = new float[outUnits]; } errorSignal = new float[inUnits]; } //===========================================================================// RemoteOutLayer::~RemoteOutLayer() { if (hid == 0) { delete[] weights; delete[] bias; delete[] gradient; delete[] funcSignal; delete[] error; } delete[] errorSignal; } //===========================================================================// void RemoteOutLayer::randomize() { if (hid == 0) { for (uint i = 0; i < connUnits; i++) weights[i] = random(); for (uint i = 0; i < outUnits; i++) bias[i] = random(); } } //===========================================================================// void RemoteOutLayer::feedforward(const float* input) { // Apenas o mestre executa o feedforward if (hid == 0) { this->input = input; // Inicializa o sinal funcional memset(funcSignal, 0, outUnits * sizeof(float)); // Calcula o sinal funcional for (uint i = 0; i < connUnits; i++) { uint j = i % inUnits; uint k = i / inUnits; funcSignal[k] += weights[i] * input[j]; } // Ativa o sinal funcional for (uint i = 0; i < outUnits; i++) funcSignal[i] = ACTIVATE(bias[i] + funcSignal[i]); } } //===========================================================================// void RemoteOutLayer::calculateError(const float* target) { if (hid == 0) { float sum = 0; // Calcula o erro cometido pela rede for (uint i = 0; i < outUnits; i++) { error[i] = target[i] - funcSignal[i]; sum += error[i] * error[i]; } // Incrementa o erro incError(sum); } } //===========================================================================// void RemoteOutLayer::feedbackward(const float* target, float learning) { // Apenas o mestre executa o feedbackward if (hid == 0) { calculateError(target); // Inicializa o sinal funcional memset(errorSignal, 0, inUnits * sizeof(float)); // Calcula o gradiente for (uint i = 0; i < outUnits; i++) { gradient[i] = DERIVATE(funcSignal[i]) * target[i]; bias[i] += gradient[i]; } // Atualiza os pesos e calcula o sinal de erro for (uint i = 0; i < connUnits; i++) { uint j = i % inUnits; uint k = i / inUnits; weights[i] += learning * gradient[k] * input[j]; errorSignal[j] += gradient[k] * weights[i]; } } // Envia o sinal de erro do mestre para os escravos COMM_WORLD.Bcast(&totalError, 1, FLOAT, 0); COMM_WORLD.Bcast(errorSignal, inUnits, FLOAT, 0); } //===========================================================================// float RemoteOutLayer::random() const { float r = rand() / (float) RAND_MAX; return 2 * r - 1; } //===========================================================================// }
true
8ca2ec72e91404cb0621b88f76a8797eaff53f8a
C++
Suanec/BachelorOfIS
/work/_jobdu/_leetcode_/_leetcode_/_leetcode_326.cpp
UTF-8
832
3.078125
3
[]
no_license
/* 326. Power of Three My Submissions QuestionEditorial Solution Total Accepted: 40791 Total Submissions: 110615 Difficulty: Easy Given an integer, write a function to determine if it is a power of three. Follow up: Could you do it without using any loop / recursion? */ #include"leetcode.h" class Solution { public: bool isPowerOfThree(int n) { int a[] = {3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467}; for( int i = 0; i< 19; i++ ) if( n == a[i] ) return true; return false; } }; /********************************************************* main() *********************************************************/ //void main(){ // Solution slt; // slt.isPowerOfThree(1); // //system("pause"); //}
true
1247f3c07cb6f0c12047b124c48b00a8e36e7cd0
C++
OC-MCS/prog5-mystring-danielmaher3
/MyString/testMyString.cpp
UTF-8
723
3.609375
4
[]
no_license
// test driver code goes here #include <iostream> #include "MyString.h" using namespace std; int main() { cout << "I am a test :)" << endl; MyString s1; MyString s2 = ":)"; MyString s3(s2); cout << "First:" << endl; cout << "s1: " << s1 << endl; cout << "s2: " << s2 << endl; cout << "s3: " << s3 << endl; MyString s4 = s1 + s2; cout << "Second:" << endl; cout << "s1 + s2: " << s4 << endl; s4 = s3 + s1; cout << "s3 + s1: " << s4 << endl; s4 = s2 + s3; cout << "s2 + s3: "<< s4 << endl; MyString s5 = s2; if (s5 == s1) { cout << ":), == works" << endl; } else if (s2 == s5) { cout << ":[, predictable" << endl; } else { cout << ":(, ++ did not work" << endl; } return 0; }
true
4fd28a0582052e1546deaadba0abfba430b12c0d
C++
lauraaustin/Computer-Science-Minor
/121/hw1pr2.cpp
UTF-8
1,542
3.234375
3
[]
no_license
//Laura Austin //CSCE 121-506 //Due: February 1, 2016 //hw1pr2.cpp //I got the formula for the area of a segment from: // http://www.mathopenref.com/segmentarea.html #include "std_lib_facilities_4.h" int main() { double c, r,PI,a,C,S; // c is chord length // radius // a is area of circle of 14 inches // C is central angle // S is area of segment int p; // p is percentage of pizza left cout << "Pizza diameter is 14\".\n"; // the pizza size and diameter is constant. cout << "Enter chord length in inches: "; // user enters a number, can be a decimal. while(cin >> c) // computer stores a new value for chord length every loop and continues { // until the user ends the loop with a character or ctrl+C if ((c>14) || (c<0)) // user can't cut a negative pizza chord or larger chord than the diameter { cout << "The pizza can't get cut with that chord length, silly Billy!\n"; } else if ((c>=0) && (c<=14)) // runs the calculation if the chord length falls between 0 and 14 { r = 7; // diameter is 14 so radius is 7, constant PI = 3.14159265359; // defining PI manually a = PI*pow(r,2); // area of the pizza BEFORE cut C = 2*(asin(c/(2*r))); // central angle that corresponds to chord length S = (r*r/2) * (C-sin(C)); // Segment area formula p = 100 - S/a*100; // percentage of the whole pizza minus percent cut off cout << "That cut leaves " << p<< "% of pizza.\n"; } cout << "Enter chord length in inches: "; } return 0; // if program succesfully runs, program ends }
true
d54051f4f3e4413c60d173431f0e2bada5e9ed02
C++
BliZZeRxD/GodLanguage
/lab3/1t.cpp
UTF-8
423
2.5625
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { int a,b,c; cin >> a >> b >> c; if ((sqrt(pow(a,2)+pow(b,2))) == c) cout << "YES"; else if ((sqrt(pow(c,2)+pow(b,2))) == a) cout << "YES"; else if ((sqrt(pow(a,2)+pow(c,2))) == b) cout << "YES"; else if (a == b && b==c) cout << "YES"; else cout << "NO"; return 0; }
true
5ee2c0aad713877a39d9eca9b551b524b2fc51d4
C++
punnu97/sanjivani
/project.cpp
UTF-8
11,272
2.796875
3
[]
no_license
/*PROJECT :SANJIVANI- ONLINE MEDICINE PORTAL NOTE :- Only ADMIN of the PORTAL can open a customer account To join SANJIVANI group, contact ADMIN -1800456789(TOLL FREE) */ #include<fstream.h> #include<conio.h> #include<stdio.h> #include<string.h> #include<dos.h> #include<process.h> #include<iomanip.h> class medicine //medicine details {char mfg[20],exp[20]; int n; float cost; float Rate(float,int) {return (cost/n) ; } public: char condition[20]; char med_name[20]; float rate; medicine() {strcpy(mfg,"NA"); strcpy(exp,"NA"); cost=0; strcpy(condition,"OUT OF STOCK"); strcpy(med_name,"NA"); } void input() //input medicine information {cout<<"\nEnter name of medicine : "; gets(med_name); cout<<"\nEnter mfg. date,press enter and enter exp. date : "; gets(mfg); gets(exp); cout<<"\nEnter cost and press enter to enter the no. of tablets : "; cin>>cost>>n; cout<<"\nEnter availability (i.e. OUT OF STOCK/IN STOCK) : "; gets(condition); rate=Rate(cost,n); } void info_display() //display medicine information { cout<<"Name : "<<med_name<<"\n"; cout<<"Mfg. : "<<mfg<<endl; cout<<"Exp. : "<<exp<<endl; cout<<"Rate (per tablet) : "<<"Rs"<<rate<<endl; cout<<"Availability : "<<condition<<endl; } void list() //display all medicines list {cout<<setw(20)<<med_name<<" "; cout<<setw(8)<<mfg<<" "; cout<<setw(8)<<exp<<" "; cout<<setw(10)<<"Rs"<<rate<<" "; } }; void Add() //add medicine { medicine s; ofstream fout; fout.open("store.dat",ios::binary|ios::app); if(!fout) {cout<<"Error opening file"; return; } s.input(); fout.write((char*)&s,sizeof(s)); fout.close(); } float calculate(medicine &s,int n) //to calculate bill {if(!(strcmpi(s.condition,"OUT OF STOCK"))==0) return (s.rate*n); else return 0; } float printbill() //printing bill {int k,flag,x,i=0; ifstream fin; medicine s; char r[20]; float cost; fin.open("store.dat",ios::in|ios::binary); if(!fin) {cout<<"Cannot open store \n"; return 0; } cout<<"Enter no. of medicines purchased : "; cin>>x; cout<<endl; do {cout<<"Enter name of "<<i+1<<" medicine purchased : "; gets(r); fin.seekg(0); while(fin.read((char*)&s,sizeof(s))) {if((strcmpi(r,s.med_name))==0) {flag=1; float cost; s.info_display(); cout<<"Enter no.of tablets purchased : "; cin>>k; cost=calculate(s,k); return cost; } } if(flag!=1) cost=0 ; }while(i<x); fin.close(); return cost; } //Customer account records struct acc { char username[20]; char password[20]; int eno; }cust[100]; void opencust(acc s) //Logging into customer's account {char c; do {clrscr(); int ch; medicine m,n[100],p;ifstream fin;ofstream fout; int i,count=0; float total; cout<<"WELCOME "<<s.username<<endl; cout<<"What would you like to do ?\n"; cout<<"1.SEARCH A MEDICINE\n"; cout<<"2.PRINT A BILL\n"; cout<<"3.CHANGE YOUR PASSWORD\n"; cout<<"4.SIGN OUT\n"; cout<<"Enter your choice no. : "; cin>>ch; switch(ch) {case 1 : char medn[20]; int flag=0; //searching medicine fin.open("store.dat",ios::in|ios::binary); if(!fin) {cout<<"Cannot open store \n"; return; } cout<<"Enter name of medicine to be searched : "; gets(medn); fin.seekg(0); while(fin.read((char*)&m,sizeof(m))) { n[count++]=m; } for(i=0;i<count;i++) {if((strcmpi(medn,n[i].med_name))==0) {flag=1; p=n[i]; } } if(flag==1) p.info_display(); else cout<<"Not found\n"; fin.close(); cout<<"\nPress any key \n"; getch(); c='N' ; break; case 2 : clrscr(); //print a bill total=printbill() ; cout<<"\nPlease pay Rs"<<total; cout<<"\nPress any key \n"; getch(); c='N' ; break; case 3 : clrscr(); //change password char p[40],n[40],p_new[40]; int j=0; flag=0; fin.open("account.dat",ios::binary|ios::in|ios::nocreate); if(!fin) {cout<<"Cannot open Account_rec\n"; return; } fout.open("temp.dat",ios::binary|ios::out); if(!fout) {cout<<"Cannot open temp_rec\n"; return; } cout<<"Enter username\n"; gets(n); cout<<"Enter old password\n"; do {p[i]=getch(); if(p[i]==13) {p[i]='\0'; break; } else {cout<<"*"; i++; } }while(p[i-1]!=13) ; int count =0; acc s,N[100]; fin.seekg(0); while(fin.read((char *)&s,sizeof(s))) { N[count++]=s; } for(i=0;i<count;i++) {if((strcmp(N[i].username,n))==0 && (strcmp(N[i].password,p))==0) {cout<<"\nEnter new password :"; do {p_new[j]=getch(); if(p_new[j]==13) {p_new[j]='\0'; break; } else {cout<<"*"; j++; } }while(p_new[j-1]!=13) ; strcpy(N[i].password,p_new); flag=1 ; cout<<"\nPASSWORD CHANGED SUCCESSFULLY\n"; } } if(flag!=1) {cout<<"\nPASSWORD CHANGE UNSUCCESSFUL\n "; } for(i=0;i<count;i++) {fout.write((char*)&N[i],sizeof(N[i])); } fin.close(); fout.close(); remove("account.dat"); rename("temp.dat","account.dat"); cout<<"\nPress any key \n"; getch(); c='N' ; break; case 4 : //sign out cout<<"\n\nAre you sure ?:"; cin>>c; break ; default:c='Y';cout<<"\nInvalid choice\n"; } }while(c=='N'||c=='n'); cout<<"Logging out of your account...\n"; delay(10); } void excust() //Logging into customer's account {acc s,N[100]; ifstream fin; fin.open("account.dat",ios::binary|ios::out|ios::nocreate); if(!fin) {cout<<"Cannot open Account_rec\n"; return; } char p[20],n[20]; int i=0,r; cout<<"Enter username\n"; gets(n); cout<<"Enter password\n"; do {p[i]=getch(); if(p[i]==13) {p[i]='\0'; break; } else {cout<<"*"; i++; } }while(p[i-1]!=13) ; int flag=0;int count=0; fin.seekg(0); while(fin.read((char*)&s,sizeof(s))) { N[count++]=s; } for(i=0;i<count;i++) {if((strcmp(N[i].username,n))==0 && (strcmp(N[i].password,p))==0) { cout<<"\nLogging into your account....\n"; delay(1000); opencust(s); flag=1; } } if(flag==0) cout<<"\nInvalid credentials\n"; fin.close(); } void adminch() //Logging into Admin's account {clrscr(); int n; char ch; do { clrscr(); ofstream fout ; ifstream fin ; cout<<"WELCOME ADMIN\n"; cout<<"1.Add a new medicine \n"; cout<<"2.Delete a medicine \n"; cout<<"3.Display all medicines list\n"; cout<<"4.Open new customer account \n"; cout<<"5.Close a customer account\n"; cout<<"6.Logout\n"; cout<<"What would you like to do? Enter choice no. : "; cin>>n; switch(n) {case 1 : medicine s[100]; int m,i; //Add a medicine fout.open("store.dat",ios::binary|ios::out); if(!fout) {cout<<"Cannot open store_rec\n"; return; } cout<<"Enter no. of medicines to be added : "; cin>>m; for(i=0;i<m;i++) {s[i].input(); fout.write((char*)&s[i],sizeof(s[i])); } fout.close(); ch='n'; cout<<"\nPress any key\n"; getch(); break; case 2 : char med[50]; //Delete a medicine fin.open("store.dat",ios::binary|ios::in|ios::nocreate) ; if(!fin) {cout<<"Cannot open store_rec\n"; return; } fout.open("temp.dat",ios::binary|ios::out); if(!fout) {cout<<"Cannot open temp_rec\n"; return; } medicine del; cout<<"Enter name of medicine to be deleted : "; gets(med); fin.seekg(0); while(fin.read((char*)&del,sizeof(del))) {if(!((strcmpi(del.med_name,med))==0)) fout.write((char*)&del,sizeof(del)); } fin.close(); fout.close(); remove("store.dat"); rename("temp.dat","store.dat"); cout<<"\n Medicine is deleted successfully\n"; ch='n'; cout<<"\nPress any key\n"; getch(); break; case 3 : clrscr(); //Display medicine list fin.open("store.dat",ios::binary|ios::in|ios::nocreate) ; if(!fin) {cout<<"Cannot open store_rec\n"; return; } fin.seekg(0); gotoxy(0,0) ; medicine list_m; cout<<setw(20)<<"Name of medicine "; cout<<setw(10)<<"Mfg. "; cout<<setw(10)<<"Exp. "; cout<<setw(8)<<"Rate "; while(fin.read((char*)&list_m,sizeof(list_m))) { cout<<endl ; list_m.list(); } ch='n'; cout<<"\nPress any key\n"; getch(); break; case 4 : acc q[100]; //Open customer accounts fout.open("account.dat",ios::binary|ios::out); if(!fout) {cout<<"Cannot open Account_rec\n"; return; } cout<<"Enter no. of accounts to be added : "; cin>>m; for(i=0;i<m;i++) {cout<<"\nEnter username for new account : "; gets(q[i].username); cout<<"\nEnter password for new account : "; gets(q[i].password); fout.write((char*)&q[i],sizeof(q[i])); cout<<"\nCustomer enrolled in successfully\n"; } fout.close(); ch='n'; cout<<"\nPress any key\n"; getch(); break; case 5 : clrscr(); char n[40]; i=0; //close customer account fin.open("account.dat",ios::binary|ios::in|ios::nocreate); if(!fin) {cout<<"Cannot open Account_rec\n"; return; } fout.open("temp.dat",ios::binary|ios::out); if(!fout) {cout<<"Cannot open temp_rec\n"; return; } cout<<"Enter username of account to be deleted\n"; gets(n); int count =0; acc r,N[100]; fin.seekg(0); while(fin.read((char *)&r,sizeof(r))) { N[count++]=r; } for(i=0;i<count;i++) {if(!((strcmp(N[i].username,n))==0)) {fout.write((char*)&N[i],sizeof(N[i])); } } cout<<"\nACCOUNT DELETION SUCCESSFUL\n "; fin.close(); fout.close(); remove("account.dat"); rename("temp.dat","account.dat"); cout<<"\nPress any key \n"; getch(); ch='N' ; cout<<"\nPress any key to continue\n"; break; case 6 : //Log out cout<<"\n\nAre you sure ?:"; cin>>ch; break ; default : ch='n'; cout<<"Invalid choice\n" ; } }while(ch=='N'||ch=='n'); } void main() {clrscr(); char c; do {int i=0,ch;char n[20],p[20]; cout<<"\n\n\n\n\t\t\tWELCOME TO E-PHARMACY-SANJIVANI\n"; cout<<"\t\tWORLD'S LARGEST SELLING ONLINE MEDICINE PORTAL\n"; delay(1000); clrscr(); cout<<"Sign in as\n"; cout<<"1.ADMIN\n"; cout<<"2.EXISTING CUSTOMER\n"; cout<<"3.EXIT\n"; cout<<"Enter choice no. : "; cin>>ch; switch(ch) {case 1 : cout<<"Enter username \n"; //Admin's account gateway gets(n); cout<<"Enter password \n"; do {p[i]=getch(); if(p[i]==13) {p[i]='\0'; break; } else {cout<<"*"; i++; } }while(p[i-1]!=13) ; if((strcmp("ADMIN",n))==0 && (strcmp("abcd",p))==0) {cout<<"\nLogging into admin account....\n"; delay(1000); adminch(); } else cout<<"\nInvalid credentials\n"; break; case 2 : excust(); //Customer's account gateway break ; case 3 :break; //Exit default :cout<<"Invalid choice \n"; } cout<<"\nDo you wish to reach main menu? :"; cin>>c; }while(c=='y'||c=='Y'); if(c=='n'||c=='N') cout<<"\t\n\tTHANK YOU ! PLEASE VISIT AGAIN\t\n"; getch(); }
true
f6e1c493b51e8426ef3d71a9b7298502301a6c4e
C++
AngelTorresParada/3DProgrammingLighting
/ugine3d/src/Entity.h
UTF-8
555
2.59375
3
[]
no_license
#pragma once #include "../lib/glm/glm.hpp" #include "../lib/glm/gtc/quaternion.hpp" class Entity { public: Entity(); virtual ~Entity(); const glm::vec3& getPosition() const; void setPosition(const glm::vec3&); const glm::quat& getRotation() const; const void setRotation(const glm::quat&); const glm::vec3& getScale() const; void setScale(const glm::vec3&); void move(const glm::vec3&); virtual void update(float deltaTime) {} virtual void draw() {} protected: glm::vec3 position; glm::quat rotation; glm::vec3 scale; };
true
114782caa9910e43ce3ddd3893113292db066313
C++
arcean/sketchit
/colorcellwidget.cpp
UTF-8
3,749
2.75
3
[]
no_license
#include "colorcellwidget.h" #include <QGraphicsSceneResizeEvent> #include <QDebug> #define NORMAL_STATE 0 #define SELECTED_STATE 6 ColorCellWidget::ColorCellWidget(QColor color, int width, int height, QGraphicsWidget *parent) : MWidget(parent) { this->color = color; this->width = width; this->height = height; this->resize(width, height); this->setMinimumWidth(96); this->setMaximumWidth(96); this->closeDialog = false; pressAnimation = new VariantAnimator(); pressAnimation->setStartValue(NORMAL_STATE); pressAnimation->setEndValue(SELECTED_STATE); pressAnimation->setDuration(200); pressAnimation->setEasingCurve(QEasingCurve::InQuad); connect(pressAnimation, SIGNAL(valueChanged(QVariant)), this, SLOT(expandAnimation(QVariant))); } ColorCellWidget::~ColorCellWidget() { delete pressAnimation; } void ColorCellWidget::resizeEvent(QGraphicsSceneResizeEvent *event) { QSizeF size = event->newSize(); this->height = size.height(); } QRectF ColorCellWidget::boundingRect() const { return QRectF(20, 4, 68, 48); } void ColorCellWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); if(height == 72) { // painter->fillRect(20, 10, 48, 48, "lightgray"); // painter->fillRect(23, 13, 42, 42, color); int x = 20 - margin; int y = 10 - margin; int w = 48 + (margin * 2); int h = 48 + (margin * 2); painter->fillRect(x, y, w, h, color); } else { // painter->fillRect(20, 4, 48, 48, "lightgray"); // painter->fillRect(23, 7, 42, 42, color); int x = 20 - margin; int y = 4 - margin; int w = 48 + (margin * 2); int h = 48 + (margin * 2); painter->fillRect(x, y, w, h, color); } } void ColorCellWidget::setColor(QColor color) { this->color = color; } void ColorCellWidget::expandAnimation(const QVariant &value) { if (isSelect) { if (margin != value.toInt()) { margin = value.toInt(); update(); } // Close the picker, after the animation is finished. if (closeDialog && margin == SELECTED_STATE) { emit this->signalClicked(this->color); closeDialog = false; setNormalState(); } } else { if (SELECTED_STATE - margin != value.toInt()) { margin = SELECTED_STATE - value.toInt(); update(); } } } void ColorCellWidget::setNormalState() { // Run the following code only for a cell in SELECTED_STATE. if (margin == SELECTED_STATE) { isSelect = false; pressAnimation->start(); } } void ColorCellWidget::setSelectedState() { // Run the following code only for a cell in NORMAL_STATE. if (margin == NORMAL_STATE) { isSelect = true; pressAnimation->start(); } } void ColorCellWidget::mousePressEvent(QGraphicsSceneMouseEvent *event) { isSelect = true; emitSignalPressed(); pressAnimation->start(); event->accept(); } void ColorCellWidget::releaseFunc() { if (isUnderMouse()) { emitSignalClicked(); setNormalState(); } else { setNormalState(); emitSignalPressed(); closeDialog = false; } } void ColorCellWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { releaseFunc(); event->accept(); } void ColorCellWidget::emitSignalPressed() { emit this->signalPressed(); } void ColorCellWidget::emitSignalClicked() { if (pressAnimation->state() == QAbstractAnimation::Running) closeDialog = true; else emit this->signalClicked(this->color); }
true
971061f9a88ed441eb6b1ddbbea715c36153622f
C++
kurff/kurff
/test/add_path_label.cpp
UTF-8
334
2.703125
3
[ "MIT" ]
permissive
#include <fstream> using namespace std; int main(int argc, char* argv[]){ ifstream f(argv[1], ios::in); string name; string path = argv[2]; ofstream fo(argv[3], ios::out); int label; while(f >> name >> label){ fo << path+name <<" "<< label<< endl; } fo.close(); f.close(); return 1; }
true
6878bbadfadb027854f31ec2f1d45f8aad5c4dc6
C++
guilhermeleobas/maratona
/UFMG/treino0409/cavalos.cc
UTF-8
3,021
2.515625
3
[]
no_license
#include <iostream> #include <queue> #include <cmath> #include <cstdlib> #include <cstring> #include <string> #include <locale> #include <vector> #include <map> #include <set> #include <functional> #include <utility> #include <algorithm> using namespace std; #define INF 0x3f3f3f3f #define endl "\n" typedef long long int ll; const int MAXN=5000; class Dinic { private: typedef struct sedge { int a, b; ll cap, flow; sedge(int _a, int _b, ll _cap, ll _flow) { a=_a; b=_b; cap=_cap; flow=_flow; } } edge; // Number of vertices, source, sink, visited, queue int n, s, t, d[MAXN], q[MAXN]; int ptr[MAXN]; vector<edge> vEdges; vector<int> g[MAXN]; bool bfs() { int qh=0, qt=0; q[qt++]=this->s; memset(this->d, -1, n*sizeof(d[0])); this->d[this->s]=0; while(qh < qt && d[this->t] == -1) { int v=q[qh++]; for(size_t i=0; i<g[v].size(); i++) { int id = g[v][i], to=vEdges[id].b; if(d[to]==-1 && vEdges[id].flow < vEdges[id].cap) { q[qt++]=to; d[to]=d[v]+1; } } } return d[t]!=-1; } ll dfs(int v, ll flow) { if(!flow) return 0; if(v == t) return flow; for(; ptr[v] < (int)g[v].size(); ptr[v]++) { int id=g[v][ptr[v]], to=vEdges[id].b; // If v did not find to on the bfs... if(d[to]!=d[v]+1) continue; ll pushed=dfs(to, min(flow, vEdges[id].cap-vEdges[id].flow)); if(pushed) { vEdges[id].flow+=pushed; vEdges[id^1].flow-=pushed; return pushed; } } return 0; } public: Dinic() { this->init(0); } Dinic(int _n) { this->init(_n); } void init(int _n) { this->clear(); this->n=_n; } void clear() { this->vEdges.clear(); for(int i=0; i < MAXN; i++) g[i].clear(); } void addEdge(int from, int to, ll cap) { edge e1(from, to, cap, 0); edge e2(to, from, 0, 0); g[from].push_back((int)vEdges.size()); vEdges.push_back(e1); g[to].push_back((int)vEdges.size()); vEdges.push_back(e2); } ll flow(int source, int sink) { this->s=source; this->t=sink; ll flow=0; while(true) { if(not bfs()) break; memset(ptr, 0, n*sizeof(ptr[0])); while(int pushed=dfs(s, INF)) flow+=pushed; } return flow; } }; int main (){ int instance = 1; while (true){ int n, m, k; cin >> n >> m >> k; if (not cin) break; int sz = 2 + n + m; Dinic dinic (sz); vector<int> vec (n); for (int i=0; i<n; i++) cin >> vec[i]; for (int i=1; i<=m; i++){ dinic.addEdge (0, i, 1); } for (int i=1; i<=n; i++){ dinic.addEdge (m+i, sz-1, vec[i-1]); } for (int i=0; i<k; i++){ int u, v; cin >> u >> v; dinic.addEdge (v, u+m, 1); } int flow = dinic.flow (0, sz-1); cout << "Instancia " << instance++ << endl; cout << flow << endl << endl; } return 0; }
true
69e15208ccec06ce79a74a6a136fe85bcf622512
C++
Foxclip/JackCompiler
/compiler.cpp
UTF-8
19,328
2.9375
3
[]
no_license
#include <algorithm> #include "compiler.h" void Compiler::writeXML(std::string line) { int braceCount = 0; bool indentDone = false; char previousChar = 0; for(char c: line) { if(c == '<' || c == '>') { braceCount++; } } if(braceCount == 2) { for(char c: line) { if(c == '/' && previousChar == '<') { xmlIndentLevel -= 1; indentDone = true; break; } previousChar = c; } } std::ofstream stream(outputXMLFilename, std::ios_base::app); for(int i = 0; i < xmlIndentLevel; i++) { for(int j = 0; j < 2; j++) { stream << ' '; } } stream << line << std::endl; if(!indentDone) { for(char c : line) { if(c == '<' || c == '>') { xmlIndentLevel += 0.5; } if(c == '/' && previousChar == '<') { xmlIndentLevel -= 2; } previousChar = c; } } } void Compiler::writeVM(std::string line) { std::ofstream stream(outputVMFilename, std::ios_base::app); stream << line << std::endl; } std::string Compiler::tokenName() { return tokenizer.currentToken().token; } int Compiler::tokenType() { return tokenizer.currentToken().type; } std::string xmlReplace(std::string str) { if(str.size() == 1) { switch(str[0]) { case '<': return "&lt;"; break; case '>': return "&gt;"; break; case '\"': return "&quot;"; break; case '&': return "&amp;"; break; default: return str; } } else { return str; } } std::string Compiler::eat(bool valid, std::string whatExpected) { std::string result = tokenName(); if(tokenizer.hasMoreTokens()) { if(valid) { writeXML("<" + tokenizer.typeToStr(tokenType()) + "> " + xmlReplace(tokenName()) + " </" + tokenizer.typeToStr(tokenType()) + ">"); tokenizer.advance(); } else { throw SyntaxError(std::string("Line " + std::to_string(tokenizer.currentToken().lineNumber) + ": '" + tokenName() + "'" + ": " + whatExpected + " expected").c_str()); } } else { throw SyntaxError(std::string(whatExpected + " expected, but file ended").c_str()); } return result; } std::string Compiler::eatIdentifier() { return eat(tokenType() == TT_IDENTIFIER, "identifier"); } std::string Compiler::eatType() { return eat(tokenName() == "int" || tokenName() == "char" || tokenName() == "boolean" || tokenType() == TT_IDENTIFIER, "type"); } std::string Compiler::eatStr(std::string str) { return eat(str == tokenName(), str); } SymbolTableEntry Compiler::findInSymbolTables(std::string name) { for(SymbolTableEntry entry: subroutineSymbolTable) { if(entry.name == name) { return entry; } } for(SymbolTableEntry entry: classSymbolTable) { if(entry.name == name) { return entry; } } return {"null", "null", "null", -1}; } void Compiler::compileClass() { writeXML("<class>"); eatStr("class"); className = eatIdentifier(); eatStr("{"); while(true) { try { compileClassVarDec(); } catch(SyntaxError e) { break; } } while(true) { try { compileSubroutineDec(); } catch(SyntaxError e) { break; } } eatStr("}"); writeXML("</class>"); } void Compiler::compileClassVarDec() { if(tokenName() == "static" || tokenName() == "field") { writeXML("<classVarDec>"); } std::string varKind = eat(tokenName() == "static" || tokenName() == "field", "'static' or 'field'"); std::string varType = eatType(); std::string varName = eatIdentifier(); std::vector<std::string> varNameList; varNameList.push_back(varName); while(true) { try { eatStr(","); std::string additionalVarName = eatIdentifier(); varNameList.push_back(additionalVarName); } catch(SyntaxError e) { break; } } for(int i = 0; i < (int)varNameList.size(); i++) { int varIndex; if(varKind == "field" || varKind == "this") { varKind = "this"; varIndex = classFieldCount; classFieldCount++; } else if(varKind == "static") { varIndex = classStaticCount; classStaticCount++; } else { debugPrintLine("oops... " + varKind + " | " + varType + " | " + varName, DL_COMPILER); } classSymbolTable.push_back({varNameList[i], varType, varKind, varIndex}); } eatStr(";"); writeXML("</classVarDec>"); } void Compiler::compileSubroutineDec() { if(tokenName() == "constructor" || tokenName() == "function" || tokenName() == "method") { writeXML("<subroutineDec>"); } subroutineKind = eat(tokenName() == "constructor" || tokenName() == "function" || tokenName() == "method", "'constructor', 'function' or 'method'"); std::string returnType = eat(tokenName() == "void" || tokenName() == "int" || tokenName() == "char" || tokenName() == "boolean" || tokenType() == TT_IDENTIFIER, "'void' or type"); subroutineName = eatIdentifier(); subroutineSymbolTable.clear(); subroutineArgCount = 0; subroutineLocalCount = 0; if(subroutineKind == "method") { subroutineSymbolTable.push_back({"this", className, "argument", 0}); subroutineArgCount++; } eatStr("("); compileParameterList(); eatStr(")"); compileSubroutineBody(); writeXML("</subroutineDec>"); writeVM(""); writeVM(""); writeVM(""); } void Compiler::addArgument() { std::string argType = eatType(); std::string argName = eatIdentifier(); subroutineSymbolTable.push_back({argName, argType, "argument", subroutineArgCount}); subroutineArgCount++; } void Compiler::compileParameterList() { writeXML("<parameterList>"); try { addArgument(); while(true) { try { eatStr(","); addArgument(); } catch(SyntaxError e) { break; } } } catch(SyntaxError e) {} writeXML("</parameterList>"); } void Compiler::compileSubroutineBody() { writeXML("<subroutineBody>"); eatStr("{"); while(true) { try { compileVarDec(); } catch(SyntaxError e) { break; } } writeVM("function " + className + "." + subroutineName + " " + std::to_string(subroutineLocalCount)); writeVM(""); if(subroutineKind == "constructor") { writeVM("push constant " + std::to_string(classFieldCount)); writeVM("call Memory.alloc 1"); writeVM("pop pointer 0"); writeVM(""); } else if(subroutineKind == "method") { writeVM("push argument 0"); writeVM("pop pointer 0"); writeVM(""); } compileStatements(); eatStr("}"); writeXML("</subroutineBody>"); } void Compiler::compileVarDec() { if(tokenName() == "var") { writeXML("<varDec>"); } eatStr("var"); std::string varType = eatType(); std::string varName = eatIdentifier(); subroutineSymbolTable.push_back({varName, varType, "local", subroutineLocalCount}); subroutineLocalCount++; while(true) { try { eatStr(","); varName = eatIdentifier(); subroutineSymbolTable.push_back({varName, varType, "local", subroutineLocalCount}); subroutineLocalCount++; } catch(SyntaxError e) { break; } } eatStr(";"); writeXML("</varDec>"); } void Compiler::compileStatements() { if(tokenName() == "let" || tokenName() == "if" || tokenName() == "while" || tokenName() == "do" || tokenName() == "return") { writeXML("<statements>"); } while(true) { if(tokenName() == "let") { compileLetStatement(); } else if(tokenName() == "if") { compileIfStatement(); } else if(tokenName() == "while") { compileWhileStatement(); } else if(tokenName() == "do") { compileDoStatement(); } else if(tokenName() == "return") { compileReturnStatement(); } else { break; } } writeXML("</statements>"); } void Compiler::compileLetStatement() { writeXML("<letStatement>"); eatStr("let"); std::string varName = eatIdentifier(); SymbolTableEntry entry = findInSymbolTables(varName); if(entry.index == -1) { throw SemanticError("Line " + std::to_string(tokenizer.currentToken().lineNumber) + ": " + "variable '" + varName + "' is undefined"); } bool arraySet = false; try { eatStr("["); arraySet = true; writeVM("push " + entry.kind + " " + std::to_string(entry.index)); compileExpression(); writeVM("add"); eatStr("]"); } catch(SyntaxError e) {} eatStr("="); compileExpression(); eatStr(";"); if(arraySet) { writeVM("pop temp 0"); writeVM("pop pointer 1"); writeVM("push temp 0"); writeVM("pop that 0"); } else { writeVM("pop " + entry.kind + " " + std::to_string(entry.index)); } writeXML("</letStatement>"); writeVM(""); } void Compiler::compileIfStatement() { std::string labelL1 = className + "_ifL1." + std::to_string(runningIndex); std::string labelL2 = className + "_ifL2." + std::to_string(runningIndex); runningIndex++; writeXML("<ifStatement>"); eatStr("if"); eatStr("("); compileExpression(); eatStr(")"); writeVM("not"); writeVM("if-goto " + labelL1); writeVM(""); eatStr("{"); compileStatements(); eatStr("}"); writeVM("goto " + labelL2); writeVM("label " + labelL1); writeVM(""); try { eatStr("else"); eatStr("{"); compileStatements(); eatStr("}"); } catch(SyntaxError e) {} writeVM("label " + labelL2); writeXML("</ifStatement>"); writeVM(""); } void Compiler::compileWhileStatement() { std::string labelL1 = className + "_whileL1." + std::to_string(runningIndex); std::string labelL2 = className + "_whileL2." + std::to_string(runningIndex); runningIndex++; writeVM("label " + labelL1); writeVM(""); writeXML("<whileStatement>"); eatStr("while"); eatStr("("); compileExpression(); eatStr(")"); writeVM("not"); writeVM("if-goto " + labelL2); writeVM(""); eatStr("{"); compileStatements(); eatStr("}"); writeVM("goto " + labelL1); writeVM("label " + labelL2); writeXML("</whileStatement>"); writeVM(""); } void Compiler::compileDoStatement() { writeXML("<doStatement>"); eatStr("do"); compileSubroutineCall(); eatStr(";"); writeVM("pop temp 0"); writeXML("</doStatement>"); writeVM(""); } void Compiler::compileReturnStatement() { writeXML("<returnStatement>"); eatStr("return"); bool isEmpty; try { isEmpty = compileExpression(); } catch(SyntaxError e) {} eatStr(";"); writeXML("</returnStatement>"); if(isEmpty) { writeVM("push constant 0"); } writeVM("return"); writeVM(""); } bool Compiler::compileExpression() { if((tokenName() == ")" || tokenName() == ";") && tokenType() == TT_SYMBOL) { return true; } writeXML("<expression>"); compileTerm(); while(true) { try { std::string func = compileOp(); compileTerm(); writeVM(func); } catch(SyntaxError e) { break; } } writeXML("</expression>"); return false; } int Compiler::compileExpressionList() { int expressionCount = 0; writeXML("<expressionList>"); try { bool empty = compileExpression(); if(!empty) { expressionCount++; } while(true) { try { eatStr(","); empty = compileExpression(); if(!empty) { expressionCount++; } } catch(SyntaxError e) { break; } } } catch(SyntaxError e) {} writeXML("</expressionList>"); return expressionCount; } void Compiler::compileTerm() { writeXML("<term>"); if(tokenType() == TT_INT) { writeVM("push constant " + tokenName()); eatStr(tokenName()); } else if(tokenType() == TT_STRING) { writeVM("push constant " + std::to_string(tokenName().size())); writeVM("call String.new 1"); for(char c: tokenName()) { writeVM("push constant " + std::to_string(c)); writeVM("call String.appendChar 2"); } writeVM(""); eatStr(tokenName()); } else if(tokenType() == TT_KEYWORD) { if(tokenName() == "true") { writeVM("push constant 1"); writeVM("neg"); } else if(tokenName() == "false") { writeVM("push constant 0"); } else if(tokenName() == "this") { writeVM("push pointer 0"); } else if(tokenName() == "null") { writeVM("push constant 0"); } else { throw SemanticError("'" + tokenName() + "' is not allowed here"); } eatStr(tokenName()); } else if(tokenType() == TT_IDENTIFIER) { if(tokenizer.hasMoreTokens()) { if(tokenizer.nextToken().token == "[") { std::string varName = eatIdentifier(); eatStr("["); SymbolTableEntry entry = findInSymbolTables(varName); if(entry.index != -1) { writeVM("push " + entry.kind + " " + std::to_string(entry.index)); } else { throw SemanticError("Line " + std::to_string(tokenizer.currentToken().lineNumber) + ": " + "variable '" + varName + "' is undefined"); } compileExpression(); writeVM("add"); writeVM("pop pointer 1"); writeVM("push that 0"); eatStr("]"); } else if(tokenizer.nextToken().token == "(" || tokenizer.nextToken().token == ".") { compileSubroutineCall(); } else { std::string varName = eatIdentifier(); SymbolTableEntry entry = findInSymbolTables(varName); if(entry.index != -1) { if(entry.kind == "this") { writeVM("push pointer 0"); //current object writeVM("pop temp 1"); //saved copy writeVM("push pointer 0"); //current object writeVM("push constant " + std::to_string(entry.index)); //field index writeVM("add"); //add writeVM("pop pointer 0"); //set pointer 0 to desired field writeVM("push this 0"); //push field to the stack writeVM("push temp 1"); //saved copy writeVM("pop pointer 0"); //restore pointer 0 writeVM(""); } else { writeVM("push " + entry.kind + " " + std::to_string(entry.index)); } } else { throw SemanticError("Line " + std::to_string(tokenizer.currentToken().lineNumber) + ": " + "variable '" + varName + "' is undefined"); } } } else { eatIdentifier(); } } else if(tokenName() == "(") { eatStr("("); compileExpression(); eatStr(")"); } else if(tokenName() == "-") { eatStr(tokenName()); compileTerm(); writeVM("neg"); } else if(tokenName() == "~") { eatStr(tokenName()); compileTerm(); writeVM("not"); } writeXML("</term>"); } std::string Compiler::compileOp() { std::string func; switch(tokenName()[0]) { case '+': func = "add"; break; case '-': func = "sub"; break; case '*': func = "call Math.multiply 2"; break; case '/': func = "call Math.divide 2"; break; case '&': func = "and"; break; case '|': func = "or"; break; case '<': func = "lt"; break; case '>': func = "gt"; break; case '=': func = "eq"; break; } eat(std::string("+-*/&|<>=").find(tokenName()[0]) != std::string::npos, "binary operator"); return func; } void Compiler::compileSubroutineCall() { std::string calledClassName, calledSubroutineName; std::string firstIdentifier = eatIdentifier(); if(tokenName() == "(") { calledSubroutineName = firstIdentifier; int parameterCount = 0; if(subroutineKind == "method" || subroutineKind == "constructor") { parameterCount = 1; writeVM("push pointer 0"); } eatStr("("); parameterCount += compileExpressionList(); eatStr(")"); writeVM("call " + className + "." + calledSubroutineName + " " + std::to_string(parameterCount)); } if(tokenName() == ".") { calledClassName = firstIdentifier; bool found = false; SymbolTableEntry entry = findInSymbolTables(calledClassName); if(entry.index != -1) { writeVM("push " + entry.kind + " " + std::to_string(entry.index)); found = true; } eatStr("."); calledSubroutineName = eatIdentifier(); eatStr("("); int parameterCount = compileExpressionList(); if(found) { parameterCount++; } eatStr(")"); std::string typeStr = calledClassName; if(found) { typeStr = entry.type; } writeVM("call " + typeStr + "." + calledSubroutineName + " " + std::to_string(parameterCount)); } } void Compiler::compile(std::string inputFilename) { std::string name = inputFilename.substr(0, inputFilename.rfind(".")); std::string individualFilename = inputFilename.substr(inputFilename.rfind("/") + 1, inputFilename.size() - 1); outputXMLFilename = name + ".xml"; outputVMFilename = name + ".vm"; std::ofstream clear1(outputXMLFilename, std::ios::trunc); std::ofstream clear2(outputVMFilename, std::ios::trunc); clear1.close(); clear2.close(); tokenizer = Tokenizer(); tokenizer.tokenize(inputFilename); //tokenizer.printTokens(); std::cout << "Compiling " + individualFilename << std::endl; try { compileClass(); } catch(CompileError e) { std::cout << "Compile error: " + std::string(e.what()) << std::endl; std::cout << std::endl; } }
true
5eb695c11ed5977fb4862044bd01ae64c33a3d84
C++
bergLowe/code-library
/BS_AllocateMinNumOfPages.cpp
UTF-8
916
3.390625
3
[]
no_license
// https://practice.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/1 #include <bits/stdc++.h> using namespace std; // Always try to change isValid method in different question. bool isValid(int arr[], int n, int m, int max) { int student = 1; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; if (sum > max) { student++; sum = arr[i]; } if (student > m) return false; } return true; } int findPages(int arr[], int n, int m) { int start = *max_element(arr, arr + n); int end = 0; for (int i = 0; i < n; i++) { end += arr[i]; } int mid, result; while (start <= end) { mid = start + (end - start) / 2; if (isValid(arr, n, m, mid)) { result = mid; end = mid - 1; } else { start = mid + 1; } } return result; }
true
0356177f3d307cbf6950493ba5850ac2695ac1e3
C++
Tutlegoss/Beginner_Cpp
/inc/cppPDF/Examples/Fruit.cpp
UTF-8
4,275
4.21875
4
[]
no_license
//Fruit.cpp #include <iostream> using std::cin; using std::cout; using std::endl; class Fruits { //By default a class is private. However, convention lists public: //first in a class. This means you have to specify public: as shown public: Fruits() : apple(0), orange(0), banana(0), strawberry(0) {} void fruitCount(); //const functions do not alter object contents void displayTotals() const; //const objects do not alter object contents void compareApples(const Fruits &Emily) const; //Specifying private. Variables/Functions can only be accessed via public functions private: int apple; int orange; int banana; int strawberry; //Helper Function void message(int &choice) const; }; //Don't forget the semicolon! //Function to ask user to input how many of each fruit was purchased or returned. // General model of a class function //Return type | Class name | Scope Resolution operator | Function void Fruits::fruitCount() { //Represent fruit as integers int choice; cout << "Fruit Selection:\n"; //Do this as many times as needed do { //Helper function invocation to display fruit to integer message //and obtain cashier's fruit choice message(choice); //Variable to capture how many of the specified fruit there are int quantity; //Branching to correct fruit or quit. Default case for mis-entered number. switch(choice) { case 1: cout << "How many apples?: "; cin >> quantity; apple += quantity; //Add to private variable break; case 2: cout << "How many oranges?: "; cin >> quantity; orange += quantity; break; case 3: cout << "How many bananas?: "; cin >> quantity; banana += quantity; break; case 4: cout << "How many Strawberries: "; cin >> quantity; strawberry += quantity; break; case 0: break; //Exit (Nothing to be done in switch) default: cout << "Invalid input\n"; } cout << endl; //Officially exit with an input of 0 } while(choice != 0); } //This function simply displays all of the fruit totals from the transaction void Fruits::displayTotals() const { cout << "Here are the total number of fruits customer bought. \n" << "Negative number means customer returned the fruit. \n"; cout << "\tApples: " << apple << endl << "\tOranges: " << orange << endl << "\tBananas: " << banana << endl << "\tStrawberries: " << strawberry << "\n\n"; } //This function displays how many apples Emily bought vs Thomas void Fruits::compareApples(const Fruits &Emily) const { cout << "Emily purchased " << Emily.apple << " apple(s) \n"; cout << "Thomas purchased " << apple << " apple(s) \n"; if((Emily.apple + apple) == 0) { cout << "No apples sold. Cannot do comparison. \n\n"; return; } cout << "\tTherefore, Emily purchased " << static_cast<double>(Emily.apple)/(Emily.apple + apple) * 100 << '%' << " of the apples! \n\n"; } //This function is a helper function for the fruitCount() function. //No return type as choice is passed in by reference. void Fruits::message(int &choice) const { //Display for user cout << "1 = Apples, 2 = Oranges\n" << "3 = Bananas, 4 = Strawberries\n" << "0 = Quit\n"; //Input from user cin >> choice; } int main() { //Initializing objects (instances) of class Fruits Thomas, Emily; //Invoking public class functions with the dot operator cout << "Enter Thomas's fruit purchase data: \n"; //Class object | Dot operator | Function Thomas.fruitCount(); cout << "Enter Emily's fruit purchase data: \n"; Emily.fruitCount(); //Compare results/Display results Thomas.compareApples(Emily); cout << "Total number of fruits Emily purchased: \n"; Emily.displayTotals(); }
true
215176a8125a7206f04659bc3645318b21bb19b6
C++
isac322/BOJ
/1753/1753.cpp14.cpp
UTF-8
932
2.78125
3
[ "MIT" ]
permissive
#include <cstdio> #include <algorithm> #include <vector> #include <queue> #include <limits> #include <functional> using namespace std; typedef pair<int, int> INTP; const int &INF = numeric_limits<int>::max(); int main() { int e, v, start; scanf("%d%d%d", &e, &v, &start); start--; vector<vector<INTP>> map(e); vector<int> dist(e, INF); dist[start] = 0; for (int i = 0; i < v; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); u--, v--; map[u].emplace_back(v, w); } priority_queue <INTP, vector<INTP>, greater<INTP>> que; que.emplace(0, start); while (que.size()) { const int here = que.top().second; const int cost = que.top().first; que.pop(); for (auto &i : map[here]) { if (dist[i.first] > dist[here] + i.second) { dist[i.first] = dist[here] + i.second; que.emplace(dist[i.first], i.first); } } } for (int d : dist) { if (d != INF) printf("%d\n", d); else puts("INF"); } }
true
dfbb2326a5fec993e0d1d5dc94da0b6f8b6cb266
C++
smdi17/Laboratornie-raboty
/LR1/LR1/LR1.cpp
UTF-8
4,411
3.390625
3
[]
no_license
// LR1.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include <string> using namespace std; void massiv() //замена всех чётных чисел в массиве на 0 { int array[10]; // массив 10 элементов for (int i = 0; i < 10; i++) array[i] = rand() % 20; // составление массива из случайных чисел от 0 до 20 for (int i = 0; i < 10; i++) cout << array[i] << ' '; cout << endl; for (int i = 0; i < 10; i++) // замена четных чисел на 0 if (array[i] % 2 == 0) array[i] = 0; for (int i = 0; i < 10; i++) cout << array[i] << ' '; cout << endl; } void poiskssimvola() // поиск символа в строке { string s, l; // s - символ, l - строка int p; // p - место символа в строке cout << "Введите символ:" << endl; do { cin >> s; if (s.size() > 1) { //проверка символа cout << "ERROR! Введите символ:" << endl; s.clear(); } else break; } while (true); cout << "Введите строку:" << endl; do { cin >> l; if (l.size() < 2) { //проверка строки cout << "ERROR! Введите строку:" << endl; l.clear(); } else break; } while (true); p = l.find(s); //поиск символа if (p < 0) cout << "Символ отсутствует." << endl; else cout << "Символ занимает " << p + 1 << " позицию." << endl; } void opredelelmatrici() { int m[3][3]; //матрица 3 на 3 int opredelitel; //определитель cout << endl << "Введите целые числа: //каждое число с новой строки " << endl; // ввод матрицы for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) cin >> m[i][j]; for (int i = 0; i < 3; i++) // вывод матрицы { cout << endl; for (int j = 0; j < 3; j++) cout << m[i][j] << " "; } //подсчет определителя матрицы: opredelitel = m[0][0] * m[1][1] * m[2][2] + m[2][0] * m[0][1] * m[1][2] + m[1][0] * m[2][1] * m[0][2] - m[2][0] * m[1][1] * m[0][2] - m[0][0] * m[2][1] * m[1][2] - m[1][0] * m[0][1] * m[2][2]; cout << endl << "Определитель матрицы = "<< opredelitel << endl; } int main() { setlocale(LC_ALL, "RUS"); massiv(); poiskssimvola(); opredelelmatrici(); } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
true
4862be87a68f037f607b657e7dee62308b0ee2c0
C++
bgianfo/serenity
/Userland/Libraries/LibWeb/DOM/NodeIterator.h
UTF-8
2,276
2.59375
3
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2022, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/RefCounted.h> #include <LibWeb/Bindings/Wrappable.h> #include <LibWeb/DOM/NodeFilter.h> namespace Web::DOM { // https://dom.spec.whatwg.org/#nodeiterator class NodeIterator : public RefCounted<NodeIterator> , public Bindings::Wrappable { public: using WrapperType = Bindings::NodeIteratorWrapper; virtual ~NodeIterator() override; static NonnullRefPtr<NodeIterator> create(Node& root, unsigned what_to_show, RefPtr<NodeFilter>); NonnullRefPtr<Node> root() { return m_root; } NonnullRefPtr<Node> reference_node() { return m_reference.node; } bool pointer_before_reference_node() const { return m_reference.is_before_node; } unsigned what_to_show() const { return m_what_to_show; } NodeFilter* filter() { return m_filter; } JS::ThrowCompletionOr<RefPtr<Node>> next_node(); JS::ThrowCompletionOr<RefPtr<Node>> previous_node(); void detach(); void run_pre_removing_steps(Node&); private: NodeIterator(Node& root); enum class Direction { Next, Previous, }; JS::ThrowCompletionOr<RefPtr<Node>> traverse(Direction); JS::ThrowCompletionOr<NodeFilter::Result> filter(Node&); // https://dom.spec.whatwg.org/#concept-traversal-root NonnullRefPtr<DOM::Node> m_root; struct NodePointer { NonnullRefPtr<DOM::Node> node; // https://dom.spec.whatwg.org/#nodeiterator-pointer-before-reference bool is_before_node { true }; }; void run_pre_removing_steps_with_node_pointer(Node&, NodePointer&); // https://dom.spec.whatwg.org/#nodeiterator-reference NodePointer m_reference; // While traversal is ongoing, we keep track of the current node pointer. // This allows us to adjust it during traversal if calling the filter ends up removing the node from the DOM. Optional<NodePointer> m_traversal_pointer; // https://dom.spec.whatwg.org/#concept-traversal-whattoshow unsigned m_what_to_show { 0 }; // https://dom.spec.whatwg.org/#concept-traversal-filter RefPtr<DOM::NodeFilter> m_filter; // https://dom.spec.whatwg.org/#concept-traversal-active bool m_active { false }; }; }
true
8360bd9f047b43cde5cff7bcec5cf83dd4ec7a57
C++
slepasteur/parse_it
/tests/parser/or_tests.cpp
UTF-8
1,352
3.28125
3
[ "MIT" ]
permissive
#include <algorithm> #include <array> #include "parse_it/parser.h" #include "parse_it/utils/byte_litterals.h" #include <doctest/doctest.h> using namespace parse_it; using namespace parse_it::byte_litterals; TEST_CASE("Operator ||") { constexpr auto parser = one_byte(0x01_b) || one_byte(0x02_b) || one_byte(0x03_b); SUBCASE("returns first alternative if it was successful.") { constexpr auto data = std::array{0x1_b, 0x5_b}; auto result = parser(data); REQUIRE(result); CHECK(result->first == 0x1_b); const auto expected_remaining = std::span(&data[1], data.size() - 1); CHECK(std::ranges::equal(result->second, expected_remaining)); } SUBCASE("returns second alternative if the first one failed.") { constexpr auto data = std::array{0x2_b, 0x5_b}; auto result = parser(data); REQUIRE(result); CHECK(result->first == 0x2_b); const auto expected_remaining = std::span(&data[1], data.size() - 1); CHECK(std::ranges::equal(result->second, expected_remaining)); } SUBCASE("fails if none of the parsers succeeds.") { constexpr auto data = std::array{0x4_b, 0x5_b}; auto result = parser(data); REQUIRE(!result); } SUBCASE("fails if input is empty.") { constexpr auto data = std::array<std::byte, 0>{}; auto result = parser(data); REQUIRE(!result); } }
true
e3e3d739542fe9bddef61726ea470b177291de2c
C++
geeksunny/Dweedee
/src/Router.cpp
UTF-8
7,304
2.546875
3
[]
no_license
#include "Deques.h" #include "Router.h" // Queue macros #define CLEAR(Queue) while (!Queue->empty()) { Queue->pop(); } // Deque macros #define FIND(Iterable, Value) (std::find(Iterable.begin(), Iterable.end(), Value)) #define HAS(Iterable, Value) (std::find(Iterable.begin(), Iterable.end(), Value) != Iterable.end()) namespace dweedee { //////////////////////////////////////////////////////////////// // Class : Mapping ///////////////////////////////////////////// //////////////////////////////////////////////////////////////// std::queue<MidiMessage *> Mapping::processQueueA; std::queue<MidiMessage *> Mapping::processQueueB; std::queue<MidiMessage *> *Mapping::inputQueue = &Mapping::processQueueA; std::queue<MidiMessage *> *Mapping::outputQueue = &Mapping::processQueueB; Mapping::Mapping() { // } void Mapping::broadcast(dweedee::MidiMessage *message) { for (auto output = outputs_.begin(); output != outputs_.end(); ++output) { (*output)->write(message); } } void Mapping::broadcast(dweedee::MidiMessage **messages, uint8_t msgCount) { for (int i = 0; i < msgCount; ++i) { for (auto output = outputs_.begin(); output != outputs_.end(); ++output) { (*output)->write(messages[i]); } } } bool Mapping::process(MidiMessage *message) { // When this method returns, inputQueue & outputQueue must both be empty for the next time this method is executed. if (filters_.empty()) { broadcast(message); return false; } inputQueue->push(new MidiMessage(*message)); for (auto filter = filters_.begin(); filter != filters_.end(); ++filter) { while (!inputQueue->empty()) { Result processed = (*filter)->process(inputQueue->front()); inputQueue->pop(); if (processed.isConsumed() || processed.isFailed()) { CLEAR(inputQueue) CLEAR(outputQueue) return processed.isConsumed(); } } std::swap(inputQueue, outputQueue); } // Broadcast messages to outputs. Using inputQueue due to pointer swap at end of filter loop. while (!inputQueue->empty()) { for (auto output = outputs_.begin(); output != outputs_.end(); ++output) { (*output)->write(inputQueue->front()); } delete inputQueue->front(); inputQueue->pop(); } return false; } bool Mapping::activate() { if (activated_ || Router::getInstance() == nullptr) { return false; } activated_ = Router::getInstance()->addMapping(this); return activated_; } bool Mapping::deactivate() { if (!activated_ || Router::getInstance() == nullptr) { return false; } activated_ = !Router::getInstance()->removeMapping(this); return activated_; } bool Mapping::isActivated() { return activated_; } bool Mapping::addInput(dweedee::MidiDevice *inputDevice) { if (!HAS(inputs_, inputDevice)) { inputs_.push_back(inputDevice); if (activated_ && Router::getInstance() != nullptr) { Router::getInstance()->mapInputDevice(inputDevice, this); } return true; } return false; } bool Mapping::removeInput(dweedee::MidiDevice *inputDevice) { auto it = FIND(inputs_, inputDevice); if (it != inputs_.end()) { inputs_.erase(it); return true; } return false; } bool Mapping::addOutput(dweedee::MidiDevice *outputDevice) { if (!HAS(outputs_, outputDevice)) { outputs_.push_back(outputDevice); return true; } return false; } bool Mapping::removeOutput(dweedee::MidiDevice *outputDevice) { auto it = FIND(outputs_, outputDevice); if (it != outputs_.end()) { outputs_.erase(it); return true; } return false; } bool Mapping::addFilter(dweedee::Filter *filter) { if (!HAS(filters_, filter)) { filters_.push_back(filter); return true; } return false; } bool Mapping::removeFilter(dweedee::Filter *filter) { auto it = FIND(filters_, filter); if (it != filters_.end()) { filters_.erase(it); return true; } return false; } //////////////////////////////////////////////////////////////// // Class : InputMapping //////////////////////////////////////// //////////////////////////////////////////////////////////////// InputMapping::InputMapping(MidiDevice *inputDevice) : device_(inputDevice) { // } bool InputMapping::operator==(const MidiDevice *rhs) const { return device_ == rhs; } bool InputMapping::operator!=(const MidiDevice *rhs) const { return device_ != rhs; } void InputMapping::onMidiData(MidiDevice *device, MidiMessage *message) { for (auto mapping = mappings_.begin(); mapping != mappings_.end(); ++mapping) { bool consumed = (*mapping)->process(message); if (consumed) { break; } } delete message; } void InputMapping::process() { device_->read(*this); } bool InputMapping::add(dweedee::Mapping *mapping) { if (!HAS(mappings_, mapping)) { mappings_.push_back(mapping); return true; } return false; } bool InputMapping::remove(dweedee::Mapping *mapping) { auto it = FIND(mappings_, mapping); if (it != mappings_.end()) { mappings_.erase(it); return true; } return false; } bool InputMapping::isEmpty() { return mappings_.empty(); } //////////////////////////////////////////////////////////////// // Class : Router ////////////////////////////////////////////// //////////////////////////////////////////////////////////////// Router *Router::instance = nullptr; Router *Router::getInstance() { return instance; } Router::Router() { if (Router::instance != nullptr) { // TODO: error? } Router::instance = this; } bool Router::addMapping(dweedee::Mapping *mapping) { if (HAS(mappings_, mapping) || mapping->isActivated()) { // TODO: Should the check to mapping->isActivated() prevent success here? return false; } mappings_.push_back(mapping); for (auto it = mapping->inputs_.begin(); it != mapping->inputs_.end(); ++it) { mapInputDevice((*it), mapping); } return true; } bool Router::removeMapping(dweedee::Mapping *mapping) { auto mappingPos = FIND(mappings_, mapping); if (mappingPos == mappings_.end()) { return false; } for (auto input = mapping->inputs_.begin(); input != mapping->inputs_.end(); ++input) { removeInputMapping(*input, mapping); } mappings_.erase(mappingPos); return false; } bool Router::mapInputDevice(dweedee::MidiDevice *inputDevice, dweedee::Mapping *mapping) { auto inputMapping = FIND(inputMappings_, inputDevice); if (inputMapping != inputMappings_.end()) { return inputMapping->add(mapping); } return false; } bool Router::removeInputMapping(dweedee::MidiDevice *inputDevice, dweedee::Mapping *mapping) { auto inputMapping = FIND(inputMappings_, inputDevice); if (inputMapping != inputMappings_.end()) { bool result = inputMapping->remove(mapping); if (inputMapping->isEmpty()) { inputMappings_.erase(inputMapping); } return result; } return false; } bool Router::deviceIsMapped(dweedee::MidiDevice *inputDevice) { return HAS(inputMappings_, inputDevice); } void Router::task() { if (paused_) { return; } for (auto it = inputMappings_.begin(); it != inputMappings_.end(); ++it) { (*it).process(); } } void Router::setPaused(bool paused) { paused_ = paused; } void Router::toggle() { paused_ = !paused_; } bool Router::isPaused() { return paused_; } }
true
26b56049a85507e992ca9904e2055ed452e9a349
C++
quaeast/DataStructure_2018
/bjfu239.cpp
UTF-8
1,342
3.046875
3
[]
no_license
//bjfu239 // #include <iostream> using namespace std; typedef struct Node{ int datum; struct Node *next; }Node,*List; void CirList(List &head, int n){ head = new Node; head->next=NULL; Node *cur=head; head->datum=1; for (int i = 1; i < n; ++i) { Node *temp=new Node; if(i==n-1){ temp->next=head; } else{ temp->next=NULL; } temp->datum=i+1; cur->next=temp; cur=cur->next; } } void showList(List head){ Node *cur=head; while (cur->next!=head){ cout<<cur->datum<<' '; cur=cur->next; } cout<<cur->datum<<endl; } Node* findPre(List head){ Node *cur=head; while (cur->next!=head){ cur=cur->next; } return cur; } void findKing(List head, int n){ Node *cur=head; while (cur->next!=cur){ for (int i = 0; i < n-1; ++i) { cur=cur->next; } Node *pre; pre=findPre(cur); cout<<cur->datum<<' '; pre->next=cur->next; //delete cur; cur=pre->next; } cout<<cur->datum<<endl; } int main() { int n,s; while (cin>>n>>s){ if (n==0&&s==0){ break; } List lis; CirList(lis, n); //showList(lis); findKing(lis, s); } return 0; }
true
3491f700258f6b43ae692804cce4dae5c5e8d891
C++
denk1/its
/WRocketLauncher.h
WINDOWS-1251
667
2.59375
3
[]
no_license
#ifndef WRocketLauncher_H #define WRocketLauncher_H #include <Ogre.h> #include "Weapon.h" namespace RAT { class WRocketLauncher: public Weapon { public: WRocketLauncher(const WeaponDescription& desc); virtual ~WRocketLauncher(); // . virtual void create(Ogre::SceneNode* parentNode); // virtual void startShoot(const Ogre::Real dTime); // virtual void stopShoot(const Ogre::Real dTime); // virtual void update(const Ogre::Real dTime); }; } #endif
true
eed8281bc9ba44a87c10107dc66a42af65eb2c65
C++
Louis-tiany/tiny_rpc
/include/EventLoop.h
UTF-8
993
2.640625
3
[]
no_license
/* * File : EventLoop.h * Author : * * Mail : * * Creation : Fri 25 Dec 2020 07:00:53 PM CST */ #ifndef _EVENTLOOP_H #define _EVENTLOOP_H #include <functional> #include <vector> #include <memory> #include "Poller.h" #include "Channel.h" #include "Timer.h" #include "TimerQueue.h" class EventLoop{ public: typedef std::function<void()> Functor; public: EventLoop(); void loop(); void update_channel(Channel *channel); void run_in_loop(Functor cb); void remove_channel(Channel *channel); TimerID run_at(TimeStamp time, TimerCallback cb); TimerID run_after(double delay, TimerCallback cb); TimerID run_every(double interval, TimerCallback cb); void cancel_timer(TimerID timer_id); public: std::unique_ptr<Poller> poller; private: std::unique_ptr<TimerQueue> timer_queue_; bool loop_; std::vector<Channel *> active_channels_; Channel *current_channel_; }; #endif
true
05e03dbc143b9434a69975b396c5210f86c1cd02
C++
mogemimi/daily-chicken
/daily/CommandLineParser.h
UTF-8
1,575
2.578125
3
[]
no_license
// Copyright (c) 2015 mogemimi. Distributed under the MIT license. #pragma once #include "Optional.h" #include <string> #include <sstream> #include <vector> #include <functional> #include <map> #include <set> #include <vector> namespace somera { enum class CommandLineArgumentType { Flag, JoinedOrSeparate, }; struct CommandLineArgumentHint { std::string name; std::string help; CommandLineArgumentType type; std::vector<std::string> values; }; struct CommandLineParser { // void addArgument( // const std::string& help, // const std::string& type); void addArgument( const std::string& flag, CommandLineArgumentType type, const std::string& help); void parse(int argc, char* argv[]) { this->parse(argc, const_cast<const char**>(argv)); } void parse(int argc, const char* argv[]); bool hasParseError() const; std::string getHelpText() const; std::string getErrorMessage() const; std::string getExecutablePath() const; bool exists(const std::string& flag) const; Optional<std::string> getValue(const std::string& name) const; std::vector<std::string> getValues(const std::string& name) const; std::vector<std::string> getPaths() const; void setUsageText(const std::string& usage); private: std::string executablePath; std::vector<CommandLineArgumentHint> hints; std::set<std::string> flags; std::vector<std::string> paths; std::stringstream errorMessage; std::string usageText; }; } // namespace somera
true
d0fa60d33f63438b1834c325bbc225bb460317a2
C++
jmarcoares98/CptS122
/PA 5/PA 5 CptSci122/wrapper.cpp
UTF-8
7,464
3.3125
3
[]
no_license
#include "wrapper.h" #include "list.h" int Menu::displayMenu() { int select = 0; cout << "Main Menu" << endl; cout << "(1) Import Course List" << endl; cout << "(2) Load Master List" << endl; cout << "(3) Store Master List" << endl; cout << "(4) Mark Absences" << endl; cout << "(5) Generate Report" << endl; cout << "(6) Exit" << endl; cout << "SELECT: "; cin >> select; system("cls"); return select; } void Menu::runApp() { int option = 0; bool exit = false, success = false; List *pHead = nullptr; cout << "WELCOME TO THE ABSENT TRACKER!!!" << endl; system("pause"); system("cls"); do { option = displayMenu(); switch (option) { case 1: success = importRecords(); if (success == false) { cout << "IT WAS NOT SUCCESSFUL" << endl; system("pause"); system("cls"); } else { cout << "IMPORT SUCCESSFUL" << endl; system("pause"); system("cls"); } break; case 2: success = loadMasterList(); if (success == false) { cout << "IT WAS NOT SUCCESSFUL" << endl; system("pause"); system("cls"); } else { cout << "LOAD SUCCESSFUL" << endl; system("pause"); system("cls"); } break; case 3: success = storeMasterList(); if (success == false) { cout << "IT WAS NOT SUCCESSFUL" << endl; system("pause"); system("cls"); } else { cout << "STORE SUCCESSFUL" << endl; system("pause"); system("cls"); } break; case 4: markAbsences(); system("pause"); system("cls"); break; case 5: generateReports(); system("pause"); system("cls"); break; case 6: cout << "GOODBYE!" << endl; system("pause"); system("cls"); exit = true; break; } } while (exit == false); } bool Menu::importRecords() { List *pList = nullptr; Node * pMem = nullptr; Node *mNext = nullptr; string stringRecord = "", stringID = ""; string name = "", email = "", units = "", major = "", level = ""; bool success = false; fstream courseList("classList.csv"); if (courseList.is_open()) { success = true; for (int counter = 0; counter < 11; counter++) { if (counter == 0) { std::getline(courseList, stringRecord, ','); std::getline(courseList, stringID, ','); std::getline(courseList, name, ','); std::getline(courseList, email, ','); std::getline(courseList, units, ','); std::getline(courseList, major, ','); std::getline(courseList, level, '\n'); } else { pMem = new Node; courseList >> *pMem; pMem->setNext(mpHead); mpHead = pMem; } } } courseList.close(); return success; } bool Menu::storeMasterList() { bool success = false; Node * pMem = nullptr; Node *mNext = nullptr; pMem = this->mpHead; fstream masterList("master.txt"); if (masterList.is_open()) { success = true; masterList << "Record,ID,Name,Email,Units,Program,Level, Date Absent, Number of Absences" << endl; for (int count = 0; count < 10; count++) { masterList << *pMem; pMem = pMem->getNext(); } } return success; } bool Menu::loadMasterList() { bool success = false; string stringRecord = "", stringID = "", extra = "", extra2 = ""; string name = "", email = "", units = "", major = "", level = "", absences = "", numAbsences = ""; string notAbsent = "", notAbsent2 = ""; int record = 0, ID = 0, num = 0; Node * pMem = nullptr; pMem = this->mpHead; fstream masterList("master.txt"); if (masterList.is_open()) { success = true; for (int count = 0; count < 11; count++) { if (count == 0) { std::getline(masterList, stringRecord, ','); std::getline(masterList, stringID, ','); std::getline(masterList, name, ','); std::getline(masterList, email, ','); std::getline(masterList, units, ','); std::getline(masterList, major, ','); std::getline(masterList, level, ','); std::getline(masterList, absences, ','); std::getline(masterList, numAbsences, '\n'); } else { std::getline(masterList, stringRecord, ','); std::getline(masterList, stringID, ','); std::getline(masterList, extra, '"'); std::getline(masterList, name, '"'); std::getline(masterList, extra2, ','); std::getline(masterList, email, ','); std::getline(masterList, units, ','); std::getline(masterList, major, ','); std::getline(masterList, level, ','); std::getline(masterList, absences, ','); std::getline(masterList, numAbsences, '\n'); record = std::stoi(stringRecord); ID = std::stoi(stringID); num = std::stoi(numAbsences); pMem->setRecord(record); pMem->setID(ID); pMem->setName(name); pMem->setEmail(email); pMem->setUnits(units); pMem->setMajor(major); pMem->setLevel(level); pMem->setAbsences(absences); pMem->setNumAbsences(num); pMem = pMem->getNext(); } } } masterList.close(); return success; } void Menu::markAbsences() { int choose = 0; int numAbsent = 0; string date = ""; Node * pMem = nullptr; Stack * pDate = nullptr; pDate = this->mDate; pMem = this->mpHead; time_t t = time(0); struct tm * now = localtime(&t); char buffer[80]; strftime(buffer, sizeof(buffer), "%m-%d-%Y", now); date = buffer; for (int count = 0; count < 10; count++) { cout << pMem->getName() << endl; cout << "Mark as Absent?" << endl; cout << "(1) Yes" << endl; cout << "(2) No" << endl; cout << "Select(num): "; cin >> choose; if (choose == 1) { cout << "Marked as Absent" << endl; pMem->setAbsences(date); numAbsent = pMem->getNumAbsences(); numAbsent += 1; pMem->setNumAbsences(numAbsent); pDate[count].push(date); pMem = pMem->getNext(); } else if (choose == 2) { pMem = pMem->getNext(); } else { cout << "INVALID INPUT" << endl; count--; } system("pause"); system("cls"); } } void Menu::generateReports() { time_t t = time(0); struct tm * now = localtime(&t); string date = ""; char buffer[80]; strftime(buffer, sizeof(buffer), "%m-%d-%Y", now); date = buffer; Node * pMem = nullptr; Stack * pDate = nullptr; pDate = this->mDate; pMem = this->mpHead; int choose = 0, num = 0; cout << "(1) Report For All Students" << endl; cout << "(2) Report Students with Absences" << endl; cout << "Select(num): "; cin >> choose; if (choose == 1) { for (int i = 0; i < 10; i++) { if (pMem->getNumAbsences() > 0) { cout << "Most Recent Date for Absences" << endl; cout << pDate[0].peek(date) << endl; break; } } for (int count = 0; count < 11; count++) { cout << pMem->getName() << " - " << "Number of Absents: " << pMem->getNumAbsences() << "- Date Absent: " << pMem->getAbsences() << endl; pMem = pMem->getNext(); } } else if (choose == 2) { cout << "Enter Number of Absences: "; cin >> num; cout << "Students:" << endl; for (int i = 0; i < 10; i++) { if (num == pMem->getNumAbsences()) { cout << pMem->getName() << endl; } pMem = pMem->getNext(); } } else { cout << "INVALID INPUT!" << endl; } system("pause"); system("cls"); }
true
fd4b5a40214b0d9e89858a262e6a217e5f0a98ce
C++
thecherry94/MazeMaker
/MazeMaker/Maze.hpp
UTF-8
1,447
2.546875
3
[]
no_license
#pragma once #include <SFML\System.hpp> #include <SFML\Window.hpp> #include <SFML\Graphics.hpp> #include <memory> #include <random> #include "MazeCell.hpp" class Maze : public sf::Drawable, public sf::Transformable { private: std::vector<std::shared_ptr<MazeCell>> _cells; sf::Vector2u _size; sf::Vector2u _cell_size; std::vector<sf::VertexArray> _render_vertices; sf::RenderTexture _tex; float _block_width; float _block_height; sf::RenderWindow* _p_win; bool _needs_redraw; public: Maze(); Maze(sf::RenderWindow* p_win, sf::Vector2u size); void render(sf::RenderTarget& target); void draw(sf::RenderTarget& target, sf::RenderStates states) const; void setScale(float fx, float fy) { sf::Transformable::setScale(fx, fy); int width = _size.x; int height = _size.y; int win_width = _p_win->getSize().x; int win_height = _p_win->getSize().y; _tex.create(width * (_block_width + 1) * getScale().x, height * (_block_height + 1) * getScale().y + 10); for (int i = 0; i < _size.x * _size.y; i++) _cells[i]->setScale(fy, fy); _needs_redraw = true; } void setPosition(sf::Vector2f pos) { //for (int i = 0; i < _size.x * _size.y; i++) // _cells[i]->setPosition(pos); //_needs_redraw = true; sf::Transformable::setPosition(pos); } void make_maze_random_walk(sf::Vector2u start, sf::Vector2u goal); void make_maze_random_walk(); void reset(); };
true
ddf5d2b734f39e455327464dfbad0f84f66e4ad4
C++
pashazz/replacer
/func.h
UTF-8
220
2.765625
3
[]
no_license
#pragma once #include <string> /* Convert numbers in the folowing string to binary approx. */ void numbersToBinary(std::string &src); /* Convert decimal to binary */ std::string decimalToBinary(const std::string &s);
true
6657dae43206440d6cb4a2a5baa64b0b862556c2
C++
Jeswang/leetcode-xcode
/src/problems/search-for-a-range.h
UTF-8
2,341
3.515625
4
[ "MIT" ]
permissive
// // search-for-a-range.h // // Created by jeswang 27/06/2014. // /* Description: Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. */ class Solution { public: void run() { int A[] = {0,0,2,3,4,4,4,5}; vector<int> res = searchRange(A, 8, 5); for(auto it = res.begin(); it!=res.end(); it++){ cout<<(*it)<<" "; } cout<<endl; } vector<int> searchRange(int A[], int n, int target) { int start = 1; int end = n; int selected = (start + end) / 2; bool find = false; do { if(A[selected-1] < target) { if (start == selected) { start ++; } else { start = selected; } } else if(A[selected-1] > target) { end = selected; } else if(A[selected-1] == target) { find = true; break; } selected = (start + end) / 2; } while(start!=end); if (!find) { if (A[start-1]==target) { find = true; selected = start; } } vector<int> res; if(find) { start = selected-1; end = selected-1; int tmp = selected; while(tmp > 1) { tmp--; if(A[tmp-1] == target){ start--; } else { break; } } tmp = selected; while(tmp < n+1) { tmp++; if(A[tmp-1] == target){ end++; } else { break; } } res.push_back(start); res.push_back(end); } if (res.size() == 0){ res.push_back(-1); res.push_back(-1); } return res; } };
true
3f3d0feae946796ac07b6e5dc12be405fa0eced2
C++
blurpy/8-bit-computer-emulator
/test/core/BusTest.cpp
UTF-8
1,825
3.140625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <doctest.h> #include <fakeit.hpp> #include "core/Bus.h" using namespace Core; TEST_SUITE("BusTest") { TEST_CASE("read() should return 0 on new instance") { Bus bus = Bus(); CHECK(bus.read() == 0); } TEST_CASE("read() should return value set with write()") { Bus bus = Bus(); bus.write(10); CHECK(bus.read() == 10); } TEST_CASE("observer should be notified when writing to the bus") { Bus bus = Bus(); fakeit::Mock<ValueObserver> observerMock; auto observerPtr = std::shared_ptr<ValueObserver>(&observerMock(), [](...) {}); bus.setObserver(observerPtr); fakeit::When(Method(observerMock, valueUpdated)).Return(); bus.write(8); fakeit::Verify(Method(observerMock, valueUpdated).Using(8)).Once(); fakeit::VerifyNoOtherInvocations(observerMock); } TEST_CASE("reset() should set value to 0") { Bus bus = Bus(); bus.write(5); CHECK(bus.read() == 5); bus.reset(); CHECK(bus.read() == 0); } TEST_CASE("reset() should notify observer") { Bus bus = Bus(); fakeit::Mock<ValueObserver> observerMock; auto observerPtr = std::shared_ptr<ValueObserver>(&observerMock(), [](...) {}); bus.setObserver(observerPtr); fakeit::When(Method(observerMock, valueUpdated)).AlwaysReturn(); bus.write(250); fakeit::Verify(Method(observerMock, valueUpdated).Using(250)).Once(); fakeit::VerifyNoOtherInvocations(observerMock); bus.reset(); fakeit::Verify(Method(observerMock, valueUpdated).Using(0)).Once(); fakeit::VerifyNoOtherInvocations(observerMock); } TEST_CASE("print() should not fail") { Bus bus = Bus(); bus.print(); } }
true
8e92ef3049f76b134f14f73d6371dbefe90bb4f2
C++
sarahdarwiche/Compiler_Projects
/Project 1/Code/CrackingtheCodingInterview/LinkedList.cpp
UTF-8
2,882
3.90625
4
[]
no_license
#include <iostream> #include <cstdlib> #include <string.h> #include <vector> #include "LinkedList.h" LinkedList::LinkedList() { head = new Node(1); head->next = NULL; head->prev = NULL; } LinkedList::LinkedList(int data) { head = new Node(data); head->next = NULL; head->prev = NULL; } LinkedList::~LinkedList() { } void LinkedList::addHead(int data) { //use only for linked list if(head == NULL) { std::cout << "error list not instantiated" << std::endl; return; } Node* newnode = new Node(data); newnode->next = head; head = newnode; } void LinkedList::AddNodeForward(int data){ Node* temp = head; Node* newnode = new Node(data); if(head == NULL) { newnode->prev = NULL; newnode->next = NULL; head = newnode; } else { while(temp->next!=NULL){ temp = temp->next; } temp->next = newnode; newnode->next = NULL; newnode->prev = temp; } } void LinkedList::AddNodeReverse(int data){ Node* temp = head; Node* newnode = new Node(data); if(head == NULL) { newnode->prev = NULL; newnode->next = NULL; head = newnode; } else { while(temp->prev!=NULL){ temp = temp->prev; } newnode->prev = NULL; newnode->next = temp; temp->prev = newnode; head = newnode; } } void LinkedList::removeNode(int data) { Node* temp = head; if(temp->data == data) { temp = head->next; head = temp; head->prev = NULL; return; } else { while(temp->next != NULL){ if(temp->next->data == data){ temp->next = temp->next->next; temp->prev = temp; return; } temp = temp->next; } } } void LinkedList::removeDuplicates() { //not working with dll Node* currptr; Node* fastptr; for(currptr = head; currptr->next!= NULL; currptr = currptr->next){ for(fastptr = head->next; fastptr->next!= NULL; fastptr = fastptr->next){ if((currptr->data == fastptr->data) && (currptr!=fastptr)) { //second check necessary so both duplicates aren't removed this->removeNode(currptr->data); std::cout << currptr->data << std::endl; } } } } int LinkedList::find_cycle(){ Node* currptr = head; Node* fastptr = currptr; while(currptr->next != NULL){ if(fastptr == currptr) return currptr->data; currptr = currptr->next; } return 0; } void LinkedList::printList() { Node* temp; for (temp = head; temp->next!= NULL; temp = temp->next){ std::cout << temp->data << " "; } std::cout << temp->data << std::endl; } int main(int argc, char* argv[]) { LinkedList* List = new LinkedList(); List->AddNodeForward(1); List->AddNodeForward(6); List->AddNodeForward(3); List->AddNodeForward(9); List->AddNodeReverse(4); List->removeNode(4); List->removeDuplicates(); List->printList(); int cycle = List->find_cycle(); if(cycle != 0) std::cout << "Found cycle in list starting at " << cycle << std::endl; }
true
16b0d126a6f3642da4067262c89e81a5d247e5d8
C++
zhenkunhe/LeetCode
/279_Perfect_Squares/main.cpp
UTF-8
891
3.46875
3
[ "MIT" ]
permissive
#include <math.h> #include <unistd.h> #include <iostream> using namespace std; class Solution { public: int numSquares( int n ) { int resultArray[n + 1]; if ( n == 0 ) return 0; if ( n == 1 ) return 1; if ( n == 2 ) return 2; resultArray[0] = 0; resultArray[1] = 1; resultArray[2] = 2; for (int i = 3; i <= n; i++) { bool first = true; for (int j = 1; j <= (int) sqrt( i ); j++) { int rest = i - j * j; if ( first ) { first = false; resultArray[i] = 1 + resultArray[rest]; } else { resultArray[i] = (1 + resultArray[rest] < resultArray[i]) ? 1 + resultArray[rest] : resultArray[i]; } } cout << "number:" << i << "\tresult:" << resultArray[i] << endl; } return resultArray[n]; } }; int main() { Solution solution; cout << solution.numSquares( 600 ) << endl; return 0; }
true
10f4f189989facb978e7f3f4d2e61ebf4c7c973c
C++
atharvak71/QOSF_PROJECT
/qram.cpp
UTF-8
5,071
2.65625
3
[]
no_license
#include "qram.h" #include<stdexcept> #include<cstring> #include<iostream> using namespace qcpp; static inline void print_binary(std::ostream& oss,const std::size_t& val,const unsigned int& bits) { for(unsigned int bi=0;bi<bits;bi++) { unsigned int rbi=bits-bi-1; oss << ( (val >> rbi) & 1 ); //oss << (int)((val >> (sizeof(std::size_t)*8-bi-1)) & 1); } } class private_qnot:public qgate { public: private_qnot():qgate(1,"NOT") {} virtual void apply(std::complex<double>* out,const std::complex<double>* in) const { out[0]=in[1]; out[1]=in[0]; } }; qram::qram(const unsigned int& nb,std::ostream& os,const unsigned int& initialstate): num_entries(1 << nb), num_bits(nb), oss(os) { if(num_bits > sizeof(std::size_t)*8) { throw std::range_error("Cannot allocate a qregister larger than the size of a machine pointer"); } state=new std::complex<double>[num_entries]; state_back=new std::complex<double>[num_entries]; /*for(std::size_t index=0;index<num_entries/2;index++) { state[2*index]=1.0/sqrt((double)num_entries/2); state[2*index+1]=0.0; }*/ memset(state,0,num_entries*sizeof(std::complex<double>)); //memset(state_back,0,num_entries*sizeof(std::complex<double>)); state[0]=1.0;//100% of being in the |0000...00> state private_qnot pqn; for(unsigned int i=0;i<num_bits;i++) { unsigned int cmask = 1 << i; if(initialstate & cmask) { op(pqn,cmask); } } for(unsigned int i=0;i<num_bits;i++) { os << "+-"; } os << "--Initialization complete--\n"; } qram::~qram() { delete [] state; delete [] state_back; } static inline std::size_t shift(std::size_t value,std::size_t mask) { std::size_t result=0; for(unsigned bi=0;bi<sizeof(std::size_t);bi++) { if(mask==0) { break; } if(mask & 1) { result |= (value & 1) << bi; value >>= 1; } mask >>= 1; } return result; } static inline std::size_t popcount(std::size_t x) { std::size_t cnt=0; while(x != 0) { if(x & 1) { cnt++; } x>>=1; } return cnt; } void qram::permute_internal_down(std::size_t mask) { std::swap(state,state_back); const std::size_t mask_bits=popcount(mask); const std::size_t lowermask=(1 << mask_bits)-1; #pragma omp parallel for for(std::size_t i=0;i<num_entries;i++) { std::size_t instance=i >> mask_bits; std::size_t ibase=shift(instance,~mask); std::size_t location=i & lowermask; std::size_t lindex=ibase+shift(location,mask); state[i]=state_back[lindex]; } } void qram::permute_internal_up(std::size_t mask) { std::swap(state,state_back); const std::size_t mask_bits=popcount(mask); const std::size_t lowermask=(1 << mask_bits)-1; #pragma omp parallel for for(std::size_t i=0;i<num_entries;i++) { std::size_t instance=i >> mask_bits; std::size_t ibase=shift(instance,~mask); std::size_t location=i & lowermask; std::size_t lindex=ibase+shift(location,mask); state[lindex]=state_back[i]; } } void qram::op(const qgate& g,std::size_t mask) { const std::size_t mask_bits=popcount(mask); const std::size_t instances=num_entries >> mask_bits; if(g.gate_bits!=mask_bits) { throw std::invalid_argument("The mask specified a different number of bits then the gate needs"); } permute_internal_down(mask); std::swap(state,state_back); #pragma omp parallel for for(std::size_t instance=0;instance<instances;instance++) { std::size_t index=instance << mask_bits; g.apply(state+index,state_back+index); } permute_internal_up(mask); for(unsigned i=0;i<num_bits;i++) { oss << "| "; } oss << "\n"; for(unsigned i=0;i<num_bits;i++) { oss << (((mask >> (num_bits-1-i)) & 1) ? "X " : "| "); } oss << "[" << g.gate_name << "]\n"; } qram::measurement qram::measure(const std::size_t mask) const { const std::size_t mask_bits=popcount(mask); const std::size_t lowermask=(1 << mask_bits)-1; qram::measurement ms(1 << mask_bits); ms.num_bits=mask_bits; std::complex<double> mag2=0.0; for(std::size_t mi=0;mi<(lowermask+1);mi++) { std::complex<double> sm=0.0; for(std::size_t i=0;i<(num_entries / (lowermask+1));i++) { std::size_t ibase=shift(i,~mask); std::size_t index=ibase+shift(mi,mask); sm+=state[index]; } ms.state[mi]=sm; mag2+=sm; } mag2=std::sqrt(mag2); for(std::vector<std::complex<double> >::iterator i=ms.state.begin();i!=ms.state.end();++i) { *i /= mag2; } /* for(std::size_t i=0;i<num_entries;i++) { std::size_t instance=i >> mask_bits; std::size_t ibase=shift(instance,~mask); std::size_t location=i & lowermask; std::size_t lindex=ibase+shift(location,mask); state[i]=state_back[lindex]; }*/ return ms; } std::ostream& operator<<(std::ostream& oss,const qram& qc) { for(std::size_t i=0;i<qc.num_entries;i++) { print_binary(oss,i,qc.num_bits); oss << " : " << qc.state[i] << "\n"; } return oss; } std::ostream& operator<<(std::ostream& oss,const qram::measurement& ms) { for(std::size_t i=0;i<ms.state.size();i++) { print_binary(oss,i,ms.num_bits); oss << " : " << ms.state[i] << "\n"; } return oss; }
true
39ba63f64784481697449c987ab411fac860363d
C++
mishikaraj/30-day-LeetCode-May-Challenge-2020
/Week-2/Day-9.cpp
UTF-8
809
3.875
4
[]
no_license
Valid Perfect Square Solution Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Output: true Example 2: Input: 14 Output: false class Solution { public: bool isPerfectSquare(int num) { if(num<0) { return false; } if(num==0||num==1) return true; long long int start=1,end=num; while(start<=end) { long long int mid=(start+end)/2; if(mid*mid==num) return true; else if(mid*mid<num) { start=mid+1; } else end=mid-1; } return false; } };
true
addf0309adcc14d4ada74aea8ad2d711571674cd
C++
Tronf92/zi_din_an
/zi din an/Source.cpp
UTF-8
2,044
3.234375
3
[]
no_license
//Nicorici Adrian, 08.03.2014 //Se considera o data calendaristica (zi, luna, an). Sa se verifice daca data respectiva este a secolului nostru sau nu. #include <iostream> using namespace std; int verificare_data(int zi,int luna,int an){ if(zi<1 && luna <1 && an < 1){ cout << "Data nu este valida!" << endl; return 0; } if(luna < 1 || luna >12){ cout << "Data nu este valida" << endl; return 0; } if(luna == 2){ if(an%4==0 ||( an % 100==0 && an %400==0)){ if(zi<1 || zi >29){ cout << "Data nu este valida!" << endl; return 0; } } else{ if(zi<1 || zi >28){ cout << "Data nu este valida!" << endl; return 0; } } } if( (luna == 1) || (luna == 3) || (luna =5) || (luna==7) || (luna == 8) || (luna == 10) || (luna == 12)){ if(zi<1 || zi >31){ cout << "Data nu este valida!" << endl; return 0; } } if ( (luna == 4) || (luna == 6) || (luna =9) || (luna==11)){ if(zi < 1 || zi > 30 ) { cout << "Data nu este valida!" << endl; return 0; } } else return 1; } void data_secolului(int zi,int luna,int an){ if(an <1950 || an >2050 ) { cout << "Data nu este a secolului nostru" << endl; } else{ cout << "Data este a secolului nostru" << endl; } } void calcul(int zi, int luna, int an){ int total=0; int ln = 1; if (ln!= luna){ switch (luna) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: total+=31; case 4: case 6: case 9: case 11: total+=30; case 2: if(an%4==0 ||( an % 100==0 && an %400==0)){ if(zi<1 || zi >29){ total+=29; } } else{ total+=28; } } } else{ total = zi; } cout << "Data " << zi << "," << luna << ", " << an << " este a " << total << " a zi a anului. " << endl; } int main(){ int zi,luna,an; cout << "Introduceti ziua: " << endl; cin >> zi; cout << "Introduceti luna: " << endl; cin >> luna; cout << "Introduceti an:" << endl; cin >> an; if(verificare_data(zi,luna,an) ){ data_secolului(zi,luna,an); calcul(zi,luna,an); } system("pause"); return 0; }
true
2eeab8ed32d7160a94cf6565880f7b026f61db5e
C++
muskan09/CppCodes
/cpp3/operatoroverloadingfriendfuncunary.cpp
UTF-8
341
3.0625
3
[]
no_license
#include<iostream> using namespace std; class number{ int x; public: void setdata(int a){ x=a; } void disp(){ cout<<"value"<<x; } friend void operator-(number& t){ t.x=-t.x; // - operator overloading with frnd func } }; int main(){ number n; n.setdata(-9); n.disp(); -n; n.disp(); return 0; }
true
756bd8f5acef59c6ae1a95fca2975a7fcec005a0
C++
green-fox-academy/pengegyuri
/week-02/day-2/lookformx/main.cpp
UTF-8
911
4.3125
4
[]
no_license
#include <iostream> int main() { // Create a program which first asks for a number // this number indicates how many integers we want to store in an array // and than asks for numbers till the user fills the array // It should print out the biggest number in the given array and the memory address of it int len; std::cout << "How many numbers do you want to compare? "; std::cin >> len; int max = arr[0]; int index = 0; int arr[len]; for (int i = 0; i < len; i++) { std::cout << "Give me the " << i + 1 << ". number : "; std::cin >> arr[i]; if (arr[i] > max) { max = arr[i]; index = i; } } std::cout << "The biggest number is the " << index + 1 << ". one, " << "which is " << max << std::endl; std::cout << "This number lives at the memory address " << &arr[index] << std::endl; return 0; }
true
a1e2954b9739d592e717429a7f6b38223116a7ea
C++
qurobert/CPP
/02/ex03/main.cpp
UTF-8
276
3.125
3
[]
no_license
#include "Point.hpp" bool bsp(Point const a, Point const b, Point const c, Point const point); int main(void) { Point a(2, 3); Point b(4, 7); Point c(7, 1); Point p(5.76f, 4.99f); if (bsp(a, b, c, p)) std::cout << "In\n"; else std::cout << "Out\n"; return (0); }
true
ddde2eaa37aa12abcded5313f77fbdde5672f0da
C++
jiaxin96/Projects
/CampusGuide/include/Spot.hpp
UTF-8
310
2.75
3
[]
no_license
#ifndef SPOT_HPP #define SPOT_HPP #include <string> using namespace std; class Spot { private: string name; int mark; string introduction; public: Spot(); Spot(string n, int m, string i); string get_name() const; int get_mark() const; string get_introduction() const; }; #endif
true
c4f752fb00d1f293ca51cb3c3787643dff91e5b1
C++
HYAR7E/WorkAgency
/Files/database.cpp
UTF-8
6,071
3.046875
3
[]
no_license
#ifndef DATABASE #define DATABASE // Arrays // These arrays should be of variable type, no pointers cuz these store the structure data static Person accounts[30]={0}; // It gets initializated with {0} cuz first element is int type // Can't declarate with Person{0} cuz it requires array elements static int _iac = 0; // Iterator for accounts static Worker workers[30]={0}; static int _iwk = 0; // Iterator for workers static Enterprise enterprises[30]={0}; static int _iet = 0; // Iterator for enterprises static Request requests[30]={0}; static int _irq = 0; // Iterator for requests // Global variables static Person *user = NULL; // Initialize pointer with NULL value for good practices static Person noone = Person{0}; // Static variables static const char st_dateseparator = '/'; static const int st_clearlines = 38; static const int st_maxerror = 3; static const int st_minage = 18; static const int st_maxage = 65; static const int st_minduration = 1; static const int st_minpay = 800; /* We're gonna check the users session by having a pointer to the current user struct variable so we're gonna get his data by pointer->person_element like user->id, and make changes to their data too We're gonna store the user's struct variable but when the user get to be a worker or a enterprise account we should */ #endif #ifndef PreLoad #define PreLoad bool preload(){ // Declaration of empty user 'noone' noone.id = 0; noone.name = ""; noone.lastname = ""; noone.accounttype = -1; noone.w_ma = NULL; noone.e_ma = NULL; user = &noone; // cout<<user->accounttype<<endl; cin.ignore(1); /* */ // PRE SET WORKER Person _new = Person{0}; // Add data _new.create(1111, "nelson", "agustin", "20/05/2000", "72112258", "neldoaf"); _new.contact.email="asesino@gmail.trb"; _new.contact.telf1="977865134"; _new.contact.address="mikaza"; _new.setAccountType(1); _new.setWorker( &workers[_iwk] ); // Set memory address before store in array accounts[_iac] = _new; // Add to accounts array workers[_iwk].setPerson(&accounts[_iac] ); // Add person to worker array element workers[_iwk].profession = "asesinador"; _iac++; // Iterate _iwk++; // Iterate // workers[0].printData(true); /* BUG FIXED We use should use the global variable to set a pointer, otherwise they will store thrash data and will be UB(undefined behavior) workers[_iwk].setPerson(&accounts[_iac] ); */ Person _new1 = Person{0}; _new1.create(2222, "kailen", "agustin falcon", "11/04/2000", "72112251", "kailen123"); _new1.contact.email="cocinero@gmail.trb"; _new1.contact.telf1="977865134"; _new1.contact.address="mikaza"; _new1.setAccountType(1); _new1.setWorker( &workers[_iwk] ); accounts[_iac] = _new1; workers[_iwk].setPerson(&accounts[_iac]); workers[_iwk].profession = "cocinero"; _iac++; _iwk++; // workers[1].printData(true); Person _new11 = Person{0}; _new11.create(3333, "carlos", "falcon", "11/04/2000", "72112252", "kailen123"); _new11.contact.email="barrendero@gmail.trb"; _new11.contact.telf1="977865134"; _new11.contact.address="mikaza"; _new11.setAccountType(1); _new11.setWorker( &workers[_iwk] ); accounts[_iac] = _new11; workers[_iwk].setPerson(&accounts[_iac]); workers[_iwk].profession = "barrendero"; _iac++; _iwk++; // workers[2].printData(true); _new1 = Person{0}; _new1.create(9999, "Homero", "Thompson", "15/04/2001", "12345698", "jay123"); _new1.contact.email="homero69@gmail.com"; _new1.contact.telf1="978645312"; _new1.contact.address="Springfield - Callefalsa N°123"; _new1.setAccountType(0); accounts[_iac] = _new1; _iac++; // PRE SET ENTERPRISE Person _new2 = Person{0}; // Add data _new2.create(4444, "jefe1", "boss", "18/07/2000", "12345673", "boos123"); _new2.contact.email="mibakita@empresa.etp"; _new2.contact.telf1="987654321"; _new2.contact.address="mikaza"; _new2.setAccountType(2); _new2.setEnterprise( &enterprises[_iet] ); accounts[_iac] = _new2; enterprises[_iet].setPerson(&accounts[_iac]); enterprises[_iet].name = "mibakita sac"; _iac++; _iet++; // enterprises[0].printData(true); Person _new3 = Person{0}; _new3.create(5555, "jefe2", "boss", "22/05/1999", "12345674", "boos123"); _new3.contact.email="inkofamra@empresa.etp"; _new3.contact.telf1="977865134"; _new3.contact.address="mikaza"; _new3.setAccountType(2); _new3.setEnterprise( &enterprises[_iet] ); accounts[_iac] = _new3; enterprises[_iet].setPerson(&accounts[_iac]); enterprises[_iet].name = "inkofarma sac"; _iac++; _iet++; // enterprises[1].printData(true); // PRE SET REQUEST Request _new4 = Request{0}; _new4.create(6666,&enterprises[0],"asesinador",1200,8,1,19,28,"necesito alguien que mate los mosquitos de mi fabrica"); requests[_irq] = _new4; enterprises[0].addRequest( &requests[_irq] ); // myJobOffer(); _irq++; Request _new5 = Request{0}; _new5.create(7777,&enterprises[0],"cocinero",900,8,3,22,48,"necesito alguien que sazone bien a mis pollos"); requests[_irq] = _new5; enterprises[0].addRequest( &requests[_irq] ); // myJobOffer(); _irq++; Request _new6 = Request{0}; _new6.create(8888,&enterprises[1],"soplavelas",850,1,1,18,20,"no puedo soplar las velas de mi pastel de cumpleaños"); requests[_irq] = _new6; enterprises[1].addRequest( &requests[_irq] ); // myJobOffer(); _irq++; // PRE SET APPLIES requests[0].addApplicant(accounts[0].w_ma); requests[1].addApplicant(accounts[1].w_ma); // PRE SET ADMIN Person _admin = Person{0}; // Add data _admin.create(0000, "admin", "god", "01/02/1993", "25478260", "admin"); _admin.contact.email="admin@root.ez"; _admin.contact.telf1="987654321"; _admin.contact.address="milap"; _admin.setAccountType(3); accounts[_iac] = _admin; // Add to accounts array _iac++; // Iterate // cin.ignore(); /**/ return true; } #endif
true
dfbbe5e4f80020e0dee52056f4a3cd7138821753
C++
CS-205-S21/205-cia
/tag.cpp
UTF-8
260
2.6875
3
[]
no_license
#include "tag.h" #include <iostream> using namespace std; Tag::Tag(string n) { name = n; } Tag::Tag(string n, string t) { name = n; type = t; } string Tag::getName() { return name; } string Tag::getType() { return type; }
true
14e4a7c3dccc8834a9a45ab0b36fb33fe39ad17d
C++
claris-yang/knowledge_planet
/cplusplus/basic/sample.cpp
UTF-8
380
2.703125
3
[ "Apache-2.0" ]
permissive
// // Created by yangtao on 20-11-12. // #include <iostream> #include <stack> using namespace std; char t; stack<int> s; int n, cnt; int main() { cin >> n; n *= 2; for(int i = 0 ; i < n; i++) { cin >> t; if(t == '(') { s.push(++cnt); } else { cout << s.top() << " "; s.pop(); } } return 0; }
true
6848b46b1f91721d4326a5eabdf3fcb1c2cfcb72
C++
taxuewill/opencv_study
/src/chapter5/c5t2.cpp
UTF-8
874
2.734375
3
[]
no_license
#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include "constants.h" int main() { cv::Mat image = cv::imread(IMAGE_BINARY); if (!image.data) return 0; // Display the image cv::namedWindow("Image"); cv::imshow("Image", image); cv::Mat element5(5,5,CV_8U,cv::Scalar(1)); cv::Mat closed; cv::morphologyEx(image,closed,cv::MORPH_CLOSE,element5);//先膨胀,后腐蚀。去除图像中小的暗点 // Display the closed image cv::namedWindow("Closed Image"); cv::imshow("Closed Image",closed); // Open the image cv::Mat opened; cv::morphologyEx(image,opened,cv::MORPH_OPEN,element5);//先腐蚀,后膨胀。去除图像中小的亮点 // Display the opened image cv::namedWindow("Opened Image"); cv::imshow("Opened Image",opened); cv::waitKey(); return 0; }
true
d20b1f076df5b710e4c1ba13d94ecf8310199d6a
C++
davidatroberts/SoftwareRenderer
/src/Vector.hpp
UTF-8
1,690
3.21875
3
[ "MIT" ]
permissive
#ifndef VECTOR_H #define VECTOR_H #include <array> #include <ostream> #include <tuple> #include <vector> class Vector { public: Vector(float x=0, float y=0, float z=0, float w=1); float p_norm(float p); float magnitude(); float dot(Vector &other); Vector normalized(); Vector project_to_3d(); Vector reflect(Vector &normal); // reflect vector around normal Vector operator*(float scalar); // scalar multiplication Vector operator/(float scalar); // scalar division Vector operator*(const Vector& vec); // element-wise multiplication Vector operator+(const Vector& vec); // addition Vector operator-(const Vector& vec); // subtraction Vector operator^(const Vector& vec); // cross Vector& operator+=(const Vector& vec); // assign addition Vector& operator-=(const Vector& vec); // assign subtraction Vector& operator=(Vector other); // assignment static void project_to_3d(std::vector<Vector> &vertices); static void normalize(std::vector<Vector> &vectors); static void sort(Vector &p1, Vector &p2, Vector &p3); static Vector plane_normal(Vector &v1, Vector &v2, Vector &v3); static Vector lerp(Vector v1, Vector v2, float alpha); static Vector up(); static Vector down(); static Vector left(); static Vector right(); static Vector backward(); static Vector forward(); static std::tuple<float, float, float> compute_barycentric3D( std::array<Vector, 3> vertices, Vector p); friend Vector operator-(const Vector &vec); friend bool operator==(Vector &v1, Vector &v2); friend bool operator!=(Vector &v1, Vector &v2); friend std::ostream& operator<<(std::ostream &strm, Vector &v); float x; float y; float z; float w; }; #endif
true
164981336865ac6039a95961ef7284b5ffe61005
C++
kliment-olechnovic/voronota
/src/scripting/operators/import_figure_voxels.h
UTF-8
2,355
2.828125
3
[ "MIT" ]
permissive
#ifndef SCRIPTING_OPERATORS_IMPORT_FIGURE_VOXELS_H_ #define SCRIPTING_OPERATORS_IMPORT_FIGURE_VOXELS_H_ #include "../operators_common.h" namespace voronota { namespace scripting { namespace operators { class ImportFigureVoxels : public OperatorBase<ImportFigureVoxels> { public: struct Result : public OperatorResultBase<Result> { int total_voxels; Result() : total_voxels(0) { } void store(HeterogeneousStorage& heterostorage) const { heterostorage.variant_object.value("total_voxels")=total_voxels; } }; std::string file; double voxel_diameter; std::vector<std::string> figure_name; ImportFigureVoxels() : voxel_diameter(0.2) { } void initialize(CommandInput& input) { file=input.get_value_or_first_unused_unnamed_value("file"); voxel_diameter=input.get_value_or_default<double>("voxel-diameter", 0.2); figure_name=input.get_value_vector<std::string>("figure-name"); } void document(CommandDocumentation& doc) const { doc.set_option_decription(CDOD("file", CDOD::DATATYPE_STRING, "path to file")); doc.set_option_decription(CDOD("voxel-diameter", CDOD::DATATYPE_FLOAT, "voxel diameter", 0.2)); doc.set_option_decription(CDOD("figure-name", CDOD::DATATYPE_STRING_ARRAY, "figure name")); } Result run(DataManager& data_manager) const { if(voxel_diameter<0.1) { throw std::runtime_error(std::string("Voxel diameter is too small, need to be not less than 0.1")); } if(file.empty()) { throw std::runtime_error(std::string("Empty input file name.")); } InputSelector finput_selector(file); std::istream& finput=finput_selector.stream(); if(!finput.good()) { throw std::runtime_error(std::string("Failed to read file '")+file+"'."); } Figure figure; figure.name=LongName(figure_name); Result result; while(finput.good()) { std::string line; std::getline(finput, line); if(!line.empty()) { apollota::SimplePoint center; std::istringstream linput(line); linput >> center.x >> center.y >> center.z; if(linput.fail()) { throw std::runtime_error(std::string("Invalid coordinates in file line '")+line+"'"); } figure.add_voxel(center, voxel_diameter); result.total_voxels++; } } data_manager.add_figure(figure); return result; } }; } } } #endif /* SCRIPTING_OPERATORS_IMPORT_FIGURE_VOXELS_H_ */
true
ba6ee129329ca8a730c62c38bc5a8dcfa7c91787
C++
Annihilater/Cpp-Primer-Plus-Source-Code-And-Exercise
/Chapter 17/17_8_4/17_8_4.cpp
UTF-8
1,772
3.109375
3
[]
no_license
// // Created by klause on 2020/9/23. // //Program arguments: // "/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test1.txt" // "/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test2.txt" // "/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test3.txt" // 将 test1.txt、test2.txt 文件内容复制到 test3.txt #include <iostream> #include <fstream> const int SIZE = 255; int main() { using namespace std; char line1[SIZE]; char line2[SIZE]; string file1{"/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test1.txt"}; string file2{"/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test2.txt"}; string file3{"/Users/klause/Documents/CLionProjects/Cpp Primer Plus/Chapter 17/17_8_4/test3.txt"}; //创建文件管理对象 ifstream fin1(file1.c_str(), ios_base::in); ifstream fin2(file2.c_str(), ios_base::in); ofstream fout(file3.c_str(), ios_base::out); //打开文件 if (!fin1.is_open()) { cout << "Can't open " << file1 << endl; exit(EXIT_FAILURE); } if (!fin2.is_open()) { cout << "Can't open " << file2 << endl; exit(EXIT_FAILURE); } if (!fout.is_open()) { cout << "Can't open " << file3 << endl; exit(EXIT_FAILURE); } //读取并合并文件内容 fin1.getline(line1, SIZE); fin2.getline(line2, SIZE); while (!fin1.eof() or !fin2.eof()) { fout << line1 << " " << line2 << endl; fin1.getline(line1, SIZE); fin2.getline(line2, SIZE); } //关闭文件 fin1.clear(); fin1.close(); fin2.clear(); fin2.close(); fout.clear(); fout.close(); return 0; }
true