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
cfee6d3411ab15f5ef012cbcefe4474764005678
C++
Gguardiola/PRO1-VACUNES
/main.cpp
UTF-8
4,264
2.9375
3
[]
no_license
#include <iostream> #include <sstream> #include "Cambra.hpp" #include "Control.hpp" #include <queue> #include <list> using namespace std; /* NOTA: ACTUALIZACIONES DE LA PRIMERA ENTREGA - Arreglado canviar_nevera - Mejorada la modularizaciรณn de las clases: ยท Ahora los siguientes metodos tienen return en vez de void: - afegir_unitats - treure_unitats - canviar_nevera - consultar_pos - afegir_vac - treure_vac - consultar_vac Esto quiere decir que se han tenido que adaptar algunas lineas de codigo. - Hemos puesto mรกs comentarios - Se pueden buscar con el find (ctrl + F en algunos editores) con la palabra clave UPDATE:) */ int main(){ vector <Cambra> almacen; int n, x, y, nevera_num, amount; string line, action, id; bool end = false; Control control; cin >> n; //es truca al mรจtode construirArbre per a generar l'arbre en preordre control.construirArbre(n); if(n!=0){ //En cas que es tracti quan no hi hagi cap cambra for(int i = 0; i < n; i++){ cin >> x >> y; almacen.push_back(Cambra(x,y)); } }else{ end=true; cout<<"fi"<<endl; } while(not end and getline(cin,line)){ istringstream ss(line); ss >> action; if(action == "escriure"){ ss >> nevera_num; cout << line << endl; almacen[nevera_num-1].escriure(); } else if(action == "afegir_unitats"){ ss >> nevera_num; ss >> id; ss >> amount; cout << line << endl; amount = almacen[nevera_num-1].afegir_unitats(id,amount,control.get_vacunas());; if(amount >= 0) cout<<" "<<amount<<endl; else cout<<" error"<<endl; } else if(action == "treure_unitats"){ ss >> nevera_num; ss >> id; ss >> amount; cout << line << endl; amount = almacen[nevera_num-1].treure_unitats(id,amount,control.get_vacunas()); if(amount >= 0) cout<<" "<<amount<<endl; else cout<<" error"<<endl; } else if(action == "afegir_vac"){ ss >> id; cout << line << endl; bool exist = control.afegir_vac(id); if(exist) cout<<" error"<<endl; } else if(action == "treure_vac"){ ss >> id; cout << line << endl; bool trobat = control.treure_vac(id,almacen); if(!trobat) cout<<" error"<<endl; } else if(action == "consultar_vac"){ ss >> id; cout << line << endl; amount = control.consultar_vac(id,almacen); if(amount >= 0) cout<<" "<<amount<<endl; else cout<<" error"<<endl; } else if(action == "inventari"){ ss >> id; cout << line << endl; control.inventari(almacen); } else if(action == "canviar_nevera"){ ss >> nevera_num; ss >> x; ss >> y; cout << line << endl; bool canvia = almacen[nevera_num-1].canviar_nevera(x,y); if(!canvia) cout<<" error"<<endl; } else if(action == "comprimir"){ ss >> nevera_num; cout << line << endl; almacen[nevera_num-1].comprimir(); } else if(action == "ordenar"){ ss >> nevera_num; cout << line << endl; almacen[nevera_num-1].ordenar(); } else if(action == "consultar_pos"){ ss >> nevera_num; ss >> x; ss >> y; cout << line << endl; cout<<" "<<almacen[nevera_num-1].consultar_pos(x-1,y-1)<<endl; } else if(action == "distribuir"){ ss >> id; ss >> amount; cout << line << endl; amount = control.distribuir(id,amount,almacen); if( amount >= 0) cout<<" "<<amount<<endl; else cout<<" error"<<endl; } else if(action == "fi"){ cout << line << endl; end = true; } } }
true
9112ada6397e336972722971a37107655658ca31
C++
microtsiu/Anaquin
/src/VarQuin/VarQuin.hpp
UTF-8
1,186
2.65625
3
[ "BSD-3-Clause" ]
permissive
#ifndef VARQUIN_HPP #define VARQUIN_HPP #include "data/data.hpp" #include "data/variant.hpp" namespace Anaquin { inline std::string gt2str(Genotype x) { switch (x) { case Genotype::Somatic: { return "Somatic"; } case Genotype::Homozygous: { return "Homozygous"; } case Genotype::Heterzygous: { return "Heterozygous"; } } } inline std::string var2str(Variation x) { switch (x) { case Variation::SNP: { return "SNP"; } case Variation::Deletion: { return "Deletion"; } case Variation::Insertion: { return "Insertion"; } case Variation::Duplication: { return "Duplication"; } case Variation::Inversion: { return "Inversion"; } } } // Eg: LAD_18 inline bool isLadQuin(const ChrID &x) { A_ASSERT(!x.empty()); return x.find("LAD_") != std::string::npos; } // Eg: chrev1, chrev10 etc... inline bool isRevChr(const ChrID &x) { A_ASSERT(!x.empty()); return x.find("rev") != std::string::npos; } } #endif
true
aeaa36c3cc4568f6868f7b2dbd8af8a060f53ab8
C++
fourthcafe/BasicCpp
/Ch02/02-5/Question02-3.cpp
UTF-8
1,525
3.859375
4
[]
no_license
// // Created by fourthcafe on 2017. 8. 23.. // // ํ•˜๋‚˜๋„ ๋ชจ๋ฅด๊ฒ ๋‹ค!!! #include <iostream> using namespace std; // 2์ฐจ์› ํ‰๋ฉด์ƒ์—์„œ์˜ ์ขŒํ‘œ๋ฅผ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ๊ตฌ์กฐ์ฒด ์ •์˜ typedef struct __Point { int xpos; int ypos; } Point; // ๊ตฌ์กฐ์ฒด๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ๋‘ ์ ์˜ ํ•ฉ์„ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋‹ค์Œ์˜ ํ˜•ํƒœ๋กœ ์ •์˜ํ•˜๊ณ (๋ง์…ˆ๊ฒฐ๊ณผ๋Š” ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜์„ ํ†ตํ•ด์„œ ์–ป๊ฒŒ ๋œ๋‹ค.) Point &PntAdder(const Point &p1, const Point &p2) { Point *pptr = new Point; pptr->xpos = p1.xpos + p2.xpos; pptr->ypos = p1.ypos + p2.ypos; return *pptr; } // ์ž„์˜์˜ ๋‘ ์ ์„ ์„ ์–ธํ•˜์—ฌ, ์œ„ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ๋ง์…ˆ์—ฐ์‚ฐ์„ ์ง„ํ–‰ํ•˜๋Š” main ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•ด๋ณด์ž. // ๋‹จ, ๊ตฌ์กฐ์ฒด Point ๊ด€๋ จ ๋ณ€์ˆ˜์˜ ์„ ์–ธ์€ ๋ฌด์กฐ๊ฑด new ์—ฐ์‚ฐ์ž๋ฅผ ์ด์šฉํ•ด์„œ ์ง„ํ–‰ํ•ด์•ผ ํ•˜๋ฉฐ ํ• ๋‹น๋œ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์˜ ์†Œ๋ฉธ๋„ ์ฒ ์ €ํ•ด์•ผ ํ•œ๋‹ค. // ์ฐธ๊ณ ๋กœ ์ด ๋ฌธ์ œ์˜ ํ•ด๊ฒฐ์„ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ ๋‘ ์งˆ๋ฌธ์— ๋‹ต์„ ํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. // - ๋™์ ํ• ๋‹น ํ•œ ๋ณ€์ˆ˜๋ฅผ ํ•จ์ˆ˜์˜ ์ฐธ์กฐํ˜• ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ์ธ์ž๋กœ ์–ด๋–ป๊ฒŒ ์ „๋‹ฌํ•ด์•ผ ํ•˜๋Š”๊ฐ€? // - ํ•จ์ˆ˜ ๋‚ด์— ์„ ์–ธ๋œ ๋ณ€์ˆ˜๋ฅผ ์ฐธ์กฐํ˜•์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๋ ค๋ฉด ํ•ด๋‹น ๋ณ€์ˆ˜๋Š” ์–ด๋–ป๊ฒŒ ์„ ์–ธํ•ด์•ผ ํ•˜๋Š”๊ฐ€? int main() { Point *pptr1 = new Point; pptr1->xpos = 3; pptr1->ypos = 30; Point *pptr2 = new Point; pptr2->xpos = 70; pptr2->ypos = 7; Point &pref = PntAdder(*pptr1, *pptr2); cout << "[" << pref.xpos << ", " << pref.ypos << "]" << endl; delete pptr1; delete pptr2; delete &pref; return 0; }
true
6902b194a943c6eedaddd0cccd0fd6a30a2ee7f3
C++
BobEh/AI-Path-Finding
/ProjectEndGame/Graph.h
UTF-8
864
3.0625
3
[ "MIT" ]
permissive
#pragma once #include <list> #include <vector> #include "Vertex.h" #include <string> using namespace std; struct Node { unsigned int id; bool visited; bool hasResource; bool hasBase; float gCostSoFar; float hDistance; string nodeType; Vertex position; //position in the game world. used for calculating heuristic distances struct Node* parent; //parent Node that we can follow back to the root node. vector<pair< Node*, float>> children; //Edges pointing to neighbouring graph <childNode, edgeWeight> }; class Graph { public: Graph(); void CreateNode(int id, Vertex position, string type, bool bHasResource, bool bHasBase); void AddEdge(Node* parent, Node* child, float weight, bool bUndirected = true); void ResetGraph(); void PrintGraph(); void PrintParents(bool includeCost = false); vector<Node*> nodes; vector<Node*> parentList; };
true
0c8a5c376a786ab62fe4afdc6294ca6e261193f3
C++
Alexander-Wilms/Advanced-Programming-Techniques
/Navigation System (Advanced features)/myCode/CJsonPersistence.h
UTF-8
4,217
3.0625
3
[]
no_license
/* * CJsonPersistence.h * * Created on: 26.12.2017 * Author: Fabian Alexander Wilms */ #ifndef MYCODE_CJSONPERSISTENCE_H_ #define MYCODE_CJSONPERSISTENCE_H_ #include "CPersistentStorage.h" #include "CWpDatabase.h" #include "CPoiDatabase.h" #include <fstream> #include <string> #include <type_traits> class CJsonPersistence: public CPersistentStorage { private: /** * Enum that contains all possible states the parser can * be in */ enum stateType { WAITING_FOR_FIRST_TOKEN, WAITING_FOR_DB_NAME, WAITING_FOR_DB_BEGIN, WAITING_FOR_ARRAY_BEGIN, WAITING_FOR_OBJECT_BEGIN, WAITING_FOR_ATTRIBUTE_NAME, WAITING_FOR_NAME_SEPARATOR, WAITING_FOR_VALUE, WAITING_FOR_ATTRIBUTE_SEPARATOR_OR_END_OF_OBJECT, WAITING_FOR_OBJECT_SEPARATOR_OR_END_OF_ARRAY, WAITING_FOR_ARRAY_SEPARATOR_OR_END_OF_FILE }; /** * Base name of the database file */ std::string mediaName; /** * Store the current level of indentation */ unsigned int m_currentIndentation; /** * Print as many tabs as m_currentIndentation specifies */ void indent(std::ofstream& file); public: /** * Constructor */ CJsonPersistence(); /** * Destructor */ ~CJsonPersistence(); /** * Fill the databases with the data from persistent storage. If * merge mode is MERGE, the content in the persistent storage * will be merged with any content already existing in the data * bases. If merge mode is REPLACE, already existing content * will be removed before inserting the content from the persistent * storage. * * @param waypointDb the the data base with way points * @param poiDb the database with points of interest * @param mode the merge mode * @return true if the data could be read successfully */ bool readData(CWpDatabase& waypointDb, CPoiDatabase& poiDb, CPersistentStorage::MergeMode mode); /** * Write the data to the persistent storage. * * @param waypointDb the data base with way points * @param poiDb the database with points of interest * @return true if the data could be saved successfully */ bool writeData(const CWpDatabase& waypointDb, const CPoiDatabase& poiDb); /* * Set the base name of the database file */ void setMediaName(std::string name); /** * Print a key value pair, where the value is either * a string or a number to the provided file * * @param key The attribute name * @param value The attribute value * @param file The file stream */ template<class T> bool printKeyValue(std::string key, T value, std::ofstream& file); /** * Print the fields of a CWaypoint or CPOI to a file * * @param file The file stream * @param wp The waypoint or POI */ bool printEntry(std::ofstream& file, const CWaypoint* wp); /** * Print the contents of the database, which may contain CWaypoints or CPOIs * * @paramm file The file stream * @param wpdb The database */ template<class T> bool printDB(std::ofstream& file, const CDatabase<std::string, T>& wpdb); }; template<class T> inline bool CJsonPersistence::printDB(std::ofstream& file, const CDatabase<std::string, T>& wpdb) { m_currentIndentation++; indent(file); if(std::is_same<T, CWaypoint>::value) { // it's a database of waypoints file << "\"waypoints\": [" << std::endl; } else if(std::is_same<T, CPOI>::value) { // it's a database of POIs file << "\"pois\": [" << std::endl; } const std::map<std::string, T> DbMap = wpdb.getDB(); int NoOfEntries = DbMap.size(); // https://stackoverflow.com/questions/5719842/what-is-wrong-with-my-usage-of-c-standard-librarys-find for (typename std::map<std::string, T>::const_iterator it = DbMap.begin(); it != DbMap.end(); it++) { printEntry(file, &(it->second)); NoOfEntries--; if (NoOfEntries != 0) { file << ","; } file << std::endl; } indent(file); file << "]"; m_currentIndentation--; return true; } template<class T> inline bool CJsonPersistence::printKeyValue(std::string key, T value, std::ofstream& file) { indent(file); file << "\"" << key << "\": "; if(std::is_same<T, std::string>::value) { file << "\"" << value << "\""; }else if(std::is_same<T, double>::value) { file << value; } return true; } #endif /* MYCODE_CJSONPERSISTENCE_H_ */
true
f6c59cd52b2480a920089b7511c6fadae8a9c641
C++
zixuanwang/iroom
/AnnotateMain.cpp
UTF-8
1,818
2.71875
3
[]
no_license
/* * AnnotateMain.cpp * * Created on: Apr 2, 2013 * Author: zxwang */ #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <fstream> #include <iostream> #include <list> #include <opencv2/opencv.hpp> #include <vector> bool is_draw = false; int start_x, start_y; cv::Mat image; std::list<cv::Rect> rect_vector; void draw_string(cv::Mat& img, const std::string& text) { cv::Size size = cv::getTextSize(text, cv::FONT_HERSHEY_COMPLEX, 0.6f, 1, NULL); cv::putText(img, text, cv::Point(0, size.height), cv::FONT_HERSHEY_COMPLEX, 0.6f, CV_RGB(200,50,50), 1, CV_AA); } void mouse_callback(int event, int x, int y, int flags, void* param) { switch (event) { case CV_EVENT_MOUSEMOVE: if (is_draw) { cv::Mat copy = image.clone(); int size = std::max(abs(x - start_x), abs(y - start_y)); cv::rectangle(copy, cv::Point(start_x, start_y), cv::Point(start_x + size, start_y + size), cv::Scalar(0, 0, 255, 0), 2, CV_AA); cv::imshow("annotate", copy); } break; case CV_EVENT_LBUTTONDOWN: start_x = x; start_y = y; is_draw = true; break; case CV_EVENT_LBUTTONUP: is_draw = false; break; } } // this executable is to generate positive samples to train the cascade classifier int main(int argc, char* argv[]) { if (argc == 1) { std::cout << "Usage: ./annotate video-file output-dir" << std::endl; return 0; } cv::VideoCapture capture(argv[1]); boost::filesystem::create_directories(argv[2]); int index = 0; cv::namedWindow("annotate"); cv::setMouseCallback("annotate", mouse_callback, NULL); if (capture.isOpened()) { while (true) { capture >> image; if (image.empty()) { break; } cv::imshow("annotate", image); int key = cv::waitKey(); if (key == 'q') { break; } } } capture.release(); return 0; }
true
55dfb0c668fde5435770f06b0fff4cdf34cf3226
C++
AnthonyG1371/College-Assignments
/Data Structures/Project2/main.cpp
UTF-8
417
2.5625
3
[]
no_license
#include <iostream> #include <fstream> #include <stack> #include <string> #include "maze.h" using namespace std; //Main simply calls functions int main() { cout << "Starting Maze Program" << endl; cout << "S is Start, F is Finish, and P is Player Location" << endl; getrows(); getcols(); Maze mazegame = load("maze.txt"); mazegame.print(mazegame); mazegame.solve(); return(0); }
true
f97e299ac3c7f72bd29d6c1df038bff187b33743
C++
BahiaSechi/AntsCPP
/src/Board/Tile.cpp
UTF-8
1,294
2.765625
3
[]
no_license
/** * Address : * ENSICAEN * 6 Boulevard Mareฬchal Juin * F-14050 Caen Cedex * Note : * This file is owned by an ENSICAEN student. No portion of this * document may be reproduced, copied or revised without written * permission of the authors. * * @author Mateo RABOTIN <mateo.rabotin@ecole.ensicaen.fr> * @author Bahia SECHI <bahia.sechi@ecole.ensicaen.fr> * * @date November 2020 * @file main.cpp * @version 1.0 * * @brief Blabla */ #include <Board/Tile.h> Tile::~Tile() { } Tile::Tile(std::vector<Ant *> ants, const sf::Vector2i &position, tile_type type) : ants(ants), pos(position), type(type) { } bool Tile::pheromone_max() { if (this->pheromones >= 1000) return true; else return false; } void Tile::evaporation() { this->pheromones *= 0.05; } tile_type Tile::getType() const { return type; } const std::vector<Ant *> &Tile::getAnts() const { return ants; } void Tile::setAnts(const std::vector<Ant *> &ants) { this->ants = ants; } const sf::Vector2i &Tile::getPos() const { return pos; } float Tile::getPheromones() const { return pheromones; } void Tile::setPheromones(float pheromones) { this->pheromones = pheromones; } bool Tile::isDiscovered() const { return discovered; } void Tile::setDiscovered(bool discovered) { this->discovered = discovered; }
true
303c4f37fe42f27dfac5df4ba3953c34f6a30e3d
C++
paulnewman1979/edocteel
/000/005/main.cpp
UTF-8
1,097
3.375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: string longestPalindrome(string s) { int i; int j; int max = 1; int maxs = 0; for (i=1; i<s.length(); ++i) { for (j=1; ((j<=i)&&(j+i<s.length())); ++j) { if (s[i-j] == s[i+j]) { if (j + j + 1 > max) { max = j + j + 1; maxs = i - j; } } else { break; } } for (j=1; ((j<=i)&&(j+i-1<s.length())); ++j) { if (s[i-j] == s[i + j - 1]) { if (j + j > max) { max = j + j; maxs = i - j; } } else { break; } } } return s.substr(maxs, max); } }; int main(int argc, char* argv[]) { string value; cin >> value; Solution solution; cout << solution.longestPalindrome(value) << endl; }
true
0d9da78c0c3b3e0647b768277c6fdaade1cca98d
C++
Shivamj075/DSA
/BITMASKING/Get_Ith_Bit.cpp
UTF-8
202
2.953125
3
[]
no_license
//Get the Ith bit #include<bits/stdc++.h> using namespace std; int getIthBit(int n,int i){ return (n&(1<<i))!=0?1:0; } int main() { int n,i; cin>>n>>i; cout<<getIthBit(n,i)<<endl; return 0; }
true
4fb17bb2f75a71012cab502b9ad1361ab24513b8
C++
yangjiang123/possumwood
/src/libs/dependency_graph/nodes_iterator.h
UTF-8
939
2.796875
3
[ "MIT" ]
permissive
#pragma once #include <stack> #include <boost/iterator/iterator_facade.hpp> namespace dependency_graph { class Network; template<typename ITERATOR> class NodesIterator : public boost::iterator_facade < NodesIterator<ITERATOR>, typename ITERATOR::value_type::element_type, // element type stored in an std smart pointer boost::forward_traversal_tag > { public: NodesIterator(); NodesIterator(ITERATOR i, ITERATOR end, bool recursive); // corresponds to the interface of boost::indirect_iterator ITERATOR base() const; private: struct Item { ITERATOR current; ITERATOR end; bool operator == (const Item& i) const; bool operator != (const Item& i) const; }; std::stack<Item> m_its; bool m_recursive; friend class boost::iterator_core_access; void increment(); bool equal(const NodesIterator<ITERATOR>& other) const; typename ITERATOR::value_type::element_type& dereference() const; }; }
true
6bde2021775ba3e2613ec19966fc7b9a4342c37d
C++
sAusk3/Cpp_White_Belt
/Week-4/008_ClassRationaleExeptions/rational.cpp
UTF-8
2,615
3.671875
4
[]
no_license
#include <iostream> #include <sstream> #include <vector> #include <map> #include <set> #include <exception> #include <stdexcept> using namespace std; int recursive_div_helper (int a, int b) { if (b == 0) return (a); else return (recursive_div_helper(b, a % b)); } class Rational { public: Rational () { p = 0; q = 1; } Rational (int numerator, int denominator) { if (denominator == 0) throw invalid_argument("zero denominator"); int div = recursive_div_helper(numerator, denominator); p = numerator / div; q = denominator / div; if (q < 0) { p *= -1; q *= -1; } } int Numerator () const { return (p); } int Denominator () const { return (q); } private: int p; int q; }; bool operator == (const Rational& left, const Rational& right) { if (left.Numerator() == right.Numerator() && left.Denominator() == right.Denominator()) return (true); else return (false); } Rational operator + (const Rational& left, const Rational& right) { int l = (left.Numerator() * right.Denominator()) + // sign of the operation (right.Numerator() * left.Denominator()); int r = left.Denominator() * right.Denominator(); return (Rational(l, r)); } Rational operator - (const Rational& left, const Rational& right) { int l = (left.Numerator() * right.Denominator()) - // sign of the operation (right.Numerator() * left.Denominator()); int r = left.Denominator() * right.Denominator(); return (Rational(l, r)); } Rational operator * (const Rational& left, const Rational& right) { int l = left.Numerator() * right.Numerator(); int r = right.Denominator() * left.Denominator(); return (Rational(l, r)); } Rational operator / (const Rational& left, const Rational& right) { if (right.Numerator() == 0) throw domain_error("division by zero"); return (left * Rational(right.Denominator(), right.Numerator())); } bool operator < (const Rational& left, const Rational& right) { return (((left - right).Numerator()) < 0); } istream& operator >> (istream& s, Rational& n) { int a, b; char c; s >> a >> c >> b; if (s && c == '/') n = Rational(a, b); return (s); } ostream& operator << (ostream& s, const Rational& n) { return (s << n.Numerator() << '/' << n.Denominator()); } int main() { try { Rational r(1, 0); cout << "Doesn't throw in case of zero denominator" << endl; return 1; } catch (invalid_argument&) { } try { auto x = Rational(1, 2) / Rational(0, 1); cout << "Doesn't throw in case of division by zero" << endl; return 2; } catch (domain_error&) { } cout << "OK" << endl; return 0; }
true
35ace8a53d7ae0c28630be9fdd5760c95794178c
C++
shyde8/Jekyll
/Jekyll/src/Jekyll/Broadcaster.cpp
UTF-8
658
2.78125
3
[]
no_license
#include "Broadcaster.h" namespace Jekyll { void Broadcaster::AddObserver(Observer* observer) { for (Observer* obs : this->_observers) { if (obs == observer) { return; } } this->_observers.push_back(observer); } void Broadcaster::RemoveObserver(Observer* observer) { std::vector<Observer*>::iterator it; it = std::find(this->_observers.begin(), this->_observers.end(), observer); if (it != this->_observers.end()) { this->_observers.erase(it); } else {} } void Broadcaster::Broadcast(const Entity& entity, Event event) { for (Observer* obs : this->_observers) { obs->OnBroadcast(entity, event); } } }
true
2f57e48ea580d01c08771f00036adb2e4978fecd
C++
mpfeifer1/150Labs
/Lab11/lab11.cpp
UTF-8
3,422
3.546875
4
[]
no_license
/*-------------------------------------------------------------------- Program: lab11.cpp This program reads data into a 2-D array named cadmium with daily readings of airborne cadmium in a room of a house every six hours (6am, noon, 6pm, and midnight) for seven consecutive days. Then, it computes the highest cadmium reading per day and the highest reading in the week. In the case of two readings with the same highest reading, it chooses the first occurrence. Writes a summary of each day's high reading and time, as well as the weekly high (day, reading, time). ---------------------------------------------------------------------*/ #include <iostream> #include <iomanip> #include <fstream> using namespace std; //------------------------------------------------------------------- // Global constants //------------------------------------------------------------------ const int NUM_DAYS = 7; const int NUM_READINGS = 4; const char DAY_NAMES[7][10] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; const char TIMES[4][10] = { "12am", "6am", "12pm", "6pm" }; //------------------------------------------------------------------- // Function Prototypes //------------------------------------------------------------------- int high_reading(double day[4]); bool read_data(ifstream& fin, double readings[7][4]); void write_summary(int heights[7], double readings[7][4]); void highestReading(int& i, int& j, double readings[7][4]); int main( ) { double readings[7][4]; int heights[7]; // contains indexes ofdaily heights ifstream fin; fin.open("readings.txt"); if(!fin) { cout << "Idiot. This program needs a file." << endl; return -1; } read_data(fin, readings); for(int i = 0; i < 7; i++) { heights[i] = high_reading(readings[i]); } write_summary(heights, readings); return 0; } bool read_data(ifstream& fin, double readings[7][4]) { int i = 0, j = 0; for(i = 0; i < 7; i++) { for(j = 0; j < 4; j++) { fin >> readings[i][j]; } } return true; } int high_reading(double day[4]) { double max = 0; int index = 0; for(int i = 0; i < 4; i++) { if(day[i] > max) { index = i; max = day[i]; } } return index; } void highestReading(int& i, int& j, double readings[7][4]) { double max = 0; int indexI = 0, indexJ = 0; for(i = 0; i < 7; i++) { for(j = 0; j < 4; j++) { if(readings[i][j] > max) { indexI = i; indexJ = j; max = readings[i][j]; } } } i = indexI; j = indexJ; } void write_summary(int heights[7], double readings[7][4]) { ofstream fout; fout.open("summary.txt"); if(!fout) { cout << "What are you even doing? You can't even make a file?!" << endl; } for(int i = 0; i < 7; i++) { fout << "Highest cadmium reading on " << DAY_NAMES[i] << " was " << readings[i][heights[i]] << " at " << TIMES[heights[i]] << endl; } fout << endl; int i = 0, j = 0; highestReading(i, j, readings); fout << "The overall highest reading was on " << DAY_NAMES[i] << " at " << TIMES[j] << endl; }
true
aab1ae2bf0bdc0a61a282a606d428a34ad14f6f1
C++
morganwilde/playful
/Models/Circle.cpp
UTF-8
2,052
3.671875
4
[]
no_license
#include "Circle.h" void Circle::init(Point center, double radius, int segments) { this->segments = segments; this->setCenter(center); this->setRadius(radius); // The environment double circleRadius = 2 * M_PI; double segmentRadius = circleRadius / this->segments; double angleStart = 0; double angle = angleStart; // Create segments for (int i = 0; i < this->segments; i++) { Point pointFrom = getPointFromPolarAngle(angle); Point pointTo = getPointFromPolarAngle(angle + segmentRadius); ShapeTriangle *segment = new ShapeTriangle(getCenter(), pointFrom, pointTo); add(segment); //std::cout << "segment #" << i << "; angle: " << angle << pointFrom << pointTo << std::endl; angle += segmentRadius; } } Circle::Circle(Point center, double radius, int segments) { // Designated constructor ShapesArray::ShapesArray(); init(center, radius, segments); } Circle::Circle(Point center, double radius) { // Convenience constructor ShapesArray::ShapesArray(); init(center, radius, 20); } Circle::~Circle() { } // Setters void Circle::setCenter(Point center) { this->center = center; } void Circle::setRadius(double radius) { this->radius = radius; } // Getters Point Circle::getCenter() const { return this->center; } double Circle::getRadius() const { return this->radius; } int Circle::getSegments() const { return this->segments; } double Circle::getPerimeter() { return 2 * M_PI * getRadius(); } Point Circle::getPointFromPolarAngle(double angle) { double x = getRadius() * cos(angle); double y = getRadius() * sin(angle); return Point(getCenter().getX() + x, getCenter().getY() + y); } // Getters private double Circle::getSegmentWidth() { return getPerimeter() / segments; } std::string Circle::getShapesArrayType() const { std::stringstream ss; ss << "Circle( "; ss << getCenter() << ", "; ss << getRadius() << ", "; ss << getSegments() << " )"; return ss.str(); }
true
8875ffb46f4245699463bc8b0ee6c1de14bc9c10
C++
Aswinv2k17/Lab_Programs
/S5/OOT/fileopr.cpp
UTF-8
848
3.3125
3
[]
no_license
#include<iostream> #include<fstream> #include<cstdlib> using namespace std; class Payroll { char name[20]; float salary; public: void readdata(void); void writedata(void); }; void Payroll::readdata(void) { cout<<name<<" "<<salary<<"\n"; } void Payroll::writedata(void) { cout<<"\nEnter the name: "; cin>>name; cout<<"\nEnter salary: "; cin>>salary; } int main() { int n; cout<<"\n Enter the number of employees to be entered\n"; cin>>n; Payroll p[10]; fstream file; file.open("emp.dat",ios::in||ios::out); cout<<"\n Enter details of employees\n"; for(int i=0;i<n;i++) { p[i].writedata(); file.write((char *) &p[i],sizeof(p[i])); } file.seekg(0); cout<<"Output\n\n"; for(int i=0;i<10;i++) { file.read((char *) &p[i],sizeof(p[i])); p[i].readdata(); } file.seekg(0); file.close(); return 0; }
true
a7198514e4fc3c256e5028edbdec46d84917fb07
C++
billy607/FTP
/LabelingBase/context/UserAuthorize.h
UTF-8
810
2.703125
3
[]
no_license
#ifndef USERAUTHORIZE_H #define USERAUTHORIZE_H #include<QString> namespace labelingbase { class UserAuthorize { public: UserAuthorize(){} QString getUserName() { return userName; } void setUserName(QString userName) { this->userName = userName; } QString getUserId() { return userId; } void setUserId(QString userId) { this->userId = userId; } QString getPassword() { return password; } void setPassword(QString password) { this->password = password; } QString getToken() { return token; } void setToken(QString token) { this->token = token; } private: QString userName; QString userId; QString password; QString token; }; } #endif // USERAUTHORIZE_H
true
7110fb9ed115ededf8906dfd2d9c399acab5fcc1
C++
LorenzoTomaz/_Bacteria_
/src/Environment.cpp
UTF-8
9,217
3.421875
3
[]
no_license
#include "Environment.hpp" void Environment::setup(vector<vector<Cell>> level){ //set the current level's matrix passed by the Game istance lifeMatrix = level; gridSize = lifeMatrix.size(); /* Creation of the player at position (gridGame/2, 1, 1) of the grid The player is alive after this call. */ player = Player(ofPoint(floor(gridSize/2) * cellSize*2, cellSize*2, cellSize), cellSize); /* Creation of the rocket (in the same player position) The rocket is not alive after this call, is still hidden. */ rocket = Rocket(player.getPos(), cellSize); } /* UPDATE This is the main game's algorithm. It updates the lifeMatrix (if the updateMatrix param is TRUE), then it checks for collisions with enemies and with the walls (this is called before the player.update() because thanks to this we don't see the player going beyond the limits for a split second) Then, the player and the rocket is updated. After this, this method checks for rocket's collisions. This happens after the rocket update because this algorithm use: -the current rocket position to check for collisions -the last rocket position (before a collision) to transform the rocket into an enemy cell. The flow is: 1) updates lifeMatrix (if updateMatrix == true) 2) checks for "player - walls" collisions 3) checks for "player - enemies" collisions 4) updates player and rocket 5) checks for "rocket - walls" collisions 6) checks for "rocket - enemies" collisions */ void Environment::update(bool updateMatrix){ ofPoint prevRocketPos = rocket.getPos(); //the rocket pos in the physical world ofPoint prevMapRocketPos = prevRocketPos/(cellSize*2); //the rocket pos in the life matrix prevMapRocketPos.x = int(prevMapRocketPos.x); prevMapRocketPos.y = int(prevMapRocketPos.y); prevMapRocketPos.z = int(prevMapRocketPos.z); //GAME OF LIFE engine if(updateMatrix){ gameOfLifeEngine(); } /* if the player collides with a wall, it goes back in its last position (I use the rocket pos. because is the same as the player's pos.) */ if(wallsCollision(player.getPos())){ player.setPos(prevRocketPos); } //if the player collides with another cell, the player dies. if(playerCollision(player.getPos())){ player.kill(); } //Here is where the player and the rocket are updated. rocket.update(player.getPos(), player.getDirection()); player.update(); ofPoint newRocketPos = rocket.getPos(); ofPoint newMapRocketPos = newRocketPos/(cellSize*2); /* if the rocket collides with a wall, it dies, and borns a new cell in the last rocket's pos. */ if(wallsCollision(newRocketPos) && rocket.isAlive() ){ lifeMatrix[prevMapRocketPos.x][prevMapRocketPos.y].giveBirth(); rocket.kill(); } /* if the rocket is near an alive cell, it dies, and borns a new cell in the last rocket's pos. If the rocket is moving on the x axis, it must considers only the cells on the x axis, the same for the y. This avoids that the cell is appended in an enemy's "neighbourhood angle". -rocket.getDirection()[0] == 1 => the rocket move in the x direction -rocket.getDirection()[0] == 0 => the rocket move in the y direction */ string mode = abs(rocket.getDirection()[0]) == 1 ? "x" : "y"; if(countNeighbours(lifeMatrix, newRocketPos, mode) > 0 && rocket.isAlive()){ lifeMatrix[newMapRocketPos.x][newMapRocketPos.y].giveBirth(); rocket.kill(); } } //it draws the player, the rocket and the game's grid (with the enemies) void Environment::draw(){ player.draw(); rocket.draw(); for(int x=0; x<lifeMatrix.size(); x++){ for(int y=0; y<lifeMatrix[0].size(); y++){ lifeMatrix[x][y].draw(); } } } /* GAMEOFLIFEENGINE This method is the game's core and is based on the Conway's Game of Life rules: - Each alive cell with one or no neighbors dies, as if by solitude. - Each alive cell with four or more neighbors dies, as if by overpopulation. - Each alive cell with two or three neighbors survives. - Each dead cell with three neighbors becomes populated. The method uses a copy of the original lifeMatrix, because if we change directly values in the orginal matrix, the algorithm doesn't work as expected. */ void Environment::gameOfLifeEngine(){ vector<vector<Cell>> matrix = lifeMatrix; for(int x=0; x<matrix.size(); x++){ for(int y=0; y<matrix[0].size(); y++){ int currentNeighbors = countNeighbours(matrix, ofPoint(x*cellSize*2, y*cellSize*2)); if(matrix[x][y].isAlive() && currentNeighbors <= 1){ lifeMatrix[x][y].kill(); } else if(matrix[x][y].isAlive() && currentNeighbors >= 4){ lifeMatrix[x][y].kill(); } else if(matrix[x][y].isAlive() && (currentNeighbors == 2 || currentNeighbors == 3)){ lifeMatrix[x][y].giveBirth(); //it is altready alive... } else if(!matrix[x][y].isAlive() && currentNeighbors == 3){ lifeMatrix[x][y].giveBirth(); } } } } //if the player's position fits with an enemy's position, it returns true, otherwise false bool Environment::playerCollision(ofPoint cell){ ofPoint currentPos = cell/(cellSize*2); //map the player pos to the matrix index if(lifeMatrix[currentPos.x][currentPos.y].isAlive()) return true; return false; } //if the passed position is outside the grid, returns true, otherwise false. bool Environment::wallsCollision(ofPoint cell){ if( (cell.y < 0 || cell.y > gridSize*cellSize*2 - cellSize) || // *2 because the grid has spaces (cell.x < 0 || cell.x > gridSize*cellSize*2 - cellSize) ){ return true; } return false; } /* It counts the neighbors of a given grid position. If mode is setted to x or y, only the neighbors in the x or y direction is taken in consideration. */ int Environment::countNeighbours(vector<vector<Cell>> &matrix, ofPoint _pos, string _mode){ int count = 0; ofPoint currentPos = _pos/(cellSize*2); //map the pos to matrix's indexes int fromX, fromY, toX, toY; if(_mode == "x"){ //if the mode is "x", the loop goes from -1 to 2 inly in the x direction fromX = -1; fromY = 0; toX = 2; toY = 1; } else if(_mode == "y"){ //if the mode is "y", the loop goes from -1 to 2 inly in the y direction fromX = 0; fromY = -1; toX = 1; toY = 2; } else{ //otherwise neighbors are checked in both directions fromX = -1; fromY = -1; toX = 2; toY = 2; } for(int x=fromX; x<toX; x++){ for(int y=fromY; y<toY; y++){ ofPoint neighborPos = ofPoint(currentPos.x + x, currentPos.y + y); if((neighborPos.x == currentPos.x) && (neighborPos.y == currentPos.y) ) continue; //the current cell is not calculated as a neighbour /*the famous PACMAN effect*/ if(neighborPos.x < 0) neighborPos.x = gridSize-1; if(neighborPos.y < 0) neighborPos.y = gridSize-1; if(neighborPos.x >= gridSize) neighborPos.x = 0; if(neighborPos.y >= gridSize) neighborPos.y = 0; //if this cell is alive (is an enemy), increments the count var if(matrix[int(neighborPos.x)][int(neighborPos.y)].isAlive()) count++; } } return count; } /* utility: it counts the alive cells (we can use also a class attribute, without call every time a method), but I use this method because the code is probably clearer. */ int Environment::countAliveCells(){ int aliveCells = 0; for(int x=0; x<lifeMatrix.size(); x++){ for(int y=0; y<lifeMatrix[0].size(); y++){ if(lifeMatrix[x][y].isAlive()) aliveCells++; } } return aliveCells; } //pass events to the player and the rocket void Environment::control(string control){ if(control == "up") player.controls("up"); if(control == "left") player.controls("left"); if(control == "right") player.controls("right"); if(control == "space") rocket.controls("space"); } /*TODO: I could pass it as a pointer...*/ //a boolean's matrix is used in the Soundtrack class. Boolean represent the cell's state: alive/dead. vector<vector<bool>> Environment::getBoolLifeMatrix(){ vector<vector<bool>> boolMatrix; for(int x=0; x<lifeMatrix.size(); x++){ boolMatrix.push_back(vector<bool>()); for(int y=0; y<lifeMatrix[0].size(); y++){ boolMatrix[x].push_back(lifeMatrix[x][y].isAlive() ? true : false); } } return boolMatrix; } int Environment::getCellSize(){ return cellSize; } bool Environment::isPlayerAlive(){ return player.isAlive(); }
true
c91f9f4ea55036d43bbd6fc9bbbc4a8bb102eb4e
C++
chriskatnic/CPSC301
/simpleFile.cpp
UTF-8
1,719
3.546875
4
[]
no_license
#include <iostream > #include < fstream > //practice writing to and getting from a file. int main() { char c[3] = { '1', '2', '3' }; char d[3]; char e[3]; char * s; int length; std::ofstream output("other.bin"); //open da file output.write( c, 3); //writing to a binary file, write( char[], int ) int for how many characters from the array to write onto the file output.close(); //done with the file std::ifstream input("other.bin"); //open da file input.read(d, 3); //simple way to read everything in a binary file, read ( char[], int ) int for how many characters to read input.seekg(0, input.end); //places the cursor at the end of the file, 0 means that it's at position 0 length = input.tellg(); //tellg() returns the int value of how many characters long the file is input.seekg(0, input.beg); //places the cursor at the beginning of the file at position 0 s = new char [ length ]; //make the character array [length] which we just got above input.read(s, length); // read( char *, int ) reads all the data in a binary file up to [length] characters input.close(); //done with the file std::cout.write(s, length); //function to print out everything in char array std::cout << "\n"; //make it pretty delete s; // *s was dynamic, gotta delete it std::ofstream output2 ( "other.txt" ); output2 << c[0] << " " << c[1] << " " << c[2]; output2.close(); std::ifstream input2 ( "other.txt" ); input2 >> e[0] >> e[1] >> e[2]; input2.close(); std::cout << e[0] << " " << e[1] << " " << e[2] << "\n"; std::cout << d[0] << " " << d[1] << " " << d[2] << "\n"; return 0; }
true
455904372e7cd8d27a13cb4203f4791aff35857d
C++
google/gvisor
/test/syscalls/linux/mkdir.cc
UTF-8
4,441
2.515625
3
[ "MIT", "Apache-2.0" ]
permissive
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "gtest/gtest.h" #include "test/util/capability_util.h" #include "test/util/fs_util.h" #include "test/util/temp_path.h" #include "test/util/temp_umask.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { class MkdirTest : public ::testing::Test { protected: // SetUp creates various configurations of files. void SetUp() override { dirname_ = NewTempAbsPath(); } // TearDown unlinks created files. void TearDown() override { EXPECT_THAT(rmdir(dirname_.c_str()), SyscallSucceeds()); } std::string dirname_; }; TEST_F(MkdirTest, CanCreateWritableDir) { ASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds()); std::string filename = JoinPath(dirname_, "anything"); int fd; ASSERT_THAT(fd = open(filename.c_str(), O_RDWR | O_CREAT, 0666), SyscallSucceeds()); EXPECT_THAT(close(fd), SyscallSucceeds()); ASSERT_THAT(unlink(filename.c_str()), SyscallSucceeds()); } TEST_F(MkdirTest, HonorsUmask) { constexpr mode_t kMask = 0111; TempUmask mask(kMask); ASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds()); struct stat statbuf; ASSERT_THAT(stat(dirname_.c_str(), &statbuf), SyscallSucceeds()); EXPECT_EQ(0777 & ~kMask, statbuf.st_mode & 0777); } TEST_F(MkdirTest, HonorsUmask2) { constexpr mode_t kMask = 0142; TempUmask mask(kMask); ASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds()); struct stat statbuf; ASSERT_THAT(stat(dirname_.c_str(), &statbuf), SyscallSucceeds()); EXPECT_EQ(0777 & ~kMask, statbuf.st_mode & 0777); } TEST_F(MkdirTest, FailsOnDirWithoutWritePerms) { // Drop capabilities that allow us to override file and directory permissions. AutoCapability cap1(CAP_DAC_OVERRIDE, false); AutoCapability cap2(CAP_DAC_READ_SEARCH, false); ASSERT_THAT(mkdir(dirname_.c_str(), 0555), SyscallSucceeds()); auto dir = JoinPath(dirname_.c_str(), "foo"); EXPECT_THAT(mkdir(dir.c_str(), 0777), SyscallFailsWithErrno(EACCES)); EXPECT_THAT(open(JoinPath(dirname_, "file").c_str(), O_RDWR | O_CREAT, 0666), SyscallFailsWithErrno(EACCES)); } TEST_F(MkdirTest, DirAlreadyExists) { // Drop capabilities that allow us to override file and directory permissions. AutoCapability cap1(CAP_DAC_OVERRIDE, false); AutoCapability cap2(CAP_DAC_READ_SEARCH, false); ASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds()); auto dir = JoinPath(dirname_.c_str(), "foo"); EXPECT_THAT(mkdir(dir.c_str(), 0777), SyscallSucceeds()); struct { int mode; int err; } tests[] = { {.mode = 0000, .err = EACCES}, // No perm {.mode = 0100, .err = EEXIST}, // Exec only {.mode = 0200, .err = EACCES}, // Write only {.mode = 0300, .err = EEXIST}, // Write+exec {.mode = 0400, .err = EACCES}, // Read only {.mode = 0500, .err = EEXIST}, // Read+exec {.mode = 0600, .err = EACCES}, // Read+write {.mode = 0700, .err = EEXIST}, // All }; for (const auto& t : tests) { printf("mode: 0%o\n", t.mode); EXPECT_THAT(chmod(dirname_.c_str(), t.mode), SyscallSucceeds()); EXPECT_THAT(mkdir(dir.c_str(), 0777), SyscallFailsWithErrno(t.err)); } // Clean up. EXPECT_THAT(chmod(dirname_.c_str(), 0777), SyscallSucceeds()); ASSERT_THAT(rmdir(dir.c_str()), SyscallSucceeds()); } TEST_F(MkdirTest, MkdirAtEmptyPath) { ASSERT_THAT(mkdir(dirname_.c_str(), 0777), SyscallSucceeds()); auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(dirname_, O_RDONLY | O_DIRECTORY, 0666)); EXPECT_THAT(mkdirat(fd.get(), "", 0777), SyscallFailsWithErrno(ENOENT)); } TEST_F(MkdirTest, TrailingSlash) { ASSERT_THAT(mkdir((dirname_ + "/").c_str(), 0777), SyscallSucceeds()); } } // namespace } // namespace testing } // namespace gvisor
true
a72eb3d45f39e1dec7348c08e48e107edf6f224f
C++
FnEsc/Course-Code
/CPlus_Source/Shiyan3/person.cpp
GB18030
909
3.453125
3
[]
no_license
#include"pch.h" #include "person.h" Person::Person() : m_nAge(0), m_nSex(0)//์บฏ เตฑฺณสผึตm_nAge=0 m_nSex=0 { strcpy_s(m_strName, "XXX"); } Person::Person(const char *name, int age, char sex) : m_nAge(age), m_nSex(sex == 'm' ? 0 : 1)//์บฏ 0ลฎ1 วณิฑสผูผ { strcpy_s(m_strName, name); } Person::Person(const Person &p) : m_nAge(p.m_nAge), m_nSex(p.m_nSex)//์บฏ { strcpy_s(m_strName, p.m_strName); } void Person::SetName(char *name) { strcpy_s(m_strName, name); } void Person::SetAge(int age) { m_nAge = age; } void Person::setSex(char sex) { m_nSex = sex == 'm' ? 0 : 1; } char* Person::GetName() { return m_strName; } int Person::GetAge() { return m_nAge; } char Person::GetSex() { return (m_nSex == 0 ? 'm' : 'f'); } void Person::ShowMe() { cout << GetName() << '\t' << GetAge() << '\t' << GetSex() << '\t'; }
true
50c414ceb31ea0df8024bc3058c4d16623497d83
C++
Rimilmandrita/lab-2-Rimilmandrita-Ghosh-1711106
/lab2.Question7.cpp
UTF-8
373
3.3125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a1,a2,a3; cout << "Enter an angle of a triangle.\n "; cin >>a1; cout<<"angle 1 is= "<<a1<<" degree.\n"; cout << "Enter another angle of the triangle.\n "; cin >>a2; cout<<"angle 2 is= "<<a2<<" degree.\n"; a3= 180-(a1+a2); cout <<"The 3rd angle is "<<a3<<" degree"<<'.'; return 0; }
true
bb9b5436880e57dd97a668bc812c2319773cf5ff
C++
schwa-lab/libschwa
/src/lib/schwa/utils/shlex.h
UTF-8
360
2.515625
3
[ "MIT" ]
permissive
/* -*- Mode: C++; indent-tabs-mode: nil -*- */ #ifndef SCHWA_UTILS_SHLEX_H_ #define SCHWA_UTILS_SHLEX_H_ #include <string> namespace schwa { namespace utils { /** * Return a shell-escaped version of the string \p s with quotes added if required. **/ std::string shlex_quote(const std::string &s); } } #endif // SCHWA_UTILS_SHLEX_H_
true
e20e98a78168fab2130ede054f3a7a8a90ad00d5
C++
TouwaErioH/Algorithm
/ๅˆ†็ฑป/ๆ•ฐๅญฆๆฆ‚ๅฟตไธŽๆ–นๆณ•/ๅ…ถไป–ๆ•ฐๅญฆไธ“้ข˜/uva10288.cpp
UTF-8
1,291
2.796875
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> #include <cstdlib> #include <cmath> #define LL long long using namespace std; LL gcd(LL a,LL b){ return a==0?b:gcd(b%a,a); } LL lcm(LL a,LL b){ return a/gcd(a,b)*b; } int main() { LL n; while(cin >> n) { LL lm = 1; for(LL i = 1;i <= n;i++) { lm = lcm(lm,i); } LL fenzi = 0; for(LL i = 1;i <= n;i++) { fenzi += (lm/i); } fenzi = fenzi * n; LL ansfz = fenzi / gcd(fenzi,lm); LL ansfm = lm / gcd(fenzi,lm); LL tmp = ansfm; int cont = 0; while(tmp / 10) { cont ++; tmp = tmp / 10; } tmp = ansfz/ansfm; int cont2 = 0; while(tmp / 10) { cont2 ++; tmp = tmp / 10; } if(ansfz % ansfm == 0) cout << ansfz / ansfm << endl; else { for(int i = 0;i <= cont2;i++) cout << " "; cout << " " << ansfz%ansfm << endl; cout << ansfz/ansfm << " "; for(int i = 0;i <= cont;i++) cout << "-"; cout << endl; for(int i = 0;i <= cont2;i++) cout << " "; cout << " " << ansfm << endl; } } return 0; }
true
c967c37e181ad8eb639a0a5842774ee1c3e927fc
C++
antoinusitos/CPP_OpenGL
/FirstProject/FirstProject/UIButton.cpp
UTF-8
2,922
2.53125
3
[]
no_license
#include "UIButton.h" #include <iostream> #include <string> #include "UIManager.h" #include "LogManager.h" #include "ResourceManager.h" #include "CameraManager.h" #include "Camera.h" #include "Shader.h" #include "Model.h" #include "TimeManager.h" #include "TextManager.h" namespace Engine { UIButton::UIButton(std::string aName) : UIContainer(aName) { myTransform.myPosition = Vector2(75.0f / 2.0f, 20.0f / 2.0f); myTransform.myScale = Vector2(75.0f, 20.0f); myImage = "CheckBox_Off"; } UIButton::~UIButton() { } void UIButton::AddUIAction(UIAction anAction) { myUIActions.push_back(anAction); } void UIButton::Init() { UIElement::Init(); myMouseClickFunction = std::bind(&UIButton::Click, this); myMouseReleaseFunction = std::bind(&UIButton::Release, this); myMouseHoverFunction = std::bind(&UIButton::Hover, this); myMouseExitFunction = std::bind(&UIButton::Exit, this); myBaseColor = Vector3(1.0f); myHoverColor = Vector3(0.5f); myColor = myBaseColor; } void UIButton::Click() { LogManager::GetInstance()->AddLog("Clicked on " + myName); myColor = Vector3(0.0f, 1.0f, 0.0f); for (unsigned int i = 0; i < myUIActions.size(); i++) { switch (myUIActions[i].myActionType) { case VISIBILITY: { myUIActions[i].myElement->SetVisibility(myUIActions[i].myValue2); break; } case TOGGLEVISIBILITY: { myUIActions[i].myElement->SetVisibility(!myUIActions[i].myElement->GetVisibility()); break; } case QUIT: { myUIManager->Quit(); break; } case POSITION: { myUIActions[i].myElement->SetPosition(myUIActions[i].myValue3); break; } case POSITIONOBJECT: { Vector3 pos = myUIActions[i].myObject->GetPosition(); pos.myX += myUIActions[i].myValue4 * TimeManager::GetInstance()->GetDeltaTime(); myUIActions[i].myObject->SetPosition(pos); break; } case ROTATIONOBJECT: { float angle = myUIActions[i].myObject->GetAngle(); angle += myUIActions[i].myValue4 * TimeManager::GetInstance()->GetDeltaTime(); myUIActions[i].myObject->SetAngle(angle); break; } case SCALEOBJECT: { Vector3 scale = myUIActions[i].myObject->GetScale(); scale.myX += myUIActions[i].myValue4 * TimeManager::GetInstance()->GetDeltaTime(); scale.myY += myUIActions[i].myValue4 * TimeManager::GetInstance()->GetDeltaTime(); scale.myZ += myUIActions[i].myValue4 * TimeManager::GetInstance()->GetDeltaTime(); myUIActions[i].myObject->SetScale(scale); break; } default: break; } } } void UIButton::Release() { //LogManager::GetInstance()->AddLog("Released on " + myName); myColor = myHoverColor; } void UIButton::Hover() { //LogManager::GetInstance()->AddLog("Mouse Enter on " + myName); myColor = myHoverColor; } void UIButton::Exit() { //LogManager::GetInstance()->AddLog("Mouse Exit on " + myName); myColor = myBaseColor; } }
true
4a483173d7e888d06aef5665d9a2ad4502824c42
C++
7on9/algorithm
/C++/Contacts.cpp
UTF-8
1,319
3.59375
4
[]
no_license
//Bร i cฦก bแบฃn vแป trie #include <iostream> #include <string> using namespace std; class Node { public: Node() { numOfNode = 0; for(int i = 0;i < 28;i++) Arr[i] = NULL; } void addString(string s) { Node *temp = this; for(int i = 0;i < s.size();i++) { if(temp->Arr[s[i]-97] == NULL) temp->Arr[s[i]-97] = new Node(); temp = temp->Arr[s[i]-97]; temp->numOfNode++; } } void findString(string s) { int i = 0; int len = s.size(); Node *temp = this; while( i < len) { if(temp->Arr[s[i]-97] != NULL) temp = temp->Arr[s[i]-97]; else { cout << "0\n"; return; } i++; } cout << temp->numOfNode << endl; } // -97 de giam so luong int numOfNode; Node *Arr[28]; }; void solve(int n, Node *root) { string req, str; for(int i = 0;i < n;i++) { cin >> req >> str; if(req == "add") root->addString(str); else root->findString(str); } } int main() { Node *root = new Node(); int n; cin >> n; solve(n, root); return 0; }
true
e7e3b535f5f9aa48f4e5f7ec0437e0b6c1f32edc
C++
shashankch/DataStructures-Algorithms
/stringcompression.cpp
UTF-8
410
3.234375
3
[]
no_license
#include <iostream> #include <string> using namespace std; void str_comp(string comp) { for (int i = 0; i < comp.length(); i++) { int cnt = 1; while (i < comp.length() - 1 && comp[i] == comp[i + 1]) { cnt++; i++; } cout << comp[i] << cnt; } } int main() { string comp; cin >> comp; str_comp(comp); return 0; }
true
beb097f26016163eb20a10be967aa1f443b71730
C++
jodaomaikham/InternGame
/Lesson4/Lesson4/Closed.cpp
UTF-8
500
3.140625
3
[]
no_license
#include"Locked.h" #include"Closed.h" #include"Openned.h" #include<iostream> using namespace std; void Closed::open(Door* door) { cout << "*****NOW THE DOOR IS OPEN*****" << endl; door->setState(new Openned); } void Closed::close(Door* door) { cout << "THE DOOR IS ALREADY CLOSED " << endl; } void Closed::unlock(Door* door) { cout << "THE DOOR IS OPEN IT ALREADY UNLOCK"<<endl; } void Closed::lock(Door* door) { cout << "*****NOW THE DOOR IS LOCK*****" << endl; door->setState(new Locked); }
true
6a5adc7be8001ff4ab3ab46d990844f3e54271a0
C++
Compiladores7009/Practicas-Laboratorio
/Practicas/p4/src/ParserLL.cpp
UTF-8
1,232
2.640625
3
[]
no_license
#include "headers/ParserLL.hpp" ParserLL::ParserLL(Lexer *lexer) { this->lexer = lexer; } ParserLL::~ParserLL() { } void ParserLL::loadSyms() { /********************************************* * 4. Agregar todos los sรญmbolos (N'โˆชT) de G'* *********************************************/ } void ParserLL::loadProds() { /************************************************ * 5. Agregar todas las producciones (P') de G' * ************************************************/ } void ParserLL::loadTable() { /************************************************* ** 6.Cargar la tabla de AS predictivo ** *************************************************/ } int ParserLL::parse() { /************************************************** ** 7. Implementar el algoritmo de AS predictivo ** **************************************************/ //Auxiliares //stack<Symbol> pila; //map<Token, int>::iterator accion; //vector<int> body; //Symbol X; } void ParserLL::error(string msg) { cout<<msg<<endl; exit(EXIT_FAILURE); } Token ParserLL::eat() { return (Token) lexer->yylex(); } void ParserLL::aceptar(string msg) { cout<<msg<<endl; }
true
3a2ef33e5d665f363f1d503a52fa180697149ea6
C++
Sumant-Dusane/Hotel-Management-System-using-CPP-
/hotel1.cpp
UTF-8
6,649
3.0625
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; class hotel { public: int rooms[5][4]= { {00,01,02,03}, {10,11,12,13}, {20,21,22,23}, {30,31,32,33}, {40,41,42,43} }; char type; char rent[6]; char status; int rent1; char name[100]; char no[10]; char add[300]; char doc[20]; char gender; int no_per; int age; int stay; int i,j,o=1; char ac_no[14]; char ifsc[10]; int cvv; char bk_name[20]; char cc; char ans; public: void search() { cout<<"Enter the floor and room number:"; cin>>rooms[i][j]; if(o==1) { cout<<"Available!"; cout<<"\nWanna Check-in??(Y/N):"; cin>>ans; if(ans=='Y') { void check_in(); } } else { cout<<"Unavailable!!"; } } void check_in() { if(o==1) { cout<<"\nEnter the Customer Name:"; cin>>name; cout<<"\nPhone Number:"; cin>>no; cout<<"\nAddress:"; cin>>add; cout<<"\nAny Verification document:"; cin>>doc; cout<<"\nGender(M/F):"; cin>>gender; cout<<"\nAge:"; cin>>age; cout<<"\nHow many people are residing?:"; cin>>no_per; cout<<"\nAc/Non-Ac(a/n):"; cin>>type; cout<<"\nRent per day:"; if(type=='A') { cout<<"\tRs.3500"; rent1=3500; } else { cout<<"\tRs.1500"; rent1=1500; } cout<<"\nEnter floor & room no:"; cin>>rooms[i][j]; o=0; cout<<"\nCheck-IN sucessfully done!!"; cout<<"\n\n*******************"; cout<<"\nSummary:\n"; cout<<"Customer Name:"<<name; cout<<"\nContact Number:"<<no; cout<<"\nAddress:"<<add; cout<<"\nGender/Age:("<<gender<<"/"<<age<<")"; cout<<"\nNo of people residing:"<<no_per; cout<<"\n\nHotel Room No:"<<rooms[i][j]; cout<<"\nRent of suite per day:"<<rent1; cout<<"\nType Ac/Non-Ac:"<<type; cout<<"\n*******************"; } else { cout<<"\nSorry rooms are booked!"; } } void check_out() { cout<<"Enter Payment status(y/n):"; cin>>status; cout<<"\nEnter floor and room number:"; cin>>rooms[i][j]; if(status=='y') { o=1; cout<<"Check-out sucessful!!Come back soon"; } else { cout<<"You are kindly requested to PAY the rent"; } } void payment() { cout<<"Ac/Non-Ac??:"; cin>>type; cout<<"Rent per day:"; if(type=='A') { cout<<"Rs.3500"; rent1=3500; } else { cout<<"Rs.1500:"; rent1=1500; } cout<<"\nHow many Stays(day):"; cin>>stay; rent1=rent1*stay; cout<<"\nAmount:"<<rent1; cout<<"\nPayment mode Cash or Card(M/C):"; cin>>cc; if(cc=='C') { cout<<"\nEnter Bank A/c Number:"; cin>>ac_no; cout<<"\nEnter IFSC Code:"; cin>>ifsc; cout<<"\nEnter CVV number:"; cin>>cvv; cout<<"\nEnter Bank Holder Name:"; cin>>bk_name; cout<<"\n\n***************************************"; cout<<"\nOnline Receipt:\n"; cout<<"\t\tAmount Transferred:"<<rent1; cout<<"\n\nName OF Bank Holder:"<<bk_name; cout<<"\nAccount Number:"<<ac_no; cout<<"\nIFSC Code:"<<ifsc; cout<<"\nCVV number:"<<cvv; cout<<"\n\n***************************************"; } else { cout<<"Pay the Cash!!"; } status='y'; cout<<"\nPayment sucessful"; } }c; int main() { int i,j,o,ch,k; for(k=0;k<5;k++) { cout<<"\n\n"; cout<<"\t\t\t\t/////////////////////////////////////\n"; cout<<"\t\t\t\t///Welcome to HOTEL SWAMI SAMARTHA///\n"; cout<<"\t\t\t\t/////////////////////////////////////"; cout<<"\n\n1.Check Avaliablity:"; cout<<"\n2.Check In:"; cout<<"\n3.Check Out:"; cout<<"\n4.Payment:"; cout<<"\n5.Exit"; cout<<"\nEnter:"; cin>>ch; switch(ch) { case 1: c.search(); break; case 2: c.check_in(); break; case 3: c.check_out(); break; case 4: c.payment(); break; case 5: exit(0); break; default: cout<<"Invalid Input!!"; break; } } return 0; } /* Output: ///////////////////////////////////// ///Welcome to HOTEL SWAMI SAMARTHA/// ///////////////////////////////////// 1.Check Avaliablity: 2.Check In: 3.Check Out: 4.Payment: 5.Exit Enter:1 Enter the floor and room number:502 Available! Wanna Check-in??(Y/N)t ///////////////////////////////////// ///Welcome to HOTEL SWAMI SAMARTHA/// ///////////////////////////////////// 1.Check Avaliablity: 2.Check In: 3.Check Out: 4.Payment: 5.Exit Enter:2 Enter the Customer Name:Sumant Phone Number:8805267254 Address:Mumbai Any Verification document:no Gender(M/F):M Age:20 How many people are residing?:3 Ac/Non-Ac(a/n):A Rent per day: Rs.3500 Enter floor & room no:502 Check-IN sucessfully done!! ******************* Summary: Customer Name:Sumant Contact Number:8805267254Mumbai Address:Mumbai Gender/Age:(M/20) No of people residing:3 Hotel Room No:502 Rent of suite per day:3500 Type Ac/Non-Ac:A ******************* ///////////////////////////////////// ///Welcome to HOTEL SWAMI SAMARTHA/// ///////////////////////////////////// 1.Check Avaliablity: 2.Check In: 3.Check Out: 4.Payment: 5.Exit Enter:1 Enter the floor and room number:502 Unavailable!! ///////////////////////////////////// ///Welcome to HOTEL SWAMI SAMARTHA/// ///////////////////////////////////// 1.Check Avaliablity: 2.Check In: 3.Check Out: 4.Payment: 5.Exit Enter: */
true
c7bfd800202e5a9da55faf301c855097598372d5
C++
NOVACProject/SpectralEvaluation
/include/SpectralEvaluation/Calibration/InstrumentLineShapeEstimation.h
UTF-8
9,756
2.828125
3
[]
no_license
#pragma once #include <memory> #include <vector> #include <string> #include <SpectralEvaluation/Calibration/InstrumentLineShape.h> #include <SpectralEvaluation/Evaluation/CrossSectionData.h> namespace novac { class CSpectrum; class IFraunhoferSpectrumGenerator; class ICrossSectionSpectrumGenerator; class DoasFit; struct IndexRange; class InstrumentLineShapeEstimationException : public std::exception { private: const char* const m_msg = ""; public: InstrumentLineShapeEstimationException(const char* msg) : m_msg(msg) {} InstrumentLineShapeEstimationException(const std::string& msg) : m_msg(msg.c_str()) {} const char* what() const noexcept override final { return m_msg; } }; /** Abstract base class for the different instrument line shape estimators. */ class InstrumentLineShapeEstimation { public: /** Sets the pixel to wavelength mapping for the spectrometer, this is the inital state before doing the calibration. */ void UpdateInitialCalibration(const std::vector<double>& newPixelToWavelengthMapping) { this->pixelToWavelengthMapping = newPixelToWavelengthMapping; } /** Sets initial estimation of the instrument line shape. Used as a starting point for the estimation routine. */ void UpdateInitialLineShape(const novac::CCrossSectionData& newInitialLineShape); bool HasInitialLineShape() const; protected: InstrumentLineShapeEstimation(const std::vector<double>& initialPixelToWavelengthMapping); InstrumentLineShapeEstimation(const std::vector<double>& initialPixelToWavelengthMapping, const novac::CCrossSectionData& initialLineShape); /** The assumed pixel-to-wavelength mapping for the device. */ std::vector<double> pixelToWavelengthMapping; /** The initial, starting guess for the instrument line shape. */ std::unique_ptr<novac::CCrossSectionData> initialLineShapeEstimation; }; /** This is a helper class for estimating the instrument line shape of an instrument using a measured spectrum with a (reasonably well known) pixel-to-wavelength calibration by measuring the distance between keypoints in the meaured and synthetic spectra. This is a rather blunt tool and may be used to get an initial estimate if the instrument line shape is not at all known. */ class InstrumentLineShapeEstimationFromKeypointDistance : public InstrumentLineShapeEstimation { public: /** A helper structure to describe the internal state of this estimator */ struct LineShapeEstimationState { double medianPixelDistanceInMeas = 0.0; GaussianLineShape lineShape; std::vector<std::pair<double, double>> attempts; }; InstrumentLineShapeEstimationFromKeypointDistance(const std::vector<double>& initialPixelToWavelengthMapping) : InstrumentLineShapeEstimation(initialPixelToWavelengthMapping) { } InstrumentLineShapeEstimationFromKeypointDistance(const std::vector<double>& initialPixelToWavelengthMapping, const novac::CCrossSectionData& initialLineShape) : InstrumentLineShapeEstimation(initialPixelToWavelengthMapping, initialLineShape) { } /** Creates a rough estimation of the instrument line shape as the Gaussian line shape which best fits to the measured spectrum. If this->HasInitialLineShape() is true, then the initial estimation will be used. This method has the advantage that the wavelength calibration does not have to be very accurate, but does take quite a few iterations to succeed. @param measuredSpectrum A measured sky spectrum containing Fraunhofer lines. @param estimatedLineShape Will on successful return be filled with the estimated line shape. @param gaussianWidth Will on successful return be filled with the estimated FWHM of the line shape. @return A structure showing how the result was achieved. */ LineShapeEstimationState EstimateInstrumentLineShape(IFraunhoferSpectrumGenerator& fraunhoferSpectrumGen, const CSpectrum& measuredSpectrum, novac::CCrossSectionData& estimatedLineShape, double& fwhm); private: double GetMedianKeypointDistanceFromSpectrum(const CSpectrum& spectrum, const IndexRange& pixelRange, const std::string& spectrumName) const; /** Returns the first and the last index value where the spectrum is consistently above the provided threshold */ static IndexRange Threshold(const std::vector<double>& spectrum, double threshold); }; /** This is a helper class for estimating the instrument line shape of an instrument using a measured spectrum with a well known pixel-to-wavelength calibration by pseudo-absorbers representing the error in measured instrument line shape into a DOAS evaluation. */ class InstrumentLineshapeEstimationFromDoas : public InstrumentLineShapeEstimation { public: InstrumentLineshapeEstimationFromDoas(const std::vector<double>& initialPixelToWavelengthMapping, const novac::CCrossSectionData& initialLineShape, bool addDebugOutput = false); InstrumentLineshapeEstimationFromDoas(const std::vector<double>& initialPixelToWavelengthMapping, const novac::SuperGaussianLineShape& initialLineShape, bool addDebugOutput = false); struct LineShapeEstimationAttempt { SuperGaussianLineShape lineShape; double error = 0.0; double shift = 0.0; }; struct LineShapeEstimationSettings { /** The first pixel (inclusive) in the range which will be used to estimate the line shape. Must be smaller than endPixel. */ size_t startPixel = 0; /** The last pixel after the range which will be used to estimate the line shape. Must be smaller than the length of the measured spectrum. */ size_t endPixel = 0; }; /** A helper structure to provide the result from the estimation as well as the measurements of the goodness-of-fit. */ struct LineShapeEstimationResult { LineShapeEstimationAttempt result; std::vector<LineShapeEstimationAttempt> attempts; }; /** Estimates the instrument line shape by fitting a Super Gaussian to the measured spectrum * @return The fitted line shape * @throw std::invalid_argument if the initial line shape hasn't been provided */ LineShapeEstimationResult EstimateInstrumentLineShape( const CSpectrum& measuredSpectrum, const LineShapeEstimationSettings& settings, IFraunhoferSpectrumGenerator& fraunhoferSpectrumGen, ICrossSectionSpectrumGenerator* ozoneSpectrumGen = nullptr); private: /** Set to true to enable debugging output to stdout */ bool debugOutput = false; struct LineShapeUpdate { double currentError = 0.0; // This is the chi2 of the DOAS fit without the parameter adjustment. double residualSize = 0.0; // This is the chi2 of the DOAS fit with the parameter adjustment. double shift = 0.0; // This is the shift of the DOAS fit with the parameter adjustment. std::vector<double> parameterDelta; // The retrieved parameter adjustment. }; /** The initial, starting guess for the instrument line shape. This contains the parameterized line shape, as apart from 'initialLineShapeEstimation' which contains the sampled data. */ SuperGaussianLineShape initialLineShapeFunction; /** Attempts to calculate the gradient of the parameters of the instrument line shape fit by calling CalculateGradientAndCurrentError. */ LineShapeUpdate GetGradient( IFraunhoferSpectrumGenerator& fraunhoferSpectrumGen, ICrossSectionSpectrumGenerator* ozoneSpectrumGen, const CSpectrum& measuredSpectrum, const SuperGaussianLineShape& currentLineShape, const LineShapeEstimationSettings& settings, bool& allowSpectrumShift); /** Calculates the gradient of the parameters of the instrument line shape using a DOAS fit. At the same time an currentError measure at the current location is calculated (by reusing the same objects). @throws DoasFitException if the fit fails. */ LineShapeUpdate CalculateGradientAndCurrentError( IFraunhoferSpectrumGenerator& fraunhoferSpectrumGen, ICrossSectionSpectrumGenerator* ozoneSpectrumGen, const CSpectrum& measuredSpectrum, const SuperGaussianLineShape& currentLineShape, const LineShapeEstimationSettings& settings, bool allowShift = true); /** Returns false if the provided parameterDelta and stepSize will result in invalid parameter setttings (typically negative values). */ static bool UpdatedParametersAreValid(const SuperGaussianLineShape& currentLineShape, const std::vector<double>& parameterDelta, double stepSize); }; /** Estimates the Full Width at Half Maximum of a given lineshape function. */ double GetFwhm(const novac::CCrossSectionData& lineshape); /** Estimates the Full Width at Half Maximum of a given lineshape function. */ double GetFwhm(const std::vector<double>& lineshapeWavelength, const std::vector<double>& lineShapeIntensity); }
true
10dad5ea1175dace14c58129462d82f7d2f3381f
C++
AndrijaS37N/doomrecey
/practice_part_two/malamute.hpp
UTF-8
595
3.078125
3
[]
no_license
#ifndef malamute_hpp #define malamute_hpp #include <vector> // example : taking a declared global constant from husky.hpp and defining it here const int GLOBAL_AVARAGE_BARKS = 7; class Malamute { private: std::vector<Yawn> yawns; public: void add_yawn(Yawn yawn); void print_yawns(); void set_yawns(std::vector<Yawn> yawns) { this->yawns = yawns; }; std::vector<Yawn> get_yawns() { return this->yawns; }; void print_global_avarage_barks() { std::cout << "Global avarage barks (from malamute's view): " << GLOBAL_AVARAGE_BARKS << '\n'; }; }; #endif /* malamute_hpp */
true
a067ab4927a3e42b3c1bb852a5b0ceafd75c21b9
C++
Marko-Jur/Wireless-CAN
/CAN_Transceiver.cpp
UTF-8
1,811
2.671875
3
[]
no_license
/* File Name:CAN Transceiver * Author: Marko Jurisic * Date Edited: 14th June 2021 * * Description: Contains functions to allow transmission and receiving of CAN messages to and from a DUT. */ // Including all header files #import <Arduino.h> #include "Pin_Assignments.h" #include "Libraries.h" float can_messages[/*TODO*/]={}; /* Function Name:CAN Transceiver Setup * Date Edited: 14th June 2021 * * Inputs: None * Outputs: None * Resources: None * * Description: Sets up the MCP2551 and MCP2515 */ void canTransceiverSetup() { while (CAN_OK != CAN.begin(CAN_500KBPS)) { Serial.println("CAN BUS init Failed"); delay(100); } } /* Function Name:CAN Communications * Date Edited: 14th June 2021 * * Inputs: Pointer to an array containing all the CAN Messages. * Outputs: None * Resources: None * * Description: Receives and Transmits CAN messages from the DUT. */ void canComms(float can_messages){ unsigned char len = 0; unsigned char buf[8]; if(CAN_MSGAVAIL == CAN.checkReceive()) { CAN.readMsgBuf(&len, buf); unsigned long canId = CAN.getCanId(); Serial.println("-----------------------------"); Serial.print("Data from ID: 0x"); Serial.println(canId, HEX); for(int i = 0; i<len; i++) { Serial.print(buf[i]); Serial.print("\t"); if(ledON && i==0) { digitalWrite(ledPin, buf[i]); ledON = 0; delay(500); } else if((!(ledON)) && i==4) { digitalWrite(ledPin, buf[i]); ledON = 1; } } Serial.println(); } }
true
a190c34e035b819cb740e71e12bc046a536a17c7
C++
TheWeberino/LoisonTan
/src/engine/ActionList.cpp
UTF-8
432
2.65625
3
[]
no_license
#include "ActionList.h" namespace engine{ ActionList::ActionList(std::vector<Action*> actions){ this->actions=actions; } ActionList::~ActionList(){ } int ActionList::size () const{ return actions.size(); } Action* ActionList::get (int i) const{ return actions.at(i); } void ActionList::add (Action* action){ actions.push_back(action); } }
true
8705ebb60eec8933745a8766573e2925ad14d95f
C++
Sitispeaks/turicreate
/src/ml/sketches/hyperloglog.hpp
UTF-8
4,343
2.90625
3
[ "BSD-3-Clause" ]
permissive
/* Copyright ยฉ 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_SKETCH_HYPERLOGLOG_HPP #define TURI_SKETCH_HYPERLOGLOG_HPP #include <cmath> #include <cstdint> #include <functional> #include <core/util/bitops.hpp> #include <core/util/cityhash_tc.hpp> #include <core/logging/assertions.hpp> namespace turi { namespace sketches { /** * \ingroup sketching * An implementation of the hyperloglog sketch for estimating the number of * unique elements in a datastream. * * Implements the hyperloglog sketch algorithm as described in: * Philippe Flajolet, Eric Fusy, Olivier Gandouet and Frederic Meunier. * HyperLogLog: the analysis of a near-optimal cardinality * estimation algorithm. Conference on Analysis of Algorithms (AofA) 2007. * * with further reference from: * Stefan Heule, Marc Nunkesser and Alexander Hall. * HyperLogLog in Practice: Algorithmic Engineering of a State of The * Art Cardinality Estimation Algorithm. * Proceedings of the EDBT 2013 Conference. * * * Usage is simple. * \code * hyperloglog hll; * // repeatedly call * hll.add(stuff) // this is a templatized function. * // will accept anything it can hash using std::hash. * hll.estimate() // will return an estimate of the number of unique element * hll.error_bound() // will return the standard deviation on the estimate * \endcode */ class hyperloglog { private: size_t m_b = 0; /// 2^b is the number of hash bins size_t m_m = 0; /// equal to 2^b: The number of buckets double m_alpha = 0; std::vector<unsigned char> m_buckets; /// Buckets public: /** * Constructs a hyperloglog sketch using 2^b buckets. * The resultant hyperloglog datastructure will require * 2^b bytes of memory. b must be at least 4. (i.e. 2^4 buckets). */ explicit inline hyperloglog(size_t b = 16): m_b(b), m_m(1 << b), m_buckets(m_m, 0) { ASSERT_GE(m_m, 16); // constants from SFlajolet et al. Fig 3 switch(m_m) { case 16: m_alpha = 0.673; break; case 32: m_alpha = 0.697; break; case 64: m_alpha = 0.709; break; default: m_alpha = 0.7213 / (1 + 1.079 / (double)m_m); } }; /** * Adds an arbitrary object to be counted. Any object type can be used, * and there are no restrictions as long as std::hash<T> can be used to * obtain a hash value. */ template <typename T> void add(const T& t) { // Then cityhash's hash64 twice to distribute the hash. // empirically, one hash64 does not produce enough scattering to // get a good estimate uint64_t h = hash64(hash64(t)); size_t index = h >> (64 - m_b); DASSERT_LT(index, m_buckets.size()); unsigned char pos = h != 0 ? 1 + __builtin_clz(static_cast<unsigned int>(h)) : sizeof(size_t); m_buckets[index] = std::max(m_buckets[index], pos); } /** * Merge two hyperloglog datastructures. * The two data structures must be constructed with the same number of * buckets. Combining of two sketches constructed on two disjoint data * streams produces identical results to generating one sketch on the both * data streams. */ void combine(const hyperloglog& other) { ASSERT_EQ(m_buckets.size(), other.m_buckets.size()); for (size_t i = 0;i < m_buckets.size(); ++i) { m_buckets[i] = std::max(m_buckets[i], other.m_buckets[i]); } } /** * Returns the standard error of the estimate. */ inline double error_bound() { return estimate() * 1.04 / std::sqrt(m_m); } /** * Returns the estimate of the number of unique items. */ inline double estimate() { double E = 0; for (size_t i = 0;i < m_buckets.size(); ++i) { E += std::pow(2.0, -(double)m_buckets[i]); } E = m_alpha * m_m * m_m / E; // perform bias correction for small values if (E <= 2.5 * m_m) { size_t zero_count = 0; for(auto i: m_buckets) zero_count += (i == 0); if (zero_count != 0) E = m_m * std::log((double)m_m / zero_count); } // we do not need correction for large values 64-bit hash, assume // collisions are unlikely return E; } }; // hyperloglog } // namespace sketch } // namespace turi #endif
true
0f2b8086d5f4add3d4b136ec4b99e88712145fdc
C++
wf225/ios_ci
/DemoLib/Counter.h
UTF-8
128
2.515625
3
[]
no_license
class Counter { public: Counter(); int GetCount() { return count_; } int Increment(); private: int count_; };
true
7fec690b86f89509a3656b1e6cc421fd4afbb7d3
C++
WescamSW/libwscDrone
/src/Pilot.cpp
UTF-8
7,054
2.703125
3
[]
no_license
/* * piloting.c * * Created on: Feb 3, 2019 * Author: slascos */ #include <iostream> #include <chrono> #include <stdexcept> #include "Utils.h" #include "Pilot.h" using namespace std; using namespace chrono_literals; namespace wscDrone { constexpr int PILOT_TIMEOUT_MS = 10000; constexpr float MOVEMENT_STEP = 0.25f; Pilot::Pilot(std::shared_ptr<DroneController> droneController, float initialFlightAltitude) { m_deviceController = droneController->getDeviceController(); if (!m_deviceController) { throw runtime_error("Pilot(...): invalid deviceController"); } m_initialFlightAltitude = initialFlightAltitude; } // THE DRONE WILL FALL!!! void Pilot::CUT_THE_MOTORS() { m_deviceController->aRDrone3->sendPilotingEmergency(m_deviceController->aRDrone3); } void Pilot::notifyMoveComplete() { moveSem.notify(); } bool Pilot::waitMoveComplete() { return !moveSem.waitTimed(PILOT_TIMEOUT_MS); } eARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE Pilot::getFlyingStateRaw() { if (!m_deviceController) { throw runtime_error("Pilot::getFlyingState(): invalid device controller"); } eARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE flyingState = ARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE_MAX; eARCONTROLLER_ERROR error; ARCONTROLLER_DICTIONARY_ELEMENT_t *elementDictionary = ARCONTROLLER_ARDrone3_GetCommandElements(m_deviceController->aRDrone3, ARCONTROLLER_DICTIONARY_KEY_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED, &error); if (error == ARCONTROLLER_OK && elementDictionary != NULL) { ARCONTROLLER_DICTIONARY_ARG_t *arg = NULL; ARCONTROLLER_DICTIONARY_ELEMENT_t *element = NULL; HASH_FIND_STR (elementDictionary, ARCONTROLLER_DICTIONARY_SINGLE_KEY, element); if (element != NULL) { // Get the value HASH_FIND_STR(element->arguments, ARCONTROLLER_DICTIONARY_KEY_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE, arg); if (arg != NULL) { // Enums are stored as I32 flyingState = static_cast<eARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE>(arg->value.I32); } } } else { fprintf(stderr, "getFlyingState: ERROR getting element dictionary\n"); } return flyingState; } void Pilot::takeOff() { if (!m_deviceController) { throw runtime_error("Pilot::takeOff(): invalid device controller"); } FlyingState flyingState = getFlyingState(); //if (getFlyingState() == ARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE_LANDED) if (flyingState == FlyingState::LANDED) { printf("takeOff(): PILOTING: Sending takeoff command\n"); m_deviceController->aRDrone3->sendPilotingTakeOff(m_deviceController->aRDrone3); // wait until state is hovering waitMilliseconds(5); while (m_flyingState != FlyingState::HOVERING) { waitMilliseconds(5); } } else { printf("takeOff(): Can't takeoff, drone is not in LANDED state\n"); } // Set initial flight altitude if (m_initialFlightAltitude > 1.0f) { m_moveRelativeMetres(0.0f, 0.0f, -(m_initialFlightAltitude - 1.0f), 0.0f); } } void Pilot::land() { if (!m_deviceController) { throw runtime_error("Pilot::land(): invalid device controller"); } //eARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE flyingState = getFlyingState(); //FlyingState flyingState = getFlyingState(); //if (flyingState == ARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE_FLYING || flyingState == ARCOMMANDS_ARDRONE3_PILOTINGSTATE_FLYINGSTATECHANGED_STATE_HOVERING) // Send land unconditionally to avoid any risk of the command being ignored by a coding bug { printf("land(): PILOTING: Sending the landing command\n"); m_deviceController->aRDrone3->sendPilotingLanding(m_deviceController->aRDrone3); } } bool Pilot::moveRelativeMetres(float dx, float dy, float heading, bool wait) { return m_moveRelativeMetres(dx, dy, 0.0f, heading, wait); } #ifndef RESTRICTED_ALTITUDE bool Pilot::moveRelativeMetresRestricted(float dx, float dy, float dz, float heading, bool wait) { return m_moveRelativeMetres(dx, dy, dz, heading, wait); } #endif // NOTE:sendPilotingMoveBy expects radians bool Pilot::m_moveRelativeMetres(float dx, float dy, float dz, float heading, bool wait) { bool timedOut = true; m_deviceController->aRDrone3->sendPilotingMoveBy(m_deviceController->aRDrone3, dx, dy, dz, degressToRadians(heading)); // not implemented in the SDK yet if (wait) { timedOut = waitMoveComplete(); } // wait until out of flying state, should go to hovering while (m_flyingState != FlyingState::HOVERING) { waitMilliseconds(5); } // Return true on success, false on timeout. return !timedOut; } void Pilot::moveDirection(MoveDirection dir) { switch(dir) { #ifndef RESTRICTED_ALTITUDE #warning "HEIGHT IS UNRESTRICTED" case MoveDirection::UP: // NOTE: -negative numbers mean increase altitude! m_moveRelativeMetres(0.0f, 0.0f, -MOVEMENT_STEP); break; case MoveDirection::DOWN: m_moveRelativeMetres(0.0f, 0.0f, MOVEMENT_STEP); break; #else #warning "HEIGHT IS RESTRICTED" case MoveDirection::UP : case MoveDirection::DOWN : std::cout << "*** CHANGING ALTITUDE IS RESTRICTED!!! ***" << std::endl; break; #endif case MoveDirection::FORWARD: m_moveRelativeMetres(MOVEMENT_STEP, 0.0f, 0.0f); break; case MoveDirection::BACK: m_moveRelativeMetres(-MOVEMENT_STEP, 0.0f, 0.0f); break; case MoveDirection::RIGHT: m_moveRelativeMetres(0.0f, MOVEMENT_STEP, 0.0f); break; case MoveDirection::LEFT: m_moveRelativeMetres(0.0f, -MOVEMENT_STEP, 0.0f); break; default: break; } } void Pilot::setHeading(float heading) { m_moveRelativeMetres(0.0f, 0.0f, 0.0f, heading); } void Pilot::setFlyingState(int state, bool debug) { FlyingState temp = static_cast<FlyingState>(state); if (debug) { switch(temp) { case FlyingState::HOVERING: printf("change to Hovering State \n"); break; case FlyingState::FLYING: printf("change to Flying State \n"); break; case FlyingState::TAKING_OFF: printf("change to TakeOFF State\n"); break; case FlyingState::LANDING: printf("change to Landing State \n"); break; case FlyingState::LANDED: printf("change to Landed State\n"); break; case FlyingState::EMERGENCY: printf("change to Emergency State, Drone Landing.\n"); break; case FlyingState::MOTOR_SPINUP: printf("change to Spinup State, Drone Motors Spining up.\n"); break; default: printf("ERROR: Unhandled State=%d\n", state); break; } } m_flyingState = temp; } }
true
c7a83977841291fe3cf456b7467afbed4457cccc
C++
freezexpert/C
/sudoku.cpp
UTF-8
1,019
2.78125
3
[]
no_license
#include <stdio.h> char array1[13][13]={0}; int array2[10]={0}; int main() { for(int i=0;i<13;i++) { for(int j=0;j<13;j++) { scanf("%c",&array1[i][j]); } } int flag1=1; for(int i=0;i<13;i++){ for(int j=0;j<13;j++){ if(array1[i][j]=='x'){ flag1=0; break; } } } if(flag1) printf("solution, "); else printf("question, "); int flag2=1; for(int i=0;i<13;i++){ for(int j=0;j<13;j++){ array2[array1[i][j]-'1']++; for(int k=1;k<=9;k++){ if(array2[k]>1) flag2=0; } } } for(int i=0;i<13;i++){ for(int j=0;j<13;j++){ array2[array1[j][i]-'1']++; for(int k=1;k<=9;k++) if(array2[k]>1) flag2=0; } } if(flag2) printf("valid\n"); else printf("invalid\n"); return 0; }
true
aaf632eb334d323c8b61ae33bda7c0bb4b4a6095
C++
pimukthee/competitive-prog
/csacademy/numbers_tournament.cpp
UTF-8
1,734
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int arr[105][105], n; pair <int, int> ans[105]; bool cmp(pair <int, int> a, pair <int, int> b) { if (a.first != b.first) return a.first > b.first; else return a.second < b.second; } pair <int, int> find_bound(int i, int j) { int high = -1, low = -1; for (int it = 0; it < n; ++it) { if (binary_search(arr[j], arr[j] + n, arr[i][it])) { high = arr[i][it]; if (low == -1) { low = arr[i][it]; } } } return make_pair(low, high); } pair <int, int> start_game(int i, int j, pair <int,int> interval) { int scorei = 0, scorej = 0; for (int it = 0; it < n; ++it) { scorei += (arr[i][it] < interval.first || arr[i][it] > interval.second); scorej += (arr[j][it] < interval.first || arr[j][it] > interval.second); } return make_pair(scorei, scorej); } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { for (int j = 0; j < n; ++j) { scanf("%d", &arr[i][j]); } sort(arr[i], arr[i] + n); } for (int i = 1; i <= n; ++i) { ans[i].second = i; for (int j = i + 1; j <= n; ++j) { auto bound = find_bound(i, j); auto score = start_game(i, j, bound); if (score.first > score.second) { ans[i].first += 2; } else if (score.first == score.second) { ans[i].first++; ans[j].first++; } else { ans[j].first += 2; } } } sort(ans + 1, ans + n + 1, cmp); for (int i = 1; i <= n; ++i) { printf("%d\n", ans[i].second); } return 0; } map
true
e037ad38ec651b134be7de4f6b3e59c6f86657e6
C++
LeThaoHuyen/CS202-Group06-Road-Crossing
/Road Crossing Game/Road Crossing Game/Game2.cpp
UTF-8
3,458
2.921875
3
[]
no_license
#include "Game2.h" Game2::Game2() { screen.init(consoleWidth, consoleHeight, frameWidth, frameHeight); laneManager.init(1); player.init(96, 34); currentLevel = 1; m_isRunning = true; } Game2::Game2(int level) { screen.init(consoleWidth, consoleHeight, frameWidth, frameHeight); laneManager.init(level); player.init(96, 34); currentLevel = level; m_isRunning = true; } Game2::~Game2() { } void Game2::clearGame() { laneManager.clear(); } void Game2::drawGame(bool isLaneCarRed, bool isLaneTruckRed) { if (isLaneCarRed) laneManager.stopVehicles("car"); else laneManager.moveVehicles(currentLevel, "car"); if (isLaneTruckRed) laneManager.stopVehicles("truck"); else laneManager.moveVehicles(currentLevel, "truck"); laneManager.update(); laneManager.draw(screen); screen.drawTrafficLight(isLaneCarRed, isLaneTruckRed); Sleep(1100 - currentLevel*50); } void Game2::drawPeople() { player.selfDraw(screen); } void Game2::newGame(int level, int x, int y) { currentLevel = level; m_isRunning = true; laneManager.init(level); player.init(x, y); screen.displayMenu(); screen.drawFrame(); player.selfDraw(screen); screen.showLevel(level); drawGame(false, false); } void Game2::pauseGame() { m_isRunning = false; } void Game2::resumeGame() { m_isRunning = true; } void Game2::saveGame() { screen.displayConfirmSave(); int key; key = _getch(); if (key == 121) { ofstream out; out.open("save.txt"); if (out.is_open()) { out << currentLevel << " " << player.getX() << " " << player.getY(); out.close(); screen.announceComplete(); Sleep(300); } } screen.deleteAnnounceFrame(); } void Game2::autoSave() { ofstream out; out.open("save.txt"); if (out.is_open()) { out << currentLevel << " " << 96 << " " << 34; out.close(); } } bool Game2::exitGame() { screen.displayConfirmExit(); int key; key = _getch(); if (key == 121) { screen.clearScreen(); return true; } else { screen.deleteAnnounceFrame(); return false; } } void Game2::loadGame() { ifstream in; in.open("save.txt"); if (in.is_open()) { int level, x, y; if (in >> level >> x >> y) { newGame(level, x, y); } else { // if no saved game, new game at level 1 player.init(96, 34); newGame(1); } in.close(); } } bool Game2::isWin() { if (player.getY() <= 6 && player.getY() >= 1) return true; return false; } void Game2::processWin() { PlaySound(TEXT("Sound/LevelUp.wav"), NULL, SND_ASYNC); if (currentLevel!= MAX_LEVEL) { currentLevel++; screen.printCongrat(false); } else if (currentLevel == MAX_LEVEL) { screen.printCongrat(true); } } void Game2::processLose() { if (laneManager.checkCollision(player, true)) { PlaySound(TEXT("Sound/GameOver.wav"), NULL, SND_ASYNC); screen.printGameover(); } } void Game2 :: printCongrat(bool isMaxLevel) { screen.printCongrat(isMaxLevel); } void Game2::printGameover() { screen.printGameover(); } bool Game2::checkCollision(bool playSound) { return laneManager.checkCollision(player, playSound); } void Game2::displayMainMenu() { screen.displayMainMenu(); } void Game2::displayMenu() { screen.displayMenu(); } void Game2::showOption(int option, int key) { if (key == key_Enter) { screen.showChoice(option); } else { screen.showOption(option); } } void Game2::resetGame() { screen.displayConfirmReset(); int key; key = _getch(); if (key == 121) { newGame(currentLevel); } screen.deleteAnnounceFrame(); }
true
9c39db079edd0b43828992686f67a5d20bfd670f
C++
Shaik-Avaies/Algo-
/Searching & Sorting(Divide and Conquer/_KTH ROOT.cpp
UTF-8
567
2.71875
3
[]
no_license
#include<iostream> #include<math.h> #define ll long long using namespace std; bool isValid(ll n,ll k,ll mid){ if(pow(mid,k) <= n) return true; else return false; } int main() { ll t; cin>>t; while(t--){ ll n,k; cin>>n>>k; ll s = 1, e = n; ll final_ans = 0; while(s <= e){ int mid = (s+e)/2; if(isValid(n,k,mid)){ final_ans = mid; s = mid + 1; } else e = mid - 1; } cout<<final_ans<<endl; } return 0; }
true
3b0f6f987cebe8eb20ae8ceba14eeccec66d15eb
C++
mrfade/depth-camera-transformer
/src/FilterPipe.cpp
UTF-8
341
2.671875
3
[ "MIT" ]
permissive
#include"FilterPipe.h" #include<vector> void FilterPipe::addFilter(PointCloudFilter* filter) { filters.push_back(filter);//!adds filter to the filters vector } void FilterPipe::filterOut(PointCloud& points) { for (int i = 0; i < filters.size(); i++) { filters[i]->filter(points);//!filters pointcloud with using filters at vector } }
true
26416c0b44a4bc942786557790e97c889efabf49
C++
xGreat/CppNotes
/src/algorithms/data_structures/string/num_to_english_string.hpp
UTF-8
2,859
3.34375
3
[ "MIT" ]
permissive
#ifndef CPPNOTESMAIN_NUM_TO_ENGLISH_STRING_HPP #define CPPNOTESMAIN_NUM_TO_ENGLISH_STRING_HPP /* */ #include <string> #include <vector> #include <algorithm> namespace Algo::DS::String { class ConvertNumToEnglishStr { enum Section { first = 0, thousand, million, billion }; const std::vector<std::string> first_ten = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; const std::vector<std::string> teens = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; const std::vector<std::string> second_ten = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; const std::vector<std::string> section_names = {"", "Thousand", "Million", "Billion"}; std::string thousand_to_string(int num, const Section section) { if (num == 0) { return {}; } std::vector<std::string> parts; if (num >= 100) { parts.push_back(first_ten[static_cast<size_t>(num / 100)]); parts.push_back("Hundred"); num %= 100; } if (num >= 20) { parts.push_back(second_ten[static_cast<size_t>(num / 10)]); num %= 10; } if (num >= 10 && num <= 19) { parts.push_back(teens[static_cast<size_t>(num - 10)]); num = 0; } if (num > 0 && num <= 9) { parts.push_back(first_ten[static_cast<size_t>(num)]); num = 0; } if (section > first) { parts.push_back(section_names[static_cast<size_t>(section)]); } auto result = std::accumulate( std::next(parts.begin()), parts.end(), parts.front(), [](const auto& left, const auto& right) { return left + " " + right; }); return result; } public: std::string convert(int num) { if (num == 0) { return "Zero"; } std::string result; Section section = Section::first; while (num > 0) { auto thousand = num % 1000; auto thousand_str = thousand_to_string(thousand, section); if (!thousand_str.empty()) { result = thousand_str + (result.empty() ? "" : " " + result); } num /= 1000; section = static_cast<Section>(static_cast<int>(section) + 1); } return result; } }; } #endif //CPPNOTESMAIN_NUM_TO_ENGLISH_STRING_HPP
true
2fd919776f537bffbce2395ae31b05ed34b7b230
C++
benoitk/COT
/tests/auto/keyboard/keyboardnormalbutton/keyboardnormalbuttontest.cpp
UTF-8
2,321
2.703125
3
[]
no_license
#include <qtest.h> #include <qtestmouse.h> #include <QSignalSpy> #include "CKeyboardNormalButton.h" #include <QObject> class KeyboadNormalButtonTest : public QObject { Q_OBJECT private slots: void shouldHaveDefaultValue(); void shouldAssignCharacter(); void shouldEmitPressSignal(); void shouldEmitClickSignal(); void shouldEmitReleasedSignal(); }; void KeyboadNormalButtonTest::shouldHaveDefaultValue() { CKeyboardNormalButton button; QVERIFY(button.character().isNull()); } void KeyboadNormalButtonTest::shouldAssignCharacter() { CKeyboardNormalButton button; QChar character(QLatin1Char('1')); button.setCharacter(character); QCOMPARE(button.character(), character); character = QLatin1Char('2'); button.setCharacter(character); QCOMPARE(button.character(), character); } void KeyboadNormalButtonTest::shouldEmitPressSignal() { CKeyboardNormalButton button; //We don't have default character. QSignalSpy spy(&button, SIGNAL(pressed(QChar))); QTest::mousePress(&button, Qt::LeftButton); QCOMPARE(spy.count(), 0); button.setCharacter(QLatin1Char('1')); QTest::mousePress(&button, Qt::LeftButton); QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(0).value<QChar>(), QChar(QLatin1Char('1'))); } void KeyboadNormalButtonTest::shouldEmitClickSignal() { CKeyboardNormalButton button; //We don't have default character. QSignalSpy spy(&button, SIGNAL(clicked(QChar))); QTest::mouseClick(&button, Qt::LeftButton); QCOMPARE(spy.count(), 0); button.setCharacter(QLatin1Char('1')); QTest::mouseClick(&button, Qt::LeftButton); QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(0).value<QChar>(), QChar(QLatin1Char('1'))); } void KeyboadNormalButtonTest::shouldEmitReleasedSignal() { //FIXME /* CKeyboardNormalButton button; //We don't have default character. QSignalSpy spy(&button, SIGNAL(released(QChar))); QTest::mouseRelease(&button, Qt::LeftButton); QCOMPARE(spy.count(), 0); button.setCharacter(QLatin1Char('1')); QTest::mouseRelease(&button, Qt::LeftButton); QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).at(0).value<QChar>(), QChar(QLatin1Char('1'))); */ } QTEST_MAIN(KeyboadNormalButtonTest) #include "keyboardnormalbuttontest.moc"
true
239aa56c511c48e9f86941532efb5a4ba39fc442
C++
matinjun/leetcode---
/1.ไธคๆ•ฐไน‹ๅ’Œ.cpp
UTF-8
932
3.1875
3
[]
no_license
/* * @lc app=leetcode.cn id=1 lang=cpp * * [1] ไธคๆ•ฐไน‹ๅ’Œ */ // @lc code=start #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { // vector<int> result(2); // for(int i = 0; i < nums.size(); ++i) { // for(int j = i + 1; j < nums.size(); ++j) { // if(nums[i] + nums[j] == target) { // result[0] = i; // result[1] = j; // break; // } // } // } // return result; unordered_map<int, int> hashtable; for(int i = 0; i < nums.size(); ++i) { if(hashtable.find(target - nums[i]) != hashtable.end()) { return {i, hashtable[target - nums[i]]}; } hashtable[nums[i]] = i; } return {}; } }; // @lc code=end
true
c5725031e5ecbc5fe9c85edbf2dd037b610c7a96
C++
aks14y/OOT
/program14.cpp
UTF-8
753
3.5625
4
[]
no_license
#include<iostream> using namespace std; class student { public: int rollno; void read() { cout<<"Enter the rollno : "; cin>>rollno; } }; class test:public student { public: int m1,m2; void read1() { cout<<"Enter the marks :"; cin>>m1>>m2; } }; class sports { public: int weightage; void sports_weightage() { cout<<"Enter the weightage :"; cin>>weightage; } }; class result:public test ,public sports { public: int sum; void display() { sum=m1+m2+weightage; cout<<"Roll no : "<<rollno<<"\nMark1 :"<<m1<<"\nMark2 : "<<m2<<"\nWeightage : "<<weightage<<"\nThe final result : "<<sum<<endl; } }; int main() { result r; r.read(); r.read1(); r.sports_weightage(); r.display(); return 0; }
true
12830813e3949c333d793f3c17fa8849889e6b1a
C++
lifujie/Misc
/Contest/BDstar/2012่ต„ๆ ผ/2.cpp
UTF-8
487
2.734375
3
[]
no_license
#include <iostream> using namespace std; int foo(int set[21],int k) { int an=0; for(int i=0;i!=k;i++) an+=set[i]; an=an-k+1; return an; } int main() { int answer[21]; int times=0; cin>>times; for(int run=0;run!=times;run++) { int k=0; cin >> k; int set[21]={0}; int n,cnt=0; while(cnt!=k &&cin>> n) { set[cnt]=n; cnt++; } answer[run] = foo(set,k); } for(int i=0;i!=times;i++) cout <<answer[i] <<endl; system("pause"); return 0; }
true
94e7561513ed9dfce30b343d63d4e0b3dfe91823
C++
masaers/cmdlp
/options.hpp
UTF-8
4,450
2.59375
3
[ "MIT" ]
permissive
#ifndef COM_MASAERS_CMDLP_OPTIONS_HPP #define COM_MASAERS_CMDLP_OPTIONS_HPP #include "cmdlp.hpp" #include "iooption.hpp" #include "paragraph.hpp" // c++ #include <vector> #include <string> #include <iostream> #include <fstream> // c #include <cstdlib> namespace com { namespace masaers { namespace cmdlp { namespace options_helper { template<typename me_T, typename parser_T> inline void init_bases(me_T&, parser_T&) {} template<typename me_T, typename parser_T, typename T, typename... Ts> inline void init_bases(me_T& me, parser_T& p) { static_cast<T&>(me).init(p); init_bases<me_T, parser_T, Ts...>(me, p); } } // namespace options_helper class options_config { public: options_config() : dumpto_m(true), config_m(true), help_m(true), argdesc_m(), preamble_m(), postamble_m() {} options_config& no_dumpto() { dumpto_m = false; return *this; } options_config& no_config() { config_m = false; return *this; } options_config& no_help() { help_m = false; return *this; } options_config& argdesc (const std::string& desc) { argdesc_m = desc; return *this; } options_config& preamble (const std::string& text) { preamble_m = text; return *this; } options_config& postamble(const std::string& text) { postamble_m = text; return *this; } const bool& dumpto() const { return dumpto_m; } const bool& config() const { return config_m; } const bool& help() const { return help_m; } const std::string& argdesc() const { return argdesc_m; } const std::string& preamble() const { return preamble_m; } const std::string& postamble() const { return postamble_m; } private: bool dumpto_m; bool config_m; bool help_m; std::string argdesc_m; std::string preamble_m; std::string postamble_m; }; template<typename... options_T> class options : public options_T... { public: inline options(const int argc, const char** argv, const options_config& cfg); inline options(const int argc, char** argv, const options_config& cfg) : options(argc, (const char**)argv, cfg) {} inline options(const int argc, const char** argv) : options(argc, argv, options_config()) {} inline options(const int argc, char** argv) : options(argc, (const char**)argv, options_config()) {} inline operator bool() const { return ! help_needed(); } inline int exit_code() const { return error_count_m == 0 ? EXIT_SUCCESS : EXIT_FAILURE; } std::vector<std::string> args; private: inline bool help_needed() const { return help_requested_m || error_count_m != 0; } bool help_requested_m; std::size_t error_count_m; }; // options } } } template<typename... options_T> com::masaers::cmdlp::options<options_T...>::options(const int argc, const char** argv, const options_config& cfg) : options_T()..., help_requested_m(false), error_count_m(0) { using namespace std; optional_ofile dumpto; config_files configs; parser p(cerr); options_helper::init_bases<options<options_T...>, parser, options_T...>(*this, p); if (cfg.dumpto()) { p.add(make_knob(dumpto)) .name("dumpto") .desc("Dumps the parameters, as undestood by the program, to a config file " "that can later be used to rerun with the same settings. Leave empty to not dump. " "Use '-' to dump to standard output.") .fallback() .is_meta() ; } if (cfg.config()) { p.add(make_knob(configs)) .name("config") .desc("Read parameters from the provided file as if they were provided " "in the same position on the command line.") ; } if (cfg.help()) { p.add(make_onswitch(help_requested_m)) .name('h', "help") .desc("Prints the help message and exits normally.") .is_meta() ; } error_count_m += p.parse(argc, argv, back_inserter(args)); error_count_m += p.validate(); error_count_m += p.additional_errors(); if (help_needed()) { cerr << endl << "usage: " << argv[0] << p.usage(); if (! cfg.argdesc().empty()) { cerr << ' ' << cfg.argdesc(); } cerr << endl << endl; if (! cfg.preamble().empty()) { const auto p = paragraph(cerr, 72, 4, 2); cerr << cfg.preamble() << endl; } cerr << p.help() << endl; if (! cfg.postamble().empty()) { const auto p = paragraph(cerr, 72, 4, 2); cerr << cfg.postamble() << endl; } } if (dumpto) { p.dumpto_stream(*dumpto, false); } } #endif
true
b8883dc05c696fd416abf4f04ff420aafb4fc43b
C++
eric-plus-plus/arduino-demo-simon
/simon-says-2/simon-says-2.ino
UTF-8
5,144
3
3
[ "MIT" ]
permissive
/* * Simon Says 2 * * This version of the simon says code uses more * features of the C language than the previous * version. It functions the same as * "simon-says.ino", but has good programming * practices (in my opinion), making it much more * readable. * * It is still simple code that doesn't implement * a time limit or account for pressing multiple * buttons at once. * * Eric Rackelin * 9/20/2021 */ // define LED pins (makes it easier to read and to // change pins later) #define P_LED1 7 #define P_LED2 6 #define P_LED3 5 #define P_LED4 4 // define button pins #define P_B1 12 #define P_B2 11 #define P_B3 10 #define P_B4 9 // define animation lengths #define TIME_ON 500 #define TIME_OFF 250 #define TIME_ANIM 100 #define TIME_DEBOUNCE 100 #define TIME_BREAK 1000 // time between new games and turns // declare functions here so they can be used in // loop(). We wait until later to define them. void allOn(); void allOff(); void oneOn(); // Note: you could declare all your variables here if // you want. However, the C++ standard (which // Arduino uses) is to declare them as late as // possible. This is because there may be a cost to // declaring them in special cases. If you're using // pure C, then it doesn't matter. void setup() { // set up outputs (LED pins) pinMode(P_LED1, OUTPUT); pinMode(P_LED2, OUTPUT); pinMode(P_LED3, OUTPUT); pinMode(P_LED4, OUTPUT); // set up inputs (button pins) pinMode(P_B1, INPUT); digitalWrite(P_B1, HIGH); pinMode(P_B2, INPUT); digitalWrite(P_B2, HIGH); pinMode(P_B3, INPUT); digitalWrite(P_B3, HIGH); pinMode(P_B4, INPUT); digitalWrite(P_B4, HIGH); // initalize the random number generator randomSeed(analogRead(0)); // The seed is based on the voltage of a pin with // no connections. This means we have no idea // what the seed is, as it's basically acting as // an antenna, which picks up random noise from // the environment. } void loop() { // new game animation (blink all leds 3 times) allOn(); delay(TIME_ANIM); allOff(); delay(TIME_ANIM); allOn(); delay(TIME_ANIM); allOff(); delay(TIME_ANIM); allOn(); delay(TIME_ANIM); allOff(); delay(TIME_BREAK); // start the game int moves[100]; // Array to hold the sequence of moves int numMoves = 0; // Tracks how many moves we're at bool lost = false; // flag for when the player loses while (!lost) { // add a move to the pattern moves[numMoves] = random(4); numMoves += 1; // play the pattern for the player to see for (int i = 0; i < numMoves; i = i+1) { // turn on this move's LED for half a second switch (moves[i]) { case 0: digitalWrite(P_LED1, HIGH); break; case 1: digitalWrite(P_LED2, HIGH); break; case 2: digitalWrite(P_LED3, HIGH); break; case 3: digitalWrite(P_LED4, HIGH); break; } delay(TIME_ON); allOff(); delay(TIME_OFF); } // player's turn to repeat the pattern for (int i = 0; i < numMoves; i = i+1) { // wait for a button to be pressed // turn on the corresponding LED when it is int selection; while (1) { if (!digitalRead(P_B1)) { selection = 0; digitalWrite(P_LED1, HIGH); break; } else if (!digitalRead(P_B2)) { selection = 1; digitalWrite(P_LED2, HIGH); break; } else if (!digitalRead(P_B3)) { selection = 2; digitalWrite(P_LED3, HIGH); break; } else if (!digitalRead(P_B4)) { selection = 3; digitalWrite(P_LED4, HIGH); break; } } delay(TIME_ON); // debounce // wait until all buttons are released while (!digitalRead(P_B1) && !digitalRead(P_B2) && !digitalRead(P_B3) && !digitalRead(P_B4)) {} allOff(); delay(TIME_DEBOUNCE); // debounce // check to see if the wrong button was pressed if (selection != moves[i]) { lost = true; break; // exit the for loop } } // wait a second before showing the next pattern delay(TIME_BREAK); } // the game has been lost, play game over animation oneOn(P_LED1); delay(TIME_ANIM); oneOn(P_LED2); delay(TIME_ANIM); oneOn(P_LED3); delay(TIME_ANIM); oneOn(P_LED4); delay(TIME_ANIM); allOff(); delay(TIME_BREAK); } // turns off all LEDs void allOff() { digitalWrite(P_LED1, LOW); digitalWrite(P_LED2, LOW); digitalWrite(P_LED3, LOW); digitalWrite(P_LED4, LOW); } // turns on all LEDs void allOn() { digitalWrite(P_LED1, HIGH); digitalWrite(P_LED2, HIGH); digitalWrite(P_LED3, HIGH); digitalWrite(P_LED4, HIGH); } // turns off all LEDs except for one specified by i void oneOn(int i) { allOff(); // we can turn everything off right before. // It's not efficient, but it's still much faster // than any human would be able to notice digitalWrite(i, HIGH); }
true
20687cc6930d54744d01b00c8ee2977a488e685d
C++
Yami-Karen/Week2
/A1.cpp
UTF-8
742
2.703125
3
[]
no_license
#include <iostream> using namespace std; int main() { //con dem voi so lan lap nhat dinh for (int i = 1;i <= 100;i++) if (i%2 == 0) cout << i << " "; cout << endl; //khong xac dinh so lan lap int i = 0; while (true) { i++; if (i%2 == 0) cout << i << " "; if (i == 100) break; } cout << endl; //chi su dung dieu kien thoat (toi uu nhat) i = 0; while (i < 100) { i++; if (i%2 == 0) cout << i << " "; } cout << endl; // dung break i = 0; while (true) { i++; if (i%2 == 0) cout << i << " "; if (i == 100) break; } cout << endl; //dung continue i = 0; while (true) { i++; if (i%2 == 0) cout << i << " "; if (i < 100) continue;else break; } return 0; }
true
b5979a2464298fa57e1c68ede4afb4d7acb404c0
C++
fhmunna/rEPaRDUINO
/PIR_Email/PIR_Email.ino
UTF-8
4,057
2.5625
3
[]
no_license
#include <SPI.h> #include <Ethernet.h> byte mac[] = { 0xDE, 0xAD, 0xBE, 0xAF, 0xCE, 0xDD }; // whatever mac you want byte ip[] = { 192, 168, 0, 109}; byte server[] = { 203, 188, 201, 253 }; // Mail server address smtp.mail.yahoo.com.tw) Client client(server, 25); // yahoo's mobile smtp server ip/port 587 ///////////////////////////// //VARS //the time we give the sensor to calibrate (10-60 secs according to the datasheet) int calibrationTime = 30; //the time when the sensor outputs a low impulse long unsigned int lowIn; //the amount of milliseconds the sensor has to be low //before we assume all motion has stopped long unsigned int pause = 5000; boolean lockLow = true; boolean takeLowTime; int pirPin = 3; //the digital pin connected to the PIR sensor's output int ledPin = 13; int nPIR_detect; void setup() { Ethernet.begin(mac, ip); Serial.begin(57600); pinMode(pirPin, INPUT); digitalWrite(pirPin, LOW); //give the sensor some time to calibrate Serial.print("calibrating sensor "); for(int i = 0; i < calibrationTime; i++){ Serial.print("."); delay(1000); } Serial.println(" done"); Serial.println("SENSOR ACTIVE"); delay(50); nPIR_detect = 0; } void loop() { delay(1000); if(PIR_detected()) // PIR : HIGH { if (client.available()) { char c = client.read(); Serial.print(c); } Serial.println("connecting..."); if (client.connect()) { Serial.println("connected"); client.println("EHLO smtp.mail.yahoo.com.tw"); // client.println("AUTH PLAIN AHNpbm9jZ3RjbGVuQHlhaH9vLmNvbSgwet323tcxYTU="); // example client.println("AUTH PLAIN *************************************************="); // replace the **'s with your auth info from the perl script. client.println("MAIL FROM:<**@yahoo.com.tw>"); // replace the ** with your mail address client.println("RCPT TO:<**@gmail.com>"); // replace the ** with to mail address client.println("DATA"); client.println("From: <**@yahoo.com.tw>"); client.println("TO: <**@gmail.com>"); client.println("SUBJECT: Something has been detected by PIR"); client.println(); client.println("This is PIR testing."); client.println("Warning: detected something!!"); client.println("."); client.println("."); delay(1000); client.stop(); Serial.println("mail sent!!"); delay(30000); } else { Serial.println("connection failed"); } } } boolean PIR_detected() { boolean bPIR; if(digitalRead(pirPin) == HIGH){ digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state if(lockLow){ //makes sure we wait for a transition to LOW before any further output is made: lockLow = false; Serial.println("---"); Serial.print("motion detected at "); Serial.print(millis()/1000); Serial.println(" sec"); delay(50); } takeLowTime = true; bPIR = true; } if(digitalRead(pirPin) == LOW){ digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state if(takeLowTime){ lowIn = millis(); //save the time of the transition from high to LOW takeLowTime = false; //make sure this is only done at the start of a LOW phase } //if the sensor is low for more than the given pause, //we assume that no more motion is going to happen if(!lockLow && millis() - lowIn > pause){ //makes sure this block of code is only executed again after //a new motion sequence has been detected lockLow = true; Serial.print("motion ended at "); //output Serial.print((millis() - pause)/1000); Serial.println(" sec"); delay(50); } bPIR = false; } return bPIR; }
true
59fc814eb932d38d4aa86cb21952284f7ebe1269
C++
MG-RAST/clustgun
/hat.hpp
UTF-8
12,858
2.953125
3
[ "BSD-2-Clause" ]
permissive
#ifndef clustgun_hat_h #define clustgun_hat_h #include <omp.h> #include "basic_tools_omp.hpp" class ReaderWriterLock; template <class T> class HashedArrayTree { // powers of two 2^20=1048576 protected: vector<T * > *hash; // the inner arrays will be fixed size, the outer vector flexibel size_t arrayChunkSize; // choose something like 1MB size_t two_power; size_t mod_mask; bool initialize_elements; T initialization_value; bool size_is_capacity; size_t currentArray; size_t nextFreePos; public: #ifdef DEBUG string name; #endif HashedArrayTree<T> (bool size_is_capacity, size_t two_power) { this->initialize_elements = false; init(size_is_capacity, two_power); } HashedArrayTree<T> (bool size_is_capacity, size_t two_power, T initialization_value) { this->initialize_elements = true; this->initialization_value = initialization_value; init(size_is_capacity, two_power); } void init(bool size_is_capacity, size_t two_power) { this->size_is_capacity = size_is_capacity; this->two_power = two_power; this->arrayChunkSize = (size_t) pow((double)2, (double)two_power); this->mod_mask=this->arrayChunkSize -1 ; // e.g. converts 1000 into 111 #ifdef DEBUG try { #endif hash = new vector<T * >(); #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (hash HAT) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif currentArray = 0; nextFreePos = 0; } ~HashedArrayTree<T>() { //cout << "XX destructor" << this->name << endl; //cout << hash->size() << endl; for (int i = 0; i < (int) hash->size(); ++i){ //cout << "currentArray:" << currentArray << endl; //cout << "delete: " << i << " " << (*hash)[i] << endl; //cout << "sizeof: " << i << " " << sizeof((*hash)[i]) << endl; delete [] (*hash)[i]; //(*hash)[i]=NULL; } delete hash; } void deleteContentPointers() { //cout << "XX deleteContentPointers" << endl; //vector<T>::iterator vec_it; //typename vector<T * >::iterator vec_it; //cout << this->name << endl; if (!initialize_elements) { cerr << "error: deleting elements" << endl; return; } size_t effective_size; if (size_is_capacity) { effective_size = this->capacity(); } else { effective_size = this->size(); } for (size_t i = 0 ; i < effective_size; ++i ){ #ifdef DEBUG try { if ( this->at(i) != this->initialization_value) { delete this->at(i); } } catch (out_of_range& oor) { cerr << "Out of Range error:(HAT: this->at(i) != this->initialization_value) " << oor.what() << endl; exit(1); } #else if ( (*this)[i] != this->initialization_value) { delete (*this)[i]; } #endif } } void deleteContentPairOfPointers() { //cout << "XX deleteContentPairOfPointers" << endl; //vector<T>::iterator vec_it; //typename vector<T * >::iterator vec_it; //int count = 0; //cout << "-------------2 " << *(this->at(0).second) << endl; for (int i = 0; i < currentArray ; ++i){ for (int j = 0 ; j < arrayChunkSize; ++j) { //count++; //cout << "want deleteA: " << i << "," << j << endl; delete (*hash)[i][j].first; delete (*hash)[i][j].second; } } //i = currentArray-1 (last array) for (int j = 0 ; j < nextFreePos; ++j) { //count++; //cout << "want deleteB: " << currentArray << "," << j << endl; //cout << hash->size() << endl; //cout << *((*hash)[currentArray][j].second) << endl; delete (*hash)[currentArray][j].first; delete (*hash)[currentArray][j].second; } //cout << "Number of pairs deleted: " << count << endl; } size_t size() { if (size_is_capacity) { return capacity(); } return ((currentArray)*arrayChunkSize + nextFreePos); } size_t capacity() { if (hash->size()*arrayChunkSize != hash->size() << two_power) { // TODO cerr << "hash->size()*arrayChunkSize != hash->size() << two_power" << endl; exit(1); } return hash->size() << two_power; // should be same as multiplying with "2^two_power" //return hash->size()*arrayChunkSize; } void reserve (size_t new_min_size) { // size, not position !! //cerr << "t: " << omp_get_thread_num() << " reserve " << new_min_size << endl; size_t array = (new_min_size-1) >> two_power; while (capacity() < new_min_size) { T * small_vec; #ifdef DEBUG try { #endif small_vec = new T [arrayChunkSize]; #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT reserve) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif if (initialize_elements) { for (size_t i =0; i < arrayChunkSize; ++i) { small_vec[i]=this->initialization_value; } } //cout << "reserve push A " << small_vec << endl; #ifdef DEBUG try { #endif hash->push_back(small_vec); #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT reserve, push_back) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif } if (array >= hash->size() ) { // hash->size() needs to be bigger than array // TODO in debug cerr << "error: (reserve HAT) array+ >= hash->size() " << endl; cerr << "array: " << array << endl; cerr << "hash->size(): " << hash->size() << endl; cerr << "new_min_size: " << new_min_size << endl; cerr << "pos, new_min_size-1: " << new_min_size-1 << endl; cerr << "capacity(): " << capacity() << endl; exit(1); } } T& at(size_t x){ // boundary check size_t array = x >> two_power; // shifts the insignificant bits away, e.g. two_power is 20 for one 1MB size_t arraypos = x & this->mod_mask; // I get the least significant bits for local array if (not size_is_capacity) { // check size ! // reserve(x); if (array > currentArray) { cerr << "array > currentArray" << endl; exit(1); } if (array == currentArray && arraypos >= nextFreePos) { cerr << "arraypos >= nextFreePos" << endl; cerr << "array: " << array << endl; cerr << "arraypos: " << arraypos << endl; cerr << "x: " << x << endl; cerr << "size: " << this->size() << endl; exit(1); } } else { // check capacity! if (array >= hash->size()) { // DO NOT CONFUSE WITH this->size() !!!! cerr << "array > hash->size()" << endl; cerr << "array: " << array << endl; cerr << "hash->size(): " << hash->size() << endl; cerr << "arraypos: " << arraypos << endl; cerr << "x: " << x << endl; cerr << "t: " << omp_get_thread_num() << endl; exit(1); } if (arraypos >= arrayChunkSize) { cerr << "exit: arraypos >= arrayChunkSize" << endl; exit(1); } } //} T* yyy; try { yyy =hash->at(array); } catch (out_of_range& oor) { cerr << "Out of Range error:(HAT: yyy =hash->at(array); " << oor.what() << endl; cerr << "arraypos >= nextFreePos" << endl; cerr << "array: " << array << endl; cerr << "arraypos: " << arraypos << endl; cerr << "x: " << x << endl; cerr << "size: " << this->size() << endl; cerr << "hash->size(): " << hash->size() << endl; exit(1); } T& xxx = yyy[arraypos ]; return xxx; //return (*hash)[x >> two_power][ x & this->mod_mask]; } inline T& operator[] (size_t x) { #ifdef DEBUG return this->at(x); #endif return (*hash)[x >> two_power][ x & this->mod_mask]; } #ifdef DEBUG int push_back(T element) { #else void push_back(T element) { #endif //cerr << "lastPos: " << nextFreePos << endl; T * small_vec; if (currentArray == 0 && nextFreePos == 0) { #ifdef DEBUG try { #endif small_vec = new T [arrayChunkSize]; //cout << "A create array of size " << arrayChunkSize << endl; #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif if (this->initialize_elements) { for (size_t i =0; i < arrayChunkSize; ++i) { small_vec[i]=this->initialization_value; } } //cout << "new vector" << endl; #ifdef DEBUG try { #endif hash->push_back(small_vec); #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT push_back,push_back) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif //cout << hash->size() << endl; //cout << "push was successful" << endl; // choose to create new or use old vector: } else if (nextFreePos >= arrayChunkSize) { // new vector //cout << "1lastPos: " << nextFreePos << endl; if (hash->size()-1 <= (currentArray+1) ) { // it might have been reserved earlier #ifdef DEBUG try { #endif small_vec = new T [arrayChunkSize]; //cout << "B create array of size " << arrayChunkSize << endl; #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif if (this->initialize_elements) { for (size_t i =0; i < arrayChunkSize; ++i) { small_vec[i]=this->initialization_value; } } //cout << "new vector!" << endl; #ifdef DEBUG try { #endif hash->push_back(small_vec); #ifdef DEBUG } catch (bad_alloc& ba) { cerr << "error: (HAT push_back, push_back) bad_alloc caught: " << ba.what() << endl; exit(1); } #endif } //cout << "hash->size(): " << hash->size() << endl; currentArray++; nextFreePos=0; } else { // old vector //cout << "old vector: " << currentArray << endl; small_vec = (*hash)[currentArray]; //cout << "done" << endl; } //cout << "write: " << nextFreePos << endl; small_vec[nextFreePos]=element; //*this)[nextFreePos] = element; //cout << "small_vec->size(): " << small_vec->size() << endl; nextFreePos++; #ifdef DEBUG return nextFreePos-1; #endif } }; class HashedArrayTreeString : public HashedArrayTree<char> { public: HashedArrayTreeString(size_t two_power) : HashedArrayTree<char> (false, two_power) { reserve(1); }; char * addSequence(const char * seq, int seqlen) { if (seqlen+1 >= (int) arrayChunkSize) { cerr << "error: seqlen+1 >= arrayChunkSize" << endl; cerr << " input sequence is bigger than internal arrays, please increase default array size" << endl; exit(1); } #ifdef DEBUG if ((int)strlen(seq) != seqlen) { cerr << "error: strlen(seq) != seqlen: "<< strlen(seq) << " " << seqlen << endl; exit(1); } #endif if (nextFreePos+seqlen+1 >= arrayChunkSize) { // go in next chunk, leave rest of current array empty... //cout << endl << seq <<endl; //cout << "nextFreePos: " << nextFreePos << endl; //cout << "arrayChunkSize: " << arrayChunkSize << endl; //cout << "seqlen: " << seqlen << endl; //cout << "this->size(): " << this->size() << endl; reserve(hash->size()*arrayChunkSize + 1); currentArray++; nextFreePos = 0; } char * small_vec = (*hash)[currentArray]; char * buffer_start = &small_vec[nextFreePos]; //memcpy(buffer_start, seq, seqlen) strcpy(buffer_start, seq); nextFreePos += seqlen+1; return buffer_start; } char * addData(const char * seq, int datalen) { if (datalen >= (int) arrayChunkSize) { cerr << "error: seqlen+1 >= arrayChunkSize" << endl; cerr << " input sequence is bigger than internal arrays, please increase default array size" << endl; exit(1); } if (nextFreePos+datalen >= arrayChunkSize) { // go in next chunk, leave rest of current array empty... //cout << endl << seq <<endl; //cout << "nextFreePos: " << nextFreePos << endl; //cout << "arrayChunkSize: " << arrayChunkSize << endl; //cout << "seqlen: " << seqlen << endl; //cout << "this->size(): " << this->size() << endl; reserve(hash->size()*arrayChunkSize + 1); currentArray++; nextFreePos = 0; } char * small_vec = (*hash)[currentArray]; char * buffer_start = &small_vec[nextFreePos]; memcpy(buffer_start, seq, datalen); // datalen would include terminal \0 // old: strcpy(buffer_start, seq); nextFreePos += datalen; return buffer_start; } }; template <class T> class HashedArrayTree_rwlock : public HashedArrayTree<T>, public ReaderWriterLock { public: HashedArrayTree_rwlock<T>(bool size_is_capacity, int thread_count): HashedArrayTree<T>(), ReaderWriterLock(thread_count) {}; HashedArrayTree_rwlock<T>(bool size_is_capacity, int thread_count, size_t two_power): HashedArrayTree<T>(size_is_capacity, two_power), ReaderWriterLock(thread_count) {}; HashedArrayTree_rwlock<T>(bool size_is_capacity, int thread_count, size_t two_power, T initialization_value): HashedArrayTree<T>(size_is_capacity, two_power, initialization_value), ReaderWriterLock(thread_count) {}; }; #endif
true
30299bc14d145060a1446588e30005953cf0b8d7
C++
Shubham1320/Data-Structure-Assignments
/Data Structures/Expression Tree/expression.h
UTF-8
1,087
3
3
[]
no_license
/* * Author: Shubham Yewalekar * Div : SE 9 H9 * Roll No : 23182 * File Name : Expression Header File */ #ifndef IMPLEMENT_H_ #define IMPLEMENT_H_ class expression { private: char *exp; int exp_size; int postFix_size; char *postFix; char *preFix; public: expression();//constructor void setExp();//input infix expression void inToPostFix();//infix to postfix conversion void inToPreFix();//infix to prefix conversion float eval_postExp();//function to evaluate postfix expression float eval_preExp();//function to evaluate prefix expression int isOperator(char temp);//function to check if the entered character is an operator int isOperand(char temp); int isValid();//validations int isValid1(); int priority(char check);//function to check priority of operators int associativity(char temp);//function to check associativity of operators float calculate(char temp,float o1,float o2); void printExp(); void printPostFix(); void printPreFix(); int getPostSize(); char* getPostFix(); ~expression(); }; #endif /* IMPLEMENT_H_ */
true
2a30813548739551228b97fb46a38ef4ef8d3d85
C++
coneco/PAT-Advanced-Practice
/1029 Median/median.cpp
UTF-8
733
2.84375
3
[]
no_license
#include <cstdio> #define MAX 1000000 int main() { int n1, n2; int* s1 = new int[MAX]; int* s2 = new int[MAX]; std::scanf("%d", &n1); for (int i = 0; i < n1; ++i) { std::scanf("%d", s1 + i); } std::scanf("%d", &n2); for (int i = 0; i < n2; ++i) { std::scanf("%d", s2 + i); } int n = n1 + n2; int* s = new int[MAX + MAX]; for (int i = 0, i1 = 0, i2 = 0; i < n; ++i) { if ((s1[i1] <= s2[i2] && i1 < n1) || i2 == n2) { s[i] = s1[i1]; ++i1; } else { s[i] = s2[i2]; ++i2; } } if (n % 2) { std::printf("%d\n", s[n / 2]); } else { std::printf("%d\n", s[n / 2 - 1]); } delete[] s1; delete[] s2; delete[] s; return 0; }
true
36c24239772eeaa333a2e85bc1b65007ee37afbf
C++
trialblazer/Algorithm
/Algorithm/shuzifanyi.cpp
UTF-8
2,286
3.3125
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; char num[20]; char a[20][10]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninteen"}; char b[9][10] = {"","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninty"}; char c[5][10] = {"","thousand","million","billion"}; void translate(int sign, int begin) { if (sign == -1) return; cout << a[(int)num[begin]-48] << " "; if ((int)num[begin] != 48) cout << "hundred "; if ((int)num[begin+1]-48 == 0) { if ((int)num[begin+2]-48 != 0) { cout << "and " << a[(int)num[begin+2]-48] << " "; } } else { cout << "and "; if ((int)num[begin+1] == 49) cout << a[(int)num[begin+2]-38] << " "; else cout << b[(int)num[begin+1]-48-1] << " " << a[(int)num[begin+2]-48] << " "; } if ((int)num[begin] != 48 || (int)num[begin+1] != 48 || (int)num[begin+2] != 48) cout << c[sign] << " "; translate(--sign, begin+3); } void translate1() { int i; for (i=0; i<strlen(num); i++) if (num[i] == '.') break; int len = i; if (i > 12) { cout << "out of size!\n"; return; } if ((int)num[0] == 48) { cout << "zero"; } else { int bit1 = len%3, bit2 = len/3, tmpt = 0; if (bit1 == 1) { cout << a[(int)num[0]-48] << " "; tmpt = 1; } if (bit1 == 2) { if ((int)num[0] == 49) cout << a[(int)num[1]-38] << " "; else cout << b[(int)num[0]-48-1] << " " << a[(int)num[1]-48] << " "; tmpt = 2; } if (bit1 != 0) cout << c[bit2] << " "; translate(--bit2, 0+tmpt); } if (i != strlen(num)) { cout << "point "; for (int j=i+1; j<strlen(num); j++) { if (num[j] == '0') {cout << "zero "; continue;} cout << a[(int)num[j]-48] << " "; } } cout << endl; } int main(void) { cout << "please input the number: "; cin >> num; if (strlen(num) > 20) cout << "out of size!"; else translate1(); cout << endl; return 0; }
true
510860fadc43b314ba9778fb4148a0ebb94d1923
C++
dreampatryk/Arkanoid
/Arkanoid/Entity.h
UTF-8
762
2.8125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> class Entity : public sf::Drawable, public sf::Transformable { protected: sf::Vector2f m_velocity; sf::RectangleShape m_shape; sf::Vector2f getVelocity() { return this->m_velocity; } sf::Vector2f getPosition() { return this->m_shape.getPosition(); } sf::Vector2f getSize() { return this->m_shape.getSize(); } void setVelocity(sf::Vector2f velocity) { this->m_velocity = velocity; } void setPosition(sf::Vector2f position) { this->m_shape.setPosition(position); } void setPosition(float x, float y) { this->m_shape.setPosition(x, y); } public: Entity(); ~Entity(); virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; virtual void update(float updateTime) = 0; };
true
580df07804dda23514e338dea18e9097cc2cf4d5
C++
yash19970/CPP-Questions
/vec.cpp
UTF-8
245
2.703125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector<int> v; int n; cout<<v.size()<<endl; for(int i=0;i<5;i++) { v.push_back(i); } for(int i=0;i<5;i++){ cout<<"Enter: "<<endl; cin>>n; cout<<v[n]<<endl; } return 0; }
true
1caee45ddd8262164026aff48568cda61062d6ad
C++
KISTI-hackathon-2017/IT-s
/Source/Client/Stop1.ino
UTF-8
5,646
2.609375
3
[]
no_license
#include "LedControl.h" #include <LiquidCrystal.h> LedControl lc1=LedControl(8,10,9,4); LiquidCrystal lcd1(7, 6, 5, 4, 3, 2); #include "Phpoc.h" #include "SPI.h" char server_name[] = "192.168.0.6"; int port = 8080; char bus_num1[5]="719 "; int bus_num_len=0; char bus_data1[20]="full"; char stop_data1[20]={0}; char time_ch[5]=" "; void setup() { Serial.begin(9600); lcd1.begin(16, 2); for(int i=0; i<4; i++){ // ๋„ํŠธ ๋งคํŠธ๋ฆญ์Šค 0~3๋ฒˆ lc1.shutdown(i,false); // ๋””์Šคํ”Œ๋ ˆ์ด ์ดˆ๊ธฐํ™” lc1.setIntensity(i,1); // ๋„ํŠธ ๋งคํŠธ๋ฆญ์Šค ๋ฐ๊ธฐ (๋งคํŠธ๋ฆญ์Šค ๋ฒˆํ˜ธ, ๋ฐ๊ธฐ) 1~15 lc1.clearDisplay(i); // led ๋ฅผ ์ „์ฒด ๊บผ์ฃผ๋Š” ํ•จ์ˆ˜ } while(!Serial); Serial.println("Sendin GET request to web server"); Phpoc.begin(PF_LOG_SPI | PF_LOG_NET); SPI.begin(); } void loop(){ PhpocClient client; String str1; if(client.connect(server_name, port)) //์—ฐ๊ฒฐ์‹œ์ž‘ Serial.println("Connected to server"); else Serial.println("connection failed"); client.print("POST /Hackaton/server.jsp"); client.print("?data=Res,"); client.println("df"); client.println(" HTTP/1.1\r\n"); client.println("Host: 192.168.0.6"); client.println("Connection:close"); client.print("\r\n\r\n"); client.println(); delay(5000); while (client.available()) { char c = client.read(); Serial.print(c); str1.concat(c); } //str1 = "St 100, 13, 121:free, 70:free, 150, 14, 122:free, 97:free 14:42"; str1.trim(); Serial.print("str1: "); Serial.println(str1); str1.toCharArray(bus_num1,5,3); str1.toCharArray(bus_data1,5,8); str1.toCharArray(stop_data1,19,13); str1.toCharArray(time_ch,6,62); //St 100, 13, 121:free, 70:free, 150, 14, 122:free, 97:free 14:42 String temp; temp=bus_num1; temp.trim(); bus_num_len=temp.length()+1; temp.toCharArray(bus_num1,temp.length()+1); temp=bus_data1; temp.trim(); temp.toCharArray(bus_data1,temp.length()+1); temp=stop_data1; temp.trim(); temp.toCharArray(stop_data1,temp.length()+1); lcd1.clear(); clean1(); // led ์ „์ฒด ๊บผ์ฃผ๊ธฐ delay(500); if(bus_num1[1]!='x'){ mark_busnum(bus_num1); set_lcd(bus_data1,stop_data1); delay(5000); } } /*********************************TEXT function**********************************/ void set_lcd(String bus_data, String stop_data) { if(bus_data<"15"){ bus_data="free"; }else if(bus_data<"25"){ bus_data="half"; }else{ bus_data="full"; } lcd1.setCursor(0,0); lcd1.print("in:"); lcd1.print(bus_data); lcd1.print(" "); lcd1.print(time_ch); lcd1.setCursor(0,1); lcd1.print(stop_data); /*for(int i=0;i<stop_data.length();i++){ lcd1.scrollDisplayLeft(); delay(500); }*/ } /*******************************other function***********************************/ void clean1(){ // ์ „์ฒดled๋ฅผ ๊บผ์ฃผ๋Š” ํ•จ์ˆ˜ for(int i = 0; i < 4; i++) lc1.clearDisplay(i);// clear screen } void mark_busnum(char bus_num[]){ for(int i=0;i<bus_num_len;i++){ if(bus_num[i]=='0'){ num0(i); }else if(bus_num[i]=='1'){ num1(i); }else if(bus_num[i]=='2'){ num2(i); }else if(bus_num[i]=='3'){ num3(i); }else if(bus_num[i]=='4'){ num4(i); }else if(bus_num[i]=='5'){ num5(i); }else if(bus_num[i]=='6'){ num6(i); }else if(bus_num[i]=='7'){ num7(i); }else if(bus_num[i]=='8'){ num8(i); }else if(bus_num[i]=='9'){ num9(i); }else{ blank(i); } } } void num1(int i){ lc1.setColumn(i,2,0xff); lc1.setColumn(i,3,0xff); } void num2(int i){ lc1.setRow(i,0,0x7E); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0xC); lc1.setRow(i,3,0x18); lc1.setRow(i,4,0x30); lc1.setRow(i,5,0x66); lc1.setRow(i,6,0x7C); lc1.setRow(i,7,0x38); } void num3(int i){ lc1.setRow(i,0,0x3E); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0x60); lc1.setRow(i,3,0x3E); lc1.setRow(i,4,0x3E); lc1.setRow(i,5,0x60); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x3E); } void num4(int i){ lc1.setRow(i,0,0x30); lc1.setRow(i,1,0x30); lc1.setRow(i,2,0xff); lc1.setRow(i,3,0xff); lc1.setRow(i,4,0x33); lc1.setRow(i,5,0x36); lc1.setRow(i,6,0x3c); lc1.setRow(i,7,0x38); } void num5(int i){ lc1.setRow(i,0,0x3E); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0x60); lc1.setRow(i,3,0x7E); lc1.setRow(i,4,0x3E); lc1.setRow(i,5,0x6); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x7E); } void num6(int i){ lc1.setRow(i,0,0x3C); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0x66); lc1.setRow(i,3,0x7E); lc1.setRow(i,4,0x3E); lc1.setRow(i,5,0xC); lc1.setRow(i,6,0x18); lc1.setRow(i,7,0x30); } void num7(int i){ lc1.setRow(i,0,0x60); lc1.setRow(i,1,0x60); lc1.setRow(i,2,0x60); lc1.setRow(i,3,0x60); lc1.setRow(i,4,0x66); lc1.setRow(i,5,0x66); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x7E); } void num8(int i){ lc1.setRow(i,0,0x3C); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0x66); lc1.setRow(i,3,0x7E); lc1.setRow(i,4,0x7E); lc1.setRow(i,5,0x66); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x3C); } void num9(int i){ lc1.setRow(i,0,0x60); lc1.setRow(i,1,0x60); lc1.setRow(i,2,0x60); lc1.setRow(i,3,0x7C); lc1.setRow(i,4,0x7E); lc1.setRow(i,5,0x66); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x3C); } void num0(int i){ lc1.setRow(i,0,0x3C); lc1.setRow(i,1,0x7E); lc1.setRow(i,2,0x66); lc1.setRow(i,3,0x66); lc1.setRow(i,4,0x66); lc1.setRow(i,5,0x66); lc1.setRow(i,6,0x7E); lc1.setRow(i,7,0x3C); } void blank(int i){ for(int j=0;j<7;j++){ lc1.setRow(i,i,0); } }
true
5cd58cbdfa02107cfc13f474a40cffb31cd9adef
C++
FASTSHIFT/ucGIS
/ucGISEngine/pcๅœฐๅ›พ่ฝฌๆข็จ‹ๅบ/v1.2/MapDll/Line.h
GB18030
1,581
2.59375
3
[]
no_license
// Line.h: interface for the CLine class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_LINE_H__8B3F7165_E05A_48D6_BD17_321D5BBE5597__INCLUDED_) #define AFX_LINE_H__8B3F7165_E05A_48D6_BD17_321D5BBE5597__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Draw.h" class AFX_EXT_CLASS CLine : public CDraw { public: CLine(); CLine(TCHAR* pszLabel, short nLayer,ObjectTypeConstants nType,ObjectTypeConstants nSubType, float x1,float y1,float x2,float y2,mapPENSTRUCT stPen) :CDraw(pszLabel,nLayer, nType, nSubType){ m_Pen = stPen; m_X1 = x1; m_X2 = x2; m_Y1 = y1; m_Y2 = y2; GetRect(&m_Rect.fMinX,&m_Rect.fMinY,&m_Rect.fMaxX,&m_Rect.fMaxY); } virtual ~CLine(); virtual void ReadFromFile(FILE *fp,int& fileoffset); virtual void WriteToFile(FILE *fp); virtual void Draw(HDC hDC, int m_DrawMode); virtual void DrawLabel(HDC hDC); virtual void GetRect(float* minX, float* minY, float* maxX, float* maxY) { *minX=min(m_X1,m_X2); //ใฒขะกxึต *maxX=max(m_X1,m_X2); //ใฒขxึต *minY=min(m_Y1,m_Y2); //ใฒขะกyึต *maxY=max(m_Y1,m_Y2); //ใฒขyึต } virtual int GetFileoffsetLen(){return m_fileoffsetlen;}; protected: int m_fileoffsetlen; float m_X1, m_X2, m_Y1, m_Y2; //ึฑ฿ตีต float m_fLong; // ึฑ฿ตฤณ mapPENSTRUCT m_Pen; }; #endif // !defined(AFX_LINE_H__8B3F7165_E05A_48D6_BD17_321D5BBE5597__INCLUDED_)
true
e5ca45797650b5301ceacd817758a66ac62e3bb7
C++
DelusionsOfGrandeur/labs
/ะฒะฒะฟ9(1).cpp
UTF-8
398
2.546875
3
[]
no_license
#include<stdio.h> #include<math.h> #include<locale.h> int main() { setlocale(LC_ALL, "Russian"); int n; printf("ะฒะฒะตะดะธั‚ะต ั†ะตะปะพะต ั‡ะธัะปะพ ัะตะบัƒะฝะด, ะฟั€ะพัˆะตะดัˆะธั… ั ะฝะฐั‡ะฐะปะฐ ััƒั‚ะพะบ\n"); scanf("%d", &n); n = (n%60); printf("ั‡ะธัะปะพ ัะตะบัƒะฝะด, ะฟั€ะพัˆะตะดัˆะธั… ั ะฝะฐั‡ะฐะปะฐ ะฟะพัะปะตะดะฝะตะน ะผะธะฝัƒั‚ั‹, ั€ะฐะฒะฝะพ %d", n); return 0; }
true
fa524f4130a935f743fad72afdacdd83f56d9fa1
C++
agudeloandres/C_Struct_Files
/other_c_files/FCCDPAL.CPP
UTF-8
1,410
2.578125
3
[]
no_license
#include <stdio.h> #include <dos.h> void main() { int *base,*dir; int A[20][20],limtif,limtsf,W,limtic,limtsc,colm,n,d[10],sma,r,i,j; printf(" POR FAVOR DIGITE EL NUMERO DE FILAS Y COLUMNAS DE LA MATRIZ A :"); do { scanf("%d",&n); } while (n<=0); printf (" POR FAVOR DAR EL LIMITE INFERIOR DE FILAS Y DE COLUMNAS : "); do { scanf ("%d",&limtif); } while (limtif<0); limtic=limtif; W=20-n+1; //HALLAMOS LOS RESPECTIVOS LIMITES limtsf=limtif+n-1; r=limtsf+W-limtic+1; // LEEMOS LOS ELEMENTOS DE LA MATRIZ A for (i=limtif;i<=limtsf;i++){ for (j=limtif;j<=limtsf;j++){ printf(" POR FAVOR DIGITE EL ELEMENTO A[%d][%d]:",i,j); scanf("%d",&A[i][j]); dir=&A[i][j]; } } /* APLICACION DE LA FUNCION DE ACCESO PARA LOS ELEMENTOS DE LA DIAGONAL PRINCIPAL DE LA MATRIZ A */ sma=0; base= &A[limtif][limtif]; for (i=limtif;i<=limtsf;i++){ dir=base+(i-limtif)*r; d[i]=*dir; sma+=*dir; } printf(" \n LA SUMA DE LOS ELEMENTOS DE LA DIAGONAL PRINCIPAL ES : %d \n",sma ); printf(" LA DIRECCION DE LA SUMA ES : %04x:%04x\n",FP_SEG(dir),FP_OFF(dir)); base=&d[limtif]; printf("\n LOS ELEMENTOS DE LA DIAGONAL PRINCIPAL :\n "); for (i=limtif;i<=limtsf;i++){ dir=base+i-limtif; printf("\n EL ELEMENTO d[%d]=%d ",i,*dir); printf(" LA DIRECCION DE ESTE ELEMENTO ES =%04x:%04x\n",FP_SEG(dir),FP_OFF(dir)); } }
true
e06e02b85ef2cb8ec3677caeaac8ef5fe482f723
C++
pharick/cpp
/2-year/22-brackets-overload/b.cpp
UTF-8
520
3.734375
4
[]
no_license
#include <iostream> class Fraction { int x, y; public: Fraction(int x = 0, int y = 1); int& operator [] (int i); }; Fraction::Fraction(int x, int y) { this->x = x; this->y = y; } int& Fraction::operator [] (int i) { if (i == 0) return this->x; if (i == 1) return this->y; throw 1; } int main() { int x, y; std::cin >> x; std::cin.ignore(1, '/'); std::cin >> y; Fraction fr(x, y); int i; std::cin >> i; std::cout << fr[i] << std::endl; return 0; }
true
726599dbfc63bbc816f302be29555cc8861b6277
C++
cnug98/CS530
/prog2/convert.cpp
UTF-8
3,301
3.5
4
[]
no_license
/* * Members: Colin Nugent, Carter Andrews, Patrick Perrine * Red ID's: 820151963, 820214623, and 820486635 * Class Users: cssc0440, cssc0425, cssc0426 * Class Information: CS530, Spring 2019 * Assignment #2, SIC/XE Disassembler * Filename: convert.cpp * Purpose: Contains helper methods for data type conversions */ #include "convert.h" // converts Hex in string to int int stringHexToInt(string hex){ int num = 0; int pow16 = 1; //cout << hex << endl; string alpha = "0123456789ABCDEF"; //bit value reference for(int i = hex.length() - 1; i >= 0; --i) //goes through each bit and converts it to its integer value multiplied by what 16s place it's in { num += alpha.find(toupper(hex[i])) * pow16; pow16 *= 16; //increments power } //cout << integerToString(num) << endl; return num; } // Takes in an int and returns a binary string string hexToStringBinary(unsigned long hex) { //IMPORTANT: all conversion methods only go through 4 bits at a time (i.e. 0000 in binary or 0 in hex, use these methods accordingly in for loops) if(hex == 0) return "0000"; else if(hex == 1) return "0001"; else if(hex == 2) return "0010"; else if(hex == 3) return "0011"; else if(hex == 4) return "0100"; else if(hex == 5) return "0101"; else if(hex == 6) return "0110"; else if(hex == 7) return "0111"; else if(hex == 8) return "1000"; else if(hex == 9) return "1001"; else if(hex == 0x0A) //here's the notation for A to F return "1010"; else if(hex == 0x0B) return "1011"; else if(hex == 0x0C) return "1100"; else if(hex == 0x0D) return "1101"; else if(hex == 0x0E) return "1110"; else if (hex == 0x0F) return "1111"; printf("Opcode Error!\n"); //simple exception handling return NULL; } //Take in a binary string and converts it into a hex string string stringBinToHex(string s){ //same as HextoBin but backwards if(s.compare("0000")==0) return "0"; else if(s.compare("0001")==0) return "1"; else if(s.compare("0010")==0) return "2"; else if(s.compare("0011")==0) return "3"; else if(s.compare("0100")==0) return "4"; else if(s.compare("0101")==0) return "5"; else if(s.compare("0110")==0) return "6"; else if(s.compare("0111")==0) return "7"; else if(s.compare("1000")==0) return "8"; else if(s.compare("1001")==0) return "9"; else if(s.compare("1010")==0) return "A"; else if(s.compare("1011")==0) return "B"; else if(s.compare("1100")==0) return "C"; else if(s.compare("1101")==0) return "D"; else if(s.compare("1110")==0) return "E"; else if(s.compare("1111")==0) return "F"; printf("Invalided Input!\n"); //simple exception handling return NULL; } //Take in an int and returns it as a string string integerToString(int number){ string convertToString; stringstream ss; // stream used for the conversion ss << number; // insert the textual representation of 'Number' in the characters in the stream convertToString = ss.str(); return convertToString; }
true
a233809a305f5e72cd109703cadacf6d9e7e4da0
C++
DevinLeamy/Competitive-Programming
/Toolkit/Algorithms/LongestIncreasingSubsequence.cpp
UTF-8
710
3.234375
3
[]
no_license
#include <vector> #include <algorithm> #define INF 2147483647 using namespace std; int long_inc_sub(vector<int> &vals) { int n = (int) vals.size(); vector<int> last(n, INF); int len = 1; last[0] = vals[0]; for (int i = 1; i < n; i++) { int val = vals[i]; if (val < last[0]) { // new smallest value last[0] = val; } else if (val > last[len - 1]) { // extends largest subsequence last[len] = val; len++; } else { int bound = (int) (lower_bound(last.begin(), last.end(), val) - last.begin()); last[bound] = val; } } return len; } int main() { vector<int> v{ 2, 5, 3, 7, 11, 8, 10, 13, 6 }; int long_inc = long_inc_sub(v); assert(long_inc == 6); return 0; }
true
c36728dcfad293902f2719167bc649f19172cd47
C++
AVNISHPATEL102/POWERGRID-GAME
/Player.cpp
UTF-8
2,642
3.421875
3
[]
no_license
/* * Player.cpp * * Created on: Feb 25, 2019 * Authors: Trevor Lall, Stephen Smith, Avnish Patel, Wenbo Zhong * Purpose: Source file for Player Object. Used to represent players for the game. */ #include "Player.h" #include "City.h" #include "House.h" using namespace std; //Default Constructor Player::Player() { name = ""; player_num = 0; elektro = 0; colour = ""; } //Constructor to create new Player Player::Player(int p_num, string player_name, Elektro* player_money, string player_colour) { name = player_name; player_num = p_num; elektro = player_money; colour = player_colour; } void Player::setPlayer(string Pname){ name = Pname; } //set the players money void Player::setElektro(int money_spent) { elektro->setPlayerMoney(money_spent); } void Player::setColour(string colours){ colour = colours; } void Player::setPlayerNum(int p_num){ player_num = p_num; } void Player::setPlayerHouses(vector<House*> house) { houses = house; } void Player::addCard(Cards* card) { cards.push_back(card); } //show a list of the cities the player owns string Player::showCityOwned() { cout << "Controlled Cities: "; for (int i = 0; i < (int)cityOwned.size(); i++) { cout << cityOwned.at(i) << ", "; } return "\n"; } //show a list of the cities the player owns string Player::showCards() { cout << "Cards: "; for (int i = 0; i < cards.size(); i++) { cout << cards.at(i)->getCardType() << ": "<< cards.at(i)->getCardNum() << "("<< cards.at(i)->getResType() << ", " << cards.at(i)->getResourceNum() << ") -> "; } return "\n"; } //Show Player information. Displays Player name, money, cities owned, and resources string Player::showInformation() { //Player Name cout << "\n----------\n" << getPlayer() << "\n----------\n" << endl; //Output for cities owned showCityOwned(); //Output for cities owned showCards(); //output for Money cout << "\nElektro: " << getElektro()->getPlayerMoney() << endl ; //Outout for Resources cout << "\nResources\n" "----------\n" "Coal: " << coal.size() << "\n" "Garbage: " << garbage.size() << "\n" "Oil: " << oil.size() << "\n" "Uranium: " << uranium.size() << endl; return "\n"; } //Getters string Player::getPlayer() { return name; } //gets player name int Player::getPlayerNum() { return player_num; } //gets player number Elektro* Player::getElektro() { return elektro; } //gets Money vector<House*> Player:: getHouse() { return houses; } vector<Cards*> Player::getCards() { return cards; } string Player::getPlayerColour(){ return colour; }
true
07f6abb236c99534abeae3d4234432cf4ea4bd88
C++
cskarthikcs/cpp-template
/main.cpp
UTF-8
2,449
2.765625
3
[]
no_license
#include<iostream> #include<fstream> #include<string> #include<math.h> #include<list> #include<vector> #include <sstream> #define SSTR( x ) dynamic_cast< std::ostringstream & >( \ ( std::ostringstream() << std::dec << x ) ).str() using namespace std; void print (vector<vector <int> >& B ){ for(long long int x=0;x<B.size();x++){ for(int y=0;y<B[x].size();y++){ cout<<B[x][y]<<" "; } cout<<endl; } } void print (vector <int> & B ){ for(int y=0;y<B.size();y++){ cout<<B[y]<<" "; } cout<<endl; } bool cover(vector< vector <int> >& B,vector<vector <int> >& A,int val){ for(int i=0;i<B.size();i++){ bool flag=false; for(int j=0;j<A.size();j++){ int b=0,a=0,count=0; while(1<2){ if(B[i][b]==A[j][a]){ b++; a++; count++; } else { if(B[i][b]>A[j][a]) b++; else a++; } if(a>=2*val||b>=2*val) break; } if(count==val){ flag=true; break; } } if(flag==false) return false; } return true; } void subset(int arr[], int size, int left, int index, list<int> &l, vector<vector <int> > &B, int n, bool &flag){ if(left==0){ vector< vector <int> > A; for(list<int>::iterator it=l.begin(); it!=l.end() ; ++it) A.push_back(B[*it]); if(cover(B,A,n)==true){ string s = SSTR(n) + ".txt"; ofstream f(s.c_str()); for(int r=0;r<A.size();r++){ for(int j=0;j<A[r].size();j++){ f<<A[r][j]<<" "; } f<<endl; } f.close(); flag=true; } A.clear(); return; } if(flag==true) return; for(int i=index; i<size;i++){ l.push_back(arr[i]); subset(arr,size,left-1,i+1,l,B,n,flag); l.pop_back(); } } int main(){ for(int i=1;i<10;i++){ vector< vector <int> > B; for(long long int j=0;j<pow(2,4*i);j++){ long long int temp=j, count=0; for(int r=4*i -1;r>=0;r--){ if(pow(2,r)<=temp){ count++; temp-=pow(2,r); } } if(count==2*i){ vector<int> A; temp=j; for(int r=4*i -1;r>=0;r--){ if(pow(2,r)<=temp){ A.push_back(r+1); temp-=pow(2,r); } } B.push_back(A); } } int *array = new int[B.size()]; for(int d=sqrt(i);d<=2*i;d++){ cout<<"i="<<i<<" d="<<d<<" |B|="<<B.size()<<endl; vector< vector <int> > pos; for(int r=0;r<B.size();r++) array[r]=r; list<int> lt; bool flag=false; subset(array,B.size(),d,0,lt,B,i,flag); if(flag==true) break; } delete[] array; } return 0; }
true
4d02678adbab1b3902bd8a2f940ea2ae69b72fd3
C++
aceiro/atm_2019
/CI-APP/Src/FormCreate.cpp
UTF-8
5,728
3.34375
3
[]
no_license
// Declaraรงรฃo das Bibliotecas internas do C++ #include <iostream> #include <string> #include <ctime> // Biblioteca interna do C++ para usar padrรตes de data hora do sistema #include <cctype> // Biblioteca interna do C++ para usar "isdigit" // Declaraรงรฃo das Bibliotecas internas do Projeto (declaรงรฃo das Classes) #include "../Include/Form.hpp" // Uso refinado do Escopo STD using std::cout; using std::cin; using std::getline; using std::endl; using std::string; void Form::formCreate() { // Vรกriaveis para inserรงรฃo no Formulรกrio string idCI; string senderCI; // SENDER_RECIPIENT_SUBJECT_SIZE string recipientCI; // SENDER_RECIPIENT_SUBJECT_SIZE string subjectCI; // SENDER_RECIPIENT_SUBJECT_SIZE string dateCI; string messageCI; // SENDER_RECIPIENT_SUBJECT_SIZE // Entrada de dados cout << endl << endl << "\tObs.: Entre com dados vรกlidos! Nรฃo omita nenhum campo!" << endl << endl; cout << endl << "DE (max 100 caracteres): "; getline(cin, senderCI); // Verificar se os dados de nรฃo estรฃo vazios senderCI = validateInput(senderCI, SENDER_RECIPIENT_SUBJECT_SIZE); cout << endl << "PARA (max 100 caracteres): "; getline(cin, recipientCI); // Verificar se os dados de nรฃo estรฃo vazios recipientCI = validateInput(recipientCI, SENDER_RECIPIENT_SUBJECT_SIZE); cout << endl << "ASSUNTO (max 100 caracteres): "; getline(cin, subjectCI); // Verificar se os dados de nรฃo estรฃo vazios subjectCI = validateInput(subjectCI, SENDER_RECIPIENT_SUBJECT_SIZE); cout << endl << "MENSAGEM (max 500 caracteres): "; getline(cin, messageCI); // Verificar se os dados de nรฃo estรฃo vazios messageCI = validateInput(messageCI, MENSSAGE_SIZE); // Inicializaรงรฃo das Vรกriaveis dataCI dateCI = getSystemDate(); // idCI รฉ uma string resultante da concatenaรงรฃo de ano+mes+dia+hora+minuto+segundos idCI = createIdCI(); // Criar rotina de utilizar do crudCreate formCreate(idCI, senderCI, recipientCI, subjectCI, dateCI, messageCI); // Rertorna da Mensagem de confirmaรงรฃo do procedimento. successfulMessage(); } void Form::formCreate(string idCI, string senderCI, string recipientCI, string subjectCI, string dateCI, string messageCI) { // Verificaรงรฃo da Posiรงรฃo a ser inserido, e inserรงรฃo // Insere no inรญcio, quando a estrutura de dados estรก vazia if (Data.empty()) Data.insert(Data.begin(), FormData(idCI, senderCI, recipientCI, subjectCI, dateCI, messageCI)); // Insere no final, quando jรก existir algum registro na estrtutura de dados else Data.push_back(FormData(idCI, senderCI, recipientCI, subjectCI, dateCI, messageCI)); } // Conversรฃo de tipo data para string string Form::getSystemDate() { // "t_Date" serรก nossa vรกriavel para passagem de referรชnica dos valores de data time_t t_Date; // "tm" รฉ um estrutura interna do C++ que indica atributos do tipo TIME struct tm *timeInfo; // "buffer" serรก atribuรญda a "sBuffer", e serรก nosso retorno com data formatada char buffer[DATE_SIZE]; string sBuffer; // Usando a funรงรฃo "time" (Interna do C++) passando como referรชncia "t_Date" time(&t_Date); // Usando a funรงรฃo "localtime", e passando nossa "t_Date", para "timeInfo", // que รฉ onde temos a entrada da data sem formataรงรฃo timeInfo = localtime(&t_Date); // "strftime", converte nosso tipo de data para uma string, que nosso caso รฉ o "buffer" strftime(buffer, DATE_SIZE, "%d/%m/%Y", timeInfo); // retornamos nossa string, para que seja usada no restante do programa sBuffer = buffer; return sBuffer; } // Gerando cรณdigo idCI (cรณdigo รบnico) // reutilizando trechos do cรณdigo da hora formatada. string Form::createIdCI() { time_t t_Date; struct tm *timeInfo; char cd[DATE_SIZE]; string sCd; // double id; time(&t_Date); timeInfo = localtime(&t_Date); // "strftime", converte nosso tipo de data para uma string: // ano(4)%mes(2)%dia(2)%hora(2)%minuto(2)%segundo(2) // Exemplo: sendo hoje 23/10/1989 e agora 10:35:56 // 23101989103556 strftime(cd, DATE_SIZE, "%Y%m%d%H%M%S", timeInfo); // retornamos nossa string, para que seja usada no restante do programa sCd = cd; return sCd; } // Validaรงรฃo de entrada de dados no formulรกrio string Form::validateInput(string inputData, int optCheckIn) { int escape = 0; // Aqui, primeiramente verifica qual campo estรก entrando e depois, valida o mesmo while (!auxValidateInput(inputData, optCheckIn)) { cout << endl<< endl << "\tEntre com dados vรกlidos! Digite novamente: "; getline(cin, inputData); // Vรกriavel de Controle de exibiรงรตes do Loop escape++; // Controle do Loop if (escape == NUMBER_OF_ATTMPTS) { escape = 0; inputStandardMessage(); } } return inputData; } // Auxiliar para validaรงรฃo da entrada dos dados bool Form::auxValidateInput(string inputData, int optCheckIn) { if (inputData.empty()) return false; if ((isdigit(inputData[0])) || (isdigit(inputData[1])) || (isdigit(inputData[2])) || (isdigit(inputData[3])) || (isdigit(inputData[4]))) return false; if (((optCheckIn == SENDER_RECIPIENT_SUBJECT_SIZE) && (inputData.size() > SENDER_RECIPIENT_SUBJECT_SIZE)) || ((optCheckIn == MENSSAGE_SIZE) && (inputData.length() > MENSSAGE_SIZE))) return false; return true; } // Mensagem padrรฃo para procedimento realizados com sucesso void Form::successfulMessage() { cout << endl << endl << "OK! pressione ENTER para continuar." << endl << endl; } // Mensagem padrรฃo, de orientaรงรตes para o cadastro void Form::inputStandardMessage() { cout << endl << endl << "ATENร‡รƒO: Cadastro nรฃo pode estar vazio, iniciar com nรบmeros ou ultrapassar quantidade de caracteres!!!"; }
true
c6d4bf212fe80d86028aeb00548aa2a996809cef
C++
kurocha/logger
/source/Logger/Log.hpp
UTF-8
1,766
2.890625
3
[ "MIT" ]
permissive
// // Log.hpp // File file is part of the "Logging" project and released under the MIT License. // // Created by Samuel Williams on 28/6/2017. // Copyright, 2017, by Samuel Williams. All rights reserved. // #pragma once #include "Level.hpp" #include <sstream> #include <Time/Timer.hpp> #include <unordered_map> #include <thread> #include <mutex> namespace Logger { typedef int FileDescriptor; typedef std::stringstream Message; static const std::string EOL = "\n"; class Log { std::mutex _lock; Time::Timer _timer; Level _level = Level::ALL; FileDescriptor _output; typedef std::unordered_map<std::thread::id, std::string> ThreadNamesT; ThreadNamesT _thread_names; bool is_tty() const; std::string header(Level level); /// Print out a logging header void start_session(); std::string thread_name() const; std::string _last; public: Log(); virtual ~Log(); void append(Level level, const std::string & string); const std::string & last(); void set_thread_name(std::string name); template <typename... TailT> void print(Level level, TailT... tail) { if (level & _level) { Message buffer; write(buffer, tail...); append(level, buffer.str()); } } void enable(Level level); void disable(Level level); protected: template <typename HeadT, typename... TailT> static void write(Message & output, HeadT head, TailT... tail) { output << head << ' '; write(output, tail...); } template <typename HeadT, typename TailT> static void write(Message & output, HeadT head, TailT tail) { output << head << ' ' << tail; } template <typename HeadT> static void write(Message & output, HeadT head) { output << head; } }; }
true
475ef93f9fda95fc03befd5f91e03d438ef81738
C++
teptind/AlgoLabs
/Labs/dp/4A.cpp
UTF-8
2,215
2.734375
3
[]
no_license
#include <bits/stdc++.h> #include <time.h> using namespace std; #define ll long long #define ld long double #define uint unsigned int #define ull unsigned long long struct P{ ll acts, resH, resW; int divInd; P() {} P(ll a, ll rH, ll rW, int dI) { acts = a; resH = rH, resW = rW; divInd = dI; } void write() { cout << acts << " " << resH << " " << resW << " " << divInd << endl; } }; int n; vector<ll> H; vector<ll> W; vector<vector<P> > dp; ll INF = 2e18; void print(vector<int> &t) { for (int i = 0; i < (int)t.size(); ++i) cout << t[i]; cout << "\n"; } void print2() { for (int c = 0; c < n; ++c) { for (int i = 0; i < n; ++i) { if (i + c >= n) continue; cout << i << " " << i + c << ": "; dp[i][i + c].write(); } } } void getAns(int l, int r) { // cout << "getAns " << l << " " << r << endl; if (l > r) return; if (r == l) { cout << "A"; return; } int dI = dp[l][r].divInd; cout << "("; getAns(l, l + dI); getAns(l + dI + 1, r); cout << ")"; return; } int main() { // freopen("file.in", "r", stdin); freopen("matrix.in", "r", stdin); freopen("matrix.out", "w", stdout); cin >> n; H.resize(n); W.resize(n); dp.assign(n, vector<P>(n, P(INF, 0, 0, 0))); for (int i = 0; i < n; ++i) { cin >> H[i] >> W[i]; } for (int i = 0; i < n; ++i) { dp[i][i] = P(0LL, H[i], W[i], -1); } for (int c = 1; c < n; ++c) { for (int i = 0; i < n; ++i) { if (i + c >= n) continue; P curAns = P(INF, 0LL, 0LL, 0); for (int d = 0; d < c; ++d) { ll curActs = 0LL; curActs = dp[i][i + d].acts + dp[i + d + 1][i + c].acts; ll H1 = dp[i][i + d].resH; ll W1 = dp[i][i + d].resW, W2 = dp[i + d + 1][i + c].resW; curActs += H1 * W1 * W2; if (curActs < curAns.acts) { curAns = P(curActs, H1, W2, d); } } dp[i][i + c] = curAns; } } // print2(); getAns(0, n - 1); return 0; }
true
22ad9105da1fdb573eddd02d184ade4681597999
C++
RKBOSAMIA/Cpp-Applications
/STL vector and List/SortedList.cpp
UTF-8
1,894
3.578125
4
[]
no_license
#include <iostream> #include <iterator> #include "SortedList.h" using namespace std; SortedList::SortedList() { Node::reset(); } SortedList::~SortedList() { Node::reset(); } /***** Complete this file. *****/ void SortedList::prepend(const long value) { this->push_front(value); } void SortedList::append(const long value) { this->push_back(value); } void SortedList::insert(const long value) { list<Node>::iterator it = begin(); list<Node>::iterator prev = it; it++; while ((it != end()) && (*it >= *prev)) { prev = it; it++; } list<Node>::insert(it,value); } void SortedList::remove(const int index) { list<Node>::iterator it = begin(); advance(it,index); this->erase(it); } void SortedList::reverse() { list<Node>::iterator it = begin(); it++; while(it!=end()) { push_front(*it); erase(it); it++; } } Node& SortedList::operator[](const int index) { list<Node>::iterator it = begin(); int idx = 0; while(idx!=index) { it++; idx++; } return *it; } bool SortedList::check() const { if (size() == 0) return true; list<Node>::const_iterator it = begin(); list<Node>::const_iterator prev = it; it++; // Ensure that each node is greater than or equal the previous node. while ((it != end()) && (*it >= *prev)) { prev = it; it++; } return it == end(); // Good if reached the end. } bool SortedList::check_reversed() const { if (size() == 0) return true; list<Node>::const_iterator it = begin(); list<Node>::const_iterator prev = it; it++; // Ensure that each node is less than or equal to the previous node. while ((it != end()) && (*it <= *prev)) { prev = it; it++; } return it == end(); // Good if reached the end. }
true
74cace1b73b212bf9ed183deadb290ae1af2d8f3
C++
SamDHodgkinson/c.pp-algorithms
/logical operators.cpp
UTF-8
879
4.09375
4
[]
no_license
/*This program asks for 3 numbers to be inputted. The first and second number entered represent the minimum and maximum of the interval respectively. The program then checks if the third number is within this interval and output a boolean type variable (1 = true, 0 = false) */ #include <iostream> using namespace std; main() { int first_integer,second_integer,third_integer; bool answer; cout << "Input the first integer: "; cin >> first_integer; cout << "Input the second integer: "; cin >> second_integer; cout << "Input the third integer: "; cin >> third_integer; answer = (first_integer < third_integer) && (third_integer < second_integer); cout << "Is the number " << third_integer << " contained in the interval from " << first_integer << " to " << second_integer << "? " << endl << answer; }
true
1d4e943bd52af7c02925b4d145a93132b89f87ec
C++
TheBuzzSaw/Nullocity
/source/SimpleBufferObject.hpp
UTF-8
701
2.78125
3
[ "Unlicense" ]
permissive
#ifndef SIMPLEBUFFEROBJECT_HPP #define SIMPLEBUFFEROBJECT_HPP #include "SimpleBuilder.hpp" class SimpleBufferObject { public: SimpleBufferObject(); SimpleBufferObject(const SimpleBuilder& builder); SimpleBufferObject(SimpleBufferObject&& other); ~SimpleBufferObject(); SimpleBufferObject& operator=(SimpleBufferObject&& other); void Draw(GLenum mode, GLint positionAttribute, GLint colorAttribute) const; protected: private: SimpleBufferObject(const SimpleBufferObject&) = delete; SimpleBufferObject& operator=(const SimpleBufferObject&) = delete; GLuint _buffer; GLsizei _count; }; #endif
true
459015cae3a809ad52e591f86b956c37f79ab654
C++
bjornt16/T113VLN1-2
/domain.h
UTF-8
2,958
2.75
3
[]
no_license
#ifndef DOMAIN_H #define DOMAIN_H #include <vector> #include <algorithm> #include <string> #include <fstream> #include <iostream> #include "data.h" using namespace std; //domain layer class Domain { private: //declare data variable, to have access to lower layer. Data data; Utils utils; public: Domain(); //returns QMap of <"GenderName", id> QMap<QString, int> getAcceptedGenderName(); //returns QMap of <"GenderChar", id> QMap<QString, int> getAcceptedGenderChar(); //returns QMap of <"Typename", id> QMap<QString, int> getAcceptedComputerTypeName(); //fetches person tableModel from data layer QSqlRelationalTableModel * getPersonModel(QString filter = ""); //fetches computer tableModel from data layer QSqlRelationalTableModel * getComputerModel(QString filter = ""); //fetches person relation tableModel from data layer QSqlQueryModel * getPersonRelationModel(QString filter = ""); //fetches computer relation tableModel from data layer QSqlQueryModel * getComputerRelationModel(QString filter = ""); //takes in a model and passes it down to the Data layer, where its changes get submitted. QSqlRelationalTableModel * submitDatabaseChanges(QSqlRelationalTableModel* model); //creates tailored search string for person.name, and returns a table of the result QSqlRelationalTableModel * searchPersonName(QString search); //creates tailored search string for person.genderId , and returns a table of the result (genderid as genderName) QSqlRelationalTableModel * searchPersonGender(QString search); //creates tailored search string for person.nationality, and returns a table of the result QSqlRelationalTableModel * searchPersonNationality(QString search); //creates tailored search string for person.birthYear, and returns a table of the result (accepts "from" or "from to") QSqlRelationalTableModel * searchPersonBY(QString search); //creates tailored search string for person.deathYear, and returns a table of the result (accepts "from" or "from to") QSqlRelationalTableModel * searchPersonDY(QString search); //creates tailored search string for computer.name, and returns a table of the result QSqlRelationalTableModel * searchComputerName(QString search); //creates tailored search string for computer.type, and returns a table of the result (typeid as typeName) QSqlRelationalTableModel * searchComputerType(QString search); //creates tailored search string for computer.designYear, and returns a table of the result QSqlRelationalTableModel * searchComputerDY(QString search); //creates tailored search string for computer.builtYear, and returns a table of the result QSqlRelationalTableModel * searchComputerBY(QString search); //passes on personId and computerId to the data layer, creates relation void createPCRelation(int p, int c); }; #endif // Domain_H
true
9c87a9d4b1971fd8c185d6c330de6687158843b3
C++
MinhazAbtahi/UVA
/10812 - Beat the spread.cpp
UTF-8
541
3.15625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> /* a+b=sum...(1) =>a=s-b; a-b=diff...(2) getting value of a from (1) and putting it in (2) s-b-b=diff s-diff=2b b=(s-diff)/2 */ using namespace std; int main() { int t; scanf("%d", &t); while(t--){ int s,d,a,b; scanf("%d %d", &s,&d); if(s<d || (s-d)%2!=0) { printf("impossible\n"); } else { b=(s-d)/2; a=s-b; printf("%d %d\n", a, b); } } }
true
603078d32c5235215070103cafff91b5157b898e
C++
zacklukem/weird-os
/tests/string.cpp
UTF-8
1,613
3.078125
3
[]
no_license
#include "test/tests.h" #include <string.h> #include <util/string.h> using util::string; TEST_CASE(string_strlen) { const char *str = "12345678"; ASSERT_EQ(strlen(str), 8); } TEST_CASE(string_strcmp) { const char *a = "asdf"; const char *b = "fdsa"; const char *c = "asdfg"; const char *d = "asdf"; ASSERT(strcmp(a, d)); ASSERT(!strcmp(a, b)); ASSERT(!strcmp(a, c)); } TEST_CASE(string_eq) { string a = "asdf"; string b = "fdsa"; string c = "asdfg"; string d = "asdf"; ASSERT(a == d); ASSERT(a != b); ASSERT(a != c); } TEST_CASE(string_concat) { string a = "abcd"; string b = "efgh"; string c = a + b; ASSERT(c == "abcdefgh"); string d = "1234"; d += a; ASSERT(d == "1234abcd"); } TEST_CASE(string_slice) { string a = "123456789"; ASSERT(a.slice(0, 5) == "12345"); ASSERT(a.slice(2, 5) == "345"); } TEST_CASE(string_split) { string a = "home/dir/path"; auto a_split = a.split('/'); ASSERT(a_split.at(0) == "home"); ASSERT(a_split.at(1) == "dir"); ASSERT(a_split.at(2) == "path"); for (auto &a : a_split) { free((void *)(size_t)a.cstr()); } // string b = "/home/dir/path"; // // auto b_split = b.split('/'); // ASSERT(b_split.at(0) == ""); // ASSERT(b_split.at(1) == "home"); // ASSERT(b_split.at(2) == "dir"); // ASSERT(b_split.at(3) == "path"); // // string c = "home/dir/path/"; // auto c_split = c.split('/'); // ASSERT(c_split.at(0) == "home"); // ASSERT(c_split.at(1) == "dir"); // ASSERT(c_split.at(2) == "path"); // ASSERT(c_split.at(3) == ""); // TODO: memory leaks like hell here }
true
0d7a13d6cab9cb37de3b0f890c14df2d63e5c8fe
C++
icalamesa/Practica-PRO2
/src/platform/user.cc
UTF-8
2,961
3.078125
3
[]
no_license
#include "user.hh" #include <iostream> using namespace std; User::User(){} void User::insertion(const string& problem_id, bool solved) { this->problem_register.emplace(make_pair(problem_id, make_pair(solved, 1))); } int User::u_tell_course() const { return this->coursing; } bool User::u_is_coursing() const { return coursing != 0; } int User::u_amount_attempts() const { return this->total_attempted; } int User::u_amount_solved_problems() const { return this->total_successes; } int User::u_different_attempts() const { return problem_register.size(); } //Value modification member function void User::u_sign_in_course(int course_id) { this->coursing = course_id; } //CONTINUAR void User::u_list_solved() const { for (const auto& problem : this->problem_register) { //Bool, whether the problem has been solved if (problem.second.first) { //id of problem cout << problem.first << '('; //total submissions cout << problem.second.second; cout << ')' << endl; } } } void User::u_list_solvable() const { for (const auto& problem : this->solvable) { cout << problem << '('; auto it = this->problem_register.find(problem); if (it != this->problem_register.end()) { cout << it->second.second; } else { cout << '0'; } cout << ')' << endl; } } void User::info_user() const { cout << '(' << this->u_amount_attempts() << ','; cout << this->u_amount_solved_problems() << ',' << this->u_different_attempts(); cout << ',' << this->u_tell_course() << ')'; cout << endl; } void User::insert_solvable(const string& problem_id) { auto it = this->problem_register.find(problem_id); //I need this weird condition since I pack both solved and unsolved (but at leat attempted) in a single container. //Those that were not even attempted aren't listed in it, though. if ((it == this->problem_register.end()) or (it != this->problem_register.end() and it->second.first == false)) { this->solvable.insert(problem_id); } } void User::u_submit_problem(const string& problem_id, bool success) { this->total_successes += success; this->total_attempted++; //Maybe auto works better here than this ugly line decltype(this->problem_register)::iterator it = this->problem_register.find(problem_id); if (it == this->problem_register.end()) { this->insertion(problem_id, success); } else { it->second.first or_eq success; it->second.second++; } //remove from solvable list if (success) { this->solvable.erase(problem_id); } } bool User::u_has_solved_problem(const string& problem_id) const { auto it = this->problem_register.find(problem_id); return it != this->problem_register.end() and it->second.first == 1; } bool User::u_update_course() { if (this->solvable.empty()) { this->coursing = 0; return true; } return false; } User::~User(){}
true
9e99227e0e1420eb9a34178fc4a34403d291fc4b
C++
gaelh7/Graphics
/include/Graphics/shader.hpp
UTF-8
6,934
2.703125
3
[ "MIT" ]
permissive
#pragma once #include <glad/glad.h> #include <string> #include <fstream> #include <sstream> namespace gmh { struct ShaderSource { std::string VertexShader, FragmentShader; }; class Shader { private: static ShaderSource ParseShader(const char* filepath); static unsigned int CompileShader(unsigned int type, const std::string &source); static unsigned int CreateShaders(const ShaderSource prg); ShaderSource src; std::string path; unsigned int id; public: Shader(); Shader(const char* filepath); Shader(const Shader& s); Shader(Shader&& s); ~Shader(); inline void bind() const {glUseProgram(id);} Shader& operator=(const Shader& s); Shader& operator=(Shader&& s); template<typename... floats> void SetUniformf(const char* uniform, float v0, floats... v1) const { float data[] = {v0, v1...}; switch (sizeof...(v1)){ case 0: glUniform1fv(glGetUniformLocation(id, uniform), 1, data); break; case 1: glUniform2fv(glGetUniformLocation(id, uniform), 1, data); break; case 2: glUniform3fv(glGetUniformLocation(id, uniform), 1, data); break; case 3: glUniform4fv(glGetUniformLocation(id, uniform), 1, data); break; } }; template<typename... ints> void SetUniformi(const char* uniform, int v0, ints... v1) const { int data[] = {v0, v1...}; switch (sizeof...(v1)){ case 0: glUniform1iv(glGetUniformLocation(id, uniform), 1, data); break; case 1: glUniform2iv(glGetUniformLocation(id, uniform), 1, data); break; case 2: glUniform3iv(glGetUniformLocation(id, uniform), 1, data); break; case 3: glUniform4iv(glGetUniformLocation(id, uniform), 1, data); break; } }; template<int col, int row> void SetUniformMatrixf(const char* uniform, const float* data, bool transpose = false) const { switch (row){ case 2: switch (col){ case 2: glUniformMatrix2fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix2x3fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix2x4fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; case 3: switch (col){ case 2: glUniformMatrix3x4fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix3fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix3x4fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; case 4: switch (col){ case 2: glUniformMatrix4x2fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix4x3fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix4fv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; } } template<int col, int row> void SetUniformMatrixd(const char* uniform, const double* data, bool transpose = false) const { switch (col){ case 2: switch (row){ case 2: glUniformMatrix2dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix2x3dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix2x4dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; case 3: switch (row){ case 2: glUniformMatrix3x2dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix3dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix3x4dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; case 4: switch (row){ case 2: glUniformMatrix4x2dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 3: glUniformMatrix4x3dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; case 4: glUniformMatrix4dv(glGetUniformLocation(id, uniform), 1, transpose, data); break; } break; } } }; }
true
c9913cbeffbcb7d9b052c8fc141af3b0e5df9d41
C++
iyappan/CPP---Maze-using-various-Graph-algorithms
/guievent.h
UTF-8
2,476
2.75
3
[]
no_license
#ifndef GUIEVEN_H_INCLUDED #define GUIEVEN_H_INCLUDED #include<string> #include"cmazeconst.h" #include"cevents.h" using namespace std; class CRoom; //These are the events used by core logic to submit on GUI for various painting. class GUIMazeEvent : public CMazeEvent { public: virtual ~GUIMazeEvent(){} //Factory method to return its own kinds. static GUIMazeEvent* GetEvent(eMaze_Event event); void SetSourceRoom(CRoom *sourceRoom){m_SourceRoom = sourceRoom;} void SetDestRoom(CRoom *destRoom){m_DestRoom = destRoom;} void SetIsBackDrag(bool isBackDrag){m_IsBackDrag = isBackDrag;} void SetAlgType(eAlg_Type algType){m_AlgType = algType;} void SetMoveDirection(unsigned char moveDirection){m_MoveDirection = moveDirection;} CRoom *GetSourceRoom(){return m_SourceRoom;} CRoom *GetDestRoom(){return m_DestRoom;} bool GetIsBackDrag(){return m_IsBackDrag;} eAlg_Type GetAlgType(){return m_AlgType;} unsigned char GetMoveDirection(){return m_MoveDirection;} private: CRoom *m_SourceRoom; CRoom *m_DestRoom; bool m_IsBackDrag; eAlg_Type m_AlgType; unsigned char m_MoveDirection; }; /*---------------------------------------------------------------*/ class GUIBuildRoomEvent: public GUIMazeEvent { public: GUIBuildRoomEvent(){} eMaze_Event GetEventID(){return EV_GUI_BUILD_ROOMS;} }; /*---------------------------------------------------------------*/ class GUIBuildMazeEvent: public GUIMazeEvent { public: GUIBuildMazeEvent(){} eMaze_Event GetEventID(){return EV_GUI_BUILD_MAZE;} }; /*---------------------------------------------------------------*/ class GUISearchDestEvent: public GUIMazeEvent { public: GUISearchDestEvent(){} eMaze_Event GetEventID(){return EV_GUI_SEARCH_DEST;} void SetReachedDestination(bool isReachedDest){m_IsReachedDestination = isReachedDest;} bool GetReachedDestination(){return m_IsReachedDestination;} private: bool m_IsReachedDestination; }; /*---------------------------------------------------------------*/ class GUINotifEvent:public GUIMazeEvent { public: virtual eMaze_Event GetEventID(){return EV_GUI_NOTIF;} GUINotifEvent(){m_Notif = SEARCH_COMPLETED;} eNotif GetNotif(){return m_Notif;} void SetNotif(eNotif notif){ m_Notif = notif;} string GetData(){ return m_Data;} void SetData(string data){ m_Data = data;} private: eNotif m_Notif; string m_Data; }; #endif // GUIEVEN_H_INCLUDED
true
e6e03a0c8bd1c69c6a4e58570c7454f443a899bf
C++
gun2841/guno
/PS/BOJ/C++/1912.cc
UTF-8
253
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace::std; int main() { int n, t, sum=0, m= 1<<31; scanf("%d", &n); while (n--){ scanf("%d", &t); if (sum < 0) sum = t; else sum += t; m = max(m, sum); } cout << m; }
true
ebda228457a3bec72c4f6d393c2f5d25d33455c5
C++
sangwa69/Data-Structures-and-Algorithims-Intro-II
/Project 3/StudentWorld.cpp
UTF-8
7,321
2.96875
3
[]
no_license
#include "StudentWorld.h" #include "GameConstants.h" #include <string> #include "Actor.h" #include<cmath> using namespace std; GameWorld* createStudentWorld(string assetDir) { return new StudentWorld(assetDir); } // Students: Add code to this file, StudentWorld.h, Actor.h and Actor.cpp StudentWorld::StudentWorld(string assetDir) : GameWorld(assetDir) { } int StudentWorld::init() { aliensDestroyed = 0; aliensNeededtoContinue = 6 + (4 * getLevel()); NB = new NachenBlaster(this); for (int i = 0; i < 30; i++) {// add the first 30 stars to the world int intX = randInt(0, VIEW_WIDTH - 1); addStar(actors, intX); } string text = "Lives: " + to_string(getLives()) + " Health: "+ to_string(int(NB->getHealth()*2)) + "% Score: "+ to_string(getScore()) + " Level: "+ to_string(getLevel()) + " Cabbages: "+ to_string(NB->getCabbagePoints()) +"% Torpedoes: "+to_string(NB->getTorpedoCount())+ " "; setGameStatText(text); return GWSTATUS_CONTINUE_GAME; //init always returns continue game; } int StudentWorld::move() { string text = "Lives: " + to_string(getLives()) + " Health: " + to_string(int(NB->getHealth() * 2)) + "% Score: " + to_string(getScore()) + " Level: " + to_string(getLevel()) + " Cabbages: " + to_string(NB->getCabbagePoints()*10 /3) + "% Torpedoes: " + to_string(NB->getTorpedoCount()) + " "; setGameStatText(text); if (NB->getHealth() <= 0) { decLives(); return GWSTATUS_PLAYER_DIED; //the player has died } if (aliensDestroyed >= aliensNeededtoContinue) { //when the players has killed enough aliens for the current level return GWSTATUS_FINISHED_LEVEL; } NB->doSomething(); vector<Actor*>::iterator it = actors.begin(); while (it != actors.end()) { (*it)->doSomething(); //let the star move one pixel to the left if (!((*it)->isAlive())) { //if the star's state is dead, remove it from the game delete *it; it = actors.erase(it); } else { it++; } } if (randInt(1, 15) == 1) { addStar(actors, (VIEW_WIDTH-1)); } int shipsRemaining = aliensNeededtoContinue - aliensNeededtoContinue; int maxShips = 4 + (.5*getLevel()); int currentShips = 0; for (int i = 0; i < actors.size(); i++) { if (actors[i]->isGon()) { currentShips++; } } if(currentShips < maxShips || currentShips < shipsRemaining) { //if instead of while loop so only int S1 = 60; int S2 = 20 + (getLevel() * 5); int S3 = 5 + (getLevel() * 10); int S = S1 + S2 + S3; int randS = randInt(1, S); Actor* N; if (randS <= S1 ) { //smallgon spawn N = new Smallgon(this, VIEW_WIDTH - 1, randInt(0, VIEW_HEIGHT - 1)); actors.push_back(N); } else if (randS > S1 && randS <= S - S3) { //smoregon spawn N = new Smoregon(this, VIEW_WIDTH - 1, randInt(0, VIEW_HEIGHT - 1)); actors.push_back(N); } else if (randS > S - S3) {//snagglegon spawn N = new Snagglegon(this, VIEW_WIDTH - 1, randInt(0, VIEW_HEIGHT - 1)); actors.push_back(N); } } return GWSTATUS_CONTINUE_GAME; } void StudentWorld::cleanUp() { for (int i = 0; i< actors.size(); i++) { delete (actors[i]); } actors.clear(); //clear star vector of all stars delete NB; //delete the current nachenblaster NB = nullptr; } void StudentWorld::addStar(vector<Actor*>& stars, int Xcoord) { double size = (randInt(5, 50)) / double(100); int intY = randInt(0, VIEW_HEIGHT-1); Star *S = new Star(this, IID_STAR, Xcoord, intY, 0, size, 3); stars.push_back(S); } bool StudentWorld::NachenInRange(Actor* OPT) { if (NB->getX() < OPT->getX() && abs(NB->getY() - OPT->getY()) <= 4) { //if the nachen is to the left of the alien and is within 4 pixels in either y direction return true; } return false; } bool StudentWorld::CollisionWithAlien(Actor*OPT) { for (int i = 0; i < actors.size(); i++) { if (actors[i]->isHostile()) { double distance = sqrt(pow(OPT->getX() - actors[i]->getX(), 2) + pow(OPT->getY() - actors[i]->getY(), 2)); //find the euclidian distance if (distance < (.75*(OPT->getRadius() + actors[i]->getRadius()))) { //if that distance is less that .75 * the sum of the radius's if (handleCollision(OPT, actors[i]) ){ return true; //collision detected } } } } return false;// no collision } bool StudentWorld::CollisionWithNachen(Actor*OPT){ double distance = sqrt(pow(OPT->getX() - NB->getX(), 2) + pow(OPT->getY() - NB->getY(), 2)); //find the euclidian distance if (distance < (.75*(OPT->getRadius() + NB->getRadius()))) { //if that distance is less that .75 * the sum of the radius's handleCollision(OPT, NB); return true; //COLLISION DETECTED } return false;// no collision } void StudentWorld::spawnExplosion(double startX, double startY) { Actor* N = new Explosion(this, startX, startY); actors.push_back(N); } void StudentWorld::shootCabbage(double startX, double startY) { Actor* N = new Cabbage(this, startX, startY); actors.push_back(N); } void StudentWorld::shootTurnip(double startX, double startY) { Actor* N = new Turnip(this, startX, startY); actors.push_back(N); } void StudentWorld::shootTorpedo(double startX, double startY, int faction) { Actor* N = new Torpedo(this, startX, startY, faction); actors.push_back(N); } bool StudentWorld::handleCollision(Actor* Dealer, Actor* taker) { if (Dealer->isProjectile() && taker->isProjectile()) { //two projectiles will never intersect return false; } if (Dealer->getObjectScore() > 0) { //when the damage dealer is an alien ship or a goodie , taker is the nachenblaster Dealer->setDead(); if (Dealer->isGon()) { //the collision is with an alien taker->sufferDamage(Dealer->getDamage()); playSound(SOUND_DEATH); spawnExplosion(Dealer->getX(), Dealer->getY()); Dealer->GoodieAction(); aliensDestroyed++; //increment the number of aliens destroyed } else { //collision with a goodie playSound(SOUND_GOODIE); } increaseScore(Dealer->getObjectScore()); } else if(Dealer->isProjectile()) { //the dealer is a projectile taker->sufferDamage(Dealer->getDamage()); Dealer->setDead(); //destroy the projectile after it hits an alien if (taker->getHealth() <= 0) { //when the alien dies, create an explosion taker->setDead(); increaseScore(taker->getObjectScore()); if (taker->isHostile()) { playSound(SOUND_DEATH); spawnExplosion(taker->getX(), taker->getY()); aliensDestroyed++; //increment the number of aliens destroyed taker->GoodieAction(); } } else { playSound(SOUND_BLAST); //sound for when the projectile impacts the alien but does not kill it } } return true;//succesful collision action } void StudentWorld::healNB(double amt) { NB->sufferDamage(-amt); if (NB->getHealth() > 50) { NB->setHealth(50); } } //suffering negative damage heals the actor void StudentWorld::addTorpedo() { NB->increaseTorpedoCount(); } void StudentWorld::spawnExtraLife(double startX, double startY) { Actor* N = new ExtraLifeGoodie(this, startX, startY); actors.push_back(N); } void StudentWorld::spawnRepair(double startX, double startY) { Actor* N = new RepairGoodie(this, startX, startY); actors.push_back(N); } void StudentWorld::spawnTorpedoG(double startX, double startY) { Actor* N = new TorpedoGoodie(this, startX, startY); actors.push_back(N); }
true
c50e5a0354d71c982c7c4a9178ca161315857279
C++
sebastiandev/muxer
/musicindexer/ui/compactplaylist.h
UTF-8
906
2.609375
3
[]
no_license
#ifndef COMPACTPLAYLIST_H #define COMPACTPLAYLIST_H #include <QWidget> #include <QModelIndex> #include <QPair> #include "entities/song.h" namespace Ui { class CompactPlaylist; } class CompactPlaylist : public QWidget { Q_OBJECT public: explicit CompactPlaylist(QWidget *parent = 0); ~CompactPlaylist(); void addSong (const Song &song, const QString &file); void setCurrentSong(int pos) { _currentSong = pos-1;}//because the index starts on 0 int currentSong(); void nextSong (); bool contains(const Song &song); void clear (); int size () { return _playlist.size();} Q_SIGNALS: void playSong(const Song&, const QString&); private Q_SLOTS: void slotSongSelected(int row, int col); private: Ui::CompactPlaylist *ui; QMap<QString, QPair<Song, QString> > _playlist; int _currentSong; }; #endif // COMPACTPLAYLIST_H
true
d26aadeed79bce5130a28f76a7176488e1fc324a
C++
gorevojd/Ivan
/Source/asset_builder.cpp
UTF-8
66,062
2.53125
3
[]
no_license
#include "asset_builder.h" /* NOTE(Dima): 1) Images are stored in gamma-corrected premultiplied-alpha format 2) Animations will be baked into models. Later maybe if I need I should make that I can do it both ways. 3) IMPORTANT!!! If you bake multiple animations in a single file, you should make sure that theese animations are common by sence. */ /* TODO(Dima): Font Atlas Model asset type with animations baked into it */ #pragma pack(push, 1) struct bitmap_header{ uint16 FileType; /*File type, always 4d42 ("BM")*/ uint32 FileSize; /*Size of the file in bytes*/ uint16 Reserved1; /*Always 0*/ uint16 Reserved2; /*Always 0*/ uint32 BitmapOffset; /*Starting position of image data in bytes*/ uint32 Size; /*Size of header in bytes*/ int32 Width; /*Image width in pixels*/ int32 Height; /*Image height in pixels*/ uint16 Planes; /*Number of color planes*/ uint16 BitsPerPixel; /*Number of bits per pixel*/ uint32 Compression; /*Compression methods used*/ uint32 SizeOfBitmap; /*Size of bitmap in bytes*/ int32 HorzResolution;/*Horizontal resolution in pixels per meter*/ int32 VertResolution;/*Vertical resolution in pixels per meter*/ uint32 ColorsUsed;/*Number of colors in the image*/ uint32 ColorsImportant;/*Minimum number of important colors*/ uint32 RedMask; /*Mask identifying bits of red component*/ uint32 GreenMask; /*Mask identifying bits of green component*/ uint32 BlueMask; /*Mask identifying bits of blue component*/ uint32 AlphaMask; /*Mask identifying bits of Alpha component*/ uint32 CSType; /*Color space type*/ int32 RedX; /*X coordinate of red endpoint*/ int32 RedY; /*Y coordinate of red endpoint*/ int32 RedZ; /*Z coordinate of red endpoint*/ int32 GreenX; /*X coordinate of green endpoint*/ int32 GreenY; /*Y coordinate of green endpoint*/ int32 GreenZ; /*Z coordinate of green endpoint*/ int32 BlueX; /*X coordinate of blue endpoint*/ int32 BlueY; /*Y coordinate of blue endpoint*/ int32 BlueZ; /*Z coordinate of blue endpoint*/ uint32 GammaRed; /*Gamma red coordinate scale value*/ uint32 GammaGreen; /*Gamma green coordinate scale value*/ uint32 GammaBlue; /*Gamma blue coordinate scale value*/ }; struct WAVE_header{ uint32 RIFFID; uint32 Size; uint32 WAVEID; }; #define RIFF_CODE(a, b, c, d) (((uint32)(a) << 0) | ((uint32)(b) << 8) | ((uint32)(c) << 16) | ((uint32)(d) << 24)) enum{ WAVE_ChunkID_fmt = RIFF_CODE('f', 'm', 't', ' '), WAVE_ChunkID_RIFF = RIFF_CODE('R', 'I', 'F', 'F'), WAVE_ChunkID_WAVE = RIFF_CODE('W', 'A', 'V', 'E'), WAVE_ChunkID_data = RIFF_CODE('d', 'a', 't', 'a'), }; struct WAVE_chunk{ uint32 Id; uint32 Size; }; struct WAVE_fmt{ uint16 wFormatTag; uint16 nChannels; uint32 nSamplesPerSec; uint32 nAvgBytesPerSec; uint16 nBlockAlign; uint16 wBitsPerSample; uint16 cbSize; uint16 wValidBitsPerSample; uint32 dwChannelMask; uint8 SubFormat[16]; }; #pragma pack(pop) struct loaded_file{ unsigned int DataSize; void* Data; }; loaded_file ReadEntireFile(char* FileName){ loaded_file Result = {}; FILE* In = fopen(FileName, "rb"); if(In){ fseek(In, 0, SEEK_END); Result.DataSize = ftell(In); fseek(In, 0, SEEK_SET); Result.Data = malloc(Result.DataSize); fread(Result.Data, Result.DataSize, 1, In); fclose(In); } else{ printf("ERROR: Can not open the file %s\n", FileName); } return(Result); } struct loaded_bitmap{ int Width; int Height; void* Memory; void* Free; }; #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_STATIC #include "stb_image.h" INTERNAL_FUNCTION loaded_bitmap LoadBMP(char* FileName, bool32 FlipOnLoad = false){ loaded_bitmap Result = {}; stbi_set_flip_vertically_on_load(FlipOnLoad); loaded_file ReadResult = ReadEntireFile(FileName); Result.Free = ReadResult.Data; Result.Memory = stbi_load_from_memory( (stbi_uc*)ReadResult.Data, ReadResult.DataSize, &Result.Width, &Result.Height, 0, STBI_rgb_alpha); uint32* Pixel = (uint32*)Result.Memory; for (int j = 0; j < Result.Height; j++){ for (int i = 0; i < Result.Width; i++){ uint32 SrcPixel = *Pixel; vec4 Color = { (float)(SrcPixel & 0xFF), (float)((SrcPixel >> 8) & 0xFF), (float)((SrcPixel >> 16) & 0xFF), (float)((SrcPixel >> 24) & 0xFF) }; #if 1 /*Gamma-corrected premultiplied alpha*/ Color = SRGB255ToLinear1(Color); real32 Alpha = Color.a; Color.r = Color.r * Alpha; Color.g = Color.g * Alpha; Color.b = Color.b * Alpha; Color = Linear1ToSRGB255(Color); #else /*Premultiplied alpha*/ Color.rgb *= Color.a; #endif *Pixel++ = (((uint32)(Color.a + 0.5f) << 24) | ((uint32)(Color.r + 0.5f) << 16) | ((uint32)(Color.g + 0.5f) << 8) | ((uint32)(Color.b + 0.5f) << 0)); } } return(Result); } enum load_mesh_flags{ LoadMesh_RecalculateNormals = 1, LoadMesh_CalculateTangents = 2, LoadMesh_LoadSkinData = 4, LoadMesh_UseExistingSkeleton = 8, }; #if BUILD_WITH_ASSIMP INTERNAL_FUNCTION void LoadBoneInfoFromAssimp( aiMesh* Mesh, uint32 VertexBase, bone_vertex_info* Infos, loaded_skeleton* Skeleton) { for(uint32 BoneIndex = 0; BoneIndex < Mesh->mNumBones; BoneIndex++) { Assert(Mesh->mNumBones <= MAX_BONE_COUNT); char* BoneName = Mesh->mBones[BoneIndex]->mName.data; std::string BoneNameString = std::string(BoneName); uint32 IndexToBoneArray = 0; if(Skeleton != 0){ if(Skeleton->BoneMapping.find(BoneName) == Skeleton->BoneMapping.end()){ IndexToBoneArray = Skeleton->BoneMapping.size(); bone_transform_info BoneTransform; BoneTransform.Name = BoneName; BoneTransform.Offset = AiMatToOurs(&Mesh->mBones[BoneIndex]->mOffsetMatrix); Skeleton->Bones.push_back(BoneTransform); Skeleton->BoneMapping[BoneNameString] = IndexToBoneArray; } else{ IndexToBoneArray = Skeleton->BoneMapping[BoneNameString]; } } for(uint32 WeightIndex = 0; WeightIndex < Mesh->mBones[BoneIndex]->mNumWeights; WeightIndex++) { uint32 VertexIndex = VertexBase + Mesh->mBones[BoneIndex]->mWeights[WeightIndex].mVertexId; AddBoneVertexInfo( &Infos[VertexIndex], Mesh->mBones[BoneIndex]->mWeights[WeightIndex].mWeight, IndexToBoneArray); } } } INTERNAL_FUNCTION void LoadSkinnedMeshDataFromAssimp( loaded_mesh* Result, char* FileName, loaded_skeleton* Skeleton) { Assimp::Importer Importer; const aiScene* AssimpScene = Importer.ReadFile(FileName, 0); Result->Type = DDAMeshType_Skinned; uint32 IndexBase = 0; uint32 VertexBase = 0; uint32 TotalVertexCount = 0; for(uint32 MeshIndex = 0; MeshIndex < AssimpScene->mNumMeshes; MeshIndex++) { TotalVertexCount += AssimpScene->mMeshes[MeshIndex]->mNumVertices; } Result->VerticesCount = TotalVertexCount; bone_vertex_info* VertexInfos = (bone_vertex_info*)calloc(TotalVertexCount, sizeof(bone_vertex_info)); for(uint32 MeshIndex = 0; MeshIndex < AssimpScene->mNumMeshes; MeshIndex++) { aiMesh* Mesh = AssimpScene->mMeshes[MeshIndex]; if(Mesh->mNumBones > 0){ LoadBoneInfoFromAssimp(Mesh, VertexBase, VertexInfos, Skeleton); } VertexBase += Mesh->mNumVertices; } VertexBase = 0; for(uint32 MeshIndex = 0; MeshIndex < AssimpScene->mNumMeshes; MeshIndex++) { aiMesh* Mesh = AssimpScene->mMeshes[MeshIndex]; for(uint32 VertexIndex = 0; VertexIndex < Mesh->mNumVertices; VertexIndex++) { aiVector3D* RefP = &Mesh->mVertices[VertexIndex]; aiVector3D* RefN = &Mesh->mNormals[VertexIndex]; Assert(VertexBase + VertexIndex <= MAX_VERTICES_COUNT); skinned_vertex* NewVertex = &Result->SkinnedVertices[VertexBase + VertexIndex]; NewVertex->P.x = RefP->x; NewVertex->P.y = RefP->y; NewVertex->P.z = RefP->z; NewVertex->N.x = RefN->x; NewVertex->N.y = RefN->y; NewVertex->N.z = RefN->z; if(Mesh->mTextureCoords[0]){ NewVertex->UV.x = Mesh->mTextureCoords[0][VertexIndex].x; NewVertex->UV.y = Mesh->mTextureCoords[0][VertexIndex].y; } for(int32 InfluenceBoneIndex = 0; InfluenceBoneIndex < MAX_INFLUENCE_BONE_COUNT; InfluenceBoneIndex++) { NewVertex->Weights[InfluenceBoneIndex] = VertexInfos[VertexBase + VertexIndex].Weights[InfluenceBoneIndex]; NewVertex->BoneIDs[InfluenceBoneIndex] = VertexInfos[VertexBase + VertexIndex].BoneIDs[InfluenceBoneIndex]; } } uint32 IndexIterator = 0; for(uint32 FaceIndex = 0; FaceIndex < Mesh->mNumFaces; FaceIndex++) { aiFace* AssimpFace = &Mesh->mFaces[FaceIndex]; for(uint32 FaceVertexIndex = AssimpFace->mNumIndices; FaceVertexIndex > 0; FaceVertexIndex--) { Result->Indices[IndexBase + IndexIterator++] = AssimpFace->mIndices[FaceVertexIndex - 1]; } } #if 1 //NOTE(Dima): Tangents calculation for(uint32 FaceIndex = 0; FaceIndex < Mesh->mNumFaces; FaceIndex++) { aiFace* AssimpFace = &Mesh->mFaces[FaceIndex]; if(AssimpFace->mNumIndices == 3){ vec3 NewT; vec3 Vert1 = AiVec3ToOurs(Mesh->mVertices[AssimpFace->mIndices[0]]); vec3 Vert2 = AiVec3ToOurs(Mesh->mVertices[AssimpFace->mIndices[1]]); vec3 Vert3 = AiVec3ToOurs(Mesh->mVertices[AssimpFace->mIndices[2]]); vec2 UV1 = AiVec3ToOurs(Mesh->mTextureCoords[0][AssimpFace->mIndices[0]]).xy; vec2 UV2 = AiVec3ToOurs(Mesh->mTextureCoords[0][AssimpFace->mIndices[1]]).xy; vec2 UV3 = AiVec3ToOurs(Mesh->mTextureCoords[0][AssimpFace->mIndices[2]]).xy; vec3 Edge1 = Vert2 - Vert1; vec3 Edge2 = Vert3 - Vert1; vec2 DeltaUV1 = UV2 - UV1; vec2 DeltaUV2 = UV3 - UV1; float f = 1.0f / (DeltaUV1.x * DeltaUV2.y - DeltaUV2.x * DeltaUV1.y); NewT.x = f *(DeltaUV2.y * Edge1.x - DeltaUV1.y * Edge2.x); NewT.y = f *(DeltaUV2.y * Edge1.y - DeltaUV1.y * Edge2.y); NewT.z = f *(DeltaUV2.y * Edge1.z - DeltaUV1.y * Edge2.z); NewT = Normalize(NewT); Result->SkinnedVertices[IndexBase + AssimpFace->mIndices[0]].T = NewT; Result->SkinnedVertices[IndexBase + AssimpFace->mIndices[1]].T = NewT; Result->SkinnedVertices[IndexBase + AssimpFace->mIndices[2]].T = NewT; } } #endif IndexBase += IndexIterator; } Result->IndicesCount = IndexBase; free(VertexInfos); } inline aiNodeAnim* FindNodeAnimInAssimpAnimation(aiAnimation* Animation, char* NodeName){ aiNodeAnim* Result = 0; for(uint32 ChannelIndex = 0; ChannelIndex < Animation->mNumChannels; ChannelIndex++) { aiNodeAnim* NodeAnim = Animation->mChannels[ChannelIndex]; if(strcmp(NodeAnim->mNodeName.data, NodeName) == 0){ Result = NodeAnim; break; } } return(Result); } INTERNAL_FUNCTION void LoadJointAnimationFromAssimpRecursively( loaded_animation* SkAnimation, aiNode* AssimpNode, aiAnimation* AssimpAnimation, loaded_skeleton* Skeleton) { std::string CurrentJointName = std::string(AssimpNode->mName.data); uint32 CurrentJointIndex = Skeleton->BoneMapping[CurrentJointName]; joint_animation* Animation = &SkAnimation->JointAnims[CurrentJointIndex]; aiNodeAnim* NodeAnim = FindNodeAnimInAssimpAnimation(AssimpAnimation, AssimpNode->mName.data); Animation->TranslationFramesCount = NodeAnim->mNumPositionKeys; Animation->RotationFramesCount = NodeAnim->mNumRotationKeys; Animation->ScalingFramesCount = NodeAnim->mNumScalingKeys; uint32 JointMemoryBlockByteSize = (Animation->TranslationFramesCount * sizeof(translation_key_frame)) + (Animation->RotationFramesCount * sizeof(rotation_key_frame)) + (Animation->ScalingFramesCount * sizeof(scaling_key_frame)); uint8* JointMemoryBlock = (uint8*)malloc(JointMemoryBlockByteSize); memset(JointMemoryBlock, 0, JointMemoryBlockByteSize); Animation->TranslationFrames = (translation_key_frame*)JointMemoryBlock; Animation->RotationFrames = (rotation_key_frame*)(JointMemoryBlock + Animation->TranslationFramesCount * sizeof(translation_key_frame)); Animation->ScalingFrames = (scaling_key_frame*)((uint8*)Animation->RotationFrames + Animation->RotationFramesCount * sizeof(rotation_key_frame)); Animation->Free = JointMemoryBlock; //NOTE(Dima): Copying the translation animation data; for(uint32 TranslationFrameIndex = 0; TranslationFrameIndex < Animation->TranslationFramesCount; TranslationFrameIndex++) { aiVectorKey* SrcFrame = &NodeAnim->mPositionKeys[TranslationFrameIndex]; translation_key_frame* DstFrame = &Animation->TranslationFrames[TranslationFrameIndex]; DstFrame->TimeStamp = (float)SrcFrame->mTime; DstFrame->Translation = AiVec3ToOurs(SrcFrame->mValue); } //NOTE(Dima): Copying the rotation animation data; for(uint32 RotationFrameIndex = 0; RotationFrameIndex < Animation->RotationFramesCount; RotationFrameIndex++) { aiQuatKey* SrcFrame = &NodeAnim->mRotationKeys[RotationFrameIndex]; rotation_key_frame* DstFrame = &Animation->RotationFrames[RotationFrameIndex]; DstFrame->TimeStamp = (float)SrcFrame->mTime; DstFrame->Rotation = AiQuatToOurs(SrcFrame->mValue); } //NOTE(Dima): Copying the scaling animation data; for(uint32 ScalingFrameIndex = 0; ScalingFrameIndex < Animation->ScalingFramesCount; ScalingFrameIndex++) { aiVectorKey* SrcFrame = &NodeAnim->mScalingKeys[ScalingFrameIndex]; scaling_key_frame* DstFrame = &Animation->ScalingFrames[ScalingFrameIndex]; DstFrame->TimeStamp = (float)SrcFrame->mTime; DstFrame->Scaling = AiVec3ToOurs(SrcFrame->mValue); } char* CurrentBoneName = AssimpNode->mName.data; std::string CurrentBoneNameStr = std::string(CurrentBoneName); bone_transform_info* CurrentBoneTransform = &(Skeleton->Bones.at(Skeleton->BoneMapping[CurrentBoneNameStr])); //NOTE(Dima): Children processing if(AssimpNode->mNumChildren > 0){ //NOTE(Dima): Allocating children CurrentBoneTransform->ChildrenCount = AssimpNode->mNumChildren; /* CurrentBoneTransform->Children = (bone_transform_info*) malloc(sizeof(bone_transform_info) * CurrentBoneTransform->ChildrenCount); */ CurrentBoneTransform->Children = (uint32*)malloc(sizeof(uint32) * CurrentBoneTransform->ChildrenCount); //NOTE(Dima): Assigning children indices to current bone for(uint32 ChildIndex = 0; ChildIndex < AssimpNode->mNumChildren; ChildIndex++) { std::string ChildNodeName = std::string(AssimpNode->mChildren[ChildIndex]->mName.data); if(Skeleton->BoneMapping.find(ChildNodeName) != Skeleton->BoneMapping.end()){ CurrentBoneTransform->Children[ChildIndex] = Skeleton->BoneMapping[ChildNodeName]; } else{ //NOTE(Dima): This should not happen because child bone should be found INVALID_CODE_PATH; } } } else{ CurrentBoneTransform->Children = 0; CurrentBoneTransform->ChildrenCount = 0; } //NOTE(Dima): Hopefully this should work if(AssimpNode->mNumChildren){ for(uint32 ChildIndex = 0; ChildIndex < AssimpNode->mNumChildren; ChildIndex++) { LoadJointAnimationFromAssimpRecursively( SkAnimation, AssimpNode->mChildren[ChildIndex], AssimpAnimation, Skeleton); } } } INTERNAL_FUNCTION loaded_animations_result LoadSkeletalAnimation( char* FileName, loaded_skeleton* Skeleton, asset_animation_type AssetAnimationType) { Assimp::Importer Importer; const aiScene* AssimpScene = Importer.ReadFile(FileName, 0); loaded_animations_result Result_ = {}; loaded_animations_result* Result = &Result_; uint32 SrcAnimationsCount = AssimpScene->mNumAnimations; Result->AnimationsCount = SrcAnimationsCount; Result->Animations = (loaded_animation*)malloc(sizeof(loaded_animation) * SrcAnimationsCount); Result->Free = (void*)Result->Animations; for(uint32 CurrentAnimationIndex = 0; CurrentAnimationIndex < SrcAnimationsCount; CurrentAnimationIndex++) { aiAnimation* SrcAnim = AssimpScene->mAnimations[CurrentAnimationIndex]; loaded_animation* DstAnim = &Result->Animations[CurrentAnimationIndex]; DstAnim->LengthTime = (float)SrcAnim->mDuration; DstAnim->PlayCursorTime = 0.0f; DstAnim->PlaybackSpeed = 1.0f; DstAnim->Type = AssetAnimationType; if(SrcAnim->mTicksPerSecond != 0){ DstAnim->TicksPerSecond = SrcAnim->mTicksPerSecond; } else{ DstAnim->TicksPerSecond = 25.0f; } uint32 BonesCount = Skeleton->Bones.size(); memset(DstAnim->JointAnims, 0, DDA_ANIMATION_MAX_BONE_COUNT * sizeof(joint_animation)); DstAnim->JointAnimsCount = BonesCount; LoadJointAnimationFromAssimpRecursively( DstAnim, AssimpScene->mRootNode, SrcAnim, Skeleton); } return(Result_); } #endif INTERNAL_FUNCTION loaded_font* LoadFont(char* FileName, char* FontName, int PixelHeight){ loaded_font* Font = (loaded_font*)malloc(sizeof(loaded_font)); #if USE_FONTS_FROM_WINDOWS AddFontResourceExA(FileName, FR_PRIVATE, 0); Font->Win32Handle = CreateFontA( PixelHeight, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, FontName); SelectObject(GlobalFontDeviceContext, Font->Win32Handle); GetTextMetrics(GlobalFontDeviceContext, &Font->TextMetric); #else loaded_file TTFFile = ReadEntireFile(FileName); Font->FileContents = TTFFile.Data; if(TTFFile.DataSize != 0){ stbtt_InitFont( &Font->FontInfo, (uint8*)TTFFile.Data, stbtt_GetFontOffsetForIndex((uint8*)TTFFile.Data, 0)); Font->Scale = stbtt_ScaleForPixelHeight(&Font->FontInfo, PixelHeight); int Ascent, Descent, LineGap; stbtt_GetFontVMetrics(&Font->FontInfo, &Ascent, &Descent, &LineGap); Font->AscenderHeight = Font->Scale * Ascent; Font->DescenderHeight = Font->Scale * -Descent; Font->ExternalLeading = Font->Scale * LineGap; } #endif Font->MinCodePoint = INT_MAX; Font->MaxCodePoint = 0; Font->MaxGlyphCount = 5000; Font->GlyphCount = 0; uint32 GlyphFromCodepointArraySize = ONE_PAST_MAX_FONT_CODEPOINT * sizeof(uint32); Font->GlyphIndexFromCodePoint = (uint32*)malloc(GlyphFromCodepointArraySize); memset(Font->GlyphIndexFromCodePoint, 0, GlyphFromCodepointArraySize); Font->Glyphs = (dda_font_glyph*)malloc(sizeof(dda_font_glyph) * Font->MaxGlyphCount); size_t HorizontalAdvanceArraySize = sizeof(float) * Font->MaxGlyphCount * Font->MaxGlyphCount; Font->HorizontalAdvance = (float*)malloc(HorizontalAdvanceArraySize); memset(Font->HorizontalAdvance, 0, HorizontalAdvanceArraySize); Font->OnePastHighestCodepoint = 0; Font->GlyphCount = 1; Font->Glyphs[0].UnicodeCodePoint = 0; Font->Glyphs[0].BitmapID.Value = 0; return(Font); } INTERNAL_FUNCTION loaded_voxel_atlas* LoadVoxelAtlas(char* FileName, uint32 AtlasWidth, uint32 OneTextureWidth) { /*AtlasWidth must be multiple of OneTextureWidth*/ Assert((AtlasWidth & (OneTextureWidth - 1)) == 0); loaded_voxel_atlas* Atlas = (loaded_voxel_atlas*)malloc(sizeof(loaded_voxel_atlas)); uint32 TexturesByWidth = AtlasWidth / OneTextureWidth; Atlas->MaxTextureCount = TexturesByWidth * TexturesByWidth; Atlas->TextureCount = 0; Atlas->AtlasWidth = AtlasWidth; Atlas->OneTextureWidth = OneTextureWidth; Atlas->TextureFileName = FileName; float UVOneTextureDelta = (float)OneTextureWidth / (float)AtlasWidth; for(int MaterialIndex = 0; MaterialIndex < VoxelMaterial_Count; MaterialIndex++) { for(int i = 0; i < VoxelFaceTypeIndex_Count; i++) { Atlas->Materials[MaterialIndex].Sets[i] = 0; } } return(Atlas); } INTERNAL_FUNCTION void FinalizeFontKerning(loaded_font* Font){ #if USE_FONTS_FROM_WINDOWS SelectObject(GlobalFontDeviceContext, Font->Win32Handle); DWORD KerningPairCount = GetKerningPairsW(GlobalFontDeviceContext, 0, 0); KERNINGPAIR* KerningPairs = (KERNINGPAIR*)malloc(KerningPairCount * sizeof(KERNINGPAIR)); GetKerningPairsW(GlobalFontDeviceContext, KerningPairCount, KerningPairs); for(DWORD KernPairIndex = 0; KernPairIndex < KerningPairCount; KernPairIndex++) { KERNINGPAIR* Pair = KerningPairs + KernPairIndex; if((Pair->wFirst < ONE_PAST_MAX_FONT_CODEPOINT) && (Pair->wSecond < ONE_PAST_MAX_FONT_CODEPOINT)) { uint32 First = Font->GlyphIndexFromCodePoint[Pair->wFirst]; uint32 Second = Font->GlyphIndexFromCodePoint[Pair->wSecond]; if((First != 0) && (Second != 0)){ Font->HorizontalAdvance[First * Font->MaxGlyphCount + Second] += (float)Pair->iKernAmount; } } } free(KerningPairs); #else for(uint32 FirstGlyphIndex = 1; FirstGlyphIndex < Font->GlyphCount; FirstGlyphIndex++) { dda_font_glyph First = Font->Glyphs[FirstGlyphIndex]; for(uint32 SecondGlyphIndex = 1; SecondGlyphIndex < Font->GlyphCount; SecondGlyphIndex++) { dda_font_glyph Second = Font->Glyphs[SecondGlyphIndex]; float KernAdvance = Font->Scale * stbtt_GetCodepointKernAdvance( &Font->FontInfo, First.UnicodeCodePoint, Second.UnicodeCodePoint); Font->HorizontalAdvance[SecondGlyphIndex * Font->MaxGlyphCount + FirstGlyphIndex] += KernAdvance; } } #endif } INTERNAL_FUNCTION void FreeFont(loaded_font* Font){ if(Font){ #if USE_FONTS_FROM_WINDOWS DeleteObject(Font->Win32Handle); #else free(Font->FileContents); #endif free(Font->Glyphs); free(Font->HorizontalAdvance); free(Font->GlyphIndexFromCodePoint); free(Font); } } INTERNAL_FUNCTION void InitializeFontDC(){ #if USE_FONTS_FROM_WINDOWS GlobalFontDeviceContext = CreateCompatibleDC(GetDC(0)); BITMAPINFO Info = {}; Info.bmiHeader.biSize = sizeof(Info.bmiHeader); Info.bmiHeader.biWidth = MAX_FONT_WIDTH; Info.bmiHeader.biHeight = MAX_FONT_HEIGHT; Info.bmiHeader.biPlanes = 1; Info.bmiHeader.biBitCount = 32; Info.bmiHeader.biCompression = BI_RGB; Info.bmiHeader.biSizeImage = 0; Info.bmiHeader.biXPelsPerMeter = 0; Info.bmiHeader.biYPelsPerMeter = 0; Info.bmiHeader.biClrUsed = 0; Info.bmiHeader.biClrImportant = 0; HBITMAP Bitmap = CreateDIBSection(GlobalFontDeviceContext, &Info, DIB_RGB_COLORS, &GlobalFontBits, 0, 0); SelectObject(GlobalFontDeviceContext, Bitmap); SetBkColor(GlobalFontDeviceContext, RGB(0, 0, 0)); #endif } INTERNAL_FUNCTION loaded_bitmap LoadGlyphBitmap(loaded_font* Font, uint32 Codepoint, dda_asset* Asset){ loaded_bitmap Result = {}; uint32 GlyphIndex = Font->GlyphIndexFromCodePoint[Codepoint]; #if USE_FONTS_FROM_WINDOWS SelectObject(GlobalFontDeviceContext, Font->Win32Handle); memset(GlobalFontBits, 0x00, MAX_FONT_WIDTH * MAX_FONT_HEIGHT * sizeof(uint32)); wchar_t FakePoint = (wchar_t)Codepoint; SIZE Size; GetTextExtentPoint32W(GlobalFontDeviceContext, &FakePoint, 1, &Size); int PreStepX = 128; int BoundWidth = Size.cx + 2 * PreStepX; if(BoundWidth > MAX_FONT_WIDTH){ BoundWidth = MAX_FONT_WIDTH; } int BoundHeight = Size.cy; if(BoundHeight > MAX_FONT_HEIGHT){ BoundHeight = MAX_FONT_HEIGHT; } SetTextColor(GlobalFontDeviceContext, RGB(255, 255, 255)); TextOutW(GlobalFontDeviceContext, PreStepX, 0, &FakePoint, 1); int MinX = 10000; int MinY = 10000; int MaxX = -10000; int MaxY = -10000; for(int j = 0; j < BoundHeight; j++){ uint32 *Pixel = (uint32*)GlobalFontBits + (MAX_FONT_HEIGHT - 1 - j) * MAX_FONT_WIDTH; for(int i = 0; i < BoundWidth; i++){ if(*Pixel != 0) { if(MinX > i) { MinX = i; } if(MinY > j) { MinY = j; } if(MaxX < i) { MaxX = i; } if(MaxY < j) { MaxY = j; } } ++Pixel; } } float KerningChange = 0; if(MinX <= MaxX){ int Width = (MaxX - MinX) + 1; int Height = (MaxY - MinY) + 1; Result.Width = Width + 2; Result.Height = Height + 2; Result.Memory = malloc(Result.Height * Result.Width * 4); Result.Free = Result.Memory; memset(Result.Memory, 0, Result.Height * Result.Width * 4); uint8* DestRow = (uint8*)Result.Memory + (Result.Height - 1 - 1) * Result.Width * 4; uint32* SourceRow = (uint32*)GlobalFontBits + (MAX_FONT_HEIGHT - 1 - MinY) * MAX_FONT_WIDTH; for(int j = MinY; j < MaxY; j++){ uint32* Source = (uint32*)SourceRow + MinX; uint32* Dest = (uint32*)DestRow + 1; for(int i = MinX; i < MaxX; i++){ uint32 Pixel = *Source; float Gray = (float)(Pixel & 0xFF); vec4 Texel = {255.0f, 255.0f, 255.0f, Gray}; Texel = SRGB255ToLinear1(Texel); Texel.rgb *= Texel.a; Texel = Linear1ToSRGB255(Texel); *Dest++ = (((uint32)(Texel.a + 0.5f) << 24) | ((uint32)(Texel.r + 0.5f) << 16) | ((uint32)(Texel.g + 0.5f) << 8) | ((uint32)(Texel.b + 0.5f) << 0)); Source++; } DestRow -= Result.Width * 4; SourceRow -= MAX_FONT_WIDTH; } Asset->Bitmap.AlignPercentage[0] = (1.0f) / (float)Result.Width; Asset->Bitmap.AlignPercentage[1] = (1.0f + (MaxY - (BoundHeight - Font->TextMetric.tmDescent))) / (float)Result.Height; KerningChange = (float)(MinX - PreStepX); } INT ThisWidth; GetCharWidth32W(GlobalFontDeviceContext, Codepoint, Codepoint, &ThisWidth); float CharAdvance = (float)ThisWidth; #else int Width, Height, XOffset, YOffset; uint8* MonoBitmap = stbtt_GetCodepointBitmap( &Font->FontInfo, 0, Font->Scale, Codepoint, &Width, &Height, &XOffset, &YOffset); Result.Width = Width + 2; Result.Height = Height + 2; Result.Memory = malloc(Result.Width * Result.Height * 4); Result.Free = Result.Memory; memset(Result.Memory, 0, Result.Width * Result.Height * 4); uint8* Source = MonoBitmap; uint8* DestRow = (uint8*)Result.Memory + (Result.Height - 1 - 1) * Result.Width * 4; for(int j = 0; j < Height; j++){ uint32* Dest = ((uint32*)DestRow) + 1; for(int i = 0; i < Width; i++){ uint32 Pixel = *Source; float Gray = (float)(Pixel & 0xFF); vec4 Texel = {255.0f, 255.0f, 255.0f, Gray}; Texel = SRGB255ToLinear1(Texel); Texel.rgb *= Texel.a; Texel = Linear1ToSRGB255(Texel); *Dest++ = (((uint32)(Texel.a + 0.5f) << 24) | ((uint32)(Texel.r + 0.5f) << 16) | ((uint32)(Texel.g + 0.5f) << 8) | ((uint32)(Texel.b + 0.5f) << 0)); Source++; } DestRow -= Result.Width * 4; } stbtt_FreeBitmap(MonoBitmap, 0); Asset->Bitmap.AlignPercentage[0] = (1.0f) / (float)Result.Width; Asset->Bitmap.AlignPercentage[1] = (1.0f + (Height + YOffset)) / (float)Result.Height; float KerningChange = (float)XOffset; int Advance; stbtt_GetCodepointHMetrics(&Font->FontInfo, Codepoint, &Advance, 0); float CharAdvance = Font->Scale * (float)Advance; #endif for(uint32 OtherGlyphIndex = 0; OtherGlyphIndex < Font->MaxGlyphCount; OtherGlyphIndex++) { Font->HorizontalAdvance[GlyphIndex * Font->MaxGlyphCount + OtherGlyphIndex] += CharAdvance - KerningChange; if(OtherGlyphIndex != 0){ Font->HorizontalAdvance[OtherGlyphIndex * Font->MaxGlyphCount + GlyphIndex] += KerningChange; } } return(Result); } struct riff_iterator{ uint8* At; uint8* Stop; }; inline riff_iterator ParseChunkAt(void* At, void* Stop){ riff_iterator Iter; Iter.At = (uint8*)At; Iter.Stop = (uint8*)Stop; return(Iter); } inline riff_iterator NextChunk(riff_iterator Iter){ WAVE_chunk* Chunk = (WAVE_chunk*)Iter.At; uint32 Size = (Chunk->Size + 1) & ~1; Iter.At += sizeof(WAVE_chunk) + Size; return(Iter); } inline bool32 IsValid(riff_iterator Iter){ bool32 Result = (Iter.At < Iter.Stop); return(Result); } inline void* GetChunkData(riff_iterator Iter){ void* Result = (Iter.At + sizeof(WAVE_chunk)); return(Result); } inline uint32 GetType(riff_iterator Iter){ WAVE_chunk* Chunk = (WAVE_chunk*)Iter.At; uint32 Result = Chunk->Id; return(Result); } inline uint32 GetChunkDataSize(riff_iterator Iter){ WAVE_chunk* Chunk = (WAVE_chunk*)Iter.At; uint32 Result = Chunk->Size; return(Result); } struct loaded_sound{ uint32 SampleCount; uint32 ChannelCount; int16* Samples[2]; void* Free; }; INTERNAL_FUNCTION loaded_sound LoadWAV(char* FileName, uint32 SectionFirstSampleIndex, uint32 SectionSampleCount){ loaded_sound Result = {}; loaded_file ReadResult = ReadEntireFile(FileName); if(ReadResult.DataSize != 0){ Result.Free = ReadResult.Data; WAVE_header* Header = (WAVE_header*)ReadResult.Data; Assert(Header->RIFFID == WAVE_ChunkID_RIFF); Assert(Header->WAVEID == WAVE_ChunkID_WAVE); int16* SampleData = 0; uint32 ChannelCount = 0; uint32 SampleDataSize = 0; for(riff_iterator Iter = ParseChunkAt(Header + 1, (uint8*)(Header + 1) + Header->Size - 4); IsValid(Iter); Iter = NextChunk(Iter)) { switch(GetType(Iter)){ case WAVE_ChunkID_fmt:{ WAVE_fmt* fmt = (WAVE_fmt*)GetChunkData(Iter); ChannelCount = fmt->nChannels; }break; case WAVE_ChunkID_data:{ SampleData = (int16 *)GetChunkData(Iter); SampleDataSize = GetChunkDataSize(Iter); }break; } } Assert(ChannelCount && SampleData); Result.ChannelCount = ChannelCount; uint32 SampleCount = SampleDataSize / (ChannelCount * sizeof(int16)); int16* NewChannel0 = 0; int16* NewChannel1 = 0; if(ChannelCount == 1){ NewChannel0 = (int16*)malloc(SampleCount * sizeof(int16) + 8 * sizeof(int16)); Result.Samples[0] = NewChannel0; Result.Samples[1] = NewChannel1; for(uint32 SampleIndex = SectionFirstSampleIndex; SampleIndex < SectionFirstSampleIndex + SectionSampleCount; SampleIndex++) { NewChannel0[SampleIndex - SectionFirstSampleIndex] = SampleData[SampleIndex]; } } else if(ChannelCount == 2){ NewChannel0 = (int16*)malloc(SampleCount * sizeof(int16) + 8 * sizeof(int16)); NewChannel1 = (int16*)malloc(SampleCount * sizeof(int16) + 8 * sizeof(int16)); Result.Samples[0] = NewChannel0; Result.Samples[1] = NewChannel1; for(uint32 SampleIndex = SectionFirstSampleIndex; SampleIndex < SectionFirstSampleIndex + SectionSampleCount; SampleIndex++) { NewChannel0[SampleIndex - SectionFirstSampleIndex] = SampleData[SampleIndex * 2]; NewChannel1[SampleIndex - SectionFirstSampleIndex] = SampleData[SampleIndex * 2 + 1]; } } else{ Assert(!"Invalid channel count in WAV file"); } bool32 AtEnd = true; if(SectionSampleCount){ Assert((SectionFirstSampleIndex + SectionSampleCount) <= SampleCount); AtEnd = ((SectionFirstSampleIndex + SectionSampleCount) == SampleCount); SampleCount = SectionSampleCount; } if(AtEnd){ for(uint32 ChannelIndex = 0; ChannelIndex < Result.ChannelCount; ChannelIndex++) { for(uint32 SampleIndex = SampleCount; SampleIndex < (SampleCount + 8); SampleIndex++) { Result.Samples[ChannelIndex][SampleIndex] = 0; } } } Result.SampleCount = SampleCount; } return(Result); } INTERNAL_FUNCTION void BeginAssetType(game_assets* Assets, asset_type_id TypeID){ Assert(Assets->DEBUGAssetType == 0); Assets->DEBUGAssetType = Assets->AssetTypes + TypeID; Assets->DEBUGAssetType->TypeID = TypeID; Assets->DEBUGAssetType->FirstAssetIndex = Assets->AssetCount; Assets->DEBUGAssetType->OnePastLastAssetIndex = Assets->DEBUGAssetType->FirstAssetIndex; } struct added_asset{ uint32 ID; dda_asset* DDA; asset_source* Source; }; INTERNAL_FUNCTION added_asset AddAsset(game_assets* Assets){ Assert(Assets->DEBUGAssetType); Assert(Assets->DEBUGAssetType->OnePastLastAssetIndex < ArrayCount(Assets->Assets)); uint32 Index = Assets->DEBUGAssetType->OnePastLastAssetIndex++; asset_source* Source = Assets->AssetSources + Index; dda_asset* DDA = Assets->Assets + Index; DDA->FirstTagIndex = Assets->TagCount; DDA->OnePastLastTagIndex = DDA->FirstTagIndex; Assets->AssetIndex = Index; added_asset Result; Result.ID = Index; Result.DDA = DDA; Result.Source = Source; return(Result); } INTERNAL_FUNCTION bitmap_id AddCharacterAsset(game_assets* Assets, loaded_font* Font, uint32 Codepoint){ added_asset Asset = AddAsset(Assets); Asset.DDA->Bitmap.AlignPercentage[0] = 0.0f; Asset.DDA->Bitmap.AlignPercentage[1] = 0.0f; Asset.DDA->Bitmap.BitmapType = DDABitmap_FontGlyph; Asset.Source->Type = AssetType_FontGlyph; Asset.Source->Glyph.Font = Font; Asset.Source->Glyph.Codepoint = Codepoint; bitmap_id Result = {Asset.ID}; Assert(Font->GlyphCount < Font->MaxGlyphCount); uint32 GlyphIndex = Font->GlyphCount++; dda_font_glyph* Glyph = Font->Glyphs + GlyphIndex; Glyph->UnicodeCodePoint = Codepoint; Glyph->BitmapID = Result; Font->GlyphIndexFromCodePoint[Codepoint] = GlyphIndex; if(Font->OnePastHighestCodepoint <= Codepoint){ Font->OnePastHighestCodepoint = Codepoint + 1; } return(Result); } INTERNAL_FUNCTION bitmap_id AddVoxelAtlasTextureAsset(game_assets* Assets, loaded_voxel_atlas* Atlas){ added_asset Asset = AddAsset(Assets); Asset.DDA->Bitmap.AlignPercentage[0] = 0.0f; Asset.DDA->Bitmap.AlignPercentage[1] = 0.0f; Asset.DDA->Bitmap.BitmapType = DDABitmap_VoxelAtlas; Asset.Source->Type = AssetType_VoxelAtlasTexture; Asset.Source->VoxelAtlasTexture.Atlas = Atlas; Asset.Source->VoxelAtlasTexture.FileName = Atlas->TextureFileName; bitmap_id Result = {Asset.ID}; Atlas->AtlasTexture.BitmapID = Result; return(Result); } #if BUILD_WITH_ASSIMP INTERNAL_FUNCTION animated_model_id AddAnimatedModelAsset( game_assets* Assets, loaded_animated_model* AnimatedModel) { added_asset Asset = AddAsset(Assets); Asset.Source->Type = AssetType_AnimatedModel; Asset.Source->AnimatedModel.AnimatedModel = AnimatedModel; Asset.DDA->AnimatedModel.AnimationsCount = 0; animated_model_id Result = { Asset.ID }; return(Result); } INTERNAL_FUNCTION void AddAnimationToModelAsset( loaded_animated_model* Model, loaded_animation* Animation) { Assert((Model->AnimationsCount) < MAX_ANIMATIONS_PER_MODEL); Model->Animations[Model->AnimationsCount++] = Animation; } INTERNAL_FUNCTION void AddAnimationsToModelAsset( loaded_animated_model* AnimatedModel, char* FileName, asset_animation_type AnimationType) { loaded_animations_result Result = LoadSkeletalAnimation( FileName, &AnimatedModel->Skeleton, AnimationType); for (uint32 AnimationIndex = 0; AnimationIndex < Result.AnimationsCount; AnimationIndex++) { AddAnimationToModelAsset(AnimatedModel, &Result.Animations[AnimationIndex]); } } INTERNAL_FUNCTION void AddSkinnedMeshToModelAsset( loaded_animated_model* AnimatedModel, char* FileName) { LoadSkinnedMeshDataFromAssimp( &AnimatedModel->Mesh, FileName, &AnimatedModel->Skeleton); } #endif INTERNAL_FUNCTION voxel_atlas_id AddVoxelAtlasAsset( game_assets* Assets, loaded_voxel_atlas* Atlas) { added_asset Asset = AddAsset(Assets); //TODO Asset.Source->Type = AssetType_VoxelAtlas; Asset.Source->VoxelAtlas.Atlas = Atlas; Asset.DDA->VoxelAtlas.AtlasWidth = Atlas->AtlasWidth; Asset.DDA->VoxelAtlas.OneTextureWidth = Atlas->OneTextureWidth; Asset.DDA->VoxelAtlas.BitmapID = Atlas->AtlasTexture.BitmapID; voxel_atlas_id Result = {Asset.ID}; return(Result); } inline void DescribeVoxelAtlasTexture( loaded_voxel_atlas* Atlas, voxel_mat_type MaterialType, voxel_face_type_index FaceTypeIndex, int CurrTextureIndex) { uint32 TexturesByWidth = Atlas->AtlasWidth / Atlas->OneTextureWidth; Assert(CurrTextureIndex < Atlas->MaxTextureCount); voxel_tex_coords_set* MatTexSet = &Atlas->Materials[MaterialType]; switch(FaceTypeIndex){ case(VoxelFaceTypeIndex_Top):{ MatTexSet->Sets[VoxelFaceTypeIndex_Top] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Bottom):{ MatTexSet->Sets[VoxelFaceTypeIndex_Bottom] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Left):{ MatTexSet->Sets[VoxelFaceTypeIndex_Left] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Right):{ MatTexSet->Sets[VoxelFaceTypeIndex_Right] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Front):{ MatTexSet->Sets[VoxelFaceTypeIndex_Front] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Back):{ MatTexSet->Sets[VoxelFaceTypeIndex_Back] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_All):{ MatTexSet->Sets[VoxelFaceTypeIndex_Bottom] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Top] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Left] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Right] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Front] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Back] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_Side):{ MatTexSet->Sets[VoxelFaceTypeIndex_Left] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Right] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Front] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Back] = CurrTextureIndex; }break; case(VoxelFaceTypeIndex_TopBottom):{ MatTexSet->Sets[VoxelFaceTypeIndex_Bottom] = CurrTextureIndex; MatTexSet->Sets[VoxelFaceTypeIndex_Top] = CurrTextureIndex; }break; default:{ INVALID_CODE_PATH; }break; } } INTERNAL_FUNCTION void DescribeByIndex( loaded_voxel_atlas* Atlas, int HorzIndex, int VertIndex, voxel_mat_type MaterialType, voxel_face_type_index FaceTypeIndex) { DescribeVoxelAtlasTexture(Atlas, MaterialType, FaceTypeIndex, VertIndex * 16 + HorzIndex); } INTERNAL_FUNCTION bitmap_id AddBitmapAsset( game_assets* Assets, char* FileName, vec2 AlignPercentage = Vec2(0.5f)) { added_asset Asset = AddAsset(Assets); Asset.DDA->Bitmap.AlignPercentage[0] = AlignPercentage.x; Asset.DDA->Bitmap.AlignPercentage[1] = AlignPercentage.y; Asset.DDA->Bitmap.BitmapType = DDABitmap_Bitmap; Asset.Source->Type = AssetType_Bitmap; Asset.Source->Bitmap.FileName = FileName; bitmap_id Result = {Asset.ID}; return(Result); } INTERNAL_FUNCTION sound_id AddSoundAsset( game_assets* Assets, char* FileName, unsigned int FirstSampleIndex = 0, unsigned int SampleCount = 0) { added_asset Asset = AddAsset(Assets); Asset.DDA->Sound.SampleCount = SampleCount; Asset.DDA->Sound.Chain = DDASoundChain_None; Asset.Source->Type = AssetType_Sound; Asset.Source->Sound.FileName = FileName; Asset.Source->Sound.FirstSampleIndex = FirstSampleIndex; sound_id Result = {Asset.ID}; return(Result); } INTERNAL_FUNCTION font_id AddFontAsset(game_assets* Assets, loaded_font* Font){ added_asset Asset = AddAsset(Assets); Asset.DDA->Font.OnePastHighestCodepoint = Font->OnePastHighestCodepoint; Asset.DDA->Font.GlyphCount = Font->GlyphCount; #if USE_FONTS_FROM_WINDOWS Asset.DDA->Font.AscenderHeight = (float)Font->TextMetric.tmAscent; Asset.DDA->Font.DescenderHeight = (float)Font->TextMetric.tmDescent; Asset.DDA->Font.ExternalLeading = (float)Font->TextMetric.tmExternalLeading; #else Asset.DDA->Font.AscenderHeight = Font->AscenderHeight; Asset.DDA->Font.DescenderHeight = Font->DescenderHeight; Asset.DDA->Font.ExternalLeading = Font->ExternalLeading; #endif Asset.Source->Type = AssetType_Font; Asset.Source->Font.Font = Font; font_id Result = {Asset.ID}; return(Result); } INTERNAL_FUNCTION void AddTag(game_assets* Assets, asset_tag_id ID, float Value){ Assert(Assets->AssetIndex); dda_asset* DDA = Assets->Assets + Assets->AssetIndex; ++DDA->OnePastLastTagIndex; dda_tag* Tag = Assets->Tags + Assets->TagCount++; Tag->ID = ID; Tag->Value = Value; } INTERNAL_FUNCTION void EndAssetType(game_assets* Assets){ Assert(Assets->DEBUGAssetType); Assets->AssetCount = Assets->DEBUGAssetType->OnePastLastAssetIndex; Assets->DEBUGAssetType = 0; Assets->AssetIndex = 0; } INTERNAL_FUNCTION void WriteDDA(game_assets* Assets, char* FileName){ FILE* fp = fopen(FileName, "wb"); if(fp){ dda_header Header = {}; Header.MagicValue = DDA_MAGIC_VALUE; Header.Version = DDA_VERSION; Header.TagCount = Assets->TagCount; Header.AssetTypeCount = Asset_Count; Header.AssetCount = Assets->AssetCount; uint32 TagArraySize = Header.TagCount * sizeof(dda_tag); uint32 AssetTypeArraySize = Header.AssetTypeCount * sizeof(dda_asset_type); uint32 AssetArraySize = Header.AssetCount * sizeof(dda_asset); Header.TagOffset = sizeof(Header); Header.AssetTypeOffset = Header.TagOffset + TagArraySize; Header.AssetOffset = Header.AssetTypeOffset + AssetTypeArraySize; fwrite(&Header, sizeof(Header), 1, fp); fwrite(Assets->Tags, TagArraySize, 1, fp); fwrite(Assets->AssetTypes, AssetTypeArraySize, 1, fp); fseek(fp, AssetArraySize, SEEK_CUR); for(uint32 AssetIndex = 1; AssetIndex < Header.AssetCount; AssetIndex++) { asset_source* Source = Assets->AssetSources + AssetIndex; dda_asset* DDA = Assets->Assets + AssetIndex; DDA->DataOffset = ftell(fp); switch(Source->Type){ case(AssetType_Sound):{ loaded_sound WAV = LoadWAV( Source->Sound.FileName, Source->Sound.FirstSampleIndex, DDA->Sound.SampleCount); DDA->Sound.SampleCount = WAV.SampleCount; DDA->Sound.ChannelCount = WAV.ChannelCount; for(uint32 ChannelIndex = 0; ChannelIndex < WAV.ChannelCount; ChannelIndex++) { fwrite(WAV.Samples[ChannelIndex], DDA->Sound.SampleCount * sizeof(int16), 1, fp); } free(WAV.Free); }break; case(AssetType_VoxelAtlasTexture): case(AssetType_FontGlyph): case(AssetType_Bitmap):{ //loaded_bitmap Bitmap = LoadBMP(Source->FileName); loaded_bitmap Bitmap; if(Source->Type == AssetType_FontGlyph){ Bitmap = LoadGlyphBitmap(Source->Glyph.Font, Source->Glyph.Codepoint, DDA); } else if(Source->Type = AssetType_VoxelAtlasTexture){ Bitmap = LoadBMP(Source->VoxelAtlasTexture.FileName); } else{ Assert(Source->Type == AssetType_Bitmap); Bitmap = LoadBMP(Source->Bitmap.FileName); } DDA->Bitmap.Dimension[0] = Bitmap.Width; DDA->Bitmap.Dimension[1] = Bitmap.Height; fwrite(Bitmap.Memory, Bitmap.Width * Bitmap.Height * 4, 1, fp); free(Bitmap.Free); }break; case(AssetType_Mesh): { #if BUILD_WITH_ASSIMP loaded_mesh* Mesh = Source->Mesh.Mesh; dda_mesh_header MeshHeader; MeshHeader.IndicesCount = Mesh->IndicesCount; MeshHeader.VerticesCount = Mesh->VerticesCount; MeshHeader.MeshType = Mesh->Type; u8* VerticesToWrite = 0; u32 VerticesToWriteSize = 0; switch (MeshHeader.MeshType) { case(DDAMeshType_Simple): { MeshHeader.VertexStructureSize = sizeof(simple_vertex); VerticesToWrite = (u8*)Mesh->SimpleVertices; }break; case(DDAMeshType_Skinned): { MeshHeader.VertexStructureSize = sizeof(skinned_vertex); VerticesToWrite = (u8*)Mesh->SkinnedVertices; }break; INVALID_DEFAULT_CASE; } VerticesToWriteSize = Mesh->VerticesCount * MeshHeader.VertexStructureSize; //NOTE(Dima): First I write the mesh header. fwrite(&MeshHeader, 1, sizeof(dda_mesh_header), fp); //NOTE(DIMA): Then I write all the vertices fwrite(VerticesToWrite, VerticesToWriteSize, 1, fp); //NOTE(Dima): Last I write indices. Index is uint32 value(4 bytes) fwrite(Mesh->Indices, Mesh->IndicesCount, sizeof(u32), fp); #endif }break; case(AssetType_Animation):{ #if BUILD_WITH_ASSIMP loaded_animation* Anim = Source->Animation.Animation; Assert(Anim->JointAnimsCount <= DDA_ANIMATION_MAX_BONE_COUNT); uint32 TotalFileSize = 0; for(uint32 JointAnimIndex = 0; JointAnimIndex < Anim->JointAnimsCount; JointAnimIndex++) { joint_animation* JointAnim = &Anim->JointAnims[JointAnimIndex]; dda_joint_frames_header TempHeader; TempHeader.BytesLength = JointAnim->TranslationFramesByteSize; TempHeader.Type = JointFrameHeader_Translation; fwrite(&TempHeader, sizeof(dda_joint_frames_header), 1, fp); fwrite(JointAnim->TranslationFrames, JointAnim->TranslationFramesByteSize, 1, fp); TotalFileSize += (sizeof(dda_joint_frames_header) + JointAnim->TranslationFramesByteSize); TempHeader.BytesLength = JointAnim->RotationFramesByteSize; TempHeader.Type = JointFrameHeader_Rotation; fwrite(&TempHeader, sizeof(dda_joint_frames_header), 1, fp); fwrite(JointAnim->RotationFrames, JointAnim->RotationFramesByteSize, 1, fp); TotalFileSize += (sizeof(dda_joint_frames_header) + JointAnim->RotationFramesByteSize); TempHeader.BytesLength = JointAnim->ScalingFramesByteSize; TempHeader.Type = JointFrameHeader_Scaling; fwrite(&TempHeader, sizeof(dda_joint_frames_header), 1, fp); fwrite(JointAnim->ScalingFrames, JointAnim->ScalingFramesByteSize, 1, fp); TotalFileSize = (sizeof(dda_joint_frames_header) + JointAnim->ScalingFramesByteSize); free(JointAnim->Free); } DDA->Animation.TotalFileSize = TotalFileSize; #endif }break; case(AssetType_AnimatedModel): { #if BUILD_WITH_ASSIMP loaded_animated_model* Model = Source->AnimatedModel.AnimatedModel; #endif }break; case(AssetType_VoxelAtlas):{ loaded_voxel_atlas* Atlas = Source->VoxelAtlas.Atlas; uint32 MaterialsSize = VoxelMaterial_Count * sizeof(voxel_tex_coords_set); fwrite(Atlas->Materials, MaterialsSize, 1, fp); }break; case(AssetType_Font):{ loaded_font* Font = Source->Font.Font; FinalizeFontKerning(Font); uint32 GlyphsSize = Font->GlyphCount * sizeof(dda_font_glyph); fwrite(Font->Glyphs, GlyphsSize, 1, fp); uint8* HorizontalAdvance = (uint8*)Font->HorizontalAdvance; for(uint32 GlyphIndex = 0; GlyphIndex < Font->GlyphCount; GlyphIndex++) { /*Here we write one row of horizontal advances for GlyphIndex*/ uint32 HorizontalAdvanceSliceSize = sizeof(float) * Font->GlyphCount; fwrite(HorizontalAdvance, HorizontalAdvanceSliceSize, 1, fp); HorizontalAdvance += sizeof(float) * Font->MaxGlyphCount; } }break; default:{ INVALID_CODE_PATH; }break; } } fseek(fp, (uint32)Header.AssetOffset, SEEK_SET); fwrite(Assets->Assets, AssetArraySize, 1, fp); fclose(fp); } else{ printf("Error while opening the file T_T\n"); } } INTERNAL_FUNCTION void Initialize(game_assets* Assets){ Assets->TagCount = 1; Assets->AssetCount = 1; Assets->DEBUGAssetType = 0; Assets->AssetIndex = 0; Assets->AssetTypeCount = Asset_Count; memset(Assets->AssetTypes, 0, sizeof(Assets->AssetTypes)); } INTERNAL_FUNCTION void WriteModels(){ #if BUILD_WITH_ASSIMP game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); loaded_animated_model OldSchoolDima = {}; AddSkinnedMeshToModelAsset(&OldSchoolDima, "../../IvanEngine/Data/Animations/Dima.fbx"); AddAnimationsToModelAsset(&OldSchoolDima, "../../IvanEngine/Data/Animations/Dima_RunF01.fbx", AssetAnimationType_RunForward); AddAnimationsToModelAsset(&OldSchoolDima, "../../IvanEngine/Data/Animations/Dima_Idle01Idle01.fbx", AssetAnimationType_Idle00); BeginAssetType(Assets, Asset_OldSchoolDima); AddAnimatedModelAsset(Assets, &OldSchoolDima); EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_animations.dda"); printf("Animation assets written successfully :D"); #endif } INTERNAL_FUNCTION void WriteFonts(){ game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); loaded_font *Fonts[] = { LoadFont("c:/Windows/Fonts/arial.ttf", "Arial", 20), LoadFont("c:/Windows/Fonts/LiberationMono-Regular.ttf", "Liberation Mono", 20), LoadFont("c:/Windows/Fonts/Antique-Olive-Std-Nord-Italic.ttf", "Antique Olive Std Nord", 20), }; BeginAssetType(Assets, Asset_FontGlyph); for(uint32 FontIndex = 0; FontIndex < ArrayCount(Fonts); FontIndex++) { loaded_font* Font = Fonts[FontIndex]; AddCharacterAsset(Assets, Font, ' '); for(uint32 Character = '!'; Character <= '~'; Character++) { AddCharacterAsset(Assets, Font, Character); } } EndAssetType(Assets); BeginAssetType(Assets, Asset_Font); AddFontAsset(Assets, Fonts[0]); AddTag(Assets, Tag_FontType, FontType_Default); AddFontAsset(Assets, Fonts[1]); AddTag(Assets, Tag_FontType, FontType_Debug); AddFontAsset(Assets, Fonts[2]); AddTag(Assets, Tag_FontType, FontType_Forsazh); EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_fonts.dda"); printf("Font assets written successfully :D\n"); } INTERNAL_FUNCTION void WriteVoxelAtlases(){ game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); loaded_voxel_atlas* Atlases[] = { LoadVoxelAtlas("../../IvanEngine/Data/Images/MyVoxelAtlas/VoxelAtlas.png", 256, 16), LoadVoxelAtlas("../../IvanEngine/Data/Images/terrain.png", 256, 16), }; loaded_voxel_atlas* Atlas = Atlases[0]; DescribeByIndex(Atlas, 0, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Top); DescribeByIndex(Atlas, 1, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Side); DescribeByIndex(Atlas, 2, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Bottom); DescribeByIndex(Atlas, 2, 0, VoxelMaterial_Ground, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 3, 0, VoxelMaterial_Tree, VoxelFaceTypeIndex_Side); DescribeByIndex(Atlas, 4, 0, VoxelMaterial_Tree, VoxelFaceTypeIndex_TopBottom); DescribeByIndex(Atlas, 5, 0, VoxelMaterial_Stone, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 6, 0, VoxelMaterial_Sand, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 7, 0, VoxelMaterial_Leaves, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 0, 1, VoxelMaterial_SnowGround, VoxelFaceTypeIndex_Top); DescribeByIndex(Atlas, 1, 1, VoxelMaterial_SnowGround, VoxelFaceTypeIndex_Side); DescribeByIndex(Atlas, 2, 1, VoxelMaterial_SnowGround, VoxelFaceTypeIndex_Bottom); DescribeByIndex(Atlas, 2, 1, VoxelMaterial_WinterGround, VoxelFaceTypeIndex_All); Atlas = Atlases[1]; DescribeByIndex(Atlas, 0, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Top); DescribeByIndex(Atlas, 1, 0, VoxelMaterial_Stone, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 2, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Bottom); DescribeByIndex(Atlas, 2, 0, VoxelMaterial_Ground, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 3, 0, VoxelMaterial_GrassyGround, VoxelFaceTypeIndex_Side); DescribeByIndex(Atlas, 4, 1, VoxelMaterial_Tree, VoxelFaceTypeIndex_Side); DescribeByIndex(Atlas, 5, 1, VoxelMaterial_Tree, VoxelFaceTypeIndex_TopBottom); DescribeByIndex(Atlas, 5, 8, VoxelMaterial_Leaves, VoxelFaceTypeIndex_All); DescribeByIndex(Atlas, 0, 3, VoxelMaterial_Sand, VoxelFaceTypeIndex_All); BeginAssetType(Assets, Asset_VoxelAtlasTexture); for(uint32 VoxelAtlasIndex = 0; VoxelAtlasIndex < ArrayCount(Atlases); VoxelAtlasIndex++) { AddVoxelAtlasTextureAsset(Assets, Atlases[VoxelAtlasIndex]); } EndAssetType(Assets); BeginAssetType(Assets, Asset_VoxelAtlas); AddVoxelAtlasAsset(Assets, Atlases[0]); AddTag(Assets, Tag_VoxelAtlasType, VoxelAtlasType_Default); AddVoxelAtlasAsset(Assets, Atlases[1]); AddTag(Assets, Tag_VoxelAtlasType, VoxelAtlasType_Minecraft); EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_voxatl.dda"); printf("Voxel Texture Atlas written successfully :D\n"); } INTERNAL_FUNCTION void WriteHero(){ game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); real32 AngleRight = 0.0f * IVAN_MATH_TAU; real32 AngleBack = 0.25f * IVAN_MATH_TAU; real32 AngleLeft = 0.5f * IVAN_MATH_TAU; real32 AngleFront = 0.75f * IVAN_MATH_TAU; vec2 HeroAlign = {0.5f, 1.0f - 0.156682029f}; BeginAssetType(Assets, Asset_Head); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_right_head.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleRight); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_back_head.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleBack); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_left_head.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleLeft); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_front_head.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleFront); EndAssetType(Assets); BeginAssetType(Assets, Asset_Cape); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_right_cape.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleRight); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_back_cape.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleBack); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_left_cape.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleLeft); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_front_cape.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleFront); EndAssetType(Assets); BeginAssetType(Assets, Asset_Torso); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_right_torso.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleRight); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_back_torso.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleBack); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_left_torso.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleLeft); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_hero_front_torso.bmp", HeroAlign); AddTag(Assets, Tag_FacingDirection, AngleFront); EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_hero.dda"); printf("Hero assets written successfully :D\n"); } INTERNAL_FUNCTION void WriteNonHero(){ game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); BeginAssetType(Assets, Asset_Backdrop); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test/test_background.bmp"); EndAssetType(Assets); BeginAssetType(Assets, Asset_LastOfUs); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/last.jpg"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Tree); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/test2/tree00.bmp", Vec2(0.5f, 0.3f)); EndAssetType(Assets); BeginAssetType(Assets, Asset_StarWars); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/star_wars.jpg"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Witcher); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/witcher.jpg"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Assassin); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/assassin.jpg"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Grass); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/grass00.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/grass01.bmp"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Stone); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/ground00.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/ground01.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/ground02.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/ground03.bmp"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Tuft); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/tuft00.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/tuft01.bmp"); AddBitmapAsset(Assets, "../../IvanEngine/Data/HH/Test2/tuft02.bmp"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Heart); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/heart.png"); EndAssetType(Assets); float ColorBlue = GetFloatRepresentOfColor(Vec3(0.0f, 0.0f, 1.0f)); float ColorGreen = GetFloatRepresentOfColor(Vec3(0.0f, 1.0f, 0.0f)); float ColorRed = GetFloatRepresentOfColor(Vec3(1.0f, 0.0f, 0.0f)); BeginAssetType(Assets, Asset_Diamond); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/gemBlue.png"); AddTag(Assets, Tag_Color, ColorBlue); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/gemGreen.png"); AddTag(Assets, Tag_Color, ColorGreen); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/gemRed.png"); AddTag(Assets, Tag_Color, ColorRed); EndAssetType(Assets); BeginAssetType(Assets, Asset_Bottle); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/potionBlue.png"); AddTag(Assets, Tag_Color, ColorBlue); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/potionGreen.png"); AddTag(Assets, Tag_Color, ColorGreen); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/potionRed.png"); AddTag(Assets, Tag_Color, ColorRed); EndAssetType(Assets); BeginAssetType(Assets, Asset_Book); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/128/tome.png"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Particle); AddBitmapAsset(Assets, "../../IvanEngine/Data/Images/ShockSpell.png"); EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_non_hero.dda"); printf("Non-hero assets written successfully :D\n"); } INTERNAL_FUNCTION void WriteSounds(){ game_assets Assets_; game_assets* Assets = &Assets_; Initialize(Assets); BeginAssetType(Assets, Asset_Bloop); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/bloop_00.wav"); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/bloop_01.wav"); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/bloop_02.wav"); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/bloop_03.wav"); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/bloop_04.wav"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Crack); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/crack_00.wav"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Drop); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/drop_00.wav"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Glide); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/glide_00.wav"); EndAssetType(Assets); BeginAssetType(Assets, Asset_Puhp); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/puhp_00.wav"); AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/puhp_01.wav"); EndAssetType(Assets); uint32 OneMusicChunk = 10 * 44100; uint32 TotalMusicSampleCount = 7468095; BeginAssetType(Assets, Asset_Music); for(uint32 FirstSampleIndex = 0; FirstSampleIndex < TotalMusicSampleCount; FirstSampleIndex += OneMusicChunk) { uint32 SampleCount; if(FirstSampleIndex + OneMusicChunk < TotalMusicSampleCount){ SampleCount = OneMusicChunk; } else{ SampleCount = TotalMusicSampleCount - FirstSampleIndex; } sound_id ThisMusic = AddSoundAsset(Assets, "../../IvanEngine/Data/HH/test3/music_test.wav", FirstSampleIndex, SampleCount); if((FirstSampleIndex + OneMusicChunk) < TotalMusicSampleCount){ Assets->Assets[ThisMusic.Value].Sound.Chain = DDASoundChain_Advance; } } EndAssetType(Assets); WriteDDA(Assets, "../../IvanEngine/Data/asset_pack_sounds.dda"); printf("Sound assets written successfully :D\n"); } int main(int ArgCount, char** Args){ InitializeFontDC(); WriteHero(); WriteNonHero(); WriteSounds(); WriteFonts(); WriteVoxelAtlases(); WriteModels(); system("pause"); return(0); }
true
d7048c60cba2f880a17c0856464fc8b3e9dcf8e0
C++
Coolog/Nanodet-Robot-PathPlanning
/path_planning.cpp
UTF-8
27,704
2.609375
3
[]
no_license
#include <path_planning.h> /*********************** DEBUGๅ‡ฝๆ•ฐๅฎๅฎšไน‰***********************/ //#define DUBUG_LINE //่พ“ๅ‡บ็”ป็š„็บฟ็š„ไฝ็ฝฎไฟกๆฏ //#define DEBUG_PRE_MESSAGE //่พ“ๅ‡บๅ‰ไธ€ๅธง็š„ไฟกๆฏ //#define DEBUG_NOW_MESSAGE //่พ“ๅ‡บๅฝ“ๅ‰ๅธง็š„ไฟกๆฏ //#define DEBUG_EACH_LINE //็”ปๆฏไธ€ๆก็บฟ float Path::judge_distance(){ if(line_max_y[last_pos_index]> 360){ return 0.35; } else if(line_max_y[last_pos_index]>240){ return 0.45; } else if(line_max_y[last_pos_index]>120){ return 0.6; } else{ return 0.7; } } void Path::set_mode(int mode,int _mage_state){ mage_num = mode; mage_state =_mage_state; if(mode != judge_mode_num){ judge_mode_num = mode; //่ฎพ็ฝฎๅฝ“ๅ‰็Šถๆ€ไธ‹็š„ๅ†ณ็ญ–ๆฌกๆ•ฐ pre_state = 1; //่กจ็คบ้ฉฌๅ“ฅๅšๅฎŒไบ† //pre_state ++; //if(pre_state >3) // pre_state = 3; } else{ pre_state = 0; //0่กจ็คบ้ฉฌๅ“ฅ่ฟ˜ๆฒกๅšๅฎŒ } } //ๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐไฟกๆฏ void Path::init(int _num_direction){ mode_3_send_angle = 90; mode_3_send_distance = 0.3; num_direction = _num_direction; mage_state = -1; cout << "num_direction:" << num_direction << endl; judge_mode_num = -1; //็”ตๆŽง๏ผšๅผ€ๅง‹่ฎพ็ฝฎไธบ0๏ผŒ่กจ็คบไธๅšๅ†ณ็ญ–๏ผŒ็ญ‰ๅพ…็”ตๆŽง้œ€่ฆๆ•ฐๆฎๅ†ๅ†ณ็ญ– pre_state = 1; //็ญ‰้ฉฌๅ“ฅๅ‘้€1 judge_mode = -1; //ๅˆๅง‹็Šถๆ€ state_mode = -1; //ๅˆๅง‹ๅŒ–ไธบๅ‰่ฟ›ๆจกๅผ mode_3_num = 0; //ๆจกๅผไธ‰็š„ไธชๆ•ฐไธบ0 send_angle = 0; last_distance = 0; pre_max_num = -1; pre_pos = -1; pre_b1 = -1; pre_b2 = -1; pre_angle = -1; //ๅผ€ๅง‹็š„ๅ…ˆๅ‰่ง’ๅบฆไธบ-1 last_angle = -1; last_pos_index = -1; Line_left_1.x = shovel_left; Line_left_1.y = img.size().height; Line_right_1.x = shovel_right; Line_right_1.y = img.size().height; last_pos = 0; last_b1=0;last_b2=0; cout << "left_blind_angleL: " << left_blind_angle << " ,delta_blind_angle: " << delta_blind_angle << endl; cout << num_direction << endl; color = new Scalar[1000]; number = new int[num_direction + 1]; line_max_y = new int[num_direction + 1]; circle_number = new int[ball_pos.size() + 1]; max_change_angle_num = ceil(360/(delta_blind_angle) - 1); cout << "ๆœ€ๅคงๆ—‹่ฝฌๆฌกๆ•ฐไธบ" << max_change_angle_num << endl; // srand(time(0)); cout << 665 << endl; for(int i=0;i<num_direction;i++){ int a=rand()%256,b=rand()%256,c=rand()%256; //cout << "็ฌฌ" << i << "ๆก็บฟ็š„้ขœ่‰ฒไธบ๏ผš" << a << " " << b << " " << c << endl; color[i] = Scalar(a,b,c); number[i] = 0; } for(int i=0;i<1000;i++){ int a=rand()%256,b=rand()%256,c=rand()%256; //cout << "็ฌฌ" << i << "ๆก็บฟ็š„้ขœ่‰ฒไธบ๏ผš" << a << " " << b << " " << c << endl; color[i] = Scalar(a,b,c); } number[num_direction] = 0; set_circle_distance((shovel_right - shovel_left)/2); } ////ๅนณ่กŒ็บฟ้€‰ๆœ€็ปˆๆ–นๅ‘ๆณ• ///* // * 1.ๅˆ’ๅˆ†ไธบnum_directionไธชๆ–นๅ‘ // * 2.forๅพช็Žฏ๏ผŒๆž„้€ ๅ‡บๅฝ“ๅ‰ๆ–นๅ‘็š„้‚ฃไธ€ๆกๅนณ่กŒ็บฟๆฎต // * 3.ๅฏนไบŽๆฏไธ€ไธช็‚น๏ผŒๅˆคๆ–ญๅ…ถๆ˜ฏๅฆๅœจๅนณ่กŒ็บฟๅ†… // * 4.ๅฏนไบŽๆฏๆก็บฟ็š„xita๏ผŒk=tan(ๅทฆๆญป่ง’ + ๏ผˆ180-ๆญป่ง’ๅทฎ๏ผ‰/๏ผˆn-1๏ผ‰*i) // * // *circle_value / void Path::last_direction(){ cout << 22222 << endl; //init(); //ๅˆๅง‹ๅŒ–ๅ‚ๆ•ฐ last_pos_index = -1; #ifdef DEBUG_PRE_MESSAGE DEBUG_MESSAGE_PRE(); #endif for(int i=0;i<= num_direction;i++){ line_max_y[i] = 0; //ๅˆๅง‹ๅŒ–y } cout << "ๆœ€ๅคงๆ—‹่ฝฌๆฌกๆ•ฐไธบ" << max_change_angle_num << endl; pre_state = 1; if(ball_pos.size()>0 &&(pre_state == 1 || judge_mode == 3)){ //ๆœ‰็ƒ็š„ๆƒ…ๅ†ต๏ผš ้œ€่ฆๅšๅ†ณ็ญ– ๆˆ–่€… ๆ‰พ็ƒ็Šถๆ€้œ€่ฆๅฎžๆ—ถๆฃ€ๆต‹ circle_process_ball(1); // origin_process_ball(1); //ๅŽŸๅง‹๏ผ›ๅค„็†็ƒ็š„ๆ€่ทฏ } else{ //ๆฒก็ƒ if(pre_state == 0 && judge_mode != 3){ //ๆฒก็ƒ+้ฉฌๅ“ฅๆฒกๅšๅฎŒ+็Šถๆ€1๏ผŒ2๏ผˆๅŽŸๅญๆ€ง๏ผŒๆญคๆ—ถ็ญ‰ๅพ…ๅšๅฎŒ๏ผ‰ if(state_mode == -1){ cout << "ๅผ€ๆœบ็Šถๆ€๏ผŒ็ญ‰้ฉฌๅ“ฅๅ‘ๅ†ณ็ญ–้œ€ๆฑ‚๏ผ๏ผ๏ผ" << endl; } else{ cout << "็Šถๆ€" << state_mode << " ๏ผŒ็ญ‰้ฉฌๅ“ฅๅ‘ๅ†ณ็ญ–้œ€ๆฑ‚๏ผ๏ผ๏ผ" << endl; } DRAW_TEXT(); //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ imshow("Cool", img); return; //่ฟ”ๅ›ž็ป“ๆžœ๏ผŒๆญคๆ—ถไธ็”จๅ‘้€ ๅˆๅง‹ๅผ€ๆœบ็Šถๆ€ไนŸreturn } else{ //ๆฒก็ƒ + ้ฉฌๅ“ฅๅšๅฎŒไบ† ๆˆ–่€… ๆฒก็ƒ+็ฌฌไธ‰็Šถๆ€ state_mode = 2; //ๅŽŸๅœฐๆ—‹่ฝฌๆจกๅผ if(judge_mode == 2){ //่‹ฅๅ…ˆๅ‰ๆ˜ฏ็ฌฌไบŒ็Šถๆ€๏ผŒๆ›ดๆ–ฐๆ—‹่ฝฌๆฌกๆ•ฐ change_rotated_num = judge_mode_num; //่กจ็คบ้ฉฌๅ“ฅๅšๅฎŒไบ†ไน‹ๅ‰็š„ๅŠจไฝœ๏ผŒๆญคๆ—ถๆ›ดๆ–ฐ็Šถๆ€ๆฌกๆ•ฐ } if(change_rotated_num >= (max_change_angle_num) || judge_mode == 3){ //่ฝฌไบ†360ๅบฆ่ฟ˜ๆ˜ฏๆฒก็ƒ ๆˆ–่€…ๅ…ˆๅ‰ๅฐฑๆ˜ฏ็ฌฌไธ‰็Šถๆ€ cout << "---------------------------------------------------------if manzu2-->3:" <<( change_rotated_num >= (max_change_angle_num) )<< endl; if(judge_mode != 3){ state_mode = 3; //่ฟ›ๅ…ฅ้šๆœบๅทกๆธธ็Šถๆ€ } if(judge_mode == 3){ mode_3_num = judge_mode_num; } if(mode_3_num > 10){ state_mode = 4;//ๅ…ณๆœบๆจกๅผ send_angle = 0; last_distance = 0; } else{ //1-2ๅ›žๅคด่ตฐๆจกๅผ // if(mode_3_num == 1 || mode_3_num == 0){ // send_angle = 0; // last_distance = distance_rate; // } // if(mode_3_num == 2){ // send_angle = 90; // last_distance = distance_rate; // } // if(mode_3_num == 3){ // send_angle = 90; // last_distance = distance_rate; // } // if(mode_3_num >3){ // send_angle = 90; // last_distance = float((mode_3_num-1))/2 * distance_rate; // } if(mode_3_num == 0){ send_angle = delta_blind_angle; last_distance = distance_rate; mode_3_send_angle = delta_blind_angle; mode_3_send_distance = distance_rate; } else{ send_angle = 45; last_distance = (mode_3_num+2)/2 * distance_rate; mode_3_send_angle = 90; mode_3_send_distance = last_distance; } } } else{ //ๅŽŸๅœฐๆ—‹่ฝฌๆจกๅผ cout << "ๅŽŸๅœฐๆ—‹่ฝฌๆจกๅผ๏ผ๏ผไปŽ" << endl; send_angle = 40; //ๅนฟ่ง’่ง’ๅบฆ last_distance = 0; //ๅŽŸๅœฐๅŠจ๏ผŒไธ่ตฐ๏ผ› } } DRAW_TEXT(); //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ imshow("Cool", img); } if(pre_state == 1){ judge_mode = state_mode; //่ฎฐๅฝ•ๅ‰้ขไธ€ๆฌกๅš็š„ๅŠจไฝœ็š„็Šถๆ€ } //pre_state = 0; //ๆฏๅšๅฎŒไธ€ๆฌกๅ†ณ็ญ–ๅฐฑ่‡ชๅทฑ่ฎพ็ฝฎไธบ0๏ผŒ็›ดๅˆฐ้ฉฌๅ“ฅไธ‹ไธ€ๆฌกๅ‘้€ไธๅŒ็š„ๆ•ฐๅ€ผๅ’Œ็Šถๆ€ // DRAW_TEXT(); //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ // imshow("Cool", img); #ifdef DEBUG_NOW_MESSAGE DEBUG_MESSAGE_NOW(); //่พ“ๅ‡บๅฝ“ๅ‰ๅธงๅ†ณ็ญ–ไฟกๆฏ #endif } //ๅ‚จๅญ˜ๅฝ“ๅ‰ๅธงๅ˜้‡๏ผŒ็”จไบŽไธ‹ไธ€ๅธง็š„ๆ–นๅ‘ๆŸๅคฑๅ‡ฝๆ•ฐๅˆคๆ–ญ // pre_pos = last_pos; // pre_b1 = last_b1; // pre_b2 = last_b2; // pre_max_num = max_ball_number; // pre_pos_index = last_pos_index; // pre_angle = last_angle; //ๆ–นๅ‘ๆŸๅคฑๅ‡ฝๆ•ฐๅˆคๆ–ญ๏ผˆๆœ€็ปˆๆ–นๅ‘ๅ†ณ็ญ–๏ผ‰ void Path::direction_loss_judge(){ pre_max_num = number[num_direction]; //ๅ‰่ฟ›็š„็ƒ็š„ไธชๆ•ฐ //ไปŽ็ฌฌไบŒๅธงๅผ€ๅง‹่€ƒ่™‘ๆ–นๅ‘ๅ็งป่ฏฏๅทฎ if(pre_angle != -1){ cout << "่ง’ๅบฆๅทฎ๏ผš" << abs(last_angle-90) << "ๆœ€ไผ˜่งฃ็ƒๆ•ฐ๏ผš " << max_ball_number << " ๆ›ดๆขๆ–นๅ‘้œ€่ฆ็š„ไธชๆ•ฐๅทฎ๏ผš" << log(abs(last_angle-90) + 1) << " ไธคๅธงๆœ€ไผ˜่งฃ็š„ไธชๆ•ฐๅทฎ๏ผš" << max_ball_number - pre_max_num << endl; DEBUG_MESSAGE_NOW(); // DEBUG_MESSAGE_PRE(); //็›ด่ตฐๆ›ดๅฅฝ if(0.2*log(abs(last_angle-90) + 1) >= (max_ball_number - number[num_direction])){ state_mode = 0; last_pos = pre_pos; last_b1 = pre_b1; last_b2 = pre_b2; max_ball_number = number[num_direction]; last_angle = 90; last_pos_index = num_direction; } //ๆ‹ๅผฏๆ›ดๅฅฝ else{ state_mode = 1; //ๆ‹ๅผฏ pre_angle = 1; // last_angle -= 90; //ๅ‘็ป™็”ตๆŽง็š„่ง’ๅบฆ if(last_pos< 0){ last_angle = 180 + atan(last_pos)*180/pi ; } else{ last_angle = atan(last_pos)*180/pi ; } } // state_mode = 1; //ๆ‹ๅผฏ // // last_angle -= 90; //ๅ‘็ป™็”ตๆŽง็š„่ง’ๅบฆ // if(last_pos< 0){ // last_angle = 180 + atan(last_pos)*180/pi ; // } // else{ // last_angle = atan(last_pos)*180/pi ; // } } else{ pre_angle = 90; state_mode = 1; //ๆ‹ๅผฏ } } //ๆ›ดๆ–ฐๆฏไธ€ๅธง็š„ๅฐ็ƒไฟกๆฏ void Path::change_ball_message(vector<Point2i> message, Mat src){ img = src; ball_pos = message; } void Path::draw_line(Point2i A, Point2i B,string name,Mat img,Scalar _color,int mode){ // line(img, A,B, Scalar(255,255,0), 3); line(img, A,B, _color, mode); // imshow("Cool", img); } void Path::find_drawline_point(float k,float b1,float b2){ cout << "k : " << k << " b1:" << b1 << " b2: " << b2 << endl; if(k > 0){ // cout << "k > 0" << endl; if(b1 >= 0 && b1 <=img_height){ // cout << "b1 >= 0 && b1 <=img_height" << endl; draw_left_point = Point2i(0,b1); // cout << "draw_left_point: " <<draw_left_point << endl; } else{ // cout << "ไธๆ˜ฏb1 >= 0 && b1 <=img_height" << endl; // cout << "-b1/k" << -b1/k << endl; draw_left_point = Point2i(-b1/k,0); // cout << "draw_left_point: " <<draw_left_point << endl; } if(b2 >= 0 && b2 <=img_height){ // cout << "b2 >= 0 && b2 <=img_height" << endl; draw_right_point = Point2i(0,b2); // cout << "draw_right_point: " <<draw_right_point << endl; } else{ // cout << "ไธๆ˜ฏb2 >= 0 && b2 <=img_height" << endl; // cout << "-k/b2" << -b2/k << endl; draw_right_point = Point2i(-b2/k,0); // cout << "draw_right_point: " <<draw_right_point << endl; } } else{ // cout << "k < 0" << endl; if((k*img_width + b1) >= 0 && (k*img_width + b1) <=img_height){ draw_left_point = Point2i(img_width,(k*img_width + b1)); } else{ draw_left_point = Point2i(-b1/k,0); } if((k*img_width + b2) >= 0 && (k*img_width + b2) <=img_height){ draw_right_point = Point2i(img_width,(k*img_width + b2)); } else{ draw_right_point = Point2i(-b2/k,0); } } } //ๆ™ฎ้€š็บฟ๏ผšๅˆคๆ–ญไธ€ไธช็‚นๆ˜ฏๅฆๅœจไธคๆก็บฟ้‡Œ้ข int Line::contain_normal(Point2i p){ if((k_left < 0 && p.x < line_shovel_left) || (k_right > 0 && p.x > line_shovel_right)){ return 0; } if(k_left > 0){ if(p.x >= line_shovel_left){ if((k_right * p.x + b_right < p.y)){return 1;} else{return 0;} } else{ if((k_left * p.x + b_left > p.y) && (k_right * p.x + b_right < p.y)) {return 1;} else{return 0;} } } else{ if(p.x <= line_shovel_right){ if((k_left * p.x + b_left < p.y)){return 1;} else{return 0;} } else{ if((k_left * p.x + b_left < p.y) && (k_right * p.x + b_right > p.y)){return 1;} else{return 0;} } } } //ๅž‚็›ด็บฟ๏ผšๅˆคๆ–ญไธ€ไธช็‚นๆ˜ฏๅฆๅœจไธคๆก็บฟ้‡Œ้ข int Line::contain_special(Point2i p){ if(p.x>b_left && p.x<b_right){ return 1; } return 0; } //ๅˆคๆ–ญๆœ‰ๅคšๅฐ‘ไธช็ƒๅœจไธคๆก็บฟ้‡Œ้ข /* * specicl: ไธบ0ๅˆ™็›ด็บฟๆญฃๅธธ๏ผŒไธบ1ๅˆ™็›ด็บฟๅž‚็›ดไบŽx่ฝด */ int Line::allnum_contain(vector<Point2i> ball_message, bool special, int &max_y,float &ori_value,int X,int Y,int value_num){ int sum = 0; if(special == 0){ for(int i=0;i<ball_message.size();i++){ sum += contain_normal(ball_message[i]); //ori_value += 1/pow(sqrt(pow(ball_message[i].x-X,2) + pow(ball_message[i].y-Y,2)),0.9); ori_value += y_to_value_num(ball_message[i].y,value_num,Y); if(max_y < ball_message[i].y){ max_y = ball_message[i].y; } } } else{ for(int i=0;i<ball_message.size();i++){ sum += contain_special(ball_message[i]); // ori_value += 1/pow(sqrt(pow(ball_message[i].x-X,2) + pow(ball_message[i].y-Y,2)),0.9); ori_value += y_to_value_num(ball_message[i].y,value_num,Y); if(max_y < ball_message[i].y){ max_y = ball_message[i].y; } } } return sum; //่ฟ”ๅ›žๅฐ็ƒๅœจ็บฟ้‡Œ้ข็š„ๆ€ปๆ•ฐ } //double Path::value_contain(vector<Point2i> ball_message){ //} /************************************DUBUGๅ‡ฝๆ•ฐๆ—****************************************/ void Path::DUBUG_LINE_POINT(){ cout << img.size() << endl; cout <<"x: " << shovel_left << " ,y:" << Line_left_1.y << endl; cout << "้ซ˜ ๏ผš " << img_height << " , ๅฎฝ๏ผš " << img_width << endl; cout <<"draw_left_pointx: " << draw_left_point.x << " draw_left_point,y:" << draw_left_point.y << endl; cout <<"Line_left_1x: " << Line_left_1.x << " ,Line_left_1y:" << Line_left_1.y << endl; cout << endl; cout <<"draw_right_pointx: " << draw_right_point.x << " ,draw_right_pointy:" << draw_right_point.y << endl; cout <<"Line_right_1x: " << Line_right_1.x << " ,Line_right_1y:" << Line_right_1.y << endl; } void Path::DEBUG_MESSAGE_PRE(){ cout << "ไธŠไธ€ๅธง็š„็ƒ็š„ไธชๆ•ฐ๏ผš" << pre_max_num << " ไธŠไธ€ๅธง็ดขๅผ•๏ผš " << pre_pos_index << " ไธŠไธ€ๅธง่ง’ๅบฆ๏ผš" << pre_angle << endl; cout << "ไธŠไธ€ๅธงk:" << pre_pos << " b1:" << pre_b1 << " b2:" << pre_b2 << endl; } void Path::DEBUG_MESSAGE_NOW(){ //ๆœ€็ปˆๅ†ณ็ญ–ๅ‡บๆฅ็š„ๆ–นๅ‘ cout << endl; if(last_pos< 0){ cout << "ๅฝ“ๅ‰ๅ†ณ็ญ–ๅบฆๆ•ฐ๏ผš " << 180 + atan(last_pos)*180/pi << endl; } else{ cout << "ๅฝ“ๅ‰ๅ†ณ็ญ–ๅบฆๆ•ฐ๏ผš " << atan(last_pos)*180/pi << endl; } cout << "ๅฝ“ๅ‰ๅธง็š„็ƒ็š„ไธชๆ•ฐ๏ผš" << max_ball_number << " ๅฝ“ๅ‰ๅธง็ดขๅผ•๏ผš " << last_pos_index << " ๅฝ“ๅ‰ๅธง่ง’ๅบฆ: " << last_angle << endl; cout << "ๅฝ“ๅ‰ๅธงk:" << last_pos << " b1:" << last_b1 << " b2:" << last_b2 << endl; } void Path::DEBUG_DRAW_EACH_LINE(int i ,float last_k,float b1,float b2){ //cout << "ๅฝ“ๅ‰ๅ†ณ็ญ–ๅบฆๆ•ฐ๏ผš " << atan(last_k)*180/pi << " ,ไธชๆ•ฐไธบ: " << number[i] << endl; // cout <<"draw_left_pointx: " << draw_left_point.x << " draw_left_point,y:" << draw_left_point.y << endl; // cout <<"Line_left_1x: " << Line_left_1.x << " ,Line_left_1y:" << Line_left_1.y << endl; // cout << endl; // cout <<"draw_right_pointx: " << draw_right_point.x << " ,draw_right_pointy:" << draw_right_point.y << endl; // cout <<"Line_right_1x: " << Line_right_1.x << " ,Line_right_1y:" << Line_right_1.y << endl; find_drawline_point(last_k,b1,b2); if(last_pos*57.3 < 0){ stringstream st; st<< 180 + atan(last_pos)*180/pi ; draw_line(Line_left_1, draw_left_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[i],1); draw_line(Line_right_1, draw_right_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[i],1); } else{ stringstream st; st<<atan(last_pos)*180/pi; draw_line(Line_left_1, draw_left_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[i],1); draw_line(Line_right_1, draw_right_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[i],1); } } /************************************ENDโ€”โ€”DUBUGๅ‡ฝๆ•ฐๆ—****************************************/ void Path::origin_process_ball(int mode){ cout << "ๅ˜ๆˆ็Šถๆ€1ไบ†,ๅผ€ๅง‹ๆก็ƒ๏ผ๏ผ๏ผ" << endl; change_rotated_num = 0; //่ฝฌไบ†0ๆฌก๏ผŒๅฏน็Šถๆ€2ๅ’Œ3็š„่ฎกๆ•ฐๅ™จ่ฟ›่กŒๅฝ’ไฝ mode_3_num = 0; max_ball_number = 0; optimal_value = 0; ori_value = new float[num_direction + 1]; for(int i=0;i<ball_pos.size();i++){ ori_value[i] = 0; } // int number[num_direction]; float last_k,b1,b2; Line temp_line(shovel_left,shovel_right,1); number[num_direction] = temp_line.allnum_contain(ball_pos,1,line_max_y[num_direction],ori_value[num_direction],(shovel_left+shovel_right)/2,img.size().height,4); for(int i=0;i<=num_direction;i++){ if(i == num_direction){ break; //ๆœ€ๅŽไธ€ไธชๆ˜ฏ็‰นๆฎŠๆƒ…ๅ†ต } //ๅˆคๆ–ญๅนณ่กŒ็บฟๅž‚็›ดไบŽx่ฝด็š„ๆƒ…ๅ†ต last_k = tan(left_blind_angle + (right_blind_angle - left_blind_angle)*(float(i)/(num_direction-1))); b1 = img.size().height - last_k * shovel_left; b2 = img.size().height - last_k * shovel_right; // cout << "็ฌฌ" << i << " ๆก็›ด็บฟ๏ผŒ " <<"ๅฝ“ๅ‰ๆ–œ็އไธบ๏ผš" << last_k << " b1 = "<<b1 << " b2= " << b2 << endl; Line now_line(last_k,last_k,b1,b2,shovel_left,shovel_right,0); number[i] = now_line.allnum_contain(ball_pos,0,line_max_y[i],ori_value[i],(shovel_left+shovel_right)/2,img.size().height,4); //ๆญฃๅธธๆจกๅผ //ๅ•็บฏ้ ไธชๆ•ฐๅˆคๆ–ญ๏ผŒไธๅŠ ๅ…ฅ่ท็ฆปไปทๅ€ผ if(mode == 1){ if(number[i] > max_ball_number){ //่ฎฐๅฝ•ๆœ€ๅคง็š„ไธชๆ•ฐ optimal_value = ori_value[i]; max_ball_number = number[i]; //cout << "ๅฝ“ๅ‰ๆœ€ๅคง็ƒ๏ผš " << max_ball_number << endl; last_pos = last_k; last_pos_index = i; last_b1 = b1; last_b2 = b2; } } if(mode == 2){ if(ori_value[i] > optimal_value){ //่ฎฐๅฝ•ๆœ€ๅคง็š„ไธชๆ•ฐ optimal_value = ori_value[i]; max_ball_number = number[i]; //cout << "ๅฝ“ๅ‰ๆœ€ๅคง็ƒ๏ผš " << max_ball_number << endl; last_pos = last_k; last_pos_index = i; last_b1 = b1; last_b2 = b2; } } #ifdef DEBUG_EACH_LINE DEBUG_DRAW_EACH_LINE(i,last_k,b1,b2); //็”ปๅ‡บๆฏไธ€ๆก็บฟ #endif } #ifdef DUBUG_LINE DUBUG_LINE_POINT(); //ๅฏน็”ป็บฟ็š„็‚น่ฟ›่กŒDEBUG #endif //ๅพ—ๅˆฐๆœ€็ปˆ่ง’ๅบฆ if(last_pos < 0){ last_angle = 180 + atan(last_pos)*180/pi; } else{ last_angle = atan(last_pos)*180/pi; } direction_loss_judge(); //ๆ‰พๅˆฐๆœ€ๅŽ็”ป็š„็บฟ็š„็‚น if(state_mode == 1){ find_drawline_point(last_pos,last_b1,last_b2); send_angle = (last_angle - 90) * trans_angle_rate; //ๆ‹ๅผฏๆก็ƒๆจกๅผ cout<< "ๅฝ“ๅ‰ๅ†ณ็ญ–่ง’ๅบฆ-------------------------" << send_angle << endl; last_distance = judge_distance(); } else{ //็›ด่ตฐๆจกๅผ draw_left_point = Point2i(shovel_left,0); draw_right_point = Point2i(shovel_right,0); send_angle = 0; last_distance = judge_distance(); cout << "ๆ—‹่ฝฌ่ง’ๅบฆไธบ" << send_angle << endl; } state_mode = 1; stringstream st; st<< last_angle; //ๆœ€็ปˆ็š„่ง’ๅบฆ draw_line(Line_left_1, draw_left_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[last_pos_index],5); draw_line(Line_right_1, draw_right_point,"ๅบฆๆ•ฐไธบ" + st.str(),img,color[last_pos_index],5); DRAW_TEXT(); //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ imshow("Cool", img); } //่ฎพ็ฝฎๅœ†ๅฟƒ่ท็ฆป void Path::set_circle_distance(float circle_dis){ circle_distance = circle_dis; //่ฎพ็ฝฎๅœ†ๅฟƒ่ท็ฆป } void Path::circle_process_ball(int mode){ cout << "ๅ˜ๆˆ็Šถๆ€1ไบ†,ๅผ€ๅง‹ๆก็ƒ๏ผ๏ผ๏ผ" << endl; circle_max_index = 0; max_ball_number = 0; max_ball_value = 0; circle_number = new int[ball_pos.size() + 1]; circle_value = new float[ball_pos.size() + 1]; for(int i=0;i<ball_pos.size();i++){ circle_number[i] = 0; circle_value[i] = 0; } float temp_k,temp_b1,temp_b2,temp_ridus; for(int i=0;i<ball_pos.size();i++){ temp_k = float(img.size().height - ball_pos[i].y)/(float(shovel_right + shovel_left)/2 - ball_pos[i].x); temp_b1 = img.size().height - temp_k * shovel_left; temp_b2 = img.size().height - temp_k * shovel_right; temp_ridus = (1 * fabs(temp_k * (float(shovel_right + shovel_left)/2) - img.size().height + temp_b1)) / (sqrt(1 + temp_k * temp_k)); set_circle_distance(temp_ridus); for(int j=0;j<ball_pos.size();j++){ if(i == j){ continue; } else{ //ๅˆคๆ–ญ่ท็ฆป if(sqrt(pow(ball_pos[i].x-ball_pos[j].x,2) + pow(ball_pos[i].y-ball_pos[j].y,2)) < temp_ridus){ circle_number[i]++; circle_value[i] += 1/pow(sqrt(pow(ball_pos[i].x-ball_pos[j].x,2) + pow(ball_pos[i].y-ball_pos[j].y,2)),1.0); } } } if(circle_number[i] > 0){ circle_value[i]/=circle_number[i]; } else{ circle_value[i] = 0; } if(mode == 1){ if(circle_number[i] > max_ball_number){ max_ball_number = circle_number[i] + 1; max_ball_value = circle_value[i]; circle_max_index = i; last_pos = float(img.size().height - ball_pos[i].y)/(float(shovel_right + shovel_left)/2 - ball_pos[i].x); last_b1 = img.size().height - last_pos * shovel_left; last_b2 = img.size().height - last_pos * shovel_right; last_circle_distance = circle_distance; find_drawline_point(last_pos,last_b1,last_b2); } } else{ if(max_ball_value<circle_value[i]){ max_ball_number = circle_number[i] + 1; max_ball_value = circle_value[i]; circle_max_index = i; last_pos = float(img.size().height - ball_pos[i].y)/(float(shovel_right + shovel_left)/2 - ball_pos[i].x); last_b1 = img.size().height - last_pos * shovel_left; last_b2 = img.size().height - last_pos * shovel_right; last_circle_distance = circle_distance; find_drawline_point(last_pos,last_b1,last_b2); } } } if(last_pos < 0){ last_angle = 180 + atan(last_pos)*180/pi; } else{ last_angle = atan(last_pos)*180/pi; } send_angle = (last_angle - 90) * trans_angle_rate; //ๆ‹ๅผฏๆก็ƒๆจกๅผ cout << 44444 << endl; draw_line(Line_left_1, draw_left_point,"ๅบฆๆ•ฐไธบ" ,img,color[last_pos_index],5); draw_line(Line_right_1, draw_right_point,"ๅบฆๆ•ฐไธบ" ,img,color[last_pos_index],5); cout << 55555 << endl; circle(img,ball_pos[circle_max_index],last_circle_distance,Scalar(0,255,255),3); cout << 66666 << endl; state_mode = 1; DRAW_CIRCLE_TEXT(); //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ cout << 77777 << endl; imshow("Cool", img); cout << 88888 << endl; } float Line::y_to_value_num(float dis,int num,int height) { for(int i=num-1;i>=1;i--){ if(dis > float(height) * i/num){ return (i + 1); } } return 1; } void Path::DRAW_CIRCLE_TEXT(){ string label_angle_text = "JUDGE ANGLE: " ; stringstream angle_text; angle_text<< label_angle_text; angle_text << int(send_angle) ; angle_text << " degrees"; string label_num = "JUDGE BALL NUMBER:" + format("%d", max_ball_number); putText(img, angle_text.str(), Point(10,30), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); putText(img, label_num, Point(10,60), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); if(state_mode == -1){ putText(img, "WAIT JUDGE NEED", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 1){ putText(img, "PICK UP BALL", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 2){ putText(img, "SPIN AROUND,MAX_NUM:" + to_string(max_change_angle_num) + " NOW_NUM: " + to_string(change_rotated_num), Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 3){ putText(img, "FIND BALL: FIND_NUM:" + to_string(mode_3_num), Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 4){ putText(img, "GO HOME", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } } //ๆ˜พ็คบๅ›พๅƒไฟกๆฏ void Path::DRAW_TEXT(){ //ๆ˜พ็คบๅ›พๅƒ็š„ๆ–‡ๅญ—ไฟกๆฏ string label_angle_text = "JUDGE ANGLE: " ; stringstream angle_text; angle_text<< label_angle_text; angle_text << int(send_angle) ; angle_text << " degrees"; cout << "ๆœ€็ปˆ่ง’ๅบฆ" << last_angle << endl; string label_num = "JUDGE BALL NUMBER:" + format("%d", max_ball_number); putText(img, angle_text.str(), Point(10,30), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); putText(img, label_num, Point(10,60), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); if(state_mode == -1){ putText(img, "WAIT JUDGE NEED", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 1){ putText(img, "PICK UP BALL", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 2){ putText(img, "SPIN AROUND,MAX_NUM:" + to_string(max_change_angle_num) + " NOW_NUM: " + to_string(change_rotated_num), Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 3){ putText(img, "FIND BALL: FIND_NUM:" + to_string(mode_3_num), Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } else if(state_mode == 4){ putText(img, "GO HOME", Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); } putText(img, "CONTINUE NUM:" + to_string(judge_mode_num), Point(10,120), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); putText(img, "SEND DIS:" + to_string(last_distance), Point(10,150), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); putText(img, "Mage STATE:" + to_string(mage_state) + " NUM:" + to_string(mage_num), Point(10,180), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); // stringstream st; // st<<number[num_direction]; // string str= "Straght Ball Num: " + st.str(); // putText(img, str, Point(10,90), FONT_HERSHEY_SIMPLEX, 0.7, Scalar(0,255,255), 2); }
true
907c68137e41cf28f9807d5911fb85dfd0341854
C++
johnoneil/dynrec-experiment
/main.cpp
UTF-8
7,259
2.828125
3
[]
no_license
/* main.c dynrec experiment for performance improvment measure */ #include <iostream> #include <stack> #include <chrono> #if __EMSCRIPTEN__ #include <emscripten.h> #define __DYNREC__ 1 #endif #define LOOPS 100 class VirtualMachine { public: #if __EMSCRIPTEN__ void dynrec_startMethod(const char* name) { std::cout<<__func__<<std::endl; EM_ASM_INT({ var name = Pointer_stringify($0|0); Module.dynrec = Module.dynrec || {}; Module.dynrec.methods = Module.dynrec.methods || {}; Module.dynrec.currentMethod = name; Module.dynrec.stack = new Array(10); var code = ''; //code += 'Module.dynrec.stack = Module.dynrec.stack || new Array();\n'; code += 'var locals = new Array(10);\n'; code += 'var localstack = new Array();\n'; code += 'var r0 = 0;\n'; Module.dynrec.code = code; return 0; } ,name); }; void dynrec_endMethod() { std::cout<<__func__<<std::endl; EM_ASM({ var name = Module.dynrec.currentMethod; var code = Module.dynrec.code; code += 'return r0;\n'; #ifdef __DEBUG__ console.log('DYNREC method: ', name,' code-->',code); #endif #if 0 Module.dynrec.methods[name] = new Function("a1","a3",'console.log("hello from dummy dynrec.");\nreturn 12345;'); #else Module.dynrec.methods[name] = new Function("a1", "a2", Module.dynrec.code); #endif }); }; int dynrec_callmethod_i(const char* name, const int a, const int b) { return EM_ASM_INT({ var name = Pointer_stringify($0|0); var a = $1; var b = $2; #ifdef __DEBUG__ console.log('invoking method ', name, ' via dynrec.'); #endif var f = Module.dynrec.methods[name]; var r = f(a,b); #ifdef __DEBUG__ console.log("dynrec_callmethod_i result: ", r); #endif return r; } ,name ,a ,b); }; void emit_setlocal_i(const int reg) { EM_ASM_INT({ var reg = $0; //Module.dynrec.code += 'locals[' + reg.toString() + '] = Module.dynrec.stack.pop();\n' Module.dynrec.code += 'locals[' + reg.toString() + '] = localstack.pop();\n' } ,reg); } void emit_getlocal_i(const int reg) { EM_ASM_INT({ var reg = $0; //Module.dynrec.code += 'Module.dynrec.stack.push(locals[' + reg.toString() + ']);\n'; Module.dynrec.code += 'localstack.push(locals[' + reg.toString() + ']);\n'; #ifdef __DEBUG Module.dynrec.code += 'console.log("locals reg: ' + reg.toString() + ' is: " + locals[' + reg.toString() + ']);\n'; #endif } ,reg); } void emit_return_local_i(const int reg) { EM_ASM_INT({ var reg = $0; Module.dynrec.code += 'r0 = locals[' + reg.toString() + '];\n'; Module.dynrec.code += 'console.log("returning value r0:", r0);\n'; } ,reg); } void emit_push_i(const int v) { EM_ASM_INT({ var v = $0; var _v = v.toString(); //Module.dynrec.code += 'Module.dynrec.stack.push(' + _v + ');\n'; Module.dynrec.code += 'localstack.push(' + _v + ');\n'; } ,v); } void emit_pop_i() { EM_ASM({ //Module.dynrec.code += 'Module.dynrec.stack.pop();\n'; Module.dynrec.code += 'localstack.pop();\n'; }); } void emit_add_i() { EM_ASM({ Module.dynrec.code += '{\n'; //Module.dynrec.code += 'var l0 = Module.dynrec.stack.pop();\n'; //Module.dynrec.code += 'var l1 = Module.dynrec.stack.pop();\n'; //Module.dynrec.code += 'Module.dynrec.stack.push(l0 + l1);\n'; Module.dynrec.code += 'var l0 = localstack.pop();\n'; Module.dynrec.code += 'var l1 = localstack.pop();\n'; Module.dynrec.code += 'localstack.push(l0 + l1);\n'; Module.dynrec.code += '}\n'; }); } void emit_return_i() { EM_ASM({ Module.dynrec.code += 'var r0 = locals[l]; l--;return r0;\n'; }); } #endif std::stack<int> s; int locals[100]; void setlocal_i(const int reg) { locals[reg] = s.top(); s.pop(); #if __EMSCRIPTEN__ && __DYNREC__ emit_setlocal_i(reg); #endif } void getlocal_i(const int reg) { s.push(locals[reg]); #if __EMSCRIPTEN__ && __DYNREC__ emit_getlocal_i(reg); #endif } int return_local_i(const int reg) { #if __EMSCRIPTEN__ && __DYNREC__ emit_return_local_i(reg); #endif return locals[reg]; } void push_i(int v) { s.push(v); #if __EMSCRIPTEN__ && __DYNREC__ emit_push_i(v); #endif }; int pop_i() { int r = s.top(); s.pop(); #if __EMSCRIPTEN__ && __DYNREC__ emit_pop_i(); #endif return r; } void add_i() { int a = s.top(); s.pop(); int b = s.top(); s.pop(); #if __EMSCRIPTEN__ && __DYNREC__ emit_add_i(); #endif s.push(a+b); } }; #if __EMSCRIPTEN__ void dummy(){}; #endif int main(int argc, char* argv[]) { int a = 1; int b = 1; int r = 0; VirtualMachine vm; #if __EMSCRIPTEN__ && __DYNREC__ vm.dynrec_startMethod("sum"); #endif using namespace std::chrono; high_resolution_clock::time_point t1 = high_resolution_clock::now(); // Let's say we have a function that has a long series of number // manipulating ocodes. Every time we call this method we traverse these // opcodes and do work for each one. vm.push_i(a); vm.push_i(b); for(int i=0; i<LOOPS; ++i) { // method had two arguments on stack: a0, a1 // method returns one value r0; vm.setlocal_i(2); vm.setlocal_i(1); vm.getlocal_i(1); vm.getlocal_i(2); vm.add_i(); vm.setlocal_i(1); vm.getlocal_i(1); vm.getlocal_i(2); } a = vm.return_local_i(1); high_resolution_clock::time_point t2 = high_resolution_clock::now(); #if __EMSCRIPTEN__ && __DYNREC__ vm.dynrec_endMethod(); #endif std::cout<<"Virtual machine implementaition result: "<<a<<std::endl; duration<double> time_span = duration_cast<duration<double>>(t2-t1); std::cout<<"operation took : "<<time_span.count()<<" seconds."<<std::endl; #if __EMSCRIPTEN__ // assume instead that the first time we traverse these opcodes in the given // method, we form a list of corresponding native expressions for each. // this code is meant to emulate what such a 'native' representation of the previous // method would look like. a = 1; b = 1; r = 0; int loops = LOOPS; high_resolution_clock::time_point t3 = high_resolution_clock::now(); #if __DYNREC__ r = vm.dynrec_callmethod_i("sum", a, b); #else // __DYNREC__ r = EM_ASM_INT({ var a = $0; var b = $1; var loops = $2; var r = 0; for(var i=0;i < loops ;i++) { var x = a; // pop a var y = b; // pop b var t = x + y; // add a = t; // push result r = t; // pop result } return r; } ,a ,b ,loops); #endif // __DYNREC__ high_resolution_clock::time_point t4 = high_resolution_clock::now(); std::cout<<"Virtual machine implementaition result: "<<r<<std::endl; duration<double> time_span_2 = duration_cast<duration<double>>(t4-t3); std::cout<<"operation took : "<<time_span_2.count()<<" seconds."<<std::endl; #endif // __EMSCRIPTEN__ #if __EMSCRIPTEN__ emscripten_set_main_loop(dummy, 0, 1); #endif return 0; }
true
4d4c297d3d80bd19078a5221f70ee9f92db92a73
C++
amirbaghi/pac-boy-game-opengl
/Headers/Obstacle.h
UTF-8
841
2.9375
3
[]
no_license
#ifndef OBSTACLE_H #define OBSTACLE_H #include "Component.h" // Obstacle Component, inheriting from Component class class Obstacle : public Component { public: Obstacle(Component *parent); ~Obstacle(); void load(int time); void update(int time); void render(int time); // x1 Getter int getX1(); // y1 Getter int getY1(); // x2 Getter int getX2(); // y2 Getter int getY2(); // Method to set the position of this obstacle and the alignment of it void setPosition(int x1, int y1, int x2, int y2, bool isVertical); private: // Lower-left corner of the rectangle (x1, y1) and the upper-right one (x2, y2) int x1, x2, y1, y2; // Is to be placed vertical or horizontal bool isVertical; // Texture id of the obstacle GLuint texture_id; protected: }; #endif
true
797c7cd9757396af762c00b123f45972ecd688f1
C++
akshayaggarwal/LeetCode
/Q_104.cpp
UTF-8
614
3.1875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ht; void max_depth(TreeNode *root,int level){ if(root == NULL) return; if(ht < level) ht = level; max_depth(root->left,level+1); max_depth(root->right,level+1); } int maxDepth(TreeNode* root) { if(root == NULL) return 0; ht = 0; max_depth(root,1); return ht; } };
true
cce688c96db3cf4c85622868cf1b6a189344787f
C++
yueyiqiu178/DataStructure
/booleanvariable.cpp
UTF-8
907
2.75
3
[]
no_license
#include <iostream> #include<iomanip> using namespace std; void printout(bool []); int main(void) { bool a[5]; int n=5; for(int i=0;i<n;i++) a[i]=false; while(!a[0]){ printout(a); int j=n-1; a[n-1]=!a[n-1]; while(!a[j]){ j--; a[j]=!a[j]; } } system("pause"); return 0; } void printout(bool x[]){ /* for(int i=1;i<5;i++){ if(x[i]) cout<<setw(8)<<"True,"; else cout<<setw(8)<<"False,"; } cout<<endl;*/ for(int i=1;i<5;i++) cout<<x[i]<<" "; cout<<endl; }
true
127a0d786ee05adb284ca4f2fab67a7fdbdb2eed
C++
kermado/Suborbital
/include/suborbital/scene/SpecificSceneFactory.hpp
UTF-8
744
2.9375
3
[ "MIT" ]
permissive
#ifndef SUBORBITAL_SPECIFIC_SCENE_FACTORY_HPP #define SUBORBITAL_SPECIFIC_SCENE_FACTORY_HPP namespace suborbital { template<typename SceneType> class SpecificSceneFactory : public SceneFactory { public: /** * Constructor. */ SpecificSceneFactory() = default; /** * Destructor. */ ~SpecificSceneFactory() = default; /** * Instantiates a scene of the templated type and returns a unique_ptr to the created scene. * * @return Unique pointer to the created component. */ std::unique_ptr<Scene> create() const { return std::unique_ptr<SceneType>(new SceneType()); } }; } #endif
true
060306c4c47b218fd736e40f9111b2ea7183bb10
C++
alexandraback/datacollection
/solutions_5652388522229760_1/C++/calfcamel7/A.cpp
UTF-8
816
2.78125
3
[]
no_license
#include <stdio.h> int a[10]; int chk() { for(int i = 0; i < 10; i++) if(!a[i]) return 0; return 1; } void add(long long x) { //printf("add %lld\n", x); while(x) { a[x % 10] = 1; x /= 10; } } long long found(long long x) { //printf("found %lld\n",x); for(int i = 0; i < 10; i++) a[i] = 0; long long ans = 0; while(!chk()) { ans++; add(x * ans); } return x * ans; } int main() { //for(int i = 1; i <= 1000000; i++) // printf("%d %lld\n", i, found(i)); //printf("%d\n",found(0)); //printf("%d\n",found(1)); //printf("%d\n",found(2)); //printf("%d\n",found(11)); //printf("%d\n",found(1692)); int _T; scanf("%d",&_T); int x; for(int CAS = 1; CAS <= _T; CAS++) { scanf("%d",&x); printf("Case #%d: ", CAS); if(x == 0) puts("INSOMNIA"); else printf("%lld\n", found(x)); } }
true
e67f74ab958d5a62aba60f9dbdfca5d9b9c65b00
C++
knightrider17/PoolsTestConsApp
/PoolsTestConsApp/tests.cpp
UTF-8
11,351
2.9375
3
[]
no_license
#include "tests.h" #include "solutionBicycle.h" #include "solutionStl.h" void fillPoolFromArray(vector<uint8_t> &_arr_from, Pool& _pool_to) { for (size_t i = 0, ilen = _arr_from.size(); i < ilen; i += 2) { _pool_to.push_back(Range(_arr_from[i], _arr_from[i + 1])); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // PRINT FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void print_test_line(const std::string _test_name) { std::cout << "========================" << _test_name.c_str() << "==========================" << std::endl; } void print_pool(const std::string _pool_name, const Pool& _print_pool) { _print_pool.empty() ? std::cout << _pool_name.c_str() << " is EMPTY" << std::endl : std::cout << _pool_name.c_str() << std::endl; for (const auto& item : _print_pool) { std::cout << "[" << item.first << " : " << item.second << "]" << std::endl; } std::cout << std::endl; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TESTS ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 1=3 4===6 10===12 15=16 // 0^1 5^^^8 11^12 13^^^16 // 0^^2 // 0^^^3 // 1^3 // 0,0 7,8 13,14 void test_1_pools() { print_test_line("test_1"); //vector<uint8_t> new_mas = { 5,6, 15,18 }; //vector<uint8_t> old_mas = { 0,10, 10,20 }; vector<uint8_t> new_mas = { 1,3, 4,6, 10,12, 15,16 }; vector<uint8_t> old_mas = { 0,3, 0,1, 5,8, 0,2, 1,3, 11,12, 13,16 }; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 11=========21 40=========50 // 15^16 45^46 // 10^12 20^22 35^42 50^62 // 8^^^^^^^^^^^^^^^^^^^^^24 30^40 50^^^^72 // 4^^6 26^28 25^^35 65^80 // 4,6 8,10 10,10, 22,22 22,24 26,28 25,35 30,39 35,39 51,62 51,72 65,80 void test_2_pools() { print_test_line("test_2"); vector<uint8_t> new_mas = { 11,21, 40,50 }; vector<uint8_t> old_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // res = 43^44 47^49 // 11^^^^^^^^^21 40^^^^^^^^^50 // 15=16 45=46 // 10=12 20=22 35=42 50=62 // 8=====================24 30=40 50===72 // 4==6 26=28 25==35 65=80 // 43,44 47,49 void test_2_inverse_pools() { print_test_line("test_2_inverse"); vector<uint8_t> old_mas = { 11,21, 40,50 }; vector<uint8_t> new_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 16===========================================50 // 11=========21 // 15^16 45^46 // 10^12 20^22 35^42 50^62 // 8^^^^^^^^^^^^^^^^^^^^^24 30^40 50^^^^72 // 4^^6 26^28 25^^35 65^80 // 4,6 10,10 8,10 51,62 51,72 65,80 void test_3_pools() { print_test_line("test_3"); vector<uint8_t> new_mas = { 11,21, 16,50 }; vector<uint8_t> old_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 43,44 47,49 /////////////////////////// void test_3_inverse_pools() { print_test_line("test_3_inverse"); vector<uint8_t> old_mas = { 11,21, 16,50 }; vector<uint8_t> new_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 5================================================================60 // 16===========================================50 // 15=====================================45 // 20========================35 // 24=========30 // 15^16 45^46 // 10^12 20^22 35^42 50^62 // 8^^^^^^^^^^^^^^^^^^^^^24 30^40 50^^^^72 // 4^^6 26^28 25^^35 65^80 // 4,4 61,62 61,72 65,80 void test_4_pools() { print_test_line("test_4"); vector<uint8_t> new_mas = { 24,30, 20,35, 15,45, 16,50, 5,60 }; vector<uint8_t> old_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } //7,7 43,44 47,49 /////////////////////////// void test_4_inverse_pools() { print_test_line("test_4_inverse"); vector<uint8_t> old_mas = { 24,30, 20,35, 15,45, 16,50, 5,60 }; vector<uint8_t> new_mas = { 4,6, 10,12, 15,16, 8,24, 20,22, 26,28, 30,40, 25,35, 35,42, 45,46, 50,62, 50,72, 65,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 5==10 20====30 40=======50 60=====65 // 4^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^80 void test_5_pools() { print_test_line("test_5"); vector<uint8_t> new_mas = { 5,10, 20,30, 40,50, 60,65 }; vector<uint8_t> old_mas = { 4,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } /////////////////////////// void test_5_inverse_pools() { print_test_line("test_5_inverse"); vector<uint8_t> old_mas = { 5,10, 20,30, 40,50, 60,65 }; vector<uint8_t> new_mas = { 4,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 5==10 11====50 51=51 52=====79 // 4^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^80 void test_6_pools() { print_test_line("test_6"); vector<uint8_t> new_mas = { 5,10, 11,50, 51,51, 52,79 }; vector<uint8_t> old_mas = { 4,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 4==10 11====50 51=51 52========80 // 4^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^80 void test_7_pools() { print_test_line("test_7"); vector<uint8_t> new_mas = { 4,10, 11,50, 51,51, 52,80 }; vector<uint8_t> old_mas = { 4,80 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } // 4==10 12=13 14=15 16=====19 21=25 28==35 37==40 51======61 52========80 81=========================99 // 4^^10 13^14 16^^^18 20^^^25 28^^^^37 38^40 55^^60 82^83 84^85 89^93 95^97 void test_8_pools() { print_test_line("test_8"); vector<uint8_t> new_mas = { 4,10, 12,13, 14,15, 16,19, 21,25, 28,35, 37,40, 51,61, 52,80, 81,99 }; vector<uint8_t> old_mas = { 4,10, 13,14, 16,18, 20,25, 28,37, 38,40, 55,60, 82,83, 84,85, 89,93, 95,97 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); } /////////////////////////// void test_8_inverse_pools() { print_test_line("test_8_inverse"); vector<uint8_t> old_mas = { 4,10, 12,13, 14,15, 16,19, 21,25, 28,35, 37,40, 51,61, 52,80, 81,99 }; vector<uint8_t> new_mas = { 4,10, 13,14, 16,18, 20,25, 28,37, 38,40, 55,60, 82,83, 84,85, 89,93, 95,97 }; size_t size_mas = 0; Pool old_pool; fillPoolFromArray(old_mas, old_pool); print_pool("old_pool", old_pool); Pool new_pool; fillPoolFromArray(new_mas, new_pool); print_pool("new_pool", new_pool); Pool res_pool = find_diff(old_pool, new_pool); print_pool("res_pool", res_pool); }
true
356a6007a7b197558a1010992f65849fc4558ce1
C++
yang947960976/Car
/lcdclock.cpp
UTF-8
959
2.796875
3
[]
no_license
#include "lcdclock.h" #include <QTime> LcdClock::LcdClock(QWidget *parent) :QLCDNumber(parent), hour(0), minute(0), second(0) { // ๅ–ๅพ—ๅฝ“ๅ‰็š„่ฐƒ่‰ฒๆฟไฟกๆฏ QPalette pal = this->palette(); this->setDigitCount(8); // ๅฐ†่ƒŒๆ™ฏ่‰ฒ่ฎพ็ฝฎไธบๆทก็ฐ่‰ฒ pal.setColor(QPalette::Background, Qt::lightGray); this->setPalette(pal); resize(300, 80); connect(&timer, SIGNAL(timeout()), this, SLOT(onTimeOut())); timer.start(1000); // ๆฏ้š”1็ง’่งฆๅ‘ไพๆฌก่ถ…ๆ—ถไฟกๅท onTimeOut(); } LcdClock::~LcdClock() { } void LcdClock::onTimeOut() { QTime now = QTime::currentTime(); QString t = now.toString("hh:mm:ss"); static bool colon = true; if(colon) { t[2] = ':'; t[5] = ':'; colon = false; } else { t[2] = ' '; t[5] = ' '; colon = true; } display(t); }
true
370d1ab1adfa72ed8ae4719b6893509b1cacf65e
C++
seritake/TwoDimetionalInvertedPendlum
/src/trackModule/cameraException.hpp
UTF-8
373
2.875
3
[]
no_license
#pragma once #include <stdexcept> #include <string> using std::string; //Exception class about camera class CameraException: public std::runtime_error{ public: CameraException(const char* message):runtime_error(message){} CameraException(const string& message):runtime_error(message){} CameraException():runtime_error("Failed something about camera"){} };
true
440488ac8db91731a39d46d6fc4817a727742c50
C++
giftycad/my-c-lessons
/factorial.cpp
UTF-8
845
4.0625
4
[]
no_license
//calculating factorial using for, while loop and do-while loop #include <iostream> #include <string> //for loop /* int main() { int factorial = 5; int fact = factorial; for (int i = factorial - 1; i > 1; i--) { factorial = factorial * i; } std::cout << "The factorial of " << fact << " is : " << factorial << std::endl; return 0; } */ //while loop /* int main() { int factorial = 5; //factorial = 5*4*3*2*1 int i = factorial - 1; while (i > 1) { factorial *= i; i--; } std::cout << "Factorial is " << factorial << std::endl; } */ //do-while loop int main() { std::string password = "tacos123"; std::string guess; do { std::cout << "Please enter your password: " << std::endl; std::cin >> guess; } while (guess != password); }
true
a5d63b7503dcca6e24ce9ff37f1ce59ff9c82af6
C++
jaye1944/lcpp
/thread/mutual.cpp
UTF-8
1,815
3.265625
3
[]
no_license
#include <iostream> #include <map> #include <string> #include <chrono> #include <thread> #include <mutex> #include <memory> #define NO_THREAD 10 #define ELEMENTS 10000 // std::this_thread::sleep_for(std::chrono::milliseconds(10)); /* 5 thread write to map and other 5 threads read from map */ std::map<std::string, std::string> g_keyResult; std::mutex g_keyResult_mutex; void set_page(const std::string &url,int tid) { // simulate writing std::string t_id = std::to_string(tid); std::string result = "write to map " + t_id; std::lock_guard<std::mutex> guard(g_keyResult_mutex); for (int k = 0; k < ELEMENTS ; k++) { std::string ke = std::to_string(k); g_keyResult[ke] = result; } } void get_page(const std::string &url,int tid) { // simulate reading std::lock_guard<std::mutex> guard(g_keyResult_mutex); for (const auto &pair : g_keyResult) { std::cout << "Thread - " << tid << " " << pair.first << " => " << pair.second << '\n'; } } int main() { std::thread art[NO_THREAD]; std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); //read from map for (int i = 0; i < NO_THREAD; ++i) { if(i%2 != 0) { std::cout << "read i " << i << std::endl; art[i] = std::thread(get_page, "read from map",i); } else { std::cout << "Write i " << i << std::endl; art[i] = std::thread(set_page, "add to map",i); } } //join to main for (int i = 0; i < NO_THREAD; ++i) { art[i].join(); } end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; auto mili = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed_seconds); std::cout << elapsed_seconds.count() << std::endl; std::cout << mili.count() << std::endl; //t1.join(); }
true
1c99761850139428c4821d2adb9a6092bece13b7
C++
astrellon/Rouge
/log/logger.h
UTF-8
2,296
2.59375
3
[ "MIT" ]
permissive
#pragma once #include "log_entry.h" #include <string> #include <sstream> #include <vector> #ifdef _VERBOSE_LOG # define am_log(type, msg) am::log::_log_verbose(type, msg, __FILE__, __LINE__) # define am_log_e(entry) am::log::_log_verbose(entry, __FILE__, __LINE__) #else # define am_log(type, msg) am::log::_log(type, msg) # define am_log_e(entry) am::log::_log(entry) #endif namespace am { namespace log { class ILogListener; class Logger { public: typedef std::vector<LogEntry> LogEntries; Logger(); ~Logger(); void log(const char *type, const char *message); void log(const char *type, const std::string &message); void log(const char *type, const std::stringstream &message); void log(const LogEntry &entry); void log_verbose(const char *type, const char *message, const char *file, int line); void log_verbose(const char *type, const std::string &message, const char *file, int line); void log_verbose(const char *type, const std::stringstream &message, const char *file, int line); void log_verbose(LogEntry &entry, const char *file, int line); void addLogListener(ILogListener *listener); void removeLogListener(ILogListener *listener); bool hasLogListener(ILogListener *listener); void clearListeners(); void getEntries(LogEntries &entries, int num, int offset, bool fromStart); static void setMainLogger(Logger *logger); static Logger *getMainLogger(); static void clearMainLogger(); protected: LogEntries mEntries; int mMaxEntries; typedef std::vector<ILogListener *> LogListeners; LogListeners mListeners; LogListeners::iterator findListener(ILogListener *listener); void alertListeners(const LogEntry &entry); static Logger *sMainLogger; }; void _log_verbose(const char *type, const char *message, const char *file, int line); void _log_verbose(const char *type, const std::string &message, const char *file, int line); void _log_verbose(const char *type, const std::stringstream &message, const char *file, int line); void _log_verbose(LogEntry &entry, const char *file, int line); void _log(const char *type, const char *message); void _log(const char *type, const std::string &message); void _log(const char *type, const std::stringstream &message); void _log(const LogEntry &entry); } }
true
a93eeb4308b9ab47931f14b78cb1907f5e42c9d8
C++
hbdhj/spoj-cpp
/1161_TOE1.cpp
UTF-8
2,183
3.109375
3
[]
no_license
/* TASK: Tic-Tac-Toe ( I ) Input: 6 X.O OO. XXX O.X XX. OOO XXO OOX OXX XXX OO. ..O XXX OOO ... 0X0 XXX 0X0 Output: yes no no no no no */ #include <iostream> #include <vector> using namespace std; int num(string m, char c) { int ret=0; for(int i=0;i<m.length();i++) if(m[i]==c) ret++; return ret; } bool success(string m, char c) { for(int i=0;i<3;i++) if((m[i*3]==c)&&(m[i*3+1]==c)&&(m[i*3+2]==c)) return true; for(int i=0;i<3;i++) if((m[i]==c)&&(m[i+3]==c)&&(m[i+6]==c)) return true; if((m[0]==c)&&(m[4]==c)&&(m[8]==c)) return true; if((m[2]==c)&&(m[4]==c)&&(m[6]==c)) return true; return false; } bool isOK(string m) { int nO=num(m, 'O'); int nX=num(m, 'X'); //printf("nO = %d, nX = %d\n", nO, nX); if(nO>nX) return false; else if(nO==nX) { //Should No success X if(success(m, 'X')) return false; } else { if(success(m, 'O')) return false; if(nX>nO+1) return false; } return true; } int main() { /*//case 1 if(isOK("X.OOO.XXX")) printf("correct!\n"); else printf("wrong!\n"); //case 2 if(isOK("O.XXX.OOO")) printf("wrong!\n"); else printf("correct!\n"); //case 3 if(isOK("XXOOOXOXX")) printf("wrong!\n"); else printf("correct!\n"); //case 4 if(isOK("XXXOO...O")) printf("wrong!\n"); else printf("correct!\n"); //case 5 if(isOK("XXXOOO...")) printf("wrong!\n"); else printf("correct!\n");*/ int i, tN; scanf("%d", &tN); vector<string> inputs(tN); for(i=0;i<tN;i++) { char line[3]; scanf("%s", line); inputs[i]=line; scanf("%s", line); inputs[i]+=line; scanf("%s", line); inputs[i]+=line; } for(i=0;i<tN;i++) { //printf("%s\n", inputs[i].c_str()); if(isOK(inputs[i])) printf("yes\n"); else printf("no\n"); } return 0; }
true
57ec62089ea5a57df888d9129e4cd0f313d4f546
C++
evoldoers/machineboss
/ext/valijson/internal/uri.hpp
UTF-8
897
2.78125
3
[ "BSD-3-Clause" ]
permissive
#pragma once #ifndef __VALIJSON_INTERNAL_URI_HPP #define __VALIJSON_INTERNAL_URI_HPP #include <string> namespace valijson { namespace internal { namespace uri { /** * @brief Placeholder function to check whether a URI is absolute * * This function just checks for '://' */ inline bool isUriAbsolute(const std::string &documentUri) { static const char * placeholderMarker = "://"; return documentUri.find(placeholderMarker) != std::string::npos; } /** * Placeholder function to resolve a relative URI within a given scope */ inline std::string resolveRelativeUri( const std::string &resolutionScope, const std::string &relativeUri) { return resolutionScope + relativeUri; } } // namespace uri } // namespace internal } // namespace valijson #endif // __VALIJSON_INTERNAL_URI_HPP
true
712aa72611ff33cf7c1bb949f28ceb2677c56d0f
C++
mu1023/select_demo
/select_client.cpp
UTF-8
1,216
2.546875
3
[]
no_license
#include <sys/select.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include<thread> #include <string.h> #include <stdio.h> #include <signal.h> #include<iostream> using namespace std; int main() { int sockfd=socket(AF_INET,SOCK_STREAM,0); sockaddr_in sock_addr; memset(&sock_addr,0,sizeof(sock_addr)); sock_addr.sin_addr.s_addr=inet_addr("127.0.0.1"); sock_addr.sin_family=AF_INET; sock_addr.sin_port=htons(55555); if(connect(sockfd,(sockaddr * )&sock_addr,sizeof(sockaddr))==-1) { perror("connect()"); return 0; } char buffer[256]; int len=recv(sockfd,buffer,200,0); buffer[len]='\0'; cout<<buffer<<endl; auto func=[](int sk){ while(true){ char buffer[256]; int len=recv(sk,buffer,200,0); if(len<=0){ cout<<"ๆœๅŠกๅ™จๆ–ญๅผ€่ฟžๆŽฅ"<<endl; return ; } buffer[len]='\0'; cout<<buffer<<endl; } return ; }; thread th(func,sockfd); th.detach(); while(true){ cin>>buffer; send(sockfd,buffer,strlen(buffer),0); } close(sockfd); return 0; }
true
9ee7ee694d119c2c42ee951a487e7cecbb96990b
C++
Chen-Qixian/BUAA-PostGraduate-Entrance-Exam
/7-DynamicPlan/eg7-3preventMissile.cpp
UTF-8
714
2.6875
3
[]
no_license
/* ๆ‹ฆๆˆชๅฏผๅผน LIS */ #include <bits/stdc++.h> #define N 50 using namespace std; int main(void) { int ans, k; int a[N]; while(scanf("%d", &k) != EOF) { for(int i = 1 ; i <= k ; i ++) { scanf("%d", &a[i]); } int dp[N]; for(int i = 0 ; i <= k ; i ++) { dp[i] = 0; } dp[1] = 1; for(int i = 2 ; i <= k ; i ++) { int tmax = 1; for(int j = 1 ; j < i ; j ++) { if(a[j] >= a[i]) { // ๆ˜“้”™็‚น1:้œ€่ฆๅฏปๆ‰พๅ‰iไธช้‡Œ็š„ๆœ€ๅคงๅ€ผ๏ผไธๆ–ญๆ›ดๆ–ฐ tmax = max(tmax, dp[j] + 1); } } dp[i] = tmax; } //ๆ˜“้”™็‚น2:้œ€่ฆๅฏปๆ‰พๆ‰€ๆœ‰dpไธญ็š„ๆœ€ๅคงๅ€ผ ans = dp[1]; for(int i = 1 ; i <= k ; i ++) { ans = max(ans, dp[i]); } printf("%d\n", ans); } return 0; }
true
0019742aafcc3e6756dbef82627a6e00c8270c52
C++
amoghj98/MLX90614
/src/mlx90614.cpp
UTF-8
5,488
2.6875
3
[ "MIT" ]
permissive
/*************************************************************************************************************************************** ยฉ2020, Amogh S. Joshi. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************************************************************************/ #include <Arduino.h> #include <Wire.h> #include "mlx90614.h" /************************************************************************************************************************************ Private functions for low-level hardware interaction CAUTION : Manipulation of these functions may lead to system malfunctions *************************************************************************************************************************************/ uint8_t mlx90614::gen_crc8(uint8_t *address, uint8_t size) { /* Function to generate the CRC-8 checksum to be transmitted while performing a write to EEPROM or RAM. CRC polynomial = x8 + x2 + x + x0 Refer to Page 19 of the datasheet for more details */ uint8_t crc = 0; while (size--) { uint8_t in_word = *address++; for (uint8_t i = 8; i; i--) { uint8_t carry = (crc ^ in_word) & 0x80; crc <<= 1; if (carry) crc ^= 0x7; in_word <<= 1; } } return crc; } uint8_t mlx90614::write_data(uint8_t address, uint16_t data) { /* Function to write 16-bit data to memory Refer to timing diagram on Page 20 of the datasheet for more details. */ uint8_t pec, pec_buf[4]; uint8_t dl=(data & 0xFF), dh=data>>8; pec_buf[0] = devid << 1; pec_buf[1] = address; pec_buf[2] = dl; pec_buf[3] = dh; pec = gen_crc8(pec_buf, sizeof(pec_buf)); Wire.beginTransmission(devid); Wire.write(address); Wire.write(dl); Wire.write(dh); Wire.write(pec); Wire.endTransmission(true); return 0; } uint16_t mlx90614::read_data(uint8_t address) { /* Function to read 16-bit data from memory CAUTION : The read operation requires a repeated START condition on the bus. Refer to Page 19 and 20 of the datasheet for more details. */ uint16_t data; Wire.beginTransmission(devid); Wire.write(address); Wire.endTransmission(false); // Transmit slave and register addresses to the sensor, followed by a repeated START condition. Wire.requestFrom(devid, 3); data=Wire.read(); // Data is received in LSByte-first order. data|=(Wire.read()<<8); uint8_t pec=Wire.read(); // An 8-bit PEC follows the 16-bit data. For the significance of the bits in the PEC, refer to Page 20 return data; } /************************************************************************************************************************************ Intermediate Function Reads temperature and converts to degK. Included to avoid code repetition May be used directly to reduce code footprint *************************************************************************************************************************************/ float mlx90614::read_temperature(uint8_t address) { float t=read_data(address); t*=0.02; return t; } /************************************************************************************************************************************ Public functions Meant for user system interaction with the MLX90614 *************************************************************************************************************************************/ uint8_t mlx90614::init() { // double em=0.3; // User-defined emmisivity value to be set into the emmisivity register Wire.begin(); // set_emissivity(em); // Rewrite emmisivity register with user-defined emmisivity value. return 0; } float mlx90614::read_obj_temp_degK() { return read_temperature(obj_temp1); } float mlx90614::read_obj_temp_degC() { return read_temperature(obj_temp1) - 273.15; } float mlx90614::read_ambient_temp_degK() { return read_temperature(ambient_temp); } float mlx90614::read_ambient_temp_degC() { return read_temperature(ambient_temp) - 273.15; } uint8_t mlx90614::set_emissivity(double em) { /* Pre-processing is as suggested on Page 14 of the datasheet An erase cycle (write '0') is required before the emissivity register is modified (Refer Page 14 of the datasheet) A delay of atleast 5ms must be inserted post EEPROM write to ensure data coherence (Refer Page 17 of the datasheet) */ uint16_t e=(uint16_t)(0xFFFF*em); write_data(emissivity, e); delay(10); return 0; } double mlx90614::get_emissivity() { return (double)read_data(emissivity)/65535.0; }
true