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
6c71a894db3bc4aaa54caf818ef30084397fed3c
C++
wacpt4/VS2017
/VoidProject/VoidProject/FindFirstFile_FindNextFile.cpp
GB18030
2,215
3.03125
3
[]
no_license
////APIĶ->ֵǾҪرվ ////wcout ֽڵcout coutڿ̨ // //#include <Windows.h> //#include <tchar.h> //#include <iostream> //using namespace std; // //BOOL EnumFiles(LPCTSTR lpszPath, LPCTSTR lpszType) //{ // TCHAR szPath[MAX_PATH] = { 0 }; // _stprintf(szPath, _T("%s\\s"), lpszPath, lpszType); // // WIN32_FIND_DATA FindData = { 0 }; // HANDLE hFind = FindFirstFile(szPath, &FindData); // if (hFind == INVALID_HANDLE_VALUE) return FALSE; // // // BOOL bRet = FALSE; // do // { // WIN32_FIND_DATA FindData = { 0 }; // FindNextFile(hFind, &FindData); // if (!bRet) break; // //--ϵͳ-ijɿ̨ ʱҪint main0 // // cout << FindData.cFileName << endl; // // } while (bRet); // // return TRUE; //} // //int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR lpCmdLine, int nCmdShow) //{ // EnumFiles(_T("C:\\Windows"), _T("*.*")); // return 0; //} // //int _tmain(int argc, TCHAR* argv) //{ // getchar(); // return 0; //} #include <windows.h> #include <tchar.h> #include <iostream> using namespace std; BOOL EnumFiles(LPCTSTR lpszPath, LPCTSTR lpszType) { TCHAR szPath[MAX_PATH] = { 0 }; _stprintf(szPath, _T("%s\\%s"), lpszPath, lpszType); WIN32_FIND_DATA FindData = { 0 }; HANDLE hFind = FindFirstFile(szPath, &FindData); if (hFind == INVALID_HANDLE_VALUE) return FALSE; BOOL bRet = FALSE; do { bRet = FindNextFile(hFind, &FindData); if (!bRet) break; if ((FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0) { if (_tcscmp(FindData.cFileName, _T(".")) == 0 || _tcscmp(FindData.cFileName, _T("..")) == 0) continue; //ļ cout << "ļУ"; } else { if ((FindData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) > 0) { // } //ļ cout << "ļ"; } wcout << FindData.cFileName << endl; } while (bRet); return TRUE; } int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { EnumFiles(_T("C:\\Windows"), _T("*.*")); return 0; } int _tmain(int argc, TCHAR* argv[]) { EnumFiles(_T("C:\\Windows"), _T("*.*")); getchar(); return 0; }
true
752736b417adf1694e80edec4127266dc9f990b0
C++
josebummer/ugr_fundamentos_de_programacion
/Sesion 13/17.Login.cpp
ISO-8859-1
2,453
3.6875
4
[]
no_license
/* (Examen Febrero 2013) Se est diseando un sistema web que recolecta datos personales de un usuario y, en un momento dado, debe sugerirle un nombre de usuario (login). Dicho login estar basado en el nombre y los apellidos; en concreto estar formado por los N primeros caracteres de cada nombre y apellido (en minsculas, unidos y sin espacios en blanco). Por ejemplo, si el nombre es "Antonio Francisco Molina Ortega" y N=2, el nombre de usuario sugerido ser "anfrmoor". Debe tener en cuenta que el nmero de palabras que forman el nombre y los apellidos puede ser cualquiera. Adems, si N es mayor que alguna de las palabras que aparecen en el nombre, se incluir la palabra completa. Por ejemplo, si el nombre es "Ana CAMPOS de la Blanca" y N=4, entonces la sugerencia ser "anacampdelablan" (observe que se pueden utilizar varios espacios en blanco para separar palabras). Implemente la clase Login que tendr como nico dato miembro el tamao N. Hay que definir el mtodo Codifica que recibir una cadena de caracteres (tipo string) formada por el nombre y apellidos (separados por uno o ms espacios en blanco) y devuelva otra cadena con la sugerencia de login. class Login{ private: int num_caracteres_a_coger; public: Login (int numero_caracteres_a_coger) :num_caracteres_a_coger(numero_caracteres_a_coger) { } string Codifica(string nombre_completo){ ...... } }; Los nicos mtodos que necesita usar de la clase string son size y push_back. Para probar el programa lea los caracteres de la cadena uno a uno con cin.get(), hasta que el usuario introduzca el carcter #. */ #include <iostream> #include <string> #include <cctype> using namespace std; class Login{ private: static const int CARACTERES=5; public: string Codifica(string nombre){ string usuario; int longitud=nombre.size(),j=0; for(int i=0;i<longitud;i++) if(nombre[i]!=' '){ if(j<CARACTERES){ usuario.push_back(tolower(nombre[i])); j++; } } else j=0; return usuario; } }; int main(){ Login usuario; string nombre; char caracter; cout << "Introduce su nombre(# para salir): "; caracter=cin.get(); while(caracter!='#'){ nombre.push_back(caracter); cout << "Introduce su nombre(# para salir): "; caracter=cin.get(); } cout << "\n\nSu nombre de usuario es: " << usuario.Codifica(nombre) << "\n\n"; system("pause"); }
true
55bb8175c88d1a65f3c024ef942f9df801c342dc
C++
xjs-js/leetcode
/0000.30_day_leetcode_challenge/0412.Last.Stone.Weight.cpp
UTF-8
672
3.15625
3
[]
no_license
class Solution { public: int lastStoneWeight(vector<int>& stones) { if (stones.size() == 0) { return 0; } if (stones.size() == 1) { return stones[0]; } priority_queue<int> q; for (int i : stones) { q.push(i); } while (q.size() > 1) { int first = q.top(); q.pop(); int second = q.top(); q.pop(); if (first != second) { q.push(first - second); } } if (q.size() == 0) { return 0; } else { return q.top(); } } };
true
152ac990ebcd06ba30fd5e6539df0bca21361876
C++
a190884810/Project2A
/File.h
UTF-8
415
3.421875
3
[]
no_license
#include <string> //holds file objects class File { private: std::string fileName; int fileSize; public: File (){} File(std::string name, int size) { fileName = name; fileSize = size; } std::string get_fileName() { return fileName; } int get_fileSize() { return fileSize; } void set_fileName(std::string& new_name) { fileName = new_name; } void set_fileSize(int& new_size) { fileSize = new_size; } };
true
1e0f929023e0852618e56f5fc481dbeb80945c26
C++
QuantumBird/ACM_Team
/gjz/String/N.cpp
UTF-8
587
2.734375
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; const int maxn = 1000001; int nextv[maxn]; char s[maxn]; void get_next(void){ int i, j; nextv[0] = j = -1; i = 0; while(i < strlen(s)){ while(j != -1 && s[j] != s[i]) j = nextv[j]; nextv[++i] = ++j; } } int main(){ while(~scanf("%s", s), s[0] != '.'){ get_next(); int len = strlen(s); int length = len - nextv[len]; if(len % length == 0) printf("%d\n", len / length); else printf("1\n"); } return 0; }
true
8694a3481f8d4fa70bbaa04e7b163b3ec17ad504
C++
ojas032/numerical
/lag_inter.cpp
UTF-8
505
2.625
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main(){ int n; cin>>n; int x[n+1],y[n+1]; cout<<"Enter the values for x\n"; for(int i=0;i<n;i++) cin>>x[i]; cout<<"Enter the values for y\n"; for(int i=0;i<n;i++) cin>>y[i]; float xn; cout<<"Enter the value of x\n"; cin>>xn; float coff=0,deno=0,sum=1,sum2=1;; for(int i=0;i<n;i++){ sum=1,sum2=1; for(int j=0;j<n;j++){ if(i!=j){ sum*=float(xn-x[j]); sum2*=float(x[i]-x[j]); } } coff+=((float(sum)/sum2)*y[i]); } cout<<coff<<'\n'; }
true
49baaa23eff8af53db1fb8a6db45d5b2ed4ea8ae
C++
ttyang/sandbox
/sandbox/SOC/2007/graphs/libs/graph/test/runtime/misc.cpp
UTF-8
2,525
2.71875
3
[]
no_license
// (C) Copyright Andrew Sutton 2007 // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0 (See accompanying file // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <vector> #include <tr1/unordered_map> #include <boost/utility.hpp> #include <boost/graph/undirected_graph.hpp> #include <boost/graph/directed_graph.hpp> #include <boost/graph/connected_components.hpp> #include <boost/graph/strong_components.hpp> using namespace std; using namespace boost; namespace std { namespace tr1 { template <> struct hash<boost::detail::edge_desc_impl<undirected_tag, void*> > : public std::unary_function< boost::detail::edge_desc_impl<undirected_tag, void*>, std::size_t> { typedef boost::detail::edge_desc_impl<undirected_tag, void*> Edge; std::size_t operator ()(Edge e) { std::tr1::hash<Edge::property_type*> hasher; return hasher(e.get_property()); } }; } } static void undirected_test() { typedef undirected_graph<> Graph; typedef Graph::vertex_descriptor Vertex; typedef Graph::edge_descriptor Edge; typedef tr1::unordered_map<Vertex, int> component_map_type; typedef associative_property_map<component_map_type> component_map; const size_t N = 5; undirected_graph<> g; vector<Vertex> verts(N); for(size_t i = 0; i < N; ++i) { verts[i] = add_vertex(g); } add_edge(verts[0], verts[1], g); add_edge(verts[1], verts[2], g); add_edge(verts[3], verts[4], g); component_map_type mapping(num_vertices(g)); component_map comps(mapping); size_t c = connected_components(g, comps); cout << c << "\n"; Graph::vertex_iterator i, end; for(tie(i, end) = vertices(g); i != end; ++i) { cout << *i << "\t" << comps[*i] << "\n"; } } static void directed_test() { typedef directed_graph<> Graph; typedef Graph::vertex_descriptor Vertex; typedef Graph::edge_descriptor Edge; typedef tr1::unordered_map<Vertex, int> component_map_type; typedef associative_property_map<component_map_type> component_map; Graph g; Vertex u = add_vertex(g); Vertex v = add_vertex(g); add_edge(u, v, g); component_map_type mapping(num_vertices(g)); component_map comps(mapping); strong_components(g, comps); } int main() { undirected_test(); directed_test(); }
true
3dea0e70c8ddd623a0c8f78c50877cf29bc8d9f7
C++
CuriousGeorgiy/double-linked-list
/DoublyLinkedPointerListMain.cpp
UTF-8
1,600
2.859375
3
[]
no_license
#include "DoublyLinkedPointerList.hpp" int main() { DoublyLinkedPointerList<int> doublyLinkedPointerList; doublyLinkedPointerList.insertAfterLogicalPos(0, 100); doublyLinkedPointerList.insertAfterLogicalPos(1, 10); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertAfterLogicalPos(2, 57); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertAfterLogicalPos(3, 7); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertAfterLogicalPos(4, 90); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertAfterLogicalPos(3, 88); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertBeforeTail(257); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertAfterHead(1000); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertBeforeLogicalPos(4, 500); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.insertBeforeLogicalPos(5, 300); doublyLinkedPointerList.dump("After insert"); doublyLinkedPointerList.deleteHead(); doublyLinkedPointerList.deleteTail(); doublyLinkedPointerList.deleteFromLogicalPos(3); doublyLinkedPointerList.dump("after deletes"); auto node1 = doublyLinkedPointerList.nodeAtLogicalPos(2); auto node2 = doublyLinkedPointerList.findNodeByValue(88); doublyLinkedPointerList.dump("Before clear"); doublyLinkedPointerList.clear(); doublyLinkedPointerList.dump("After clear"); return 0; }
true
cd20b20cf97efec7c0dfa57b831d7fca27243528
C++
riomat13/simple-mapreduce
/include/simplemapreduce/base/fileformat.h
UTF-8
1,422
3.1875
3
[]
no_license
#ifndef SIMPLEMAPREDUCE_BASE_FILE_FORMAT_H_ #define SIMPLEMAPREDUCE_BASE_FILE_FORMAT_H_ #include <filesystem> #include <string> #include <vector> namespace mapreduce { namespace base { class FileFormat { public: // FileFormat() {} virtual ~FileFormat() {}; /** * Add directory path containing input files. * * @param path input directory path */ virtual void add_input_path(const std::string&) = 0; /** * Add multiple directory paths containing input files. * * @param paths input directory paths */ virtual void add_input_paths(const std::vector<std::string>&) = 0; /** Get next file. */ virtual std::string get_filepath() = 0; /** Reset input file path extraction. */ void reset_input_paths() { input_idx_ = 0; }; /** Set target directory path to save output files */ virtual void set_output_path(const std::string& path) = 0; /** Get target output path */ virtual std::filesystem::path get_output_path() const = 0; protected: /// Current input file path index in input_dirs_ size_t input_idx_{0}; /// Current directory iterator std::filesystem::directory_iterator curr_; /// directory paths to read input files std::vector<std::filesystem::path> input_dirs_; /// target directory path to save files std::filesystem::path output_path_; }; } // namespace base } // namespace mapreduce #endif // SIMPLEMAPREDUCE_BASE_FILE_FORMAT_H_
true
7f309138f9e008e7ecda0daf26b3000a4b03ccb4
C++
flylong0204/projects
/src/filter/piecewise_linear_vector.cc
UTF-8
4,102
2.921875
3
[]
no_license
// ========================================================================== // piecewise_linear_vector class member function definitions // ========================================================================== // Last modified on 5/14/08; 6/20/08; 4/5/14 // ========================================================================== #include <iostream> #include "math/mathfuncs.h" #include "filter/piecewise_linear_vector.h" #include "templates/mytemplates.h" using std::cin; using std::cout; using std::endl; using std::ios; using std::ostream; using std::vector; // --------------------------------------------------------------------- // Initialization, constructor and destructor functions: // --------------------------------------------------------------------- void piecewise_linear_vector::allocate_member_objects() { } void piecewise_linear_vector::initialize_member_objects() { } piecewise_linear_vector::piecewise_linear_vector( const vector<double>& T_input,const vector<threevector>& R_input) { allocate_member_objects(); initialize_member_objects(); for (unsigned int i=0; i<T_input.size(); i++) { T.push_back(T_input[i]); R.push_back(R_input[i]); } n_vertices=T.size(); } piecewise_linear_vector::piecewise_linear_vector( const vector<double>& T_input,const vector<rpy>& R_input) { allocate_member_objects(); initialize_member_objects(); for (unsigned int i=0; i<T_input.size(); i++) { T.push_back(T_input[i]); threevector curr_R( R_input[i].get_roll(),R_input[i].get_pitch(),R_input[i].get_yaw()); R.push_back(curr_R); } n_vertices=T.size(); } // Copy constructor: piecewise_linear_vector::piecewise_linear_vector( const piecewise_linear_vector& p) { allocate_member_objects(); initialize_member_objects(); docopy(p); } piecewise_linear_vector::~piecewise_linear_vector() { } // --------------------------------------------------------------------- void piecewise_linear_vector::docopy(const piecewise_linear_vector & p) { } // Overload = operator: piecewise_linear_vector& piecewise_linear_vector::operator= ( const piecewise_linear_vector& p) { if (this==&p) return *this; docopy(p); return *this; } // Overload << operator: ostream& operator<< (ostream& outstream,const piecewise_linear_vector& p) { outstream.precision(10); outstream.setf(ios::scientific); for (unsigned int v=0; v<p.n_vertices; v++) { cout << "v = " << v << " t = " << p.T[v] << " x = " << p.R[v].get(0) << " y = " << p.R[v].get(1) << " z = " << p.R[v].get(2) << endl; } outstream << endl; return outstream; } // ========================================================================== // Polynomial evaluation methods // ========================================================================== int piecewise_linear_vector::get_segment_number(double t) const { return mathfunc::binary_locate(T,0,n_vertices-1,t); } int piecewise_linear_vector::closest_vertex_ID(double t) const { // cout << "inside piecewise_linear_vector::closest_vertex_ID()" << endl; int n_lo=get_segment_number(t); int n_hi=n_lo+1; if (n_lo < 0) { n_lo=n_hi=0; } else if (n_lo >= int(n_vertices-1)) { n_lo=n_hi=n_vertices-1; } double dt_lo=fabs(t-T[n_lo]); double dt_hi=fabs(T[n_hi]-t); // cout << "n_lo = " << n_lo << " n_hi = " << n_hi << endl; // cout << "dt_lo = " << dt_lo << " dt_hi = " << dt_hi << endl; if (dt_lo < dt_hi) { return n_lo; } else { return n_hi; } } // --------------------------------------------------------------------- threevector piecewise_linear_vector::value(double t) const { // cout << "inside piecewise_linear_vector::value(), t = " << t << endl; int n=get_segment_number(t); if (n < 0) { return R[0]; } else if (n >= int(n_vertices-1)) { return R[n_vertices-1]; } else { double frac=(t-T[n])/(T[n+1]-T[n]); return ( R[n] + frac*(R[n+1]-R[n]) ); } }
true
6be96a5ef93ca06294e551cdd5a83dfe432b6973
C++
tejaanuchuri/My_work
/data structures/linkedlist/insertion/insert_at_position.cpp
UTF-8
1,041
3.515625
4
[]
no_license
#include<iostream> #include<malloc.h> using namespace std; struct node{ int data; struct node *next; }; void print_list(struct node* head){ while(head!=NULL){ cout<<head->data<<" "; head=head->next; }cout<<endl; return ; } struct node* new_node(int data){ struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = data; newnode->next = NULL; return newnode; } int size_of_list(struct node* head){ int count=0; while(head!=NULL){ count++; head = head->next; } return count; } struct node* insert_end(struct node* head,int data,int pos){ struct node* newnode = new_node(data); struct node* temp = head; if(pos==0){ newnode->next = head; head = newnode; }else{ int idx = 0; while(idx!=pos-1){ idx++; temp = temp->next; } newnode->next = temp->next; temp->next = newnode; } return head; } int main(){ struct node* head=NULL; int n,i,x,pos; cin>>n; for(i=0;i<n;i++){ cin>>x>>pos; head = insert_end(head,x,pos); print_list(head); } print_list(head); return 0; }
true
ed0dd902601811b37fa8c9c662936a89b790c520
C++
Daimare1114/dual_scara
/src/command_action/src/motion_planning.cpp
UTF-8
11,173
2.703125
3
[]
no_license
#include "../include/command_action/motion_planning.h" #include <stdio.h> #include <math.h> static void CalcTrajectoryCoef(float *AccCoef, float *ConstCoef, float *DccCoef, float AccTime, float ConstTime, float DccTime, float DstTime, float DstVal, float CurVal); static float CalcCmdTrajectory(float *CmdCoef, float ElaspedTime, float ConstTime); void InitPlannnigState(PranningParam *Param){ int i = 0; int j = 0; Param->AccTime = 0; Param->ConstTime = 0; Param->DccTime = 0; Param->DstTime = 0; Param->ElappsedTime = 0; for(i = 0; i < ANGLE_NUM; i++){ Param->DstAngle[i] = 0; for(j = 0; j < 6; j++){ Param->AccCoef[i][j] = 0; Param->ConstCoef[i][j] = 0; Param->DccCoef[i][j] = 0; } } Param->PlanningState = STATE_STANDBY; } int ExecMoveJoint(PranningParam *PParam, MotorParam *MParam, float VelRatio) { int i = 0; int Ret = NO_ERROR; float TmpDst; switch (PParam->PlanningState) { case STATE_STANDBY: break; case STATE_PLANNING: //calc destination time about each angle PParam[0].DstTime = 0; for (i = 0; i < ANGLE_NUM; i++) { PParam->DstAngle[i] = MParam->DstAngle[i]; TmpDst = fabs(PParam->DstAngle[i] - MParam->CurAngle[i]); if (TmpDst > PParam->DstTime) { PParam->DstTime = TmpDst; } } //deside destination time PParam->DstTime = (2 * PParam->DstTime) / ((CONST_RATIO + 1) * (MOTOR_MAXSPEED * VelRatio)); printf("Destination time: %f[s]\n", PParam->DstTime); //calc each part time PParam->AccTime = ACC_RATIO * PParam->DstTime; PParam->ConstTime = CONST_RATIO * PParam->DstTime; PParam->DccTime = DCC_RATIO * PParam->DstTime; //calc coeficient for (i = 0; i < ANGLE_NUM; i++) { CalcTrajectoryCoef(PParam->AccCoef[i], PParam->ConstCoef[i], PParam->DccCoef[i], PParam->AccTime, PParam->ConstTime, PParam->DccTime, PParam->DstTime, PParam->DstAngle[i], MParam->CurAngle[i]); } //update state of motion planning PParam->PlanningState = STATE_EXECUTE; PParam->ElappsedTime = 0.0; break; case STATE_EXECUTE: //calc desired angle for nextstep if (PParam[0].ElappsedTime <= PParam[0].AccTime) { //calc desired angle of acceleration section for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->AccCoef[i], PParam->ElappsedTime, 0.0); } } else if ((PParam->ElappsedTime > PParam->AccTime) && (PParam->ElappsedTime <= (PParam->AccTime + PParam->ConstTime))) { //calc desired angle of constant velocity section for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->ConstCoef[i], PParam->ElappsedTime, PParam->AccTime); } } else if ((PParam->ElappsedTime > (PParam->AccTime + PParam->ConstTime)) && (PParam->ElappsedTime <= PParam->DstTime)) { //calc desired angle of deceleration section for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->DccCoef[i], PParam->ElappsedTime, (PParam->AccTime + PParam->ConstTime)); } } else { //update state PParam->PlanningState = STATE_FINISH; } //update sampling time PParam->ElappsedTime = PParam->ElappsedTime + SAMPLING_TIME; break; case STATE_FINISH: break; default: Ret = STATE_ERROR; break; } return Ret; } int ExecMovePosPtP(PranningParam *PParam, MotorParam *MParam, float VelRatio) { int i = 0; int Ret = NO_ERROR; float TmpDst; switch (PParam->PlanningState) { case STATE_STANDBY: break; case STATE_PLANNING: Ret = CalcInverseKinematics(MParam, IK_MODE_DEST); if (Ret != SCARA_SINGULARITY) { PParam[0].DstTime = 0; for (i = 0; i < ANGLE_NUM; i++) { PParam->DstAngle[i] = MParam->DstAngle[i]; TmpDst = fabs(PParam->DstAngle[i] - MParam->CurAngle[i]); if (TmpDst > PParam->DstTime) { PParam->DstTime = TmpDst; } } PParam->DstTime = (2 * PParam->DstTime) / ((CONST_RATIO + 1) * (MOTOR_MAXSPEED * VelRatio)); printf("Destination time: %f[s]\n", PParam->DstTime); PParam->AccTime = ACC_RATIO * PParam->DstTime; PParam->ConstTime = CONST_RATIO * PParam->DstTime; PParam->DccTime = DCC_RATIO * PParam->DstTime; for (i = 0; i < ANGLE_NUM; i++) { CalcTrajectoryCoef(PParam->AccCoef[i], PParam->ConstCoef[i], PParam->DccCoef[i], PParam->AccTime, PParam->ConstTime, PParam->DccTime, PParam->DstTime, PParam->DstAngle[i], MParam->CurAngle[i]); } PParam->PlanningState = STATE_EXECUTE; PParam->ElappsedTime = 0.0; } else { printf("Singularity\n"); PParam->PlanningState = STATE_FINISH; } break; case STATE_EXECUTE: if (PParam[0].ElappsedTime <= PParam[0].AccTime) { for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->AccCoef[i], PParam->ElappsedTime, 0.0); } } else if ((PParam->ElappsedTime > PParam->AccTime) && (PParam->ElappsedTime <= (PParam->AccTime + PParam->ConstTime))) { for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->ConstCoef[i], PParam->ElappsedTime, PParam->AccTime); } } else if ((PParam->ElappsedTime > (PParam->AccTime + PParam->ConstTime)) && (PParam->ElappsedTime <= PParam->DstTime)) { for (i = 0; i < ANGLE_NUM; i++) { MParam->DstAngle[i] = CalcCmdTrajectory(PParam->DccCoef[i], PParam->ElappsedTime, (PParam->AccTime + PParam->ConstTime)); } } else { PParam->PlanningState = STATE_FINISH; } PParam->ElappsedTime = PParam->ElappsedTime + SAMPLING_TIME; break; case STATE_FINISH: break; default: Ret = STATE_ERROR; break; } return Ret; } int ExecMovePosStraight(PranningParam *PParam, MotorParam *MParam, float VelRatio) { int Ret = NO_ERROR; int i = 0; float TmpDst; switch (PParam[0].PlanningState) { case STATE_STANDBY: break; case STATE_PLANNING: PParam[0].DstTime = 0; for (i = 0; i < DIM3; i++) { PParam->DstPos[i] = MParam->DstPos[i]; TmpDst = fabs(PParam->DstPos[i] - MParam->Pos[i]); if (TmpDst > PParam->DstTime) { PParam->DstTime = TmpDst; } } PParam->DstTime = (2 * PParam->DstTime) / ((CONST_RATIO + 1) * (HAND_MAXSPEED * VelRatio)); //printf("Destination time: %f[s]\n", PParam->DstTime); PParam->AccTime = ACC_RATIO * PParam->DstTime; PParam->ConstTime = CONST_RATIO * PParam->DstTime; PParam->DccTime = DCC_RATIO * PParam->DstTime; for (i = 0; i < DIM3; i++) { CalcTrajectoryCoef(PParam->AccCoef[i], PParam->ConstCoef[i], PParam->DccCoef[i], PParam->AccTime, PParam->ConstTime, PParam->DccTime, PParam->DstTime, PParam->DstPos[i], MParam->Pos[i]); } PParam->PlanningState = STATE_EXECUTE; PParam->ElappsedTime = 0.0; break; case STATE_EXECUTE: if (PParam[0].ElappsedTime <= PParam[0].AccTime) { for (i = 0; i < DIM3; i++) { MParam->DstPos[i] = CalcCmdTrajectory(PParam->AccCoef[i], PParam->ElappsedTime, 0.0); } } else if ((PParam->ElappsedTime > PParam->AccTime) && (PParam->ElappsedTime <= (PParam->AccTime + PParam->ConstTime))) { for (i = 0; i < DIM3; i++) { MParam->DstPos[i] = CalcCmdTrajectory(PParam->ConstCoef[i], PParam->ElappsedTime, PParam->AccTime); } } else if ((PParam->ElappsedTime > (PParam->AccTime + PParam->ConstTime)) && (PParam->ElappsedTime <= PParam->DstTime)) { for (i = 0; i < DIM3; i++) { MParam->DstPos[i] = CalcCmdTrajectory(PParam->DccCoef[i], PParam->ElappsedTime, (PParam->AccTime + PParam->ConstTime)); } } else { PParam->PlanningState = STATE_FINISH; } Ret = CalcInverseKinematics(MParam, IK_MODE_DEST); PParam->ElappsedTime = PParam->ElappsedTime + SAMPLING_TIME; break; case STATE_FINISH: break; default: Ret = STATE_ERROR; break; } return Ret; } static void CalcTrajectoryCoef(float *AccCoef, float *ConstCoef, float *DccCoef, float AccTime, float ConstTime, float DccTime, float DstTime, float DstVal, float CurVal) { float TmpTilt, TmpIntrcpt; float TmpPos, TmpVel; TmpTilt = (DstVal - CurVal) / ((DstTime - (DccTime / 2)) - (AccTime / 2)); TmpIntrcpt = CurVal - (TmpTilt * (AccTime / 2)); ConstCoef[0] = TmpTilt * AccTime + TmpIntrcpt; ConstCoef[1] = TmpTilt; ConstCoef[2] = 0.0; ConstCoef[3] = 0.0; ConstCoef[4] = 0.0; ConstCoef[5] = 0.0; TmpPos = TmpTilt * AccTime + TmpIntrcpt;; TmpVel = (2 * (TmpPos - CurVal)) / AccTime; AccCoef[0] = CurVal; AccCoef[1] = 0.0; AccCoef[2] = 0.0; AccCoef[3] = (1 / (2 * powf(AccTime, 3.0))) * ((20 * TmpPos - 20 * CurVal) - (8 * TmpVel) * AccTime); AccCoef[4] = (1 / (2 * powf(AccTime, 4.0))) * ((30 * CurVal - 30 * TmpPos) + (14 * TmpVel) * AccTime); AccCoef[5] = 0.0; TmpPos = TmpTilt * (AccTime + ConstTime) + TmpIntrcpt; TmpVel = (2 * (DstVal - TmpPos)) / DccTime; DccCoef[0] = TmpPos; DccCoef[1] = TmpVel; DccCoef[2] = 0.0; DccCoef[3] = (1 / (2 * powf(DccTime, 3.0))) * ((20 * DstVal - 20 * TmpPos) - (12 * TmpVel) * DccTime); DccCoef[4] = (1 / (2 * powf(DccTime, 4.0))) * ((30 * TmpPos - 30 * DstVal) + (16 * TmpVel) * DccTime); DccCoef[5] = 0.0; } static float CalcCmdTrajectory(float *CmdCoef, float ElaspedTime, float ConstTime) { float Cmd = 0.0; float Time = ElaspedTime - ConstTime; Cmd = CmdCoef[0] + CmdCoef[1] * Time + CmdCoef[2] * powf(Time, 2.0) + CmdCoef[3] * powf(Time, 3.0) + CmdCoef[4] * powf(Time, 4.0); return Cmd; }
true
b9ac3fab92121c2935005473ce4f02e014b6c3c9
C++
h3ic/cpp-projects
/hw03-number-trie-h3ic/number/number.h
UTF-8
2,099
3.1875
3
[]
no_license
#pragma once #include <cstdint> #include <iostream> class number_t { public: number_t(); number_t(long); // implicit conv void swap(number_t &); number_t &operator=(const number_t &); explicit operator bool() const; explicit operator long() const; explicit operator std::string() const; friend bool operator==(const number_t &, const number_t &); friend bool operator!=(const number_t &, const number_t &); friend bool operator<(const number_t &, const number_t &); friend bool operator>(const number_t &, const number_t &); friend bool operator<=(const number_t &, const number_t &); friend bool operator>=(const number_t &, const number_t &); friend std::ostream &operator<<(std::ostream &, const number_t &); friend std::istream &operator>>(std::istream &, number_t &); number_t operator+=(const number_t &); number_t operator-=(const number_t &); number_t operator*=(const number_t &); number_t operator/=(const number_t &); number_t operator%=(const number_t &); number_t operator^=(const number_t &); number_t operator&=(const number_t &); number_t operator|=(const number_t &); friend number_t operator+(const number_t &, const number_t &); friend number_t operator-(const number_t &, const number_t &); friend number_t operator*(const number_t &, const number_t &); friend number_t operator/(const number_t &, const number_t &); friend number_t operator%(const number_t &, const number_t &); friend number_t operator^(const number_t &, const number_t &); friend number_t operator&(const number_t &, const number_t &); friend number_t operator|(const number_t &, const number_t &); number_t &operator++(); number_t operator++(int); number_t &operator--(); number_t operator--(int); number_t operator-() const; number_t operator+() const; number_t operator!() const; number_t operator~() const; number_t &operator<<=(const number_t &); number_t &operator>>=(const number_t &); number_t operator<<(const number_t &) const; number_t operator>>(const number_t &) const; private: long _value{0}; };
true
ba0fef266edaa7f8d3b3b6a7bbdb9ad3faebee9f
C++
plusminus34/Interactive_thin_shells_Bachelor_thesis
/FEMSimLib/src/CSTriangle3D.cpp
UTF-8
9,424
2.59375
3
[]
no_license
#include <GUILib/GLUtils.h> #include <FEMSimLib/CSTriangle3D.h> #include <FEMSimLib/SimulationMesh.h> #define SCALE_FACTOR 10000000.0 CSTriangle3D::CSTriangle3D(SimulationMesh* simMesh, Node* n1, Node* n2, Node* n3) : SimMeshElement(simMesh) { // shearModulus = 0.3 * 10e9 / SCALE_FACTOR; // bulkModulus = 1.5 * 10e9 / SCALE_FACTOR; this->n[0] = n1; this->n[1] = n2; this->n[2] = n3; setRestShapeFromCurrentConfiguration(); shearModulus = 0.3; bulkModulus = 1.5; //distribute the mass of this element to the nodes that define it... for (int i = 0;i<3;i++) n[i]->addMassContribution(getMass() / 3.0); matModel = MM_STVK; } CSTriangle3D::~CSTriangle3D(){ } void CSTriangle3D::setRestShapeFromCurrentConfiguration(){ //edge vectors V3D V1(n[0]->getWorldPosition(), n[1]->getWorldPosition()), V2(n[0]->getWorldPosition(), n[2]->getWorldPosition()); //matrix that holds three edge vectors Matrix2x2 dX; dX << V1[0], V2[0], V1[1], V2[1];// Warning: Rest shape is assumed to be in the plane dXInv = dX.inverse();//TODO .inverse() is baaad //compute the area of the element... restShapeArea = computeRestShapeArea(this->simMesh->X); } double CSTriangle3D::getMass() { return restShapeArea * massDensity; } double CSTriangle3D::computeRestShapeArea(const dVector& X) { P3D p1 = n[0]->getCoordinates(X); P3D p2 = n[1]->getCoordinates(X); P3D p3 = n[2]->getCoordinates(X); V3D V1(p1, p2), V2(p1, p3); //now compute the area of the element... return 1 / 2.0 * fabs(V1.cross(V2).length()); } void CSTriangle3D::addEnergyGradientTo(const dVector& x, const dVector& X, dVector& grad) { //compute the gradient, and write it out computeGradientComponents(x, X); for (int i = 0;i<3;i++) for (int j = 0;j<3;j++) grad[n[i]->dataStartIndex + j] += dEdx[i][j]; } void CSTriangle3D::addEnergyHessianTo(const dVector& x, const dVector& X, std::vector<MTriplet>& hesEntries) { //compute the hessian blocks and computeHessianComponents(x, X); for (int i = 0;i<3;i++) for (int j = 0;j < 3;j++) addSparseMatrixDenseBlockToTriplet(hesEntries, n[i]->dataStartIndex, n[j]->dataStartIndex, ddEdxdx[i][j], true); } void CSTriangle3D::draw(const dVector& x) { double dn = 0.00005; P3D p[3]; for (int idx = 0; idx < 3; idx++) { p[idx] = n[idx]->getCoordinates(x); } V3D normal = V3D(p[1], p[0]).cross(V3D(p[2], p[0])).normalized(); glBegin(GL_TRIANGLES); glColor3d(1.0, 0.75, 0.75);//light red front side glNormal3d(normal[0], normal[1], normal[2]); for (int idx = 0; idx < 3; idx++) { glVertex3d(p[idx][0] + dn * normal[0], p[idx][1] + dn * normal[1], p[idx][2] + dn * normal[2]); } glColor3d(0.75, 0.75, 1.0);//light blue back side glNormal3d(-normal[0], -normal[1], -normal[2]); for (int idx = 0; idx < 3; idx++) { glVertex3d(p[idx][0] - dn * normal[0], p[idx][1] - dn * normal[1], p[idx][2] - dn * normal[2]); } glEnd(); glColor3d(0.5, 0.5, 0.5); glBegin(GL_LINES); for (int i = 0; i < 2; i++) for (int j = i + 1; j < 3; j++) { P3D pi = p[i]; P3D pj = p[j]; glVertex3d(pi[0], pi[1], pi[2]); glVertex3d(pj[0], pj[1], pj[2]); } glEnd(); } void CSTriangle3D::drawRestConfiguration(const dVector& X) { glColor3d(0, 0, 0); glBegin(GL_LINES); for (int i = 0; i<2;i++) for (int j = i + 1;j<3;j++) { P3D pi = n[i]->getCoordinates(X); P3D pj = n[j]->getCoordinates(X); glVertex3d(pi[0], pi[1], pi[2]); glVertex3d(pj[0], pj[1], pj[2]); } glEnd(); } /** F maps deformed vectors dx to undeformed coords dX: dx = F*dX (or, in general F = dx/dX. By writing x as a weighted combination of node displacements, where the weights are computed using basis/shape functions, F can be computed anywhere inside the element). For linear basis functions, F is constant throughout the element so an easy way to compute it is by looking at the matrix that maps deformed triangle edges to their underformed counterparts: v = FV, where v and V are matrices containing edge vectors in deformed and undeformed configurations */ void CSTriangle3D::computeDeformationGradient(const dVector& x, const dVector& X, Matrix3x2& dxdX){ //edge vectors V3D v1(n[0]->getCoordinates(x), n[1]->getCoordinates(x)), v2(n[0]->getCoordinates(x), n[2]->getCoordinates(x)); dx << v1[0], v2[0], v1[1], v2[1], v1[2], v2[2]; dxdX = dx * dXInv; } //implements the StVK material model double CSTriangle3D::getEnergy(const dVector& x, const dVector& X){ //compute the deformation gradient computeDeformationGradient(x, X, F); double energyDensity = 0; if (matModel == MM_STVK){ //compute the Green Strain = 1/2 * (F'F-I) strain = F.transpose() * F; strain(0, 0) -= 1; strain(1, 1) -= 1; strain *= 0.5; //add the deviatoric part of the energy, which penalizes the change in the shape of the element - the frobenius norm of E [tr (E'E)] measures just that energyDensity += shearModulus * strain.squaredNorm(); //and the volumetric/hydrostatic part, which is approximated as the trace of E and aims to maintain a constant volume energyDensity += bulkModulus/2 * (strain(0,0) + strain(1,1)) * (strain(0,0) + strain(1,1)); }else if (matModel == MM_LINEAR_ISOTROPIC){ // not implemented }else if (matModel == MM_NEO_HOOKEAN){ // not implemented } return energyDensity * restShapeArea; } void CSTriangle3D::computeGradientComponents(const dVector& x, const dVector& X){ //compute the gradient of the energy using the chain rule: dE/dx = dE/dF * dF/dx. dE/dF is the first Piola-Kirchoff stress sensor, for which nice expressions exist. //compute the deformation gradient computeDeformationGradient(x, X, F); dEdF.setZero(); if (matModel == MM_STVK){ strain = F.transpose() * F; strain(0, 0) -= 1; strain(1, 1) -= 1; strain *= 0.5; Matrix2x2 stress = 2 * shearModulus * strain; stress(0, 0) += bulkModulus * (strain(0, 0) + strain(1, 1)); stress(1, 1) += bulkModulus * (strain(0, 0) + strain(1, 1)); dEdF = F * stress; }else if (matModel == MM_LINEAR_ISOTROPIC){ // not implemented }else if (matModel == MM_NEO_HOOKEAN){ // not implemented } //dF/dx is going to be some +/- Xinv terms. The forces on nodes 1,2 can be writen as: dE/dF * XInv', while the force on node 0 is -f1-f2; dEdx[1] = V3D(dEdF(0, 0) * dXInv(0, 0) + dEdF(0, 1) * dXInv(0, 1), dEdF(1, 0) * dXInv(0, 0) + dEdF(1, 1) * dXInv(0, 1), dEdF(2, 0)*dXInv(0, 0) + dEdF(2, 1)*dXInv(0, 1)) * restShapeArea; dEdx[2] = V3D(dEdF(0, 0) * dXInv(1, 0) + dEdF(0, 1) * dXInv(1, 1), dEdF(1, 0) * dXInv(1, 0) + dEdF(1, 1) * dXInv(1, 1), dEdF(2, 0)*dXInv(1, 0) + dEdF(2, 1)*dXInv(1, 1)) * restShapeArea; dEdx[0] = -dEdx[1]-dEdx[2]; } void CSTriangle3D::computeHessianComponents(const dVector& x, const dVector& X) { /* Most of this is simply copied from CSTElement2D. The only thing that's different is that some matrices are 3x2 or 3x3 as opposed to 2x2. H = dfdx = ddEdxdx. H = restShapeArea * dPdx(F; dFdx) * transpose(dXInv) There are different formula of dPdx in different models. See below. dFdx = dDsdx * dXInv dDs = [ dx1 - dx0, dx2 - dx0 dy1 - dy0, dy2 - dy0 dz1 - dz0, dz2 - dz0 ] (that is one extra row not in the 2D case) let dx0,dy0,dx1,dy1,dx2,dy2 be 1 respectively (while others keep 0 so that we get dDsd(xk)), we can calculate 6 elements of H in each turn ( {l = 0..5}ddEd(xk)d(xl) ), and finally fill out whole H matrix. (9 3x3 matrices as opposed to the 2x2 matrices of the 2D case) */ if (matModel == MM_STVK) { /* dPdx(F; dFdx) = dFdx * (2 * shearModulus * E + bulkModulus * trace(E) * I) + F * (2 * shearModulus * dEdx + bulkModulus * trace(dEdx) * I) dEdx = 0.5 * (transpose(dFdx) * F + transpose(F) * dFdx) */ computeDeformationGradient(x, X, F); Matrix2x3 FT = F.transpose(); Matrix2x2 E = 0.5 * (FT * F); E(0, 0) -= 0.5; E(1, 1) -= 0.5; Matrix2x2 I; I(0, 0) = I(1, 1) = 1; I(0, 1) = I(1, 0) = 0; for (int i = 0;i < 3;++i) for (int j = 0;j < 3;++j) { Matrix3x2 dFdXij; dFdXij(0, 0) = dFdXij(0, 1) = dFdXij(1, 0) = dFdXij(1, 1) = dFdXij(2,0) = dFdXij(2, 1) = 0; if (i > 0) dFdXij(j, i - 1) = 1; else dFdXij(j, 0) = dFdXij(j, 1) = -1; dFdXij = dFdXij * dXInv; Matrix2x2 dEdXij = 0.5 * (dFdXij.transpose() * F + FT * dFdXij); Matrix3x2 dPdXij = dFdXij * (2.0 * shearModulus * E + bulkModulus * E.trace() * I); dPdXij += F * (2.0 * shearModulus * dEdXij + bulkModulus * dEdXij.trace() * I); Matrix3x2 dHdXij = restShapeArea * dPdXij * dXInv.transpose(); for (int ii = 0;ii < 2;++ii) for (int jj = 0;jj < 3;++jj) ddEdxdx[ii + 1][i](jj, j) = dHdXij(jj, ii); ddEdxdx[0][i](0, j) = -dHdXij(0, 1) - dHdXij(0, 0); ddEdxdx[0][i](1, j) = -dHdXij(1, 1) - dHdXij(1, 0); ddEdxdx[0][i](2, j) = -dHdXij(2, 1) - dHdXij(2, 0); } //Logger::consolePrint("%lf %lf\n%lf %lf\n", ddEdxdx[0][1](0, 0), ddEdxdx[0][1](0, 1), ddEdxdx[0][1](1, 0), ddEdxdx[1][1](1, 1)); } else if (matModel == MM_LINEAR_ISOTROPIC) { // not implemented } else if (matModel == MM_NEO_HOOKEAN) { // not implemented } }
true
10134a609b02875dc7e79b4b658ee7813111409d
C++
chaeeon-lim/Deep_Learning_Routines
/v1.3/src/linear_1d.cpp
UTF-8
4,595
2.59375
3
[ "BSD-2-Clause" ]
permissive
#include "linear_1d.hpp" extern "C" { void Linear1dInt ( int *out_data // out_size , const int *in_data // in_size , const int *weight // out_size x in_size , const int *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<int, 0, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } void Linear1dFloat ( float *out_data // out_size , const float *in_data // in_size , const float *weight // out_size x in_size , const float *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<float, 0, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } void Linear1dDouble ( double *out_data // out_size , const double *in_data // in_size , const double *weight // out_size x in_size , const double *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<double, 0, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } void Linear1dIntReLu ( int *out_data // out_size , const int *in_data // in_size , const int *weight // out_size x in_size , const int *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<int, 1, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } void Linear1dFloatReLu ( float *out_data // out_size , const float *in_data // in_size , const float *weight // out_size x in_size , const float *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<float, 1, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } void Linear1dDoubleReLu ( double *out_data // out_size , const double *in_data // in_size , const double *weight // out_size x in_size , const double *bias // out_size , const uint16_t out_size , const uint16_t in_size , const uint16_t bias_size #if !defined(__SYNTHESIS__) , const int rigor // check rigorously when 1 , const int verbose // verbose level #endif ) { Linear1d<double, 1, 0> ( out_data , in_data , weight , bias , out_size , in_size , bias_size #if !defined(__SYNTHESIS__) , rigor , verbose #endif ); } } // extern "C"
true
5b828c360d341e1165d53f621f315ce116c19adc
C++
yzbx/opencv-qt
/linux/src/objectTracking/extern/UrbanTracker/include/ObjectState.h
UTF-8
847
2.859375
3
[]
no_license
#ifndef OBJECT_STATE_H #define OBJECT_STATE_H #include <string> enum ObjectState { UNDEFINED = 0x1, ENTERING = 0x2, HYPOTHESIS = 0x4, OBJECT = 0x8, LOST = 0x10, OBJECTGROUP = 0x20, INGROUP = 0x40, LEAVING = 0x80, DELETED = 0x100, SAVEANDELETE = 0x200, ESTIMATED = 0x400, //Only valid for bounding box STOPPED = 0x800, ALL = 0x8FF }; static std::string getStateRepresentativeString(ObjectState state) { std::string tmp; switch(state) { case UNDEFINED: tmp="U"; break; case ENTERING: tmp="In"; break; case HYPOTHESIS: tmp="H"; break; case OBJECT: tmp="O"; break; case LOST: tmp="L"; break; case OBJECTGROUP: tmp="G"; break; case INGROUP: tmp=""; break; case LEAVING: tmp="Out"; break; case DELETED: tmp="D"; break; case SAVEANDELETE: tmp="S"; break; } return tmp; } #endif
true
e85e447b1fb59be522c25b28c9c4f896fb268152
C++
dreamJarvis/Problem_Solving
/arrays/maxDistance.cpp
UTF-8
2,491
3.640625
4
[]
no_license
// Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].If there is no solution possible, return -1. #include <bits/stdc++.h> using namespace std; // TODO : do it again // t : O(n^2) // s : O(1) int maxDistance(vector<int> &arr){ int n = arr.size(); int maxJ = 0; for(int i = 0; i < n; i++){ for(int j = i+1; j < n; j++){ if(arr[i] <= arr[j]) maxJ = max((j-i), maxJ); } } return maxJ; } // t : O(n) // s : O(2n) int maxDistance_2(vector<int> &arr){ int n = arr.size(); vector<int> Lmin(n, 0); vector<int> Rmax(n, 0); int leftMinIndex = 0; int leftMinValue = arr[0]; int rightMaxValue = arr[n-1]; int rightMaxIndex = n-1; for(int i = 0; i < n; i++){ if(leftMinValue > arr[i]){ leftMinIndex = i; leftMinValue = arr[i]; } Lmin[i] = leftMinValue; } for(auto value:Lmin) cout << value << " "; cout << "\n\n"; for(int i = n-1; i >= 0; i--){ if(rightMaxValue < arr[i]){ cout << rightMaxValue << ", " << arr[i] << endl; rightMaxIndex = i; rightMaxValue = arr[i]; } Rmax[i] = rightMaxValue; } cout << "max : " << rightMaxValue << ", " << rightMaxIndex << endl; cout << "min : " << leftMinValue << ", " << leftMinIndex << "\n\n"; for(auto value:Rmax) cout << value << " "; cout << endl; int distance_so_far = -1; int i = 0, j = 0; while(i < n && j < n){ if(Lmin[i] < Rmax[j]){ if(j-i > distance_so_far){ distance_so_far = j-i; } j++; }else i++; } return distance_so_far; } // t : O(n) // s : O(n) int maximumGap(const vector<int> &num) { // edge cases: if (num.size() == 0) return -1; if (num.size() == 1) return 0; vector<pair<int, int> > toSort; for (int i = 0; i < num.size(); i++) { toSort.push_back(make_pair(num[i], i)); } sort(toSort.begin(), toSort.end()); int len = toSort.size(); int maxIndex = toSort[len - 1].second; int ans = 0; for (int i = len - 2; i >= 0; i--) { ans = max(ans, maxIndex - toSort[i].second); maxIndex = max(maxIndex, toSort[i].second); } return ans; } // Driver function int main(){ vector<int> arr({3, 5, 4, 2}); cout << maxDistance_2(arr) << endl; return 0; }
true
792a8a14923593a5ee064a558de7aea4d83a9c58
C++
PPQingZhao/XPlay
/app/src/main/cpp/videoviewer/XTexture.cpp
UTF-8
1,856
2.578125
3
[]
no_license
// // Created by qing on 19-1-5. // #include "XTexture.h" #include "../log/XLog.h" #include "XEGL.h" #include "XShader.h" class CXTexture : public XTexture { public: XShader shader; XTextureType textureType; XEGL *xegl = 0; std::mutex mux; virtual void Drop() { mux.lock(); xegl->Close(); shader.Close(); mux.unlock(); //删除当前对象 delete (this); } virtual bool Init(void *win, XTextureType type) { mux.lock(); if (xegl) { xegl->Close(); } shader.Close(); this->textureType = type; XLOGE("Enter CXTexture Init()!"); if (!win) { mux.unlock(); XLOGE("XTexture init failed!"); return false; } if (!xegl) xegl = XEGL::GetIntance(); if (!xegl->Init(win)) { XLOGE("XEGL::GetIntance()->Init(win) failed!"); mux.unlock(); return false; } bool ret = shader.Init((XShaderType) type); mux.unlock(); XLOGE("XTexture init success!"); return true; } virtual void Draw(unsigned char *data[], int width, int height) { // XLOGE("XTexture Draw!"); // XLOGE("width %d height %d", width, height); mux.lock(); shader.GetTexture(0, width, height, data[0]); //y if (XSHADER_yuv420P == textureType) { shader.GetTexture(1, width / 2, height / 2, data[1]); //u shader.GetTexture(2, width / 2, height / 2, data[2]); //v } else { shader.GetTexture(1, width / 2, height / 2, data[1], true); //uv } shader.Draw(); if (xegl) { xegl->Draw(); } mux.unlock(); } }; XTexture *XTexture::GetInstance() { return new CXTexture(); }
true
2615d44731355969b78ca6259a0efee293e6d1ec
C++
sardarhassan10/Banking-Management-System
/Priority_Queue.cpp
UTF-8
3,523
3.671875
4
[]
no_license
#include<iostream> #include<stdlib.h> #include"DataBase.h" using namespace std; void swapElement(int &a, int &b); //Mininum Heap Class! struct Queue // Node of priority Queue { int priority; int code; Queue* next; }; class Priority_Queue { private: int heapSize; int heapCap;// Heap Capacity Queue *heap; // Pointer to Heap array DataBase d1; public: Priority_Queue(int capacity) //Constructor { heapSize = 0; heapCap = capacity; heap = new Queue[heapCap]; Menu(); } bool isEmpty() { if (heapSize != 0) return false; return true; } int HeapSize() { return heapSize; } int parent(int index) // Return Parent INdex { return (index - 1) / 2; } int Height() // Height of tree { return (heapSize); } void Print() { cout << "\n\nQueue linearly is: "; for (int i = 0; i < heapSize; i++) { cout << heap[i].code << " (" << heap[i].priority << ") "<< "\t"; } } int AddToQueue() { int priority; cout << "\n\t1. VIP" << "\n\t2. Old" << "\n\t3. Woman" << "\n\t4. Other" << "\n\t5. Man"; cout << "\n Please enter the priority of the customer: "; cin >> priority; if (heapSize == heapCap) { cout << "\n Stack OverFlow!!"; return 0; } heapSize++; int i = heapSize - 1; heap[i].priority = priority; heap[i].code = heapSize; while (i != 0 && heap[parent(i)].priority > heap[i].priority)// To compare if child is smaller than parent { swap(heap[parent(i)], heap[i]); // If it smaller than just swap. We do not need to consider other // childs because they were already greater than parent i = parent(i); } } void MakeTransaction()//Remove element of that index { if (isEmpty() == true) { cout << "\n Queue is empty!"; return; } Queue temp = heap[0];//Store the first element heap[0] = heap[heapSize - 1]; //Store the last value into first node heapSize--; MinHeapify(0);//Compare the tree cout << "\n Next person in queue is: " << temp.code; d1.Menu(); } void MinHeapify(int index)//To ensure the characteristics of heap are followed { int r = index * 2 + 2; int l = index * 2 + 1; int smallest = index; if (r<heapSize) if (heap[r].priority <= heap[index].priority)//Checking the minimum of the child { smallest = r; cout << r << "\t" << heap[r].code; } if (l<heapSize) if (heap[l].priority <= heap[smallest].priority) { smallest = l; cout << l; } if ((heap[l].priority == heap[r].priority) && (smallest == l || smallest == r)) // If both have same priority then { if (heap[l].code < heap[r].code)//Then we find one with the lower code smallest = l; else smallest = r; } if (smallest != index) { swap(heap[index], heap[smallest]); MinHeapify(smallest); } } void Menu() { int choice; do { cout << "\n1. Add to Queue" << "\n2. Make Transaction" << "\n3. Size of Queue" << "\n4. Show Queue" << "\n5. Exit" << "\n\n Please select one of the option:"; cin >> choice; if (choice == 1) { AddToQueue(); } else if (choice == 2) { MakeTransaction(); } else if (choice == 3) { cout << "\nSize:" << HeapSize(); } else if (choice == 4) { Print(); } //else if (choice == 5) //{ // //exit(1); //} } while (choice != 5); } };
true
289e02751aba6a9c6febd3f13b9e8264564162f0
C++
sanjivr/practise
/permutations.cpp
UTF-8
2,338
3.984375
4
[]
no_license
#include<stack> #include<queue> #include<string> #include<iostream> #include<algorithm> using namespace std; void print_stack(stack<char> &st) { stack<char> tmp; while(!st.empty()) { char c = st.top(); st.pop(); tmp.push(c); } while(!tmp.empty()) { char c= tmp.top(); tmp.pop(); st.push(c); cout<<c; } cout<<"\n"; } /* eg: prefix = abc (c being top of stack) suffix = defg (d being front of queue) If size of prefix is "n" and size of suffix is "m", then there are "m" ways of populating the position "n+1"th position. For each way of filling position "n+1" there are m-1 remaining characters which need to be permuted. eg: permute (abc, defg) abc+d + permute(efg) abc+e + permute(fgd) abc+f + permute(gde) abc+g + permute(def) This cycling of elements to be considered for "n+1"th position can be achieved by maintaining suffix as a queue iterating over the length of the queue pop from front of queue push to top of stack (i.e new prefix) generate all permutations for the remaining items in suffix queue. pop from top of stack push to back of queue Once the iteration is complete, the queue will be in same ordering of elements as before the iteration to permute a whole string permute(empty_stack, queue_with_all_chars_in_string) */ void permute (stack<char> &prefix, queue<char> &suffix, int &perm_count) { if(suffix.size() == 0) { //if it is required to print all combinations of lenght "n", then insted of suffix.size() == 0, check prefix.size() == n print_stack(prefix); perm_count++; return; } for(int i = 0; i < suffix.size(); i++) { char c = suffix.front(); suffix.pop(); prefix.push(c); permute(prefix, suffix, perm_count); c = prefix.top(); prefix.pop(); suffix.push(c); } } int main() { stack<char> prefix; queue<char> suffix; string input; int perm_count = 0; while(1) { cout << "Enter the string: "; cin >> input; cout << "\n"; for(string::iterator it = input.begin(); it != input.end(); it++) { if(*it != '\0') suffix.push(*it); } permute(prefix, suffix, perm_count); cout << "Number of permutations = "<<perm_count << "\n"; while(!prefix.empty()) prefix.pop(); while(!suffix.empty()) suffix.pop(); perm_count = 0; } }
true
8dc6587bd62f086e0b6e525da1808ac6776e8bf8
C++
zhongxinghong/LeetCode
/submissions/118-杨辉三角-91265541.cpp
UTF-8
774
3.109375
3
[ "MIT" ]
permissive
/** * Submission ID: 91265541 * Question ID: 118 * Question Title: 杨辉三角 * Question URL: https://leetcode-cn.com/problems/pascals-triangle/ * Solution Time: 2020-07-25 12:29:41 * Solution Test Result: 15 / 15 * Solution Status: Accepted * Solution Memory: 6.6 MB * Solution Runtime: 4 ms */ class Solution { public: vector<vector<int>> generate(int numRows) { int i, j; std::vector<std::vector<int>> ret(numRows); if (numRows == 0) return ret; ret[0] = {1}; for (i = 1; i < numRows; ++i) { ret[i] = ret[i - 1]; ret[i].push_back(0); for (j = 1; j <= i; ++j) ret[i][j] += ret[i - 1][j - 1]; } return ret; } };
true
81346ba0f09e00faff03a1d026407abde728216d
C++
IdoGuzi/basic_ed_copy
/Editor.cpp
UTF-8
3,299
2.75
3
[]
no_license
#include <iostream> #include "Editor.h" void Editor::loop(){ std::string arg; while (true){ getline(std::cin,arg); if (arg=="a"){ append(); }else if (arg=="c"){ doc.deleteLine(line--); append(); }else if (arg=="d"){ doc.deleteLine(line); }else if (arg=="i"){ --line; if (line<0) line=0; append(); }else if (arg=="j"){ if (line!=doc.getLineSize()){ join(); }else std::cout << "?" << std::endl; }else if (arg=="q"){ if (saved) return; std::cout << "?" << std::endl; saved=true; }else if (arg=="$"){ line=doc.getLineSize(); }else if (arg.at(0)=='w' && arg.at(1)==' '){ arg=arg.substr(2); writeToFile(arg); saved=true; }else if (arg.at(0)=='s' && arg.at(1)=='/' && arg.substr(2).find('/')!=arg.size()-1 && arg.at(arg.size()-1)=='/'){ changeString(arg); }else if (arg.at(0)=='/' && arg.at(arg.size()-1)=='/'){ findText(arg); }else if (isInteger(arg)){ changeLine(arg); }else{ std::cout << "?" << std::endl; } } } void Editor::join(){ std::string tmp = doc.getLine(line); doc.deleteLine(line); tmp.append(doc.getLine(line)); doc.deleteLine(line); doc.addLine(--line,tmp); } void Editor::append(){ std::string text = ""; getline(std::cin,text); while (text!="."){ saved=false; doc.addLine(line++, text); getline(std::cin,text); } } void Editor::changeLine(std::string &s){ int num = std::stoi(s); if (s.at(0)=='+' || s.at(0)=='-'){ if (line+num<=0 || (line+num)>doc.getLineSize()){ std::cout << "?" << std::endl; return; } line+=num; }else { if (num<=0 || num>doc.getLineSize()){ std::cout << "?" << std::endl; return; } line=num; } std::cout << doc.getLine(line) << std::endl; } void Editor::changeString(std::string &s){ std::string old,replacement; s = s.substr(2); int pos = s.find('/'); old = s.substr(0,pos); replacement = s.substr(pos+1,s.size()-(pos+1)-1); int op = doc.getLine(line).find(old); if (op==-1) return; replacement = doc.getLine(line).replace(op,old.size(),replacement); doc.deleteLine(line); doc.addLine(line-1,replacement); } void Editor::findText(std::string &s){ std::string text = s.substr(1,s.size()-2); int l = doc.findLine(line,doc.getLineSize(),text); if (l==-1) { l = doc.findLine(0,line,text); if (l==-1) return; } line=l+1; } void Editor::writeToFile(std::string &fileName){ remove(fileName.c_str()); std::ofstream myfile(fileName); int size = doc.getLineSize(); for (int i=1;i<=size;i++) myfile << doc.getLine(i) << '\n'; std::cout << myfile.tellp() << std::endl; myfile.close(); } inline bool Editor::isInteger(const std::string & s){ if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char * p; strtol(s.c_str(), &p, 10); return (*p == 0); }
true
3898bc7afda6c976fa29d0ff662cb5546fe32fbe
C++
Pakequis/arcade-led-light
/arcade-led.ino
UTF-8
1,614
2.734375
3
[]
no_license
/* Arcade LED button effects Rodrigo Feliciano https://www.pakequis.com.br youtube.com/pakequis */ #include <SoftPWM.h> //library: https://github.com/bhagman/SoftPWM //LED OFF to ON time (ms) #define FADE_IN 50 //LED ON to OFF time (ms) #define FADE_OUT 1000 //Number of Buttons and LED Channels #define N_CHANNELS 8 /******************************/ /* Arduino Uno R3 */ //Buttons pins: //#define BT1 A0 //#define BT2 A1 //#define BT3 A2 //#define BT4 A3 //#define BT5 A4 //#define BT6 A5 //#define BT7 1 //#define BT8 2 //LED pins //#define LED1 3 //#define LED2 4 //#define LED3 5 //#define LED4 6 //#define LED5 7 //#define LED6 8 //#define LED7 9 //#define LED8 10 /******************************/ /******************************/ /* Arduino Mini Pro */ //Buttons pins: #define BT1 A3 #define BT2 A2 #define BT3 A1 #define BT4 A0 #define BT5 13 #define BT6 12 #define BT7 11 #define BT8 10 //LED pins #define LED1 2 #define LED2 3 #define LED3 4 #define LED4 5 #define LED5 6 #define LED6 7 #define LED7 8 #define LED8 9 /******************************/ int b[N_CHANNELS] = {BT1,BT2,BT3,BT4,BT5,BT6,BT7,BT8}; int LED[N_CHANNELS] = {LED1,LED2,LED3,LED4,LED5,LED6,LED7,LED8}; int i = 0; void setup() { SoftPWMBegin(); for (i = 0; i < N_CHANNELS; i++) { SoftPWMSet(LED[i],0); SoftPWMSetFadeTime(LED[i], FADE_IN, FADE_OUT); pinMode(b[i],INPUT); } } void loop() { for(i = 0; i < N_CHANNELS; i++) { if(!digitalRead(b[i])) { SoftPWMSet(LED[i], 0); }else { SoftPWMSet(LED[i], 255); } } }
true
80450773468cff69c896f51f5bf1e6a8584e5d9b
C++
PhilipNelson5/class-projects
/CS1400_CS1/4-TicTacToe/main.cpp
UTF-8
383
2.6875
3
[]
no_license
#include "game.hpp" int main(void) { Player p1 = make_player("Player1", 'X', location_state::ONE); Player p2 = make_player("Player2", 'O', location_state::TWO); //Player p1 = make_userdef_player("Player 1", location_state::ONE); //Player p2 = make_userdef_player("Player 2", location_state::TWO); while (ask("Do you want to play TicTacToe?")){ game(p1, p2); } }
true
1b2b7556b045504ffd746baefeac706ecb133465
C++
AhmedSalamaCs2020/Problem-Solving
/solving/main.cpp
UTF-8
559
3.046875
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; int main() { int value; int sum=0; int counter=0; while (cin>>value&&value!=0){ if(counter==0) cout<<"PERFECTION OUTPUT"<<endl; for(int r=1;r<value;r++){ if(value%r==0) sum+=r; } printf("%5d ", value); if(sum==value){ cout<<"PERFECT"<<endl; } else if (sum<value){ cout<<"DEFICIENT"<<endl; } else{ cout<<"ABUNDANT"<<endl; } sum=0; counter++; } cout<<"END OF OUTPUT"<<endl; return 0; }
true
8793dba4bec545fdf5c5ba3a6799a4928f8f7c18
C++
tccmobile/Fall2018CPP
/groceryList.cpp
UTF-8
879
3.390625
3
[]
no_license
// // Created by T10115885 on 9/25/2018. // #include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> groceryList; // Vector storing shopping list string groceryItem; // Individual grocery items string userCmd; // User input // Prompt user to populate shopping list cout << "Enter grocery items or type done." << endl; cin >> groceryItem; while (groceryItem != "done") { groceryList.push_back(groceryItem); cin >> groceryItem; } // Display shopping list cout << endl << "Enter any key for next item." << endl; while (groceryList.size() > 0) { groceryItem = groceryList.back(); groceryList.pop_back(); cout << groceryItem << " "; cin >> userCmd; } cout << endl << "Done shopping." << endl; return 0; }
true
f9a92a11a443ae098d1d09c395a8dcb102e60b7b
C++
wangtingbest/cpptrain
/cppPrimer/10/p10-15.cpp
UTF-8
221
2.953125
3
[]
no_license
#include "p10.hpp" int main() { int i1, i2; cout << "请输入两个整型变量:" << endl; cin >> i1 >> i2; auto sum = [i1](const int &a){ return i1 + a; }; cout << sum(i2) << endl; return 0; }
true
46710e1f5469d55d4128fc5f181da0a2b5831d19
C++
moodboom/Reusable
/c++/Win32/MFC/ObjectStream/DatabaseArray.cpp
UTF-8
4,727
2.90625
3
[ "MIT" ]
permissive
#include "stdafx.h" // Required for precompiled header #include <direct.h> // For _tmkdir #include "BaseDatabase.h" #include <AppHelpers.h> // For GetProgramPath() #include "DatabaseArray.h" //-------------------------------------------------------------------// // Initialize statics/globals. //-------------------------------------------------------------------// // The database schema requires exactly one database array object. // On program startup, it should be created, and this pointer should // be pointed to it. // We use a pointer and not an actual object because a derived class // may be created. If so, we create the derived object and set // this pointer to it. DatabaseArray* pDBArray = 0; //-------------------------------------------------------------------// //-------------------------------------------------------------------// // DatabaseArray() // //-------------------------------------------------------------------// DatabaseArray::DatabaseArray() { // A program should only have one db array object. Here, we make // sure the global pointer has not yet been set, then set it to // point to this object. ASSERT( pDBArray == 0 ); pDBArray = this; } //-------------------------------------------------------------------// // ~DatabaseArray() // //-------------------------------------------------------------------// DatabaseArray::~DatabaseArray() { } //-------------------------------------------------------------------// // LookUpDatabase() // //-------------------------------------------------------------------// // This function uses the given database ID to find the matching // database in the known databases list. The pointer to the // database is returned through the use of a pointer to a pointer // to a database. // The caller can specify NULL for pDBID, in which case the target // database is used. The target database is the one which receives // all new objects. Its pointer is always located in slot[1] // of the Databases array. // If a DBID is provided, but it is not found in the DB list, we // set the DB pointer to the target DB and return false. //-------------------------------------------------------------------// bool DatabaseArray::LookUpDatabase( const DatabaseID* pDBID, BaseDatabase** ppDatabase // Pointer to a pointer ) { bool bReturn = true; // Init to NULL. *ppDatabase = 0; // If pDBID is NULL or blank, use the target database. if ( !pDBID || *pDBID == DatabaseID() ) { *ppDatabase = pTargetDB; } else { // Search for the DBID in the database list. // Return is false until found. bReturn = false; int nCount = Databases.GetSize(); for ( int i = 0; i < nCount && !bReturn; i ++ ) { if ( bReturn = ( *pDBID == Databases[i]->GetDBID() ) ) // We found it, set the database pointer. *ppDatabase = Databases[i]; } // We should always return a valid database pointer // from this function. If the provided DBID did not // resolve, use the target db. if ( !bReturn ) *ppDatabase = pTargetDB; } return bReturn; } //-------------------------------------------------------------------// // GetDatabasePath() // //-------------------------------------------------------------------// void DatabaseArray::GetDatabasePath( CString* pstrDBPath ) { /* TCHAR tDBDirRegValue[] = _T("Database Directory"); bool bFoundDBDir = ( GetRegistryString( tDBDirRegValue, pstrDBPath ) ); // If we find the directory in the registry... if ( bFoundDBDir ) { // Make sure the dir ends with a backslash. if ( pstrDBPath->Right( 1 ) != _T("\\") ) *pstrDBPath += _T("\\"); // Make sure the dir exists. // Check the error result and set bFoundDBDir to false // if this doesn't work. errno = 0; if ( _tmkdir( LPCTSTR( *pstrDBPath ) ) == -1 ) bFoundDBDir = !( errno == ENOENT ); } // If we didn't find anything or couldn't create the dir... if ( !bFoundDBDir ) { // Build the default database path. *pstrDBPath = GetProgramPath() + _T("Databases\\"); // Create it. _tmkdir( LPCTSTR( *pstrDBPath ) ); // Place it in the registry. VERIFY( SetRegistryString( tDBDirRegValue, pstrDBPath ) ); } */ ASSERT( false ); *pstrDBPath = _T("c:\\"); } //-------------------------------------------------------------------// // GetDBBackupPath() // //-------------------------------------------------------------------// void DatabaseArray::GetDBBackupPath( CString* pstrPath ) { GetDatabasePath( pstrPath ); *pstrPath += _T("Backup\\"); // Make sure it exists. _tmkdir( LPCTSTR( *pstrPath ) ); }
true
8eb324791431d6915fd813c22f76dd212ab89467
C++
azell003/Algorithms
/Graphs/Kruskal.cpp
UTF-8
685
2.84375
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> using namespace std; const int N = 1000000; int p[N]; pair<int, pair<int, int> >edgeList[N]; int getp(int x) { return (p[x] == x ? x : p[x] = getp(p[x])); } int main() { int e, v, ans = 0; cin >> v >> e; for(int i = 0; i < e; i++) cin >> edgeList[i].second.first >> edgeList[i].second.second >> edgeList[i].first; sort(edgeList, edgeList + e); for(int i = 0; i < v; i++) p[i] = i; for(int i = 0; i < e; i++) { int a = getp(edgeList[i].second.first); int b = getp(edgeList[i].second.second); if(a != b) { p[b] = a; ans += edgeList[i].first; } } cout << ans << endl; }
true
e068c05ba5c8c26ce93c2ac143ba6ced5be124bb
C++
cs2103jan2015-f09-1c/main
/Aliases/CommandAlias.h
UTF-8
616
2.578125
3
[]
no_license
//@author A0086626W #pragma once #include <string> class CommandAlias { public: CommandAlias(void); ~CommandAlias(void); // the following isAdd, isDel ... isExit methods returns true if "cmd" matches // one of the allowed aliases for the corresponding command static bool isAdd(std::string cmd); static bool isDel(std::string cmd); static bool isEdit(std::string cmd); static bool isUndo(std::string cmd); static bool isSearch(std::string cmd); static bool isView(std::string cmd); static bool isDone(std::string cmd); static bool isStorage(std::string cmd); static bool isExit(std::string cmd); };
true
a732dd82fe4ca87230e577f5c3a4704f3d549dd4
C++
dave325/cs211
/Labs/Lab-MoreReview/Question4.cpp
UTF-8
196
3.125
3
[]
no_license
#include <iostream> int main(){ int num; int sum = 0; std::cout << "Enter number"<<std::endl; std::cin >> num; for(int i = 1; i <= num; i++){ sum += i; } std::cout << sum << std::endl; }
true
d8bd518d08d326e224e5f60fc938e4cdea5eda03
C++
MichaelGhosn/Data_Structure_huffman
/Testing_fifth_fct.cpp
UTF-8
7,190
3.609375
4
[]
no_license
#include <iostream> #include <string> #include <Stack> #include <fstream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; struct Node { int frequency; std::string txt; Node* next; Node* left; Node* right; Node* parent; }; struct Stack { int data; Stack* next; }; Stack* Create() { return NULL; } bool isEmpty(Stack* S) { return (S == NULL); } Stack* push(Stack* S, int val) { Stack* elt = new Stack; elt->data = val; elt->next = S; return elt; } Stack* pop(Stack *S, int *res) { if (S == NULL) return S; *res = S->data; Stack* tmp = S->next; delete S; return tmp; } int compare(Node* First, Node* Second) { if (First->frequency < Second->frequency) return -1; if (First->frequency > Second->frequency) return 1; if (First->txt < Second->txt) return -1; if (First->txt > Second->txt) return 1; return 0; } Node* Initialize() { return NULL; } void DisplayList(Node* Head) { std::cout << std::endl; for (Node* curr = Head; curr != NULL; curr = curr->next) { std::cout << curr->txt << " : " << curr->frequency << std::endl; } std::cout << std::endl; } void Sort(Node* Head) { // This function sorts the simply linked list in ascending order using the Selection Sort algorithm. // For this purpose, you may use the already defined function : int compare(Node* First, Node* Second) // The compare function compares two nodes according to their frequencies and lexicographic order. // The compare function returns -1 if the first node is smaller than the second node. // The compare function returns +1 if the first node is larger than the second node. // The compare function returns 0 if both nodes are equal. Node *cur=new Node; cur=Initialize(); Node *min=new Node; min=Initialize(); Node *cur1=new Node; cur1=Initialize(); for(cur=Head;cur->next!=NULL;cur=cur->next) { min=cur; for(cur1=cur->next;cur1!=NULL;cur1=cur1->next) { if(compare(cur1,min)==-1) { min=cur1; } } if(compare(cur,min)==1) { int x=min->frequency; min->frequency=cur->frequency; cur->frequency=x; char s=min->txt[0]; min->txt[0]=cur->txt[0]; cur->txt=s; } } DisplayList(Head); } Node* InsertSorted(Node* Head, Node* elt) { // This function inserts the node elt in the simply linked list while keeping the list // sorted according to the frequencies of occurrence and the lexicographic order. // For this purpose, you may use the already defined function : int compare(Node* First, Node* Second) Node *tmp=new Node; tmp=elt; if(Head==NULL) { cout<<"Head is null so creating a new LL with "<<tmp->txt<<" as it's first node..."<<endl; Head=tmp; return tmp; } Node *cur=new Node; cur=Head; for(cur=Head;cur->next!=NULL;cur=cur->next) { if(cur->txt==tmp->txt) { cout<<"Element found adding 1 to it's frequency..."<<endl; cur->frequency++; Sort(Head); return Head; } } for(cur=Head;cur->next!=NULL&&compare(cur->next,tmp)==-1;cur=cur->next); cout<<"Adding "<<tmp->txt<<" in the LL..."<<endl; tmp->next=cur->next; cur->next=tmp; Sort(Head); return Head; } Node* IncFrequency(Node* Head, char c) { // This function searches for the character C in the simply linked list. // If it was able to find a node containing this character, it increments it frequency by 1. // If no such node exists, it creates a new node and append it to the beginning of the simply linked list, where : // the 'txt' field is equal to the character // the 'frequnecy' field is equal to 1 // the 'parent', 'left' and 'right' fields are set to NULL if(Head==NULL) { cout<<"Head is null so creating LL from scratch..."<<endl; Node *temp=new Node; if(temp==NULL) { cout<<"Error creating temporary node exit..."<<endl; exit(1); } temp->txt=c; temp->next=NULL; temp->left=NULL; temp->right=NULL; temp->parent=NULL; temp->frequency=1; Head=temp; cout<<c<<" added to LL with frequency 1"<<endl; return Head; } Node *element=new Node; element=NULL; for(element=Head;element!=NULL;element=element->next) { if(element->txt[0]==c) { element->frequency++; cout<<c<<" already exists adding 1 to his frequency..."<<endl; return Head; } } Node *tmp; tmp=new Node; if(tmp==NULL) { cout<<"Error with node creation"<<endl; exit(1); } tmp->txt=c; tmp->next=NULL; tmp->left=NULL; tmp->right=NULL; tmp->parent=NULL; tmp->frequency=1; tmp->next=Head; Head=tmp; cout<<c<<" is a new element adding it with frequency 1..."<<endl; return Head; } Node* ReadFile(const char* fileName) { // This function reads a file given by its name. // It creates a simply linked list containing the letters present in the file along with their frequency of occurence. // You can use the previous function : Node* IncFrequency(Node* Head, char c) ifstream myfile; myfile.open("E://Uni year 2//Data Structure//Huffman Code-20181226//file.txt"); string line; if(myfile.is_open()) { cout<<"Reading from file..."<<endl; getline(myfile,line); } if(myfile.fail()) { cout<<"Unable to open file"<<endl; } myfile.close(); Node *head=new Node; head=Initialize(); int i=0; while(line[i]!='\0') { //if(line[i]==' ') //{ // i++; //} //hayde bass eza ma badna l space w ma3 hayde l if byotla3 l tree metel ma badoun head=IncFrequency(head,line[i]); i++; } return head; } void DisplayTree(Node* Tree, Node* charNode) { if (Tree == NULL || charNode == NULL) return; Stack* S = Create(); Node* curr = charNode, *parent; while (curr != NULL && curr->parent != NULL) { parent = curr->parent; if (parent->left == curr) S = push(S, 0); else S = push(S, 1); curr = parent; } int x; std::cout << charNode->txt << " : "; while (!isEmpty(S)) { S = pop(S, &x); std::cout << x << " "; } std::cout << std::endl; } Node* Encode(Node* Tree) { if (Tree == NULL || Tree->next == NULL) return Tree; Node *newTree = Tree->next->next; Node* newNode = new Node; newNode->frequency = Tree->frequency + Tree->next->frequency; newNode->txt = Tree->txt + Tree->next->txt; newNode->left = Tree; newNode->right = Tree->next; newNode->parent = NULL; newNode->next = NULL; Tree->parent = newNode; Tree->next->parent = newNode; newTree = InsertSorted(newTree, newNode); return newTree; } Node* HuffmanTree(Node* Tree) { while (Tree != NULL && Tree->next != NULL) { Tree = Encode(Tree); } return Tree; } Node * SearchTree(Node * Tree, string C){ Node *temp=new Node; temp=NULL; if(Tree==NULL) { return NULL; } if(Tree->txt==C) { return Tree; } temp=SearchTree(Tree->right,C); if(temp) { return temp; } temp=SearchTree(Tree->left,C); if(temp) { return temp; } return NULL; } int main(int argc, char** argv) { Node* H = NULL; //const char*c=NULL; if (argc == 1) { H = ReadFile("file.txt"); } else { H = ReadFile(argv[1]); } Sort(H); DisplayList(H); H = HuffmanTree(H); for (char c = 'a'; c <= 'z'; c++) { Node* res = SearchTree(H, string(1,c)); DisplayTree(H, res); } cout << "Press Any Key to Continue ..." << endl; getchar(); return 0; }
true
0e56f2bb4c0d7180bca6af2ddb174b28438a5101
C++
jonghoinside/LearningtheCpp
/class/stack2/stack.h
UTF-8
607
3.15625
3
[]
no_license
#ifndef STACK_H #define STACK_H #include <iostream> #define STACKSIZE 10 class Stack { friend std::ostream& operator<<(std::ostream& out, const Stack& rhs); private: int* pArr_; int size_; int tos_; Stack(const Stack& rhs); Stack& operator=(const Stack& rhs); public: Stack(int size = STACKSIZE); ~Stack(); int size() const; bool full(); bool empty(); void push(int data); int pop(); // Stack* operator&() { return this; } // const Stack* operator&() const { return this; } // 함수 중복이지만 const까지 구별 가능함. 함수 이름 인자 개수 타입 + const }; #endif
true
a2b922ea602a58096f8ff135d7c1a01b17948669
C++
numerodix/accelerated-cpp
/chapter-03/ex-03/main.cpp
UTF-8
498
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <map> using std::cout; using std::endl; int main() { std::string word; std::map<std::string, int> dct; while (std::cin >> word) { if (dct.find(word) == dct.end()) { dct[word] = 0; } dct[word]++; } for (auto it = dct.begin(); it != dct.end(); it++) { auto key = it->first; auto value = it->second; std::cout << key << ": " << value << std::endl; } return 0; }
true
92f02aa26de692730410755d7d70622e1dd476e0
C++
CarolineZhu/Leetcode
/leetcode387.cpp
UTF-8
491
2.953125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int firstUniqChar(string s) { vector<vector<int> >table(26); for (int i = 0; i < s.length(); i++) { table[s[i] - 'a'].push_back(i); } int minpos = s.length(); for (int i = 0; i < table.size(); i++) { if (table[i].size() == 1 && table[i][0] < minpos) { minpos = table[i][0]; } } if (minpos != s.length()) return minpos; else return -1; } int main() { cout << firstUniqChar("leetltcodecod"); return 0; }
true
e2e3a204f331585707de1d3d16a8002ab153793f
C++
mohit200008/DSA
/DSA_Udemy/11_Recursion_basic/8countZeros.cpp
UTF-8
367
3.078125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int countZero(int n) { //base case if (n == 0) { return 0; } //recursive case int smallOutput = countZero(n / 10); //calculation int lastdigit = n % 10; return lastdigit == 0 ? smallOutput + 1 : smallOutput; } int main() { cout << countZero(2059004000); return 0; }
true
6896421b99ca9d266e36898c796956778610c7e2
C++
minlexx/l2informer
/src/db/charclassdb.cpp
UTF-8
2,883
2.640625
3
[]
no_license
#include "charclassdb.h" #include <QFile> #include <QXmlStreamReader> CharClassDB *CharClassDB::_s_instance = NULL; CharClassDB *CharClassDB::getInstance() { if( _s_instance == NULL ) { _s_instance = new CharClassDB(); } return _s_instance; } CharClassDB::CharClassDB() { } bool CharClassDB::load() { QFile f( "data/classList.xml" ); if( !f.open(QIODevice::ReadOnly | QIODevice::Text) ) { qDebug( "Failed to read class list: data/classList.xml" ); return false; } QXmlStreamReader xml( &f ); while( !xml.atEnd() && !xml.hasError() ) { QXmlStreamReader::TokenType token = xml.readNext(); if( token == QXmlStreamReader::StartDocument ) continue; if( token == QXmlStreamReader::StartElement ) { if( xml.name() == "class" ) { // <class classId="12" name="Sorcerer" serverName="sorcerer" parentClassId="11" /> QXmlStreamAttributes attrs = xml.attributes(); int id = -1; int parent_id = -1; QString name; if( attrs.hasAttribute( "classId" ) ) id = attrs.value( "classId" ).toInt(); if( attrs.hasAttribute( "parentClassId" ) ) parent_id = attrs.value( "parentClassId" ).toInt(); if( attrs.hasAttribute( "name" ) ) name = attrs.value( "name" ).toString(); // //qDebug( "Loaded class [%s] (%d, %d)", name.toLocal8Bit().data(), id, parent_id ); // L2CharClass l2_class( id, name, parent_id ); m_classDb[ id ] = l2_class; // token = xml.readNext(); while( token != QXmlStreamReader::EndElement ) xml.readNext(); } } } if( xml.hasError() ) { qCritical( "XML read error: (data/classList.xml) %s", xml.errorString().toLocal8Bit().data() ); } xml.clear(); f.close(); qDebug( "CharClassDB: Read class list: %d classes", m_classDb.size() ); return true; } L2CharClass CharClassDB::getClassById( int classId ) { L2CharClass ret; if( m_classDb.contains( classId ) ) { ret = m_classDb[ classId ]; return ret; } qWarning( "CharClassDB: requested nonexistent class ID %d!", classId ); return ret; } QList<L2CharClass> CharClassDB::getBaseClassesList() { return getChildClassesList( -1 ); } QList<L2CharClass> CharClassDB::getChildClassesList( int baseClassId ) { QList<L2CharClass> ret; QMapIterator<int, L2CharClass> iter( m_classDb ); while( iter.hasNext() ) { iter.next(); // const L2CharClass& cl = iter.value(); if( cl.parentClassId() == baseClassId ) ret.append( cl ); } return ret; }
true
9bffefe98c96e3b3fc1b494bc21dadfd8facdf6f
C++
tenox7/ntutils
/fte/src/s_string.cpp
UTF-8
1,836
2.875
3
[]
no_license
#include "s_string.h" #include <string.h> size_t UnTabStr(char *dest, size_t maxlen, const char *source, size_t slen) { const char * const end = dest + maxlen - 1; char *p = dest; unsigned pos = 0; for (unsigned i = 0; p < end && i < slen; ++i) { if (source[i] == '\t') { do { if (p < end) *p++ = ' '; } while (++pos & 0x7); } else { *p++ = source[i]; pos++; } } if (p <= end) *p = '\0'; return pos; } size_t UnEscStr(char *dest, size_t maxlen, const char *source, size_t slen) { const char * const end = dest + maxlen - 1; char *p = dest; for (unsigned i = 0; p < end && i < slen; ++i) { if (source[i] == 0x1B) { // ESC-seq if (++i < slen && (source[i] == '[')) { while (++i < slen && ((source[i] >= '0' && source[i] <= '9') || source[i] == ';')) ; } else *p++ = '^'; } else if (source[i] == (char)0xE2 && (i + 1) < slen && source[i + 1] == (char)0x80) { // Replace localized UTF8 apostrophes used by gcc. *p++ = '\''; i += 2; } else *p++ = source[i]; } if (p <= end) *p = '\0'; return p - dest; } #if !defined(HAVE_STRLCPY) /* returns size of src */ size_t strlcpy(char *dst, const char *src, size_t size) { size_t sz = 0; while (sz < size && (dst[sz] = src[sz])) sz++; if (sz && (sz == size)) dst[sz - 1] = 0; while (src[sz]) sz++; return sz; } #endif // !HAVE_STRLCPY #if !defined(HAVE_STRLCAT) size_t strlcat(char *dst, const char *src, size_t size) { size_t dst_len = strlen(dst); size_t src_len = strlen(src); if (size) { size_t len = (src_len >= size-dst_len) ? (size-dst_len-1) : src_len; memcpy(&dst[dst_len], src, len); dst[dst_len + len] = '\0'; } return dst_len + src_len; } #endif // !HAVE_STRLCAT
true
5e56fac18e131eea3431aa78d58446be03642133
C++
esoup/PowerMinder
/PowerMinder/Calendar.cpp
UTF-8
15,036
2.53125
3
[]
no_license
//------------------------------------------------------------------------------ // Copyright 2013 Janick Bergeron // All Rights Reserved Worldwide // // 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 <stdint.h> #ifdef DEBUG #include <stdio.h> #endif #include "Calendar.h" using namespace PowerMinder; /** The maximum number of period change points in a daily schedule */ const unsigned int MAX_CHANGE_POINTS = 5; /** A daily schedule, composed of MAX_CHANGE_POINTS period change points. * * The first period change point MUST be at midnight (m_time == 0). * Subsequent period change points must be in chronological order. * If fewer than MAX_CHANGE_POINTS period change points are required, * the daily schedule must be padded with dummy period change points with * a m_time == 0. * * Time is specified using 30-min precision, so 0 == midnight, 5 = 2:30a, and 28 == 2:00p. */ typedef struct schedule_s { struct period_change_s { uint8_t m_time : 6; ///< Time of the period change, in 30-min intervals period_t m_period : 2; ///< Type of period that starts at this time } m_periodChange[MAX_CHANGE_POINTS]; } schedule_t; /** A season specification. * * A season starts at the specified date and lasts until the start of the next season. * * A calendar is composed by a an array of season descriptors, in chronological order. * A calendar is terminated by a season with an ID == 0xFF. */ typedef struct season_s { uint8_t m_startMonth; uint8_t m_startDay; uint8_t m_workdayScheduleIdx; uint8_t m_holidayScheduleIdx; } season_t; /** Default schedule, from PG&E * http://www.pge.com/en/myhome/environment/whatyoucando/electricdrivevehicles/rateoptions/index.page */ static const schedule_t PGE_schedules[2] = {{{{0, OFF_PEAK}, // Weekday {14, PARTIAL_PEAK}, {28, ON_PEAK}, {42, PARTIAL_PEAK}, {44, OFF_PEAK}}}, {{{0, OFF_PEAK}, // Weekend/Holidays {30, ON_PEAK}, {38, OFF_PEAK}, {0, OFF_PEAK}, {0, OFF_PEAK}}}}; /** Default calendar, from PG&E */ static const season_t PGE_seasons[3] = {{5, 1, 0, 1}, {11, 1, 0, 1}, {0, 0, 0, 0}}; /** Where the user-defined schedules are stored in NVRAM */ static schedule_t *user_schedules = 0x0000; //*/ new schedule_t[31]; // When using new operator these two lines do not compile. Several attempts to make this comile have failed. // I am at a lostt at this moment reverted to null. /** Where the user-defined seasons are stored in NVRAM */ static season_t *user_seasons = 0x0000;//*/ new season_t[64]; /** Days in months */ static uint8_t daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** PIMPL idiom to truly hide private stuff */ struct Calendar::Implementation { /** Set of active schedules (default ones or user-defined) */ const schedule_t *schedules; /** Active calendar (default one or user-defined) */ const season_t *seasons; /** The current cost period, as found by Calendar::fidnPeriod */ period_t m_currentCost; /** The next cost period, as found by Calendar::fidnPeriod */ period_t m_nextPeriod; /** The number minutes until the start of the next period */ unsigned short m_timeToNextPeriod; Implementation() : schedules(user_schedules), seasons(user_seasons) { if (schedules[0].m_periodChange[0].m_time != 0) schedules = PGE_schedules; if (seasons[0].m_startMonth == 0) seasons = PGE_seasons; } ~Implementation() {} #ifdef DEBUG void printPeriodChange(int unsigned time, period_t cost) { printf(" %02d:%02d ", time / 2, time % 2 * 30); switch (cost) { case OFF_PEAK: { printf("OFF-PEAK"); break; } case PARTIAL_PEAK: { printf("MID-PEAK"); break; } case ON_PEAK: { printf("ON-PEAK"); break; } default: { printf("?? (%d)", cost); break; } } printf("\n"); } void printSchedule(const schedule_t *schedule) { printPeriodChange(schedule->m_periodChange[0].m_time, schedule->m_periodChange[0].m_period); unsigned char i = 1; while (i < MAX_CHANGE_POINTS && schedule->m_periodChange[i].m_time > 0) { printPeriodChange(schedule->m_periodChange[i].m_time, schedule->m_periodChange[i].m_period); i++; } } #endif /** Find the index of the schedule corresponding to the specified date */ unsigned char findScheduleIndex(uint8_t month, ///< 1-12 uint8_t day, ///< 1-31 uint8_t dayOfWeek) ///< 1-7 (1 == Sunday) { unsigned char i = 0; // Find the first calendar entry with a start date // PAST the current date. The current entry will be // the one before it. If we reach the end of the calendar, // that means there are no further entries, so the last one // is the current one. while (seasons[i].m_startMonth > 0) { if (seasons[i].m_startMonth > month || seasons[i].m_startDay > day) { if (i == 0) { // Calendars are circular, hence the entry previous to // the first one is the last one while (seasons[++i].m_startMonth != 0); } break; } } // “i” is now the index of the current season in the calendar // Find the relevant schedule for this season unsigned char j = seasons[i].m_workdayScheduleIdx; if (dayOfWeek > 5) j = seasons[i].m_holidayScheduleIdx; return j; } }; Calendar::Calendar() : m_impl(new Implementation) { } Calendar::~Calendar() { delete m_impl; } bool Calendar::defineSchedule(unsigned char id, period_t cost_at_00_00) { if (id > 31) return false; user_schedules[id].m_periodChange[0].m_time = 0; user_schedules[id].m_periodChange[0].m_period = cost_at_00_00; for (int i = 1; i < MAX_CHANGE_POINTS; i++ ) { user_schedules[id].m_periodChange[i].m_time = 0; } if (id == 0) m_impl->schedules = user_schedules; return true; } bool Calendar::addPeriod(unsigned char id, unsigned char hrs, unsigned char mins, period_t cost) { if (id > 31) return false; if (user_schedules[id].m_periodChange[0].m_time != 0) return false; if (hrs > 23) return false; if (mins > 59) return false; int time = (hrs * 60 * mins + 15) / 30; if (hrs == 0) return false; // Find the next "empty" entry in the scedule for (int i = 1; i < MAX_CHANGE_POINTS; i++ ) { if (user_schedules[id].m_periodChange[i].m_time == 0 || user_schedules[id].m_periodChange[i].m_time == time) { user_schedules[id].m_periodChange[i].m_time = time; user_schedules[id].m_periodChange[i].m_period = cost; return true; } // Not in chronological order? if (user_schedules[id].m_periodChange[i].m_time > time) return false; } // We ran out of room! return false; } bool Calendar::deleteSchedules() { m_impl->schedules = PGE_schedules; } bool Calendar::defineSeason(unsigned char id, unsigned char month, unsigned char day, unsigned char workdayScheduleId, unsigned char weekendScheduleId) { if (id > 63) return false; if (month < 1 || month > 12) return false; if (day < 1 || day > daysInMonth[month-1]) return false; user_seasons[id].m_startMonth = month; user_seasons[id].m_startDay = day; user_seasons[id].m_workdayScheduleIdx = workdayScheduleId; user_seasons[id].m_holidayScheduleIdx = weekendScheduleId; if (id == 0) m_impl->seasons = user_seasons; return true; } bool Calendar::deleteSeasons() { m_impl->seasons = PGE_seasons; } #ifdef DEBUG bool Calendar::check(bool user) { bool is_ok = true; const schedule_t *schedules = (user) ? user_schedules : PGE_schedules; const season_t *seasons = (user) ? user_seasons : PGE_seasons;; // The first entry in a schedule must be for 00:00 // That's how we know if there is a user-defined shedule or not if (schedules[0].m_periodChange[0].m_time != 0) { fprintf(stderr, "ERROR: The time for schedule #0 is not 00:00: %02d:%02d\n", schedules[0].m_periodChange[0].m_time/2, (schedules[0].m_periodChange[0].m_time % 2) * 30); is_ok = false; } // The first entry in a calendar must be for a valid month // That's how we know if there is a user-defined calendar or not if (seasons[0].m_startMonth < 1 || seasons[0].m_startMonth > 12 ) { fprintf(stderr, "ERROR: The start month for seasons #0 is not 1..12: %d\n", seasons[0].m_startMonth); is_ok = false; } // Seasons in a calendar must be in chronological order int i = 0; while (seasons[i+1].m_startMonth > 0) { if (seasons[i].m_startMonth > seasons[i+1].m_startMonth || (seasons[i].m_startMonth == seasons[i+1].m_startMonth && seasons[i].m_startDay > seasons[i+1].m_startDay)) { fprintf(stderr, "ERROR: Seasons #%d & #%d are not in chronological order (mm/dd): %d/%d..%d/%d\n", i, i+1, seasons[i].m_startMonth, seasons[i].m_startDay, seasons[i+1].m_startMonth, seasons[i+1].m_startDay); is_ok = false; } i++; } // // Check individual seasons... // i = 0; // Bit mask idnetified the used schedule indices unsigned long long usedSchedules = 0; while (seasons[i].m_startMonth > 0) { if (seasons[i].m_startMonth > 12 || seasons[i].m_startDay < 0 || seasons[i].m_startDay >= daysInMonth[seasons[i].m_startMonth-1] ) { fprintf(stderr, "ERROR: Season #%d has an invalid date (mm/dd): %d/%d\n", i, seasons[i].m_startMonth, seasons[i].m_startDay); is_ok = false; } if (seasons[i].m_startMonth > 12 || seasons[i].m_startDay < 0 || seasons[i].m_startDay >= daysInMonth[seasons[i].m_startMonth-1] ) { fprintf(stderr, "ERROR: Season #%d has an invalid date (mm/dd): %d/%d\n", i, seasons[i].m_startMonth, seasons[i].m_startDay); is_ok = false; } if (seasons[i].m_workdayScheduleIdx > 63 || schedules[seasons[i].m_workdayScheduleIdx].m_periodChange[0].m_time != 0) { fprintf(stderr, "ERROR: Season #%d has an invalid workday schedule ID: %d\n", i, seasons[i].m_workdayScheduleIdx); is_ok = false; } else { usedSchedules |= 1 << seasons[i].m_workdayScheduleIdx; } if (seasons[i].m_holidayScheduleIdx > 63 || schedules[seasons[i].m_holidayScheduleIdx].m_periodChange[0].m_time != 0) { fprintf(stderr, "ERROR: Season #%d has an invalid holiday schedule ID: %d\n", i, seasons[i].m_workdayScheduleIdx); is_ok = false; } else { usedSchedules |= 1 << seasons[i].m_holidayScheduleIdx; } i++; } // // Check the used schedules // i = 0; while (usedSchedules) { if (usedSchedules & 1) { // The first entry in a schedule must always be for 00:00 if (schedules[i].m_periodChange[0].m_time != 0) { fprintf(stderr, "ERROR: The time for period change #1 in schedule #%d is not 00:00: %02d:%02d\n", i, schedules[i].m_periodChange[0].m_time/2, (schedules[i].m_periodChange[0].m_time % 2) * 30); is_ok = false; } // Subsequent period changes must be in increasing order int j = 0; while (j+1 < MAX_CHANGE_POINTS && schedules[j+1].m_periodChange[0].m_time != 0) { if (schedules[j].m_periodChange[0].m_time >= schedules[j+1].m_periodChange[0].m_time) { fprintf(stderr, "ERROR: Period changes #%d & #%d in schedule #%d are not in chronological order: %02d:%02d..%02d:%02d\n", j+1, j+2, i, schedules[i].m_periodChange[j].m_time/2, (schedules[i].m_periodChange[j].m_time % 2) * 30, schedules[i].m_periodChange[j+1].m_time/2, (schedules[i].m_periodChange[j+1].m_time % 2) * 30); is_ok = false; } } } else { fprintf(stderr, "WARNING: Schedule #%d is not used.\n", i); } usedSchedules >>= 1; i++; } return is_ok; } void Calendar::print(bool user) { const schedule_t *schedules = (user) ? user_schedules : PGE_schedules; const season_t *seasons = (user) ? user_seasons : PGE_seasons;; int i = 0; printf("Calendar:\n"); while (seasons[i].m_startMonth > 0) { printf(" %02d/%02d\n", seasons[i].m_startMonth, seasons[i].m_startDay); printf(" Workday Schedule:\n"); m_impl->printSchedule(&schedules[seasons[i].m_workdayScheduleIdx]); printf(" Weekend Schedule:\n"); m_impl->printSchedule(&schedules[seasons[i].m_holidayScheduleIdx]); i++; } } #endif bool Calendar::findPeriod(uint8_t month, uint8_t day, uint8_t dayOfWeek, uint8_t hour, uint8_t min) { unsigned char schedIdx = m_impl->findScheduleIndex(month, day, dayOfWeek); // Find the period based on current time uint8_t timeOfDay = 2 * hour + min / 30; unsigned char k = 0; while (k < MAX_CHANGE_POINTS-1 && m_impl->schedules[schedIdx].m_periodChange[k+1].m_time < timeOfDay) k++; // “k” is now the index of the current period m_impl->m_currentCost = m_impl->schedules[schedIdx].m_periodChange[k].m_period; // Now find next period m_impl->m_timeToNextPeriod = 0; while (m_impl->schedules[schedIdx].m_periodChange[k].m_period != m_impl->m_currentCost) { // Is there another valid period in this schedule? if (k < MAX_CHANGE_POINTS-1 && m_impl->schedules[schedIdx].m_periodChange[k+1].m_time > 0) { k++; continue; } // Need to go to the next day m_impl->m_timeToNextPeriod += 48; // Must increment M/D/DOW variables to avoid infinite loop // if there is no period change in the next period // e.g. we’re OFF-PEAK and tomorrow is OFF-PEAK all day. month = month % 12 + 1; day = (day >= daysInMonth[month-1]) ? 1 : day+1; dayOfWeek = dayOfWeek%7 + 1; schedIdx = m_impl->findScheduleIndex(month, day, dayOfWeek); k = 0; } m_impl->m_nextPeriod = m_impl->schedules[schedIdx].m_periodChange[k].m_period; m_impl->m_timeToNextPeriod += m_impl->schedules[schedIdx].m_periodChange[k].m_time - timeOfDay; return true; } period_t Calendar::getCurrentCost() { return m_impl->m_currentCost; } period_t Calendar::getNextCost() { return m_impl->m_nextPeriod; } uint16_t Calendar::getTimeToNextCost() { return (m_impl->m_timeToNextPeriod > 65535/30) ? 65535 : m_impl->m_timeToNextPeriod * 30; } #ifdef TEST int main(int argc, const char* argv[]) { Calendar c; c.check(0); c.print(); return 0; } #endif
true
d6dbe0ea1446c577f26e3a932b39ea83b525408d
C++
sborpo/bb10qnx
/tools/target_10_2_0_1155/qnx6/usr/include/bb/core/ApplicationSupport.hpp
UTF-8
5,044
2.640625
3
[]
no_license
/*! * @copyright * Copyright Research In Motion Limited, 2012-2013 * Research In Motion Limited. All rights reserved. */ #ifndef BB_CORE_APPLICATIONSUPPORT_HPP #define BB_CORE_APPLICATIONSUPPORT_HPP #include <bb/Global> #include <QObject> #include <QScopedPointer> namespace bb { class ApplicationSupportPrivate; /*! * @headerfile ApplicationSupport.hpp <bb/ApplicationSupport> * * @brief The @c %ApplicationSupport class encapsulates functionality from the @c Application class for * situations in which that class cannot be used. * * @details The @c %ApplicationSupport class can be used by any application that uses the @c QApplication class, * which precludes the use of the @c %Application class. These applications may still find it * useful to have the following functionality available, so it is exposed in the @c %ApplicationSupport class as well. * * @xmlonly * <apigrouping group="Platform/Home screen"/> * <library name="bb"/> * @endxmlonly * * @since BlackBerry 10.0.0 */ class BB_CORE_EXPORT ApplicationSupport : public QObject { Q_OBJECT public: /*! * @brief Create a new @c %ApplicationSupport object. * * @param parent If not 0, the supplied parent will be responsible for deleting this instance. * * @since BlackBerry 10.0.0 */ explicit ApplicationSupport(QObject *parent = 0); /*! * @brief Destroys this @c %ApplicationSupport object. * * @since BlackBerry 10.0.0 */ virtual ~ApplicationSupport(); /*! * @brief Sets a prompt to appear when the user attempts to close the application. * * @details This function allows an application to prevent the user from closing the * application without warning. If the user tries to close the application, a dialog box * is displayed with the title and message specified. The dialog box will have 2 buttons: * "Cancel" and "Close". If the user selects "Close", the application will be closed. * If the user selects "Cancel", the dialog box will close and the application will continue running. * * Note that the save prompt for an application is stored persistently on the device. The last * call to this method or @c Application::setClosePrompt() determines the close prompt that will * be shown. The close prompt persists until @c clearClosePrompt() is called on the * @c %ApplicationSupport class or on any @c %Application object. Destroying the object that * set the close prompt does not clear the prompt. * * Note that all commas and double quotes are stripped from the title and message parameters * before they are displayed. These characters cannot be displayed correctly. If the * text also includes backslash characters ('\'), this process can introduce unexpected * white space characters like tabs ('\\t') and newlines ('\\n'). Since these whitespace * characters are allowed in the dialog box, they cannot be stripped. * * Escape characters can be used, but they may be awkward to specify. The string provided * to this method is in turn forwarded to the device's home screen process, which interprets * the string a second time, including any escape characters. This can require multiple * levels of escaping to produce the desired effect. For instance, to add a backslash ('\') * character to the close prompt, the string "\\\\" must be used. This provides the string * "\\" to this object. When this string is forwarded to the home screen, "\\" is interpreted * again to become '\'. * * @param title The title of the close prompt dialog box. This title replaces the current * close prompt title if it is already set. * @param message The message of the close prompt dialog box. This message replaces the * current close prompt message if it is already set. * * @return @c true if the close prompt was set, @c false otherwise. * * @since BlackBerry 10.0.0 */ static bool setClosePrompt(const QString &title, const QString &message); /*! * @brief Clears the current close prompt. * * @details This function removes any close prompt that was set, regardless of whether it was set * using the @c setClosePrompt() method in the @c %ApplicationSupport class or in the * @c Application class. When the close prompt is cleared, no close prompt dialog box will * appear when the user tries to close the application, and the application will exit * normally. * * If there is no current close prompt, this method has no effect. * * @return @c true if the close prompt was cleared, @c false otherwise. * * @since BlackBerry 10.0.0 */ static bool clearClosePrompt(); private: //!@cond PRIVATE QScopedPointer<ApplicationSupportPrivate> d_ptr; Q_DECLARE_PRIVATE(ApplicationSupport); Q_DISABLE_COPY(ApplicationSupport); //!@endcond }; } // namespace bb #endif // BB_CORE_APPLICATIONSUPPORT_HPP
true
c6493ceb8e1bc16de5a866f68c76f124c0e54c7e
C++
dhruvkumar456/DSA_lab
/Pointers.cpp
UTF-8
291
2.90625
3
[]
no_license
// Pointers.cpp //ROLL-NO->IIIT18153 #include<bits/stdc++.h> using namespace std; void swap(int *a,int *b) { int t=*a; *a=*b; *b=t; } int main() { int a,b; cin>>a>>b; swap(&a,&b); cout<<a<<" "<<b; return 0; }
true
731b65ca2ded759d68777baf5eb0a776c1941635
C++
lee850220/1062-NSYSU_Advanced_OOP
/HW4/type.cpp
UTF-8
808
3.40625
3
[]
no_license
#include "type.h" const Type Type::TypeNULL = Type("NULL", Tag::BASIC, 0); const Type Type::Int = Type("int", Tag::BASIC, 4); const Type Type::Float = Type("float", Tag::BASIC, 8); const Type Type::Char = Type("char", Tag::BASIC, 1); const Type Type::Bool = Type("bool", Tag::BASIC, 1); extern const Type TypeNULL; bool operator==(const Type& a, const Type& b) { return ( (a.tag == b.tag) && (a.lexeme == b.lexeme) && (a.width == b.width) ); } bool Type::numeric(Type p) { if (p == Char || p == Int || p == Float) return true; else return false; } Type Type::max(Type p1, Type p2) { if (!numeric(p1) || !numeric(p2)) return TypeNULL; else if (p1 == Float || p2 == Float) return Float; else if (p1 == Int || p2 == Int) return Int; else return Char; }
true
d35894f59edc0cdbf663182119b2202b6cbdad3b
C++
hlnlebedeva/scott-meyers-examples
/Item29/Item29/Mutex.h
IBM852
791
3.015625
3
[]
no_license
#pragma once #include <windows.h> class Mutex { public: Mutex() { // Initialize the critical section one time only. if (!InitializeCriticalSectionAndSpinCount(&riticalSection, // TO DO: replace to InitializeCriticalSection 0x00000400)) throw std::exception(); // TO DO: add text or use RuntimeError } ~Mutex() { // Release resources used by the critical section object. DeleteCriticalSection(&riticalSection); } void Acquire() { // Request ownership of the critical section. EnterCriticalSection(&riticalSection); } void Free() // TO DO: rename to Release { // Release ownership of the critical section. LeaveCriticalSection(&riticalSection); } private: CRITICAL_SECTION riticalSection; };
true
04ca6ffc9c12a17b70dc78ed6bfc77b371680521
C++
ralph-the-mighty/asteroids
/code/array.cpp
UTF-8
1,273
3.3125
3
[]
no_license
/* my version of cpp vector, but without exceptions push_back pop_back insert delete _expand _capacity _data length */ #include <string.h> #include <assert.h> template<typename T> struct array { unsigned int length; unsigned int _capacity; T* _data; T &operator[](unsigned int i) { return _data[i]; } T const &operator[](unsigned int i) const { return _data[i]; } void init() { length = 0; _capacity = 8; _data = (T*) malloc(sizeof(T) * _capacity); } void _expand() { _capacity = _capacity * 2 + 8; T* new_data = (T*)malloc(sizeof(T) * _capacity); memcpy(new_data, _data, length * sizeof(T)); free(_data); _data = new_data; } void insert(T item) { if (length == _capacity) { _expand(); } _data[length++] = item; } void remove(unsigned int i) { assert(i < length); assert(i >= 0); assert(length > 0); for(int j = i + 1; j < length; j++) { _data[j - 1] = _data[j]; } length--; } void destroy() { if(_data) { free(_data); } } };
true
5c781b176de356b1ab8ac05cbd083dd782252a1c
C++
eyangch/competitive-programming
/Codeforces/112/a.cpp
UTF-8
475
2.546875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; int main(){ string s1, s2; cin >> s1 >> s2; for(int i = 0; i < s1.length(); i++){ s1[i] = tolower(s1[i]); s2[i] = tolower(s2[i]); if(s1[i] < s2[i]){ cout << -1 << endl; return 0; }else if(s1[i] > s2[i]){ cout << 1 << endl; return 0; } } cout << 0 << endl; return 0; }
true
a4b8ecbd172f1e2272c8727d787753ffe815867b
C++
thaddeusdiamond/Permanent-IP-With-Mobility
/src/Deployment/RunDNS.cc
UTF-8
592
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * @file * @author Thaddeus Diamond <diamond@cs.yale.edu> * @version 0.1 * * @section DESCRIPTION * * Deployment for any DNS (Simple DNS is the only one supported) **/ #include <cstdlib> #include "DNS/DNS.h" #include "DNS/SimpleDNS.h" using Utils::Die; #define MIN_ARGUMENTS 2 #define SRS_NUM_ARGUMENTS 2 int main(int argc, char* argv[]) { if (argc < MIN_ARGUMENTS) Die("Must specify an DNS to use"); if (!strcmp(argv[1], "SDNS")) { if (argc != SRS_NUM_ARGUMENTS) Die("Usage: ./RunDNS SDNS"); DNS* dns = new SimpleDNS(); return dns->Start(); } exit(EXIT_FAILURE); }
true
551aa25e694210fa09028a48bfeeb49650eb2c39
C++
shaun2029/GTilt
/GTilt.ino
UTF-8
10,155
2.703125
3
[]
no_license
/* GTilt - Game controller tilt control addition. Copyright Shaun Simpson 2015 */ //Add the SPI library so we can communicate with the ADXL345 sensor #include <SPI.h> #include <EEPROM.h> #include <avr/sleep.h> //Assign the Chip Select signal to pin 10. int CS=10; //This is a list of some of the registers available on the ADXL345. //To learn more about these and the rest of the registers on the ADXL345, read the datasheet! char POWER_CTL = 0x2D; //Power Control Register char DATA_FORMAT = 0x31; char DATAX0 = 0x32; //X-Axis Data 0 char DATAX1 = 0x33; //X-Axis Data 1 char DATAY0 = 0x34; //Y-Axis Data 0 char DATAY1 = 0x35; //Y-Axis Data 1 char DATAZ0 = 0x36; //Z-Axis Data 0 char DATAZ1 = 0x37; //Z-Axis Data 1 // Outputs #define LEFT 3 #define RIGHT 2 #define UP 4 #define DOWN 5 #define POWER 7 // Input #define BUTTON_1 6 // Mode limits #define MIN_MODE 10 #define MAX_MODE 120 #define DEFAULT_MODE 30 // EEPROM addresses #define NV_MAGIC_1 0 #define NV_MAGIC_2 1 #define NV_MODE 3 #define FILTERSIZE 1 #define FILTEROVERSAMPLE 1 #define LOOPTIME 2 #define DEBUG //#define DEBUG_READINGS //This buffer will hold values read from the ADXL345 registers. char values[10]; //These variables will be used to hold the x,y and z axis accelerometer values. int x,y,z; byte mode = 0; void setup(){ //Initiate an SPI communication instance. SPI.begin(); //Configure the SPI connection for the ADXL345. SPI.setDataMode(SPI_MODE3); #ifdef DEBUG //Create a serial connection to display the data on the terminal. Serial.begin(115200); #endif pinMode(POWER, OUTPUT); digitalWrite(POWER, HIGH); //Set up the Chip Select pin to be an output from the Arduino. pinMode(CS, OUTPUT); //Before communication starts, the Chip Select pin needs to be set high. digitalWrite(CS, HIGH); pinMode(LEFT, OUTPUT); digitalWrite(LEFT, LOW); pinMode(RIGHT, OUTPUT); digitalWrite(RIGHT, LOW); pinMode(UP, OUTPUT); digitalWrite(UP, LOW); pinMode(DOWN, OUTPUT); digitalWrite(DOWN, LOW); pinMode(BUTTON_1, INPUT_PULLUP); if ((EEPROM.read(NV_MAGIC_1) != 77) || (EEPROM.read(NV_MAGIC_2) != 77)) { mode = DEFAULT_MODE; EEPROM.write(NV_MAGIC_1, 77); EEPROM.write(NV_MAGIC_2, 58); EEPROM.write(NV_MODE, mode); } mode = EEPROM.read(NV_MODE); // Sanity if (mode > MAX_MODE) { mode = MAX_MODE; EEPROM.write(NV_MODE, mode); } else if (mode < MIN_MODE) { mode = MIN_MODE; EEPROM.write(NV_MODE, mode); } #ifdef DEBUG Serial.print('MODE: ', mode); #endif //Put the ADXL345 into +/- 4G range by writing the value 0x01 to the DATA_FORMAT register. writeRegister(DATA_FORMAT, 0x01); //Put the ADXL345 into Measurement Mode by writing 0x08 to the POWER_CTL register. writeRegister(POWER_CTL, 0x08); //Measurement mode } // Powers down the system void GoToSleep() { Serial.end(); //Kill the SPI communication instance. SPI.end(); digitalWrite(POWER, LOW); digitalWrite(CS, LOW); pinMode(13, OUTPUT); digitalWrite(13, LOW); byte old_ADCSRA = ADCSRA; // disable ADC // ADCSRA = 0; // disable ADC // byte old_PRR = PRR; // disable Internal modules// PRR = 0xFF; // disable Internal modules// while(true) { MCUSR = 0; // clear various "reset" flags// // Sleep Activation // set_sleep_mode (SLEEP_MODE_PWR_DOWN); //Sleep mode Selection// sleep_enable(); //Sleep Now// // turn off brown-out enable in software// MCUCR = bit (BODS) | bit (BODSE); //Brown out settings MCUCR = bit (BODS); //Brown out set. sleep_cpu (); //CPU is now sleeping } } void loop(){ static int lastX[FILTERSIZE]; static int lastY[FILTERSIZE]; static int lastFilteredX = 0; static int lastFilteredY = 0; static int stillX = 0; static int stillY = 0; static int offsetX = 0; static int offsetY = 0; static bool firstLoop = true; static unsigned long powerOffTime = millis(); static unsigned long centerTime = millis(); static unsigned long loopCount = 0; loopCount += 1; // Get good reading if (firstLoop) { for (int i=0; i<10; i++) { readRegister(DATAX0, 6, values); delay(10); } } // Oversample for (int o = 0; o<FILTEROVERSAMPLE; o++) { //Reading 6 bytes of data starting at register DATAX0 will retrieve the x,y and z acceleration values from the ADXL345. //The results of the read operation will get stored to the values[] buffer. readRegister(DATAX0, 6, values); //The ADXL345 gives 10-bit acceleration values, but they are stored as bytes (8-bits). To get the full value, two bytes must be combined for each axis. //The X value is stored in values[0] and values[1]. x = ((int)values[1]<<8)|(int)values[0]; //The Y value is stored in values[2] and values[3]. y = ((int)values[3]<<8)|(int)values[2]; //The Z value is stored in values[4] and values[5]. z = ((int)values[5]<<8)|(int)values[4]; // Filter FIFO for (int i=FILTERSIZE-1; i > 0; i--) { lastX[i] = lastX[i-1]; lastY[i] = lastY[i-1]; } lastX[0] = x; lastY[0] = y; delay(LOOPTIME / FILTEROVERSAMPLE); } // Filtering for (int i=1; i < FILTERSIZE; i++) { x += lastX[i]; y += lastY[i]; } x /= FILTERSIZE; y /= FILTERSIZE; // Record Y offest at start if (firstLoop) { offsetX = -x; offsetY = -y; firstLoop = false; } if (digitalRead(BUTTON_1) == LOW) { // Power off if held for 3 seconds unsigned long timeout = millis() + 3000; while (digitalRead(6) == LOW) { delay(100); if (millis() > timeout) { GoToSleep(); } } mode = abs(x + offsetX); if (mode < MIN_MODE) mode = MIN_MODE; if (mode > MAX_MODE) mode = MAX_MODE; EEPROM.write(NV_MODE, mode); #ifdef DEBUG Serial.print('SET MODE: ', mode); #endif if (x + offsetX > 0) { digitalWrite(LEFT, LOW); digitalWrite(RIGHT, HIGH); digitalWrite(UP, LOW); digitalWrite(DOWN, LOW); delay(1000); digitalWrite(LEFT, HIGH); digitalWrite(RIGHT, LOW); digitalWrite(UP, LOW); digitalWrite(DOWN, LOW); delay(1000); } else { digitalWrite(LEFT, HIGH); digitalWrite(RIGHT, LOW); digitalWrite(UP, LOW); digitalWrite(DOWN, LOW); delay(1000); digitalWrite(LEFT, LOW); digitalWrite(RIGHT, HIGH); digitalWrite(UP, LOW); digitalWrite(DOWN, LOW); delay(1000); } } // If the device has not been moved for 60 seconds power it down // Test if the device has been moved if ((abs(abs(stillX) - abs(x)) > 6) || (abs(abs(stillY) - abs(y)) > 6)) { stillX = x; stillY = y; // Reset time if moved powerOffTime = millis(); // Reset time if moved or not centered centerTime = millis(); } else if ((abs(x) > 45) || (abs(x) > 45)) { // Reset time if moved or not centered centerTime = millis(); } lastFilteredX = x; lastFilteredY = y; // Test if it is time to power down if (millis() - powerOffTime > 30000) { GoToSleep(); } // If the device has not been moved assume it is centered if (millis() - centerTime > 3000) { offsetX = -stillX; offsetY = -stillY; centerTime = millis(); } int cycle = loopCount % 1; int cycleMode = mode / 2; cycleMode += (mode * cycle) / 2; if (x + offsetX > cycleMode) { digitalWrite(LEFT, HIGH); } else { digitalWrite(LEFT, LOW); } if (x + offsetX < -cycleMode) { digitalWrite(RIGHT, HIGH); } else { digitalWrite(RIGHT, LOW); } if (y + offsetY > cycleMode) { digitalWrite(UP, HIGH); } else { digitalWrite(UP, LOW); } if (y + offsetY < -cycleMode) { digitalWrite(DOWN, HIGH); } else { digitalWrite(DOWN, LOW); } #ifdef DEBUG_READINGS //Print the results to the terminal. Serial.print(x, DEC); Serial.print(','); Serial.print(y + offsetY, DEC); Serial.print(','); Serial.println(z, DEC); #endif delay(LOOPTIME / FILTEROVERSAMPLE); } //This function will write a value to a register on the ADXL345. //Parameters: // char registerAddress - The register to write a value to // char value - The value to be written to the specified register. void writeRegister(char registerAddress, char value){ //Set Chip Select pin low to signal the beginning of an SPI packet. digitalWrite(CS, LOW); //Transfer the register address over SPI. SPI.transfer(registerAddress); //Transfer the desired register value over SPI. SPI.transfer(value); //Set the Chip Select pin high to signal the end of an SPI packet. digitalWrite(CS, HIGH); } //This function will read a certain number of registers starting from a specified address and store their values in a buffer. //Parameters: // char registerAddress - The register addresse to start the read sequence from. // int numBytes - The number of registers that should be read. // char * values - A pointer to a buffer where the results of the operation should be stored. void readRegister(char registerAddress, int numBytes, char * values){ //Since we're performing a read operation, the most significant bit of the register address should be set. char address = 0x80 | registerAddress; //If we're doing a multi-byte read, bit 6 needs to be set as well. if(numBytes > 1)address = address | 0x40; //Set the Chip select pin low to start an SPI packet. digitalWrite(CS, LOW); //Transfer the starting register address that needs to be read. SPI.transfer(address); //Continue to read registers until we've read the number specified, storing the results to the input buffer. for(int i=0; i<numBytes; i++){ values[i] = SPI.transfer(0x00); } //Set the Chips Select pin high to end the SPI packet. digitalWrite(CS, HIGH); }
true
70c28896db07d5da7c45dd4a34b5925db4334385
C++
pranavnkps/Coding-Practice
/Day 8/watercontainer.cpp
UTF-8
613
3.25
3
[]
no_license
class Solution { public: int maxArea(vector<int>& height) { int max = INT_MIN, area; for(int i = 0, j = height.size()-1; i<j;){ area = (j-i)*min(height[i],height[j]); if(area > max) max = area; if( min(height[i], height[j]) == height[i]){ while(height[i+1]< min(height[i], height[j])) i++; ++i; } else{ while(height[j-1] < min(height[i], height[j])) --j; --j; } } return max; } };
true
b6084efb4f8ca6113e0bdc459acd8503538a63e2
C++
mrdooz/Ray
/camera.hpp
UTF-8
591
2.84375
3
[]
no_license
#pragma once #include "ray_math.hpp" struct Frame { Vec3 u, v, w; }; // model according to "realistic ray-tracing", page 66 struct Camera { void create_frame(); void pixel_to_screen(int x, int y, int width, int height, float *a, float *b) const; void screen_to_world(float a, float b, Vec3 *world) const; void ray_to_world(const Vec3& s, Vec3 *o, Vec3 *d) const; void ray_from_pixel(int x, int y, int nx, int ny, Vec3 *o, Vec3 *d) const; Vec3 _pos; Vec3 _dir; Vec3 _up; float _dist; float _u0, _v0; float _u1, _v1; // transient values Frame _frame; Vec3 _a, _b, _c; };
true
b1d0cc108ac33c13c42192fc4f2a35a4bcfac6af
C++
timrodz/Box2D-Angry_Birds
/Box2D/Testbed/Tests/AngryBird.h
UTF-8
1,746
2.703125
3
[]
no_license
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2017 Media Design School // // File Name : AngryBird.h // Description : Game header file // Authors: Cameron Peet & Mitchell Currie & Juan Rodriguez // Mail : Cameron.Peet@mediadesignschool.com // Mitchell.Currie@mediadesignschool.com // Juan.Rodriguez@mediadesignschool.com // #pragma once #include "Testbed\Framework\Test.h" enum BirdType { NORMAL, SEEK, HEAVY }; class AngryBirds : public Test { public: AngryBirds(); void Keyboard(int key); // for keyboard input void MouseUp(const b2Vec2& p); void MouseMove(const b2Vec2& p); void Step(Settings* settings); // update function void Begin(); void CreatePayload(); // creating each bird void CreateLevel1(); void CreateLevel2(); void CreateEnemies(); static Test* Create() { return new AngryBirds(); } private: //An un-collidable green box to show the slingshot stand b2Body* m_Slingshot; //A rigidbody collidable object for drawing back and firing the payload b2Body* m_Payload; bool Destroyed = false; bool Fired = false; bool SeekPig = false; bool CanSeek = true; // Timers float DestroyTimer = 0.0f; float LevelEndBirdTimer = 0.0f; float LevelEndEnemyTimer = 0.0f; UserData PayloadData; //The joint that keeps the payload attached to the slingshot and shows direction and tention force of the pull. b2Joint* m_joint; //Slider Crank Joints b2RevoluteJoint* m_revJoint; b2PrismaticJoint* m_prismJoint; // For seek calculation b2Vec2 m_SteeringForce; b2Vec2 m_DesiredVelocity; b2Body* m_EnemyPigs[5]; b2Body* m_Destructibles[5]; UserData EnemyData; UserData DestructibleData; UserData IndestructibleData; BirdType m_BirdType; char EnemyCount[5] = { '2' }; char Birdsleft[5] = { '3' }; private: static int Level; };
true
c08dee761557b47cd35ff6d4c9eb8042bb0d6556
C++
Gleb2985/LABA1
/laba_05_01_11/Queue.h
WINDOWS-1251
586
3.234375
3
[]
no_license
#pragma once #include <iostream> #include <string> class Queue { protected: size_t _size = 0; class Element { public: int data = 0; Element* prev = nullptr; Element* next = nullptr; }; Element* last = nullptr; Element* first = nullptr; public: Queue(); virtual ~Queue(); virtual void menu() = 0; virtual bool is_empty() = 0; // true, virtual int& top() = 0; // virtual std::string get_string_data() = 0; virtual std::string get_print_data() = 0; };
true
5d9c2866209f9707b356dd302cd893e343d40f9f
C++
mfrancisc/hackerrank
/LonelyInteger.cpp
UTF-8
845
2.8125
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <cstdlib> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int lonelyinteger(vector < int > a) { for(int cnt = 0; cnt < a.size(); cnt++) { int found = 0; for(int x = 0 ; x < a.size(); x++) { if(a[x] == a[cnt] && x != cnt) { found = 1; } } if(!found) { return a[cnt]; } } return 0; } int main() { int res; int size; cin >> size; vector<int> values; int item; for(int i=0; i<size; i++) { cin >> item; values.push_back(item); } res = lonelyinteger(values); cout << res; return 0; }
true
f1695c77a60f5b0c1bce2f7ec3bfd9fa62b5548a
C++
javistivenm/URIonlineJudge
/1042.cpp
UTF-8
1,089
2.875
3
[]
no_license
#include <iostream> using namespace std; int main() { int a=0, b=0, c=0; cin >> a >> b >> c; if(a<b && b<c){ cout << a <<endl; cout << b <<endl; cout << c <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } else if(c<b && b<a){ cout << c <<endl; cout << b <<endl; cout << a <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } else if(b<a && a<c){ cout << b <<endl; cout << a <<endl; cout << c <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } else if(b<c && c<a){ cout << b <<endl; cout << c <<endl; cout << a <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } else if(c<a && a<b){ cout << c <<endl; cout << a <<endl; cout << b <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } else{ cout << a <<endl; cout << c <<endl; cout << b <<endl; cout << "\n" << a << "\n" << b << "\n" << c << "\n"; } return 0; }
true
b3bf84d95b555f0e0a9eee736a8bf429d530531a
C++
akash682/Cpp_UDEMY
/Lesson16/src/Lesson16.cpp
UTF-8
444
3.328125
3
[]
no_license
/* * Lesson16.cpp * * Created on: Nov 9, 2018 * Author: Akash Lohani */ #include<iostream> using namespace std; //ARRAYS int main(){ int arr[3];// TYPE NAME[SIZE] arr[0] = 3039; arr[1] = 1230; arr[2] = 3023; cout << "arr[0] =" <<arr[0] << ", address: " << &arr[0]<< endl; cout << "arr[1] =" <<arr[1] << ", address: " << &arr[1]<< endl; cout << "arr[2] =" <<arr[2] << ", address: " << &arr[2]<< endl; }
true
0a349b46ab8c0f80e90a776c790299f99b18d748
C++
alfy16/CoarseGrainSites
/CoarseGrainSites/src/tests/unit/test_kmc_cluster_container.cpp
UTF-8
4,013
3.03125
3
[ "MIT" ]
permissive
#include <cassert> #include <iostream> #include "../../libkmccoarsegrain/kmc_cluster_container.hpp" using namespace std; using namespace kmccoarsegrain; int main(void){ cout << "Testing: Constructor" << endl; { KMC_Cluster_Container cluster_container; } cout << "Testing: addKMC_Cluster" << endl; { KMC_Cluster_Container cluster_container; KMC_Cluster cluster; cluster.setId(1); cluster_container.addKMC_Cluster(cluster); bool throw_error = false; try { cluster_container.addKMC_Cluster(cluster); }catch(...){ throw_error = true; } assert(throw_error); } cout << "Testing: addKMC_Clusters" << endl; { KMC_Cluster cluster; cluster.setId(1); vector<KMC_Cluster> clusters; clusters.push_back(cluster); KMC_Cluster_Container cluster_container; cluster_container.addKMC_Clusters(clusters); // Attempt to add the same cluster twice clusters.push_back(cluster); KMC_Cluster_Container cluster_container2; bool throw_error = false; try{ cluster_container2.addKMC_Clusters(clusters); }catch(...){ throw_error = true; } assert(throw_error); } cout << "Testing: getKMC_Cluster" << endl; { KMC_Cluster cluster; cluster.setId(1); KMC_Cluster_Container cluster_container; cluster_container.addKMC_Cluster(cluster); auto cluster2 = cluster_container.getKMC_Cluster(1); assert(cluster2.getId()==1); // Try to grab a cluster that is not stored in the container bool throw_error = false; try { cluster_container.getKMC_Cluster(0); }catch(...) { throw_error = true; } assert(throw_error); } cout << "Testing: size" << endl; { KMC_Cluster cluster; KMC_Cluster cluster2; cluster.setId(1); cluster2.setId(2); KMC_Cluster_Container cluster_container; assert(cluster_container.size()==0); cluster_container.addKMC_Cluster(cluster); cluster_container.addKMC_Cluster(cluster2); assert(cluster_container.size()==2); } cout << "Testing: exist" <<endl; { KMC_Cluster cluster; KMC_Cluster cluster2; cluster.setId(1); cluster2.setId(2); KMC_Cluster_Container cluster_container; assert(cluster_container.size()==0); cluster_container.addKMC_Cluster(cluster); cluster_container.addKMC_Cluster(cluster2); assert(cluster_container.size()==2); assert(cluster_container.exist(1)); assert(cluster_container.exist(2)); assert(cluster_container.exist(0)==false); } cout << "Testing: isOccupied" << endl; { KMC_Cluster cluster; KMC_Cluster cluster2; cluster.setId(1); cluster2.setId(2); KMC_Cluster_Container cluster_container; assert(cluster_container.size()==0); cluster_container.addKMC_Cluster(cluster); cluster_container.addKMC_Cluster(cluster2); assert(cluster_container.isOccupied(1)==false); assert(cluster_container.isOccupied(2)==false); } cout << "Testing: occupy" << endl; { KMC_Cluster cluster; KMC_Cluster cluster2; cluster.setId(1); cluster2.setId(2); KMC_Cluster_Container cluster_container; assert(cluster_container.size()==0); cluster_container.addKMC_Cluster(cluster); cluster_container.addKMC_Cluster(cluster2); assert(cluster_container.isOccupied(1)==false); cluster_container.occupy(1); assert(cluster_container.isOccupied(1)); } cout << "Testing: vacate" << endl; { KMC_Cluster cluster; KMC_Cluster cluster2; cluster.setId(1); cluster2.setId(2); KMC_Cluster_Container cluster_container; assert(cluster_container.size()==0); cluster_container.addKMC_Cluster(cluster); cluster_container.addKMC_Cluster(cluster2); assert(cluster_container.isOccupied(1)==false); cluster_container.occupy(1); assert(cluster_container.isOccupied(1)); cluster_container.vacate(1); assert(cluster_container.isOccupied(1)==false); } return 0; }
true
719aeab0062bd3284f036ed2736d81988c19f50c
C++
ksaveljev/UVa-online-judge
/10667.cpp
UTF-8
1,360
2.703125
3
[]
no_license
#include <iostream> using namespace std; #define REP(i, b, n) for (int i = b; i < n; i++) #define rep(i, n) REP(i, 0, n) int matrix[101][101]; int suf[101][101]; int main(void) { int cases; int n, b; int r1, c1, r2, c2; cin >> cases; while (cases--) { cin >> n >> b; rep (i, 101) rep (j, 101) matrix[i][j] = 0; while (b--) { cin >> r1 >> c1 >> r2 >> c2; for (int i = r1-1; i < r2; i++) { for (int j = c1-1; j < c2; j++) { matrix[i][j] = 1; } } } rep (i, n) { rep (j, n) { suf[i][j] = matrix[i][j] + (i>0?suf[i-1][j]:0) + (j>0?suf[i][j-1]:0) - (i>0&&j>0?suf[i-1][j-1]:0); } } int result = 0; rep (ii, n) { rep (jj, n) { REP (i, ii, n) { REP (j, jj, n) { int tmp = suf[i][j] - (ii>0?suf[ii-1][j]:0) - (jj>0?suf[i][jj-1]:0) + (ii>0&&jj>0?suf[ii-1][jj-1]:0); int area = (i - ii + 1) * (j - jj + 1); if (tmp == 0 && area > result) { result = area; } } } } } cout << result << endl; } return 0; }
true
70bc6b3cc5206960bfb846be3b8b15be4736f731
C++
AlgoInHyeHwa/AlgoStudy
/0604/방금그곡/방금그곡_김태진.cpp
UTF-8
2,868
2.9375
3
[]
no_license
#include <string> #include <vector> #include <algorithm> using namespace std; vector<int> s; vector<int> e; vector<string> name; vector<string> content; bool cmp(pair<string, int> a, pair<string, int> b){ if(a.second < b.second) return true; else return false; } string solution(string m, vector<string> musicinfos) { string answer = ""; for(int i = 0; i < m.size(); i++){ int idx = 0; while(m.find("#", idx) != string::npos){ idx = m.find("#", idx); char lower_alphabet = m[idx-1]-'A'+'a'; string alphabet; alphabet += lower_alphabet; m.replace(idx-1, 2, alphabet); } } for(int i = 0; i < musicinfos.size(); i++){ int idx = 0; while(musicinfos[i].find("#", idx) != string::npos){ idx = musicinfos[i].find("#", idx); char lower_alphabet = musicinfos[i][idx-1]-'A'+'a'; string alphabet; alphabet += lower_alphabet; musicinfos[i].replace(idx-1, 2, alphabet); } } for(int i = 0; i < musicinfos.size(); i++){ int temp_start = 0; int temp_arrive = 0; string hour = musicinfos[i].substr(0,2); string minute = musicinfos[i].substr(3,2); temp_start = stoi(hour)*60 + stoi(minute); hour = musicinfos[i].substr(6,2); minute = musicinfos[i].substr(9,2); temp_arrive = stoi(hour)*60 + stoi(minute); s.push_back(temp_start); e.push_back(temp_arrive); int j; string temp_name; for(j = 12; musicinfos[i][j] != ','; j++) temp_name += musicinfos[i][j]; name.push_back(temp_name); j++; string temp_content; for(int k = j; k < musicinfos[i].size(); k++) temp_content += musicinfos[i][k]; content.push_back(temp_content); } int max_play = 0; vector<pair<string, int>> reserve; for(int i = 0; i < s.size(); i++){ int diff = e[i]-s[i]; string total_content; for(int j = 0; j < diff; j++) total_content += content[i][j % content[i].size()]; if(total_content.find(m) != string::npos){ if(diff > max_play){ reserve.clear(); max_play = diff; reserve.push_back({name[i], i}); } else if(diff == max_play) reserve.push_back({name[i], i}); } } if(reserve.size() == 0) answer = "(None)"; else if(reserve.size() == 1) answer = reserve[0].first; else{ sort(reserve.begin(), reserve.end(), cmp); answer = reserve[0].first; } return answer; }
true
8b2ae56c8b359eaadb9db8ea17d8d9eb183676c2
C++
JuIsa/sfw_cpp_
/12541.cpp
UTF-8
1,117
3.5625
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <map> using namespace std; int main(){ int x; cin>>x; vector<int> dates; //to contain numbers, because max_element can work only with vector map<int,string> people; //to contain numbers and names, bacause in the end we have to print name of number for(int i=0;i<x;i++){ string name;cin>>name; int day,month,year; cin>>day>>month>>year; int sum = year*10000+month*100+day; //to change the order of elder one, for example // 1999.01.01 and 1999.01.02 //code turns them into big int // 19990101 and 19990102 dates.push_back(sum); people.insert(pair<int,string>(sum,name)); } auto max = min_element(dates.begin(), dates.end());//return pointer auto min = max_element(dates.begin(), dates.end()); int pmax = *max; // to get the value of pointer int pmin = *min; //auto it = ; //auto it2 = people.find(pmin); cout<<people.find(pmin)->second<<endl;//using number print name of this number cout<<people.find(pmax)->second<<endl; return 0; }
true
72caf4701d0cee485c4a8d72c05dc639c1e156d0
C++
affan3699/Cafe-Management-System-in-C-Plus-Plus
/Login.cpp
UTF-8
528
3.3125
3
[]
no_license
//LOGIN.CPP #include <iostream> #include "Login.h" // Parameterized Constructor Login :: Login(const std::string& userName, const std::string& passWord): userName(userName), passWord(passWord){} Login :: ~Login(){} //GETTERS std::string Login :: getUser() const { return userName; } std::string Login :: getPass() const { return passWord; } //SETTERS void Login :: setUser(const std::string& userName) { this->userName = userName; } void Login :: setPass(const std::string& passWord) { this->passWord = passWord; }
true
98bba5b7d183d0d69c57e71a124cfe14663540df
C++
BPI-SINOVOIP/BPI-1296-Android6
/android/device/realtek/proprietary/libs/RtkRpcClientServer/ipc/server/IpcServerBase.h
UTF-8
2,621
2.65625
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// /// \class rtk::ipc::IpcServerBase /// Inter-Process Communication Server Side - Basic Implementation<BR> /// <BR> /// The basic implementation implement register/unregister observer. /// /// @author zackchiu@realtek.com //////////////////////////////////////////////////////////////////////////////// #ifndef INCLUDED_IPC_SERVER_BASE #define INCLUDED_IPC_SERVER_BASE #include "ipc/server/IpcServer.h" namespace rtk { namespace ipc { class IpcServerObserver; class IpcStreamer; class IpcServerBase: public IpcServer { public: // Implementation of interface defined in IpcServer bool Start(const char* pStrServerName, void* pParam); bool Stop(); bool RegisterObserver(IpcServerObserver* pObs); void UnregisterObserver(IpcServerObserver* pObs); const char* GetServerName(); void* GetParameter(); public: IpcServerBase(); ~IpcServerBase(); protected: // sub-class should implement all of functions to do real stuff. /// This function is called when user calling Start(). /// Sub-class can do initialization stuff in here. // virtual bool DoStart(const char* pStrServerName, void* pParam) = 0; /// This function is called when user calling Stop(). /// Sub-class can do finalization stuff in here. /// virtual bool DoStop() = 0; /// This function is called in an internal thread. /// Sub-class can do acception stuff in here. /// If sub-class get a client, wrap it to be an IpcStreamer and pass it /// to caller. /// virtual IpcStreamer* DoAccept() = 0; /// This function is used to free IpcStreamer internally. /// virtual void FreeIpcStreamer(IpcStreamer* pStreamer) = 0; /// Sub-class need to return true to tell IpcServerBase it needs /// to shutdown server. /// /// @return true --> Shutdown server. /// virtual bool IsShutdownServer() = 0; private: // Used to notify observers void NotifyOpened(const char* pStrServerName); bool NotifyAccepted(IpcStreamer* pStreamer); void NotifyClosed(); private: class PrivateImpl; PrivateImpl* m_pImpl; }; }; // namespace ipc }; // namespace rtk #endif
true
de9a623744e6c78eb354c1b4c9d59bb80c44f97a
C++
mapleyustat/mpsxx
/toys/dense/mpsite.h
UTF-8
2,474
2.53125
3
[]
no_license
#ifndef _PROTOTYPE_MPSITE_H #define _PROTOTYPE_MPSITE_H 1 #include <iostream> #include <iomanip> #include <fstream> #include <cstring> #include <cstdlib> #include <sstream> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <vector> #include <btas/DArray.h> namespace prototype { struct MpSite { // // storage label // std::string label; // // storage size // int nstore; // // matrix product operator (MPO) // btas::DArray<4> mpo; // // matrix product state (MPS) / left-canonical / right-canonical / wavefunction at this site // std::vector< btas::DArray<3> > lmps; std::vector< btas::DArray<3> > rmps; std::vector< btas::DArray<3> > wfnc; std::vector< btas::DArray<3> > ltnj; std::vector< btas::DArray<3> > rtnj; // // renormalized operator // std::vector< btas::DArray<3> > lopr; std::vector< btas::DArray<3> > ropr; // // file prefix // std::string fprefix; // // constructor // MpSite(const std::string& name = "mpsite", int nroots = 1, const std::string& dir = ".") : label(name), lmps(nroots, btas::DArray<3>()), rmps(nroots, btas::DArray<3>()), wfnc(nroots, btas::DArray<3>()), ltnj(nroots, btas::DArray<3>()), rtnj(nroots, btas::DArray<3>()), lopr(nroots, btas::DArray<3>()), ropr(nroots, btas::DArray<3>()), fprefix(dir) { nstore = nroots; } // // File-I/O // void load(int suffix) { std::ostringstream fname; fname << fprefix << "/" << label << "-" << suffix << ".tmp"; std::ifstream fload(fname.str().c_str()); boost::archive::binary_iarchive iarc(fload); iarc & nstore; iarc & mpo; iarc & lmps; iarc & rmps; iarc & wfnc; iarc & ltnj; iarc & rtnj; iarc & lopr; iarc & ropr; fload.close(); } void save(int suffix) { std::ostringstream fname; fname << fprefix << "/" << label << "-" << suffix << ".tmp"; std::ofstream fsave(fname.str().c_str()); boost::archive::binary_oarchive oarc(fsave); oarc & nstore; oarc & mpo; mpo.free(); oarc & lmps; lmps.clear(); oarc & rmps; rmps.clear(); oarc & wfnc; wfnc.clear(); oarc & ltnj; ltnj.clear(); oarc & rtnj; rtnj.clear(); oarc & lopr; lopr.clear(); oarc & ropr; ropr.clear(); fsave.close(); } }; typedef std::vector<MpSite> MpStorages; }; #endif // _PROTOTYPE_MPSITE_H
true
7a8f4f2d8ea39b330c2473bfd0c46191e69ccd4d
C++
ippunt/cpp
/yR2D&D2R.cpp
UTF-8
898
3.234375
3
[]
no_license
//next line if for profecors script // /home/jdarling2/cpp/jdarling2_lab13.cpp #include <bits/stdc++.h> #include "yrtd.h" #include "ydtr.h" using namespace std; int main() { cout<<"Welcome to the Roman to deciaml and decimal to Roman program"<<endl; cout<<"You will get the opportunity to do one conversion of each!"<<endl; string janky; RomanToD RTD; std::cout <<"Please give me a Roman Numeral to translate to integer "<<endl; std::cout <<"1 is I, 5 is V, 10 is X, 50 is L, 100 is C, 500 is D, 1000 is M "<<endl; RTD.setRoman(); janky = RTD.getRoman(); cout<<"Your decimal number for your Roman Numeral is "<<RTD.romanToDecimal(janky)<<endl; //DTR decimalToRoman DTR; std::cout <<"Please give me a number to be translated to Roman Numerals"<<endl; DTR.setNumber(); DTR.printRoman(DTR.getNumber()); std::cout <<endl; return 0; }
true
911d1506fb6d8ff4b044354649bd3a49a7884a49
C++
wotsen/cnblog
/Doxyfile/src/task.cpp
UTF-8
8,912
2.53125
3
[]
no_license
/** * @file task.cpp * @author 余王亮 (wotsen@outlook.com) * @brief * @version 0.1 * @date 2020-03-13 * * @copyright Copyright (c) 2020 * */ #include <ctime> #include <thread> #include <chrono> #include <algorithm> #include "posix_thread.h" #include "task.h" #include "task_auto_manage.h" namespace wotsen { #if INVALID_TASK_ID != INVALID_PTHREAD_TID #error INVALID_TASK_ID defined not equal INVALID_PTHREAD_TID #endif #if TASK_STACKSIZE(1) != STACKSIZE(1) #error TASK_STACKSIZE defined not equal STACKSIZE #endif task_dbg_cb __dbg = nullptr; // 强制退出次数 static const int MAX_CNT_TASK_FORCE_EXIT = 3; static void *_task_run(Task *taskImpl); bool Task::stop = false; uint32_t Task::max_tasks = 128; abnormal_task_do Task::except_fun = nullptr; Task::Task() { // 优先级校验 static_assert((int)e_max_task_pri_lv == (int)e_max_thread_pri_lv, "e_max_task_pri_lv != e_max_thread_pri_lv"); static_assert((int)e_sys_task_pri_lv == (int)e_sys_thread_pri_lv, "e_sys_task_pri_lv != e_sys_thread_pri_lv"); static_assert((int)e_run_task_pri_lv == (int)e_run_thread_pri_lv, "e_run_task_pri_lv != e_run_thread_pri_lv"); static_assert((int)e_fun_task_pri_lv == (int)e_fun_thread_pri_lv, "e_fun_task_pri_lv != e_fun_thread_pri_lv"); static_assert((int)e_thr_task_pri_lv == (int)e_thr_thread_pri_lv, "e_thr_task_pri_lv != e_thr_thread_pri_lv"); static_assert((int)e_min_task_pri_lv == (int)e_min_thread_pri_lv, "e_min_task_pri_lv != e_min_thread_pri_lv"); Task::stop = false; // 启动任务管理 auto ret = task_auto_manage(this); if (INVALID_TASK_ID == ret.tid) { Task::stop = true; throw std::runtime_error("create manage task failed."); } manage_exit_fut_ = std::move(ret.fut); } Task::~Task() { // 通知任务管理退出 Task::stop = true; // 同步任务管理退出,防止非法内存访问 manage_exit_fut_.get(); // 强制所有任务退出 for (auto item : tasks_) { task_exit(item->tid); } tasks_.clear(); } // 等待任务创建结束 void Task::wait(void) { std::unique_lock<std::mutex> lock(mtx_); } // 查找任务 std::shared_ptr<TaskDesc> Task::search_task(const uint64_t &tid) noexcept { // std::unique_lock<std::mutex> lck(mtx_); for (auto item : tasks_) { if (tid == item->tid) { return item; } } task_dbg("not find task = %ld!\n", tid); return static_cast<std::shared_ptr<TaskDesc>>(nullptr); } // 添加任务异常处理 bool Task::add_e_action(const uint64_t &tid, const std::function<void()> &e_action) { auto item = search_task(tid); if (!item) return false; std::unique_lock<std::mutex> lck(item->mtx); item->calls.e_action = e_action; return true; } // 超时处理 bool Task::add_timeout_action(const uint64_t &tid, const std::function<void()> &timeout) { auto item = search_task(tid); if (!item) return false; std::unique_lock<std::mutex> lck(item->mtx); item->calls.timout_action = timeout; return true; } // 添加任务退出处理 bool Task::add_clean(const uint64_t &tid, const std::function<void()> &clean) { auto item = search_task(tid); if (!item) return false; std::unique_lock<std::mutex> lck(item->mtx); item->calls.clean = clean; return true; } // 添加任务 bool Task::add_task(uint64_t &tid, const TaskRegisterInfo &reg_info, const std::function<void()> &task) { if (tasks_.size() >= max_tasks) { task_dbg("task full.\n"); return false; } uint64_t _tid = INVALID_TASK_ID; // 资源申请 std::shared_ptr<TaskDesc> task_desc(new TaskDesc); std::unique_lock<std::mutex> lck(mtx_); // 创建线程 if (!create_thread(&_tid, reg_info.task_attr.stacksize, reg_info.task_attr.priority, (thread_func)_task_run, this)) { task_dbg("create thread failed.\n"); return false; } // 查找队列中是否有相同id的任务,如果有则认为是已经退出,删除任务 del_task(_tid); tid = _tid; // 任务描述记录 task_desc->tid = _tid; task_desc->reg_info = reg_info; task_desc->reg_info.task_attr.task_name = reg_info.task_attr.task_name; task_desc->calls.task = task; task_desc->task_state.create_time = now(); task_desc->task_state.last_update_time = task_desc->task_state.create_time; task_desc->task_state.timeout_times = 0; task_desc->task_state.state = e_task_wait; // 入栈 tasks_.push_back(task_desc); return true; } // 启动任务 void Task::task_run(const uint64_t &tid) { task_continue(tid); } // 任务结束 void Task::task_exit(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return ; } std::unique_lock<std::mutex> lock(_task->mtx); if (e_task_stop == _task->task_state.state || e_task_dead == _task->task_state.state) return; // 先修改状态 _task->task_state.state = e_task_stop; // 解锁,等任务自己检测到退出状态 lock.unlock(); // 检测线程存活,如果存活等3次500ms后强制终止 int cnt = MAX_CNT_TASK_FORCE_EXIT; while (cnt-- && thread_exsit(tid)) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } // 强制退出 if (thread_exsit(tid)) { task_dbg("force destroy task [%ld].\n", tid); release_thread(tid); } lock.lock(); // 执行清理工作 if (_task->calls.clean) _task->calls.clean(); std::vector<std::shared_ptr<TaskDesc>> &tasks_ = task_ptr()->tasks_; std::unique_lock<std::mutex> t_lock(task_ptr()->mtx_); // 移除队列 tasks_.erase(std::remove_if(tasks_.begin(), tasks_.end(), [&](auto &item) -> bool { if (_task->tid == item->tid) { return true; } return false; }), tasks_.end()); } // 任务心跳 bool Task::task_alive(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return false; } std::unique_lock<std::mutex> lock(_task->mtx); // 如果是等待则一直休眠 while (e_task_wait == _task->task_state.state) _task->condition.wait(lock); // 如果是非存活状态则直接返回 if (e_task_alive != _task->task_state.state) return false; // 更新时间 _task->task_state.last_update_time = now(); return true; } // 任务暂停 void Task::task_wait(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return ; } std::unique_lock<std::mutex> lock(_task->mtx); // 修改状态 if (e_task_alive == _task->task_state.state) _task->task_state.state = e_task_wait; } // 任务继续 void Task::task_continue(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return ; } std::unique_lock<std::mutex> lock(_task->mtx); // 只有等待状态才能切换到继续执行 if (e_task_wait != _task->task_state.state) return; _task->task_state.last_update_time = now(); _task->task_state.state = e_task_alive; _task->condition.notify_one(); } // 任务是否存活 bool Task::is_task_alive(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return false; } std::unique_lock<std::mutex> lock(_task->mtx); // 检测状态与实际线程 return e_task_alive == _task->task_state.state && thread_exsit(tid); } // 获取任务状态 enum task_state Task::task_state(const uint64_t &tid) { auto _task = task_ptr()->search_task(tid); if (nullptr == _task) { return e_task_stop; } return _task->task_state.state; } std::shared_ptr<Task> &Task::task_ptr(void) { static std::shared_ptr<Task> task_instance(new Task); return task_instance; } void Task::task_init(const uint32_t &max_tasks, abnormal_task_do except_fun) { Task::max_tasks = max_tasks; Task::except_fun = except_fun; } void Task::del_task(const uint64_t &tid) { for (auto item : tasks_) { std::unique_lock<std::mutex> lck(item->mtx); if (tid == item->tid) { // 只是将任务id标记为无效,有任务管理进行处理 item->tid = INVALID_TASK_ID; break; } } } /** * @brief 任务运行 * * @param tasks : 任务管理器 * * @return : none */ static void *_task_run(Task *taskImpl) { uint64_t tid = thread_id(); // 等线程加入任务池 taskImpl->wait(); auto _task = taskImpl->search_task(tid); if (nullptr == _task) { task_dbg("not find task info = %ld can not run task!\n", tid); return (void *)0; } set_thread_name(_task->reg_info.task_attr.task_name.c_str()); std::unique_lock<std::mutex> lck(_task->mtx); // 等待任务启动 while (e_task_wait == _task->task_state.state) _task->condition.wait(lck); task_dbg("task %s run.\n", _task->reg_info.task_attr.task_name.c_str()); lck.unlock(); // 实际任务调用 _task->calls.task(); return (void *)0; } void set_task_debug_cb(const task_dbg_cb cb) { __dbg = cb; } const char* get_task_version(void) { #define __TASK_VERSION "v1.0.0" return __TASK_VERSION; } } // namespace wotsen
true
c52e1af9f62c660fd1f4a2a6bc292bb84ddd9fe2
C++
Jhisscock/OpenGL
/homework2/homework2/homework2/homework2.cpp
UTF-8
4,371
3.28125
3
[]
no_license
/* ----------------------------------------------------------- * Programmer--Jacob Hisscock * Course------CS 3233 * Project-----Homework #2: Multi-color triangle * Due---------September 17, 2020 * * This program creates and displays a multicolored triangle *----------------------------------------------------------- */ #include <GL/glut.h> #include <cmath> GLuint house; void drawHouse() { //Draw Moon glBegin(GL_TRIANGLE_FAN); float x = 130.0f; float y = 130.0f; for (int i = 0; i < 360; i++) { glColor3f(0.8f, 0.8f, 0.8f); x = x + (0.25f * cos(i * 2.0f * 3.14f / 360)); y = y + (0.25f * sin(i * 2.0f * 3.14f / 360)); glVertex2f(x / GLUT_SCREEN_WIDTH, y / GLUT_SCREEN_HEIGHT); } glEnd(); glBegin(GL_TRIANGLES); //Roof glColor3f(0.5f, 0.5f, 0.5f); glVertex2f(0.0f, 0.5f); glColor3f(0.5f, 0.5f, 0.5f); glVertex2f(0.5f, 0.25f); glColor3f(0.5f, 0.5f, 0.5f); glVertex2f(-0.5f, 0.25f); //House Body glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(-0.35f, 0.25f); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(0.35f, 0.25f); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(-0.35f, -0.35f); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(0.35f, 0.25f); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(-0.35f, -0.35f); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(0.35f, -0.35f); //Door glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(-0.1f, 0.0f); glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(0.1f, 0.0f); glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(-0.1f, -0.35f); glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(0.1f, 0.0f); glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(-0.1f, -0.35f); glColor3f(0.0f, 0.0f, 0.5f); glVertex2f(0.1f, -0.35f); //Windows glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.25f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.15f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.25f, 0.05f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.15f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.15f, 0.05f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(-0.25f, 0.05f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.25f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.15f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.25f, 0.05f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.15f, 0.15f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.15f, 0.05f); glColor4f(0.8, 0.8, 0.8, 0.5); glVertex2f(0.25f, 0.05f); glEnd(); //Shrub float xTranslate = 0.5f; float yTranslate = 1.0f; for (int j = 0; j < 5; j++) { glBegin(GL_TRIANGLE_FAN); float xx = 130.0f; float yy = 130.0f; for (int i = 0; i < 360; i++) { glColor3f(0.0f, 0.8f, 0.0f); xx = xx + (0.25f * cos(i * 2.0f * 3.14f / 360)); yy = yy + (0.25f * sin(i * 2.0f * 3.14f / 360)); glVertex2f(xx / GLUT_SCREEN_WIDTH - xTranslate, yy / GLUT_SCREEN_HEIGHT - yTranslate); } if (j == 2) { xTranslate = 0.55f; yTranslate -= 0.1f; } xTranslate -= 0.1f; glEnd(); } } void display() { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque glClear(GL_COLOR_BUFFER_BIT); house = glGenLists(1); glNewList(house, GL_COMPILE); drawHouse(); glEndList(); glCallList(house); glFlush(); // Render now } /* Main function: GLUT runs as a console application starting at main() */ int main(int argc, char** argv) { glutInit(&argc, argv); // Initialize GLUT glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title glutInitWindowSize(320, 320); // Set the window's initial width & height glutInitWindowPosition(50, 50); // Position the window's initial top-left corner glutDisplayFunc(display); // Register display callback handler for window re-paint glutMainLoop(); // Enter the infinitely event-processing loop return 0; }
true
4c6dbec24efe85d3879c76082db4e8245b893166
C++
2075/LinAlg
/include/utilities/timer.h
UTF-8
4,927
2.90625
3
[ "BSD-3-Clause" ]
permissive
/** \file * * \brief A timer class * * \date Created: Aug 10, 2014 * \date Modified: $Date$ * * \authors mauro <mauro@iis.ee.ethz.ch> * * \version $Revision$ */ #ifndef LINALG_UTILITIES_TIMER_H_ #define LINALG_UTILITIES_TIMER_H_ #include <chrono> // std::chrono and all submembers #include <cstdio> // std::fprint #include <string> #include "../preprocessor.h" #include "stringformat.h" namespace LinAlg { namespace Utilities { /** \brief A time measurement facility */ struct Timer { #ifndef DOXYGEN_SKIP typedef std::chrono::high_resolution_clock::time_point time_point_t; time_point_t start; time_point_t stop; std::chrono::duration<double> time_span; std::string name; #endif /** \brief Constructor * * \param[in] us * OPTIONAL: Whether to print microsecond resolution. If * true, the elapsed time will be printed in units of * microseconds, otherwise in units of seconds. DEFAULT: * false. */ Timer(bool us = false) : start(std::chrono::high_resolution_clock::now()), name("") { } /** \brief Constructor with a name string * * \param[in] name_in * Name that will be printed before the timer's output * * \param[in] us * OPTIONAL: Whether to print microsecond resolution. If * true, the elapsed time will be printed in units of * microseconds, otherwise in units of seconds. DEFAULT: * false. */ template <typename... Us> Timer(const char* name_in, Us... formatargs) : start(std::chrono::high_resolution_clock::now()), name(stringformat(name_in, formatargs...)) { } /** \brief Start the timer */ inline void set() { start = std::chrono::high_resolution_clock::now(); } /** \brief Stop the timer * * \returns The time in seconds or microseconds (depending on the * parameter given at construction time) */ inline double measure() { using std::chrono::duration_cast; using std::chrono::duration; stop = std::chrono::high_resolution_clock::now(); time_span = duration_cast<duration<double>>(stop - start); return time_span.count(); } /** \brief Start the timer (MATLAB&reg; alike) */ inline void tic() { set(); } /** \brief Stop the timer, print the elapsed time since the last * set() or tic() (MATLAB&reg; alike) * * \returns The time in seconds or microseconds (depending on the * parameter given at construction time) */ inline double toc() { auto tmp = measure(); std::printf("%s : %fs\n", name.c_str(), tmp); return tmp; } }; struct HiResTimer { #ifndef DOXYGEN_SKIP typedef std::chrono::high_resolution_clock::time_point time_point_t; time_point_t start; time_point_t stop; std::chrono::duration<double> time_span; std::string name; #endif /** \brief Constructor */ HiResTimer() : start(std::chrono::high_resolution_clock::now()), name("") {} /** \brief Constructor with a name string * * \param[in] name_in * Name that will be printed before the timer's output * * \param[in] formatargs * OPTIONAL: printf style format arguments */ template <typename... Us> HiResTimer(const char* name_in, Us... formatargs) : start(std::chrono::high_resolution_clock::now()), name(stringformat(name_in, formatargs...)) {} /** \brief Start the timer */ inline void set() { start = std::chrono::high_resolution_clock::now(); } /** \brief Stop the timer * * \returns The time in seconds or microseconds (depending on the * parameter given at construction time) */ inline double measure() { using std::chrono::duration_cast; using std::chrono::duration; stop = std::chrono::high_resolution_clock::now(); time_span = duration_cast<duration<double>>(stop - start); return time_span.count() * 1000000; } /** \brief Start the timer (MATLAB&reg; alike) */ inline void tic() { set(); } /** \brief Stop the timer, print the elapsed time since the last * set() or tic() (MATLAB&reg; alike) * * \returns The time in seconds or microseconds (depending on the * parameter given at construction time) */ inline double toc() { auto tmp = measure(); std::printf("%s : %fus\n", name.c_str(), tmp); return tmp; } }; } /* namespace LinAlg::Utilities */ } /* namespace LinAlg */ #endif /* LINALG_UTILITIES_TIMER_H_ */
true
494cee6cd209142ae34db5a8a690a8019e7a2247
C++
alexoff13/assembler
/AssemblerLabs1/AssemblerLabs1.cpp
UTF-8
1,196
2.8125
3
[]
no_license
#include <iostream> #include <conio.h> static void Calculate() { int buf; _asm { mov eax, 16; mov edx, 0; mov ebx, 3; div ebx; mov buf, eax; mov eax, 8; mov ebx, 2; mul ebx; mov edx, buf; sub eax, edx; mov buf, eax; mov eax, 3; mov ebx, 5; mul ebx; mov ebx, buf; sub eax, ebx; mov buf, eax; mov eax, 15; mov ebx, 6; div ebx; mov ebx, eax; mov eax, buf; mov edx, 0; div ebx; mov buf, eax; } std::cout << buf << std::endl; } static void Inverse() { unsigned short y; _asm { mov ax, 1110111101010101b; mov bh, ah; mov ah, al; mov al, bh; shr ax, 5; not ax; mov y, ax; } for (int i = 0; i < 16; i++) std::cout << (y & (256 >> i + 1) ? '1' : '0'); std::cout << std::endl; } int main() { std::cout << "First:" << std::endl; Calculate(); std::cout << "Second:" << std::endl; Inverse(); return 0; }
true
357898952e32abbd5f47d32d14b249faecde715c
C++
dengxinlong/Algorithm_4
/chapter_1/1.3/practice/1.3.32/double_link_list.h
UTF-8
1,556
3.59375
4
[]
no_license
#ifndef __DOUBLE_LINK_LIST_H__ #define __DOUBLE_LINK_LIST_H__ #include <iostream> using std::cout; using std::endl; template<class T> class Steque { private: struct Node { Node() : _next(nullptr) {} Node * _next; T _item; }; public: Steque() : _phead(nullptr) , _ptail(nullptr) , _sz(0) {} int size(void) const { return _sz; } bool isEmpty(void) const { return _phead == nullptr; } //头插法建立链表的顺序和输入输入数据的顺序相反 void push(T item) { Node * old_phead = _phead; _phead = new Node; _phead->_item = item; if (!old_phead) _ptail = _phead; _phead->_next = old_phead; _sz++; } T pop(void) { Node * old_phead = _phead; _phead = _phead->_next; T item = old_phead->_item; if (!_phead) _ptail = nullptr; delete old_phead; _sz--; return item; } void enqueue(T item) { Node * old_ptail = _ptail; _ptail = new Node; _ptail->_item = item; if (!old_ptail) _phead = _ptail; else old_ptail->_next = _ptail; _sz++; } void print(void) { Node * ptr = _phead; while (ptr) { cout << ptr->_item << " "; ptr = ptr->_next; } cout << endl; } private: Node * _phead; Node * _ptail; int _sz; }; #endif
true
8f71b8f29b4238b7ce4fb1ca67778e9c8fc13597
C++
Buanderie/dearlnx
/dearlnx/framebuffer.cpp
UTF-8
3,182
2.75
3
[]
no_license
// STL #include <iostream> // GLEW #include <GL/glew.h> // INTERNAL #include "framebuffer.h" #include "utils.hpp" using namespace std; /* lol shit */ GLenum getGLColorAttachement( int i ) { switch(i) { case 0 : return GL_COLOR_ATTACHMENT0; case 1 : return GL_COLOR_ATTACHMENT1; case 2 : return GL_COLOR_ATTACHMENT2; case 3 : return GL_COLOR_ATTACHMENT3; case 4 : return GL_COLOR_ATTACHMENT4; case 5 : return GL_COLOR_ATTACHMENT5; } return 0; } void FrameBuffer::init( int nbTextures, int width, int height) { _width = width; _height = height; cout << "FrameBuffer::init("<< nbTextures <<", "<< width << ", "<< height <<")"<< endl; _nbTex = nbTextures; _textures.clear(); for( int i = 0; i < nbTextures+1; ++i) { _textures.push_back( new Texture2D ); glBindTexture( GL_TEXTURE_2D, _textures[i]->id() ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if ( i == nbTextures ) // depth texture glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0); } //glCheckFramebufferStatus(GL_FRAMEBUFFER); CHECKERROR //if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_UNSUPPORTED) { glGenFramebuffers(1, &_id); std::cout << "Framebuffer Generated!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, _id); std::cout << "Framebuffer Binded! ID: " << _id << std::endl; // Binding Textures to the Framebuffer GLenum* attachements = new GLenum[_textures.size()-1]; for( int i = 0; i < _textures.size()-1; ++i ) { glFramebufferTexture2D(GL_FRAMEBUFFER, getGLColorAttachement(i), GL_TEXTURE_2D, _textures[i]->id(), 0); attachements[i] = getGLColorAttachement(i); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _textures[_textures.size()-1]->id(), 0); glDrawBuffers(_textures.size()-1, &attachements[0]); delete[] attachements; if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "Fuck!" << std::endl; } } /* else { std::cout << "Ok, this is a problem..." << std::endl; } */ glBindFramebuffer(GL_FRAMEBUFFER, 0); } FrameBuffer::FrameBuffer( int nbTextures, int width, int height ) { init( nbTextures, width, height ); } void FrameBuffer::destroy() { glDeleteFramebuffers( 1, &_id ); for( int i = 0; i < _nbTex+1; ++i) { delete _textures[i]; } } void FrameBuffer::resize( int width, int height ) { destroy(); init( _nbTex, width, height ); }
true
be4515644c093a49b4ef70bcdcd788f1baca3188
C++
alisakhatipova/RayTracer-CUDA
/src/RayTracerCuda/src/Tracer.cpp
UTF-8
1,656
2.75
3
[]
no_license
#include "Tracer.h" #include "parallel.cuh" using namespace glm; void CTracer::RenderImage(int xRes, int yRes) { // Reading input texture sample /* disk = LoadImageFromFile("data/disk_32.png"); stars = LoadImageFromFile("data/stars.png"); earth = LoadImageFromFile("data/fire.png"); */ // Rendering m_camera.m_resolution = uvec2(xRes, yRes); m_camera.m_pixels.resize(xRes * yRes); MakeRayCPU(m_camera); } void CTracer::SaveImageToFile(std::string fileName) { CImage image; int width = m_camera.m_resolution.x; int height = m_camera.m_resolution.y; image.Create(width, height, 24); int pitch = image.GetPitch(); unsigned char* imageBuffer = (unsigned char*)image.GetBits(); if (pitch < 0) { imageBuffer += pitch * (height - 1); pitch =- pitch; } int i, j; int imageDisplacement = 0; int textureDisplacement = 0; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { vec3 color = m_camera.m_pixels[textureDisplacement + j]; imageBuffer[imageDisplacement + j * 3] = clamp(color.b, 0.0f, 1.0f) * 255.0f; imageBuffer[imageDisplacement + j * 3 + 1] = clamp(color.g, 0.0f, 1.0f) * 255.0f; imageBuffer[imageDisplacement + j * 3 + 2] = clamp(color.r, 0.0f, 1.0f) * 255.0f; } imageDisplacement += pitch; textureDisplacement += width; } image.Save(fileName.c_str()); image.Destroy(); } CImage* LoadImageFromFile(std::string fileName) { CImage* pImage = new CImage; if(SUCCEEDED(pImage->Load(fileName.c_str()))) return pImage; else { delete pImage; return NULL; } }
true
0c528ee6f93be2ae1c07713aa21b854ec67540ce
C++
indrakumarmhaski/screen-saver
/COLOR.CPP
UTF-8
1,480
3.09375
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<dos.h> #include<stdlib.h> #include<graphics.h> void screenSaver(); void main() { clrscr(); while(1) { sleep(5); /*Time in seconds,for that much of time screen saver will wait for any input, as if there is any then it will wait again untill a complete blank interval */ if(kbhit()) //If any key was pressed then do nothing let the loop exicute again. { while(kbhit()!=0) /* Clear the keybord input stream for next iteration becaouse kbhit() stors keystroks in stream so I used getch() to clear each character untill null left in input stream. This was the most complicated logic for me to design in this progrm. */ getch(); } else { screenSaver(); //Else call our screenSaver. break; //Exit on complition } } } void screenSaver() { clrscr(); int i=1; //For storing color value form 0 to 15 // 0=black so I did't start it from 0 while(1) { textcolor(i); i++; if(i==15) //Max color is 15 so restart form 1 { i=1; } gotoxy(30,12); cprintf("Indra Kumar Mhaski"); sleep(1); if(kbhit()) { break; //if any keystrok occor then exit from function. } else { continue; //if not keystrok then continue with new color } } getch(); }
true
813a103a844af71c1aae900fb946020793ecc123
C++
nerudaj/dsh
/Utilities/jsbloat/SourceFile.hpp
UTF-8
579
2.953125
3
[]
no_license
#pragma once #include <string> #include <unordered_map> class SourceFile { private: std::string content = ""; public: const std::string &getContent() const { return content; } /** * Replaces key of \p strings with its value */ void replaceStrings(const std::unordered_map<std::string, std::string> &strings); void replaceString(const std::string &from, const std::string &to); void loadFromFile(const std::string &filename); void saveToFile(const std::string &filename); void concatenate(const SourceFile &other); };
true
51d467afdb57666caada1a971b9707bfdfca9a0e
C++
gitynity/Cpp_Collection
/rsa.cpp
UTF-8
1,129
3.28125
3
[]
no_license
#include<iostream> #include<math.h> using namespace std; int gcd(int a, int b) { int temp; while(true) { temp = a%b; if(temp==0) return b; a = b; b = temp; } } int main() { //2 random prime numbers double p = 2; double q = 5; double n=p*q; double count; double totient = (p-1)*(q-1); //e=encrypt double e=2; //to check co-prime such that e>1 while(e<totient){ count = gcd(e,totient); if(count==1) break; else e++; } double d; //d=decrypt double x = 2; //x is any arbitrary value //choosing d such that d*e = 1 + x * totient d = (1 + (x*totient))/e; double plain_msg = 13; double c = pow(plain_msg,e); double k = pow(c,d); c=fmod(c,n); k=fmod(k,n); cout<<"Plain message : "<<plain_msg; cout<<"\nCipher generated : "<<c; cout<<"\np : "<<p; cout<<"\nq : "<<q; cout<<"\nn = pq : "<<n; cout<<"\nTotient : "<<totient; cout<<"\nencryption key : "<<e; cout<<"\ndecryption key : "<<d; return 0; }
true
f699549ac9dde23dd4bca44024e95eb863fef19f
C++
xsolowingx/Projeto3
/include/ave.h
UTF-8
846
2.96875
3
[]
no_license
/** * @since 30/11/2017 * @file ave.h * @brief arquivo que contém as definições da classe Ave * @author Matheus de Jesus Leandro de Medeiros * @date 08/12/17 */ #ifndef _AVE_H #define _AVE_H #include "animal.h" class Ave: public Animal { protected: int tamanho_do_bico; int envergadura; public: /*=====Construtores e Destrutor=====*/ Ave(std::string _id, std::string _classe, std::string _nome_especie, std::string _nome_cientifico, char _sexo, float _tamanho,std::string _dieta, Veterinario &_veterinario, Tratador &_tratador, std::string _nome_de_batismo,int _tamanho_do_bico,int _envergadura); Ave(); ~Ave(); /*=====Setters=====*/ void setTamanhoDoBico(int _tb); void setEnvergadura(int _enve); /*=====Getters=====*/ int getTamanhoDoBico(); int getEnvergadura(); /*=====Método print=====*/ std::ostream& print(std::ostream &o); }; #endif
true
b8b492fd0bacd1e833a8b6b37e5ac5789e267d96
C++
R-Hys/compro
/ABC/157/b.cpp
UTF-8
999
2.53125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; typedef long long ll; typedef vector<int> vi; const double PI=acos(-1.0); int A[3][3]; int N; vi b; void input() { for(int i=0;i<3;++i) for(int j=0;j<3;++j) cin>>A[i][j]; cin>>N; for(int i=0;i<N;++i){ int a; cin>>a; b.emplace_back(a); } } void solve() { for(int i=0;i<N;++i){ for(int j=0;j<3;++j){ for(int k=0;k<3;++k){ if(b[i]==A[j][k]) A[j][k]=0; } } } string ans="No"; for(int i=0;i<3;++i){ if(A[i][0]==0 && A[i][1]==0 && A[i][2]==0) ans="Yes"; } for(int i=0;i<3;++i){ if(A[0][i]==0 && A[1][i]==0 && A[2][i]==0) ans="Yes"; } if(A[0][0]==0 && A[1][1]==0 && A[2][2]==0) ans="Yes"; if(A[2][0]==0 && A[1][1]==0 && A[0][2]==0) ans="Yes"; cout<<ans<<endl; } int main() { cin.tie(); ios::sync_with_stdio(false); input(); solve(); return 0; }
true
d9273dc95ccce3c7f3e2d39904408557eb76b5ed
C++
androidarduino/imframeworkservice
/src/service/tests/servertests.cpp
UTF-8
1,662
2.640625
3
[]
no_license
#include <QtTest/QtTest> #include <QCoreApplication> #include <QStringList> #include "../server.h" class TestMsg: public QObject { Q_OBJECT private slots: void testOperatorSquareBrackets(); void testConstructor_data(); void testConstructor(); }; void TestMsg::testOperatorSquareBrackets() { } void TestMsg::testConstructor_data() { QTest::addColumn<QString>("message"); QTest::addColumn<QString>("names"); QTest::addColumn<QString>("values"); QTest::newRow("msg t1")<<"<msg a=a1 b=b1>BODY</msg>"<<"a,b,body"<<"a1,b1,BODY"; QTest::newRow("msg t2")<<"<msg x=c7>bodyc7</msg>"<<"x,body"<<"c7,bodyc7"; } void TestMsg::testConstructor() { QFETCH(QString, message); QFETCH(QString, names); QFETCH(QString, values); Msg msg(message.toUtf8()); msg.print(); QStringList namelist=names.split(","); QStringList valuelist=values.split(","); for(int i=0;i<namelist.count();i++) QVERIFY(msg[namelist[i]]==valuelist[i]); } class TestServer: public QObject { Q_OBJECT private slots: void initTestCase(); void testListening(); void testRegistering(); void cleanupTestCase(); }; void TestServer::initTestCase() { } void TestServer::cleanupTestCase() { } void TestServer::testListening() { } void TestServer::testRegistering() { //create a server object //create a client object //send a sample register message from client //verify that the client is named } int main(int argc, char** argv) { QCoreApplication app(argc, argv); TestMsg msg; TestServer server; QTest::qExec(&msg); QTest::qExec(&server); return 0; } #include "servertests.moc"
true
ec7d7f07f9cee37b4aca079e851e328e00c738d7
C++
btcup/sb-admin
/exams/2559/02204111/2/midterm/4_1_714_5920501286.cpp
UTF-8
465
2.8125
3
[ "MIT" ]
permissive
// 5920501286 Onuma Intasang #include <iostream> using namespace std; int main() { char size,pice; int x,y,h,m,A,L; cout<<"Type of vehicle ((C)Car or (M)Motorcycle):"; cin>>size; cout<<"Arrival time :"; cin>>x; cout<<"Leave time :"; cin>>y; cout<<y-x<<"hours and"<<0<<"minutes"<<endl; if(h>=3&&m<=5) pice=h*m; cout<<"You have to pay "<<pice<<"bath"; system ("pause"); return 0; }
true
3a10d89cbf09302e25b602364ac6cba600c47f63
C++
theDreamBear/algorithmn
/leetcode/283.移动零.cpp
UTF-8
1,165
3.484375
3
[]
no_license
/* * @lc app=leetcode.cn id=283 lang=cpp * * [283] 移动零 * * https://leetcode-cn.com/problems/move-zeroes/description/ * * algorithms * Easy (58.34%) * Likes: 474 * Dislikes: 0 * Total Accepted: 98.9K * Total Submissions: 168.3K * Testcase Example: '[0,1,0,3,12]' * * 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 * * 示例: * * 输入: [0,1,0,3,12] * 输出: [1,3,12,0,0] * * 说明: * * * 必须在原数组上操作,不能拷贝额外的数组。 * 尽量减少操作次数。 * * */ // @lc code=start class Solution { public: void fakePartition(vector<int>& nums) { int low = 0, high = nums.size() - 1; int block = low - 1; for (int i = 0; i <= high; ++i) { if (nums[i] != 0) { if (++block != i) { swap(nums[block], nums[i]); } } } if (++block < high) { swap(nums[block], nums[high]); } } void moveZeroes(vector<int>& nums) { fakePartition(nums); } }; // @lc code=end
true
bedfd63472cea1092c315411947f89871900f260
C++
vlluvia/algorithm
/leetcode/[18]-四数之和.cpp
UTF-8
878
2.890625
3
[]
no_license
vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(), nums.end()); set<vector<int>> res; if (nums.empty() || nums.back() < 0 || nums.front() > 0) return {}; for (int k = 0; k < (int)nums.size() - 2; ++k) { for(int l = nums.size()-1;l >= 0; l--){ if(k >= l) break; int targ = target - nums[k]- nums[l], i = k + 1, j = l - 1; while (i < j) { if (nums[i] + nums[j] == targ) { res.insert({nums[k], nums[i], nums[j], nums[l]}); while (i < j && nums[i] == nums[i + 1]) ++i; while (i < j && nums[j] == nums[j - 1]) --j; ++i; --j; } else if (nums[i] + nums[j] < targ) ++i; else --j; } } } return vector<vector<int>>(res.begin(), res.end()); }
true
ed95d54c0e45fea6c7990815b46d75f9ad04f9e6
C++
PrakharPipersania/LeetCode-Solutions
/Greedy/cinema-seat-allocation.cpp
UTF-8
1,199
2.578125
3
[ "MIT" ]
permissive
class Solution { public: int maxNumberOfFamilies(int n, vector<vector<int>>& reservedSeats) { int num=0,res=0,v=0,a[8]; map<int,vector<int>> row; for(int i=0;i<reservedSeats.size();i++) row[reservedSeats[i][0]].push_back(reservedSeats[i][1]); for(auto e=begin(row);e!=end(row);e++) { num++; for(int i=0;i<8;i++) a[i]=0; for(auto c:e->second) { switch(c) { case 2:a[0]++;break; case 3:a[1]++;break; case 4:a[2]++;break; case 5:a[3]++;break; case 6:a[4]++;break; case 7:a[5]++;break; case 8:a[6]++;break; case 9:a[7]++;break; } } if(a[0]==0&&a[1]==0&&a[2]==0&&a[3]==0) v++; if(a[4]==0&&a[5]==0&&a[6]==0&&a[7]==0) v++; if(v==0&a[2]==0&&a[3]==0&&a[4]==0&&a[5]==0) v++; res+=v; v=0; } res=res+((n-num)*2); return res; } };
true
45699ee6b8b9ac4df0ccbd6d746252dd46591b21
C++
gwqw/LeetCodeCpp
/Algorithms/easy/674_longest_continuous_inc_subseq.cpp
UTF-8
1,409
3.765625
4
[]
no_license
/** 674. Longest Continuous Increasing Subsequence Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). Example 1: Input: [1,3,5,4,7] Output: 3 Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. Example 2: Input: [2,2,2,2,2] Output: 1 Explanation: The longest continuous increasing subsequence is [2], its length is 1. Note: Length of the array will not exceed 10,000. Algo: simply go through array: O(N) + O(1) - go through array and check if increasing (save previous) - if inc: cur++ - else: update max - update max after the end */ class Solution { public: int findLengthOfLCIS(const vector<int>& nums) { if (nums.empty()) return 0; int max_length = 0; int cur_length = 1; int prev_value = nums[0]; for (size_t i = 1; i < nums.size(); ++i) { if (nums[i] > prev_value) { ++cur_length; } else { if (cur_length > max_length) max_length = cur_length; cur_length = 1; } prev_value = nums[i]; } return max(max_length, cur_length); } }; /* 1 3 5 4 7 2 1 2 3 1 2 1 3 2 1 2 3 4 1 2 1 1 2 3 4 */
true
43ec8448ec7fb3320c6eb27891ab27708866ea17
C++
jungchunkim/study_algorithm
/greedy_algorithm/greedy_5585_2.cpp
UTF-8
289
2.984375
3
[]
no_license
#include <iostream> using namespace std; int main() { int coin[] = { 500,100,50,10,5,1 }; int price; cin >> price; int rec_price = 1000 - price; int count = 0; for (int i = 0; i < 6; i++) { count += rec_price / coin[i]; rec_price = rec_price % coin[i]; } cout << count; }
true
e45c38687ce16a60a1c7d116cb8485e124ead9e4
C++
alanghiese/Go-Game
/Go Game 2 (1).0/src/Reglas.cpp
UTF-8
4,035
2.671875
3
[]
no_license
#include "Reglas.h" Reglas::Reglas(){ } bool Reglas::KO(Ficha f, Tablero t, Tablero estAnt) const{ return t.igualCruces(estAnt); } bool Reglas::ojo(Ficha f, Tablero t) const{ int huecos = 0; if (f.getFila()-1>=0 && (t.getCruces()[f.getFila()-1][f.getColumna()] == -1 || t.getCruces()[f.getFila()-1][f.getColumna()] == f.getColor())) huecos++; if (f.getColumna()-1>=0 && (t.getCruces()[f.getFila()][f.getColumna()-1] == -1 || t.getCruces()[f.getFila()][f.getColumna()-1] == f.getColor())) huecos++; if (f.getFila()+1<tSize && (t.getCruces()[f.getFila()+1][f.getColumna()] == -1 || t.getCruces()[f.getFila()+1][f.getColumna()] == f.getColor())) huecos++; if (f.getColumna()+1<tSize && (t.getCruces()[f.getFila()][f.getColumna()+1] == -1 || t.getCruces()[f.getFila()][f.getColumna()+1] == f.getColor())) huecos++; return huecos<1; } bool Reglas::suicidio(Ficha f, Tablero t) const{ list<Cadena> cadenas = t.getCadenas(); typename list<Cadena> :: iterator itC = cadenas.begin(); while (itC != cadenas.end()){ if (itC->pertenece(f)) break; itC++; } list<Ficha> hijos = itC->getFichas(); typename list<Ficha> :: iterator itLista = hijos.begin(); while (itLista != hijos.end()){ Ficha fA(itLista->getFila(),itLista->getColumna(),itLista->getColor()); if (!cantHuecos(fA,t,0)) return false; itLista++; } return true; } bool Reglas::comprobar(Ficha f, Tablero t, Tablero estAnt) const{ if (t.getCruces()[f.getFila()][f.getColumna()] != -1) { return false; } Tablero tAux; list<Ficha> lista; list<Ficha> yaPase; tAux.crear(t.getSize()); tAux.copiarTablero(t); tAux.actualizarTablero(f,lista); bool sui = suicidio(f,tAux); bool ko = KO(f,tAux,estAnt); bool oj = ojo(f,tAux); if (ko || oj || sui) return false; else return true; } void Reglas::getHijos(Ficha f, Tablero t, list<Ficha> &hijos, Ficha o) const { Utilidad util; if (f.getFila()-1>=0 && t.getCruces()[f.getFila()-1][f.getColumna()] == f.getColor()){ Ficha fAux(f.getFila()-1,f.getColumna(),f.getColor()); if(!fAux.equal(o) && !f.equal(fAux) && !util.perteneceFichaALista(hijos,fAux)) { hijos.push_back(fAux); getHijos(fAux,t,hijos,o); } } if (f.getColumna()-1>=0 && t.getCruces()[f.getFila()][f.getColumna()-1] == f.getColor()) { Ficha fAux(f.getFila(),f.getColumna()-1,f.getColor()); if(!fAux.equal(o) && !f.equal(fAux) && !util.perteneceFichaALista(hijos,fAux)) { hijos.push_back(fAux); getHijos(fAux,t,hijos,o); } } if (f.getFila()+1<tSize && t.getCruces()[f.getFila()+1][f.getColumna()] == f.getColor()) { Ficha fAux(f.getFila()+1,f.getColumna(),f.getColor()); if(!fAux.equal(o) && !f.equal(fAux) && !util.perteneceFichaALista(hijos,fAux)) { hijos.push_back(fAux); getHijos(fAux,t,hijos,o); } } if (f.getColumna()+1<tSize && t.getCruces()[f.getFila()][f.getColumna()+1] == f.getColor()){ Ficha fAux(f.getFila(),f.getColumna()+1,f.getColor()); if(!fAux.equal(o) && !f.equal(fAux) && !util.perteneceFichaALista(hijos,fAux)) { hijos.push_back(fAux); getHijos(fAux,t,hijos,o); } } } bool Reglas::cantHuecos(Ficha f, Tablero t, int maximo) const{ int huecos = 0; // int v = t.getCruces()[f.getFila()+1][f.getColumna()]; if (f.getFila()-1>=0 && t.getCruces()[f.getFila()-1][f.getColumna()] == -1) huecos++; if (f.getColumna()-1>=0 && t.getCruces()[f.getFila()][f.getColumna()-1] == -1) huecos++; if (f.getFila()+1<tSize && t.getCruces()[f.getFila()+1][f.getColumna()] == -1) huecos++; if (f.getColumna()+1<tSize && t.getCruces()[f.getFila()][f.getColumna()+1] == -1) huecos++; return huecos == maximo; } Reglas::~Reglas(){ }
true
46d94612f269a0a8ec6259b6b41f5116cffedd51
C++
MichaelEssmyer/201R-Spring-2020
/Program 4 TerrAnnie Scott 2/Board.h
UTF-8
525
2.515625
3
[]
no_license
#pragma once #include <string> #include <fstream> #include <stdexcept> #include <iostream> #include <ctime> #include <iomanip> #include "Player.h" using namespace std; struct Tile { string tile; bool CheckTitle(string myArr[], int index); //Check title bool CheckWinner(Tile myArr[], string symbol); }; class Board { public: void createBoard(); void PrintBoard(); void playerTurn(); Tile board[9]; Player names[2]; void GetName(); void Output(int Round); int PlayAgain(); };
true
545222192cfc608be9e830c267d9085a666948ca
C++
mr-X3/ads
/obst.cpp
UTF-8
3,476
2.78125
3
[]
no_license
#include<iostream> #include<stdlib.h> #include<string> #defineMAX 20 usingnamespace std; typedefstructOBST { string KEY; structOBST *left, *right; } OBST; int C[MAX][MAX]; //cost matrix int W[MAX][MAX]; //weight matrix int R[MAX][MAX]; //root matrix int q[MAX]; //unsuccesful searches int p[MAX]; //frequencies int n; //number of keys in the tree string KEYS[MAX]; OBST *ROOT=NULL; void calculate_wcr() { int x, min; int i, j, k, h, m; //Construct weight matrix W for (i = 0; i <= n; i++) { W[i][i] = q[i]; for (j = i + 1; j <= n; j++) W[i][j] = W[i][j - 1] + p[j] + q[j]; } //Construct cost matrix C and root matrix R for (i = 0; i <= n; i++) C[i][i] = 0; for (i = 0; i <= n - 1; i++) { j = i + 1; C[i][j] = C[i][i] + C[j][j] + W[i][j]; R[i][j] = j; } for (h = 2; h <= n; h++) for (i = 0; i <= n - h; i++) { j = i + h; m = R[i][j - 1]; min = C[i][m - 1] + C[m][j]; for (k = m + 1; k <= R[i + 1][j]; k++) { x = C[i][k - 1] + C[k][j]; if (x < min) { m = k; min = x; } } C[i][j] = W[i][j] + min; R[i][j] = m; } //Display weight matrix W cout<<"\nThe weight matrix W:\n"; for (int k = 0; k <=n; k++) { for (i = 0; i <=n; i++) { for (j = 0; j <=n; j++) if((j-i)==k) cout << W[i][j] <<" "; } cout <<"\n"; } //Display Cost matrix C cout<<"\nThe cost matrix C:\n"; for (int i = 0; i <= n; i++) C[i][i] = 0; for (int k = 0; k <= n; k++) { for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) if ((j - i) == k) cout << C[i][j] <<" "; } cout <<"\n"; } //Display root matrix R cout<<"\nThe root matrix R:\n"; for (int k = 0; k <= n; k++) { for (i = 0; i <= n; i++) { for (j = 0; j <= n; j++) if ((j - i) == k) cout << R[i][j] <<" "; } cout <<"\n"; } } //Construct the optimal binary search tree OBST *CONSTRUCT_OBST(inti, intj) { OBST *p; if (i == j) p = NULL; else { p = newOBST; p->KEY = KEYS[R[i][j]]; p->left = CONSTRUCT_OBST(i, R[i][j] - 1); //left subtree p->right = CONSTRUCT_OBST(R[i][j], j); //right subtree } return p; } //Display the optimal binary search tree void DISPLAY(OBST *ROOT, intl) { int i; if (ROOT != 0) { DISPLAY(ROOT->right, l + 1); for (i = 0; i <= l; i++) cout <<" ";; cout <<ROOT->KEY <<"\n"; DISPLAY(ROOT->left, l + 1); } } void OPTIMAL_BINARY_SEARCH_TREE() { float avg; calculate_wcr(); cout <<"\nC[0] = "<< C[0][n] <<" W[0] = "<< W[0][n] <<"\n"; avg =C[0][n]/ (float)W[0][n]; cout<<"The cost per weight ratio is : "<<avg<<"\n\n"; ROOT = CONSTRUCT_OBST(0, n); } int main() { int i, ch; cout<<"How many keys : "; cin>>n; for (i = 1; i <=n; i++) { cout<<"key["<<i<<"] = "; cin>>KEYS[i]; cout <<"Frequency of "<< KEYS[i]<<" = "; cin >> p[i]; } for (i = 0; i <= n; i++) { cout<<"q["<<i<<"] = "; cin >> q[i]; } while (1) { cout<<"\n1.Construct tree\n2.Display tree\n3.Exit\nEnter choice : "; cin>>ch; switch(ch) { case 1: OPTIMAL_BINARY_SEARCH_TREE(); break; case 2: if (ROOT == NULL) cout <<"No tree created\nFirst create tree\n"; else { cout <<"\n\nDisplaying the tree\n"; DISPLAY(ROOT, 0); } break; case 3: exit(0); break; } } system("PAUSE"); }
true
8b24c859f045851533d16dc51430d88c09e28ab3
C++
dshnightmare/LeetCodeC
/src/LowestCommonAncestorOfBST.cpp
UTF-8
489
3.421875
3
[]
no_license
struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution{ public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){ if(root == nullptr) return root; if(p->val > q->val) std::swap(p, q); if(p->val > root->val) return lowestCommonAncestor(root->right, p, q); else if(q->val < root->val) return lowestCommonAncestor(root->left, p, q); else return root; } };
true
00286d43cc748af82e028bd1e0942a261ccfde44
C++
unpluggedLink/puzzle
/puzzle/Source.cpp
WINDOWS-1252
11,600
2.734375
3
[]
no_license
#include <iostream> #include <math.h> #include <SFML/Graphics.hpp> #include <SFML/Window/Keyboard.hpp> #include <SFML/System/Time.hpp> using namespace std; using namespace sf; #include "ResourcePath.hpp" #include "Jugador.h" #include "Bloque.h" #include "Animation.h" #include "Item.h" int main() { int nivel = 1; jugador yo = jugador(10, 13); int counter; //Nueva variable auxiliar int score = 0; Font sansation; sansation.loadFromFile(resourcePath() + "sansation.ttf"); Text scoreLabel(to_string(score),sansation); scoreLabel.setColor(Color::White); scoreLabel.setPosition(2 * 34, 15 * 34); Sprite player = yo.getCharSprite(); Item lata = Item(1); Vector2f testPosition = Vector2f(8 , 11); bloque box = bloque(1); vector <Item>::const_iterator iter1; //Nuevo - iterador :3 si lo estudias bien sers un dios :: nota personal vector <Item> contenedorDeLatas; // Nuevo - estudiar el tipo vector :: nota personal lata.setPosition(1,5); contenedorDeLatas.push_back(lata); lata.setPosition(11, 1); contenedorDeLatas.push_back(lata); lata.setPosition(10, 11); contenedorDeLatas.push_back(lata); vector <Vector2f> contenedorDeCajas; //Contenedor de posiciones (Ya estan todas) contenedorDeCajas.push_back(Vector2f(8, 13)); contenedorDeCajas.push_back(Vector2f(10, 9)); contenedorDeCajas.push_back(Vector2f(8, 7)); contenedorDeCajas.push_back(Vector2f(8, 4)); contenedorDeCajas.push_back(Vector2f(11, 2)); contenedorDeCajas.push_back(Vector2f(2, 7)); contenedorDeCajas.push_back(Vector2f(4, 2)); bloque Tile1 = bloque(0); vector <Vector2f> contenedorDeSuelo; //Contenedor de posiciones //fila 1 contenedorDeSuelo.push_back(Vector2f(4, 1)); contenedorDeSuelo.push_back(Vector2f(7, 1)); contenedorDeSuelo.push_back(Vector2f(8, 1)); contenedorDeSuelo.push_back(Vector2f(9, 1)); contenedorDeSuelo.push_back(Vector2f(11, 1)); //fila 2 contenedorDeSuelo.push_back(Vector2f(4, 2)); contenedorDeSuelo.push_back(Vector2f(6, 2)); contenedorDeSuelo.push_back(Vector2f(7, 2)); contenedorDeSuelo.push_back(Vector2f(9, 2)); contenedorDeSuelo.push_back(Vector2f(10, 2)); contenedorDeSuelo.push_back(Vector2f(11, 2)); //fila 3 contenedorDeSuelo.push_back(Vector2f(1, 3)); contenedorDeSuelo.push_back(Vector2f(2, 3)); contenedorDeSuelo.push_back(Vector2f(3, 3)); contenedorDeSuelo.push_back(Vector2f(4, 3)); contenedorDeSuelo.push_back(Vector2f(6, 3)); contenedorDeSuelo.push_back(Vector2f(8, 3)); contenedorDeSuelo.push_back(Vector2f(11, 3)); //fila 4 contenedorDeSuelo.push_back(Vector2f(1, 4)); for (int i = 4; i <= 11; i++) { contenedorDeSuelo.push_back(Vector2f(i, 4)); }; //fila 5 contenedorDeSuelo.push_back(Vector2f(1, 5)); contenedorDeSuelo.push_back(Vector2f(4, 5)); contenedorDeSuelo.push_back(Vector2f(8, 5)); //fila 6 contenedorDeSuelo.push_back(Vector2f(1, 6)); contenedorDeSuelo.push_back(Vector2f(3, 6)); contenedorDeSuelo.push_back(Vector2f(4, 6)); contenedorDeSuelo.push_back(Vector2f(8, 6)); //fila 7 contenedorDeSuelo.push_back(Vector2f(1, 7)); contenedorDeSuelo.push_back(Vector2f(2, 7)); contenedorDeSuelo.push_back(Vector2f(3, 7)); contenedorDeSuelo.push_back(Vector2f(4, 7)); contenedorDeSuelo.push_back(Vector2f(8, 7)); contenedorDeSuelo.push_back(Vector2f(9, 7)); contenedorDeSuelo.push_back(Vector2f(10, 7)); //fila 8 contenedorDeSuelo.push_back(Vector2f(3, 8)); contenedorDeSuelo.push_back(Vector2f(8, 8)); contenedorDeSuelo.push_back(Vector2f(10, 8)); //fila 9 contenedorDeSuelo.push_back(Vector2f(8, 9)); contenedorDeSuelo.push_back(Vector2f(9, 9)); contenedorDeSuelo.push_back(Vector2f(10, 9)); contenedorDeSuelo.push_back(Vector2f(11, 9)); //fila 10 contenedorDeSuelo.push_back(Vector2f(9, 10)); //fila 11 contenedorDeSuelo.push_back(Vector2f(8, 11)); contenedorDeSuelo.push_back(Vector2f(9, 11)); contenedorDeSuelo.push_back(Vector2f(10, 11)); //fila 12 contenedorDeSuelo.push_back(Vector2f(8, 12)); //fila 13 contenedorDeSuelo.push_back(Vector2f(7, 13)); contenedorDeSuelo.push_back(Vector2f(8, 13)); contenedorDeSuelo.push_back(Vector2f(9, 13)); contenedorDeSuelo.push_back(Vector2f(10, 13)); RenderWindow window(VideoMode(800, 600), "Las vacas son chidas"); window.setFramerateLimit(60); //Gameloop while (window.isOpen()) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } //Si la aplicacion esta seleccionada if (event.type != Event::LostFocus) { window.clear(); switch (nivel) { case 1: //Dibujar escenario window.draw(scoreLabel); for (int i = 0; i < contenedorDeSuelo.size(); i++) { Tile1.positionOnMap(&contenedorDeSuelo[i]); window.draw(Tile1.getSprite()); }; //Dibujar cajas for (int i = 0; i < contenedorDeCajas.size(); i++) { box.positionOnMap(&contenedorDeCajas[i]); window.draw(box.getSprite()); }; //Dibujar Latas counter=0; for (iter1=contenedorDeLatas.begin(); iter1 != contenedorDeLatas.end(); iter1++) { window.draw(contenedorDeLatas[counter].sprite); counter++; } //Borrar Latas counter=0; for(iter1 = contenedorDeLatas.begin(); iter1 != contenedorDeLatas.end();iter1++) { if( contenedorDeLatas[counter].destroy == true){ contenedorDeLatas.erase(iter1); break; }; counter++; }; //Colision con latas counter=0; for(iter1 = contenedorDeLatas.begin(); iter1 != contenedorDeLatas.end();iter1++) { if(yo.getPosition() == contenedorDeLatas[counter].getPosition()){ contenedorDeLatas[counter].destroy = true; score += 100; scoreLabel.setString(to_string(score)); break; }; counter++; }; //Revisar que accion quieres hacer (Solo si no te estas moviendo). if (!yo.getMovingState()) { yo.checkMove(); }; //Comprobar que tu accion es posible for (int a = 0; a < contenedorDeSuelo.size(); a++) //For suelo { //Hay suelo a 1 de distancia de mi direccion? if (yo.IsPossible(&contenedorDeSuelo[a], 1)) //Si (Hay suelo a 1 de distancia de mi direccion) { for (int b = 0; b < contenedorDeCajas.size(); b++) //For caja { //Hay caja a 1 de distancia de mi direccion? if (yo.IsPossible(&contenedorDeCajas[b], 1)) //Si (Hay caja a 1 de distancia de mi direccion) { yo.setBoxID(b); //Estas empujando la caja? if (yo.getIfHoldingBox()) //Si (Estoy empujando la caja) { for (int c = 0; c < contenedorDeSuelo.size(); c++) //For suelo { //Hay suelo a 2 de distancia de mi direccion? if (yo.IsPossible(&contenedorDeSuelo[c], 2)) //Si (Hay suelo a 2 de distancia de mi direccion) { //For caja for (int d = 0; d < contenedorDeCajas.size(); d++) { //Hay una caja a 2 de mi direccion? if (yo.IsPossible(&contenedorDeCajas[d],2)) //Si (Hay caja a 2 de mi direccion) { yo.setIfMove(false); break; } else //No (No hay caja a 2 de mi direccion) { yo.setIfMove(true); }; //Hay una lata a 2 de mi direccin }; if (yo.getIfMove()) //Si te puedes mover { yo.setGoalByKey(); //Marcar a donde ir segun la tecla que oprimas }; break; } else //No (No hay suelo a 2 de distancia de mi direccion) { yo.setIfMove(false); }; }; break; } else //No (No estoy empujando la caja) { yo.setIfMove(false); break; }; } else //No (No hay caja a 1 de distancia de mi direccion) { yo.setIfMove(true); }; }; } else //No (No hay suelo a 1 de distancia de mi direccion) { yo.setIfMove(false); }; if (yo.getIfMove()) //Si te puedes mover { yo.setGoalByKey(); //Marcar a donde ir segun la tecla que oprimas }; }; //Si la caja esta cerca if (yo.getPosition().x - 34 <= contenedorDeCajas[yo.getBoxID()].x * 34 && yo.getPosition().x + 34 >= contenedorDeCajas[yo.getBoxID()].x * 34 && yo.getPosition().y - 34 <= contenedorDeCajas[yo.getBoxID()].y * 34 && yo.getPosition().y + 34 >= contenedorDeCajas[yo.getBoxID()].y * 34 ) { yo.setIfBoxNear(true); //Puedes empujarla/jalarla } else { yo.setIfBoxNear(false); //No puedes empujarla/jalarla }; //Moverse a la direccion que quieres (Solo si te estas moviendo), una vez que llegues ya no te moveras if (yo.getMovingState()) { yo.movimiento(yo.getNextMove()); if (yo.getIfHoldingBox() && yo.getIfBoxNear())//Si estas agarrando una caja y si esta cerca... { if (yo.getNextMove() == 'W' && contenedorDeCajas[yo.getBoxID()].x == yo.getPosition().x/34) { if (yo.getPosition().y/34 > contenedorDeCajas[yo.getBoxID()].y) //Si la caja esta arriba de ti contenedorDeCajas[yo.getBoxID()].y = (yo.getPosition().y - 34) / 34;//empujar caja arriba else contenedorDeCajas[yo.getBoxID()].y = (yo.getPosition().y + 34) / 34;//jalar caja arriba } else if (yo.getNextMove() == 'S' && contenedorDeCajas[yo.getBoxID()].x == yo.getPosition().x / 34) { if (yo.getPosition().y / 34 > contenedorDeCajas[yo.getBoxID()].y) //Si la caja esta arriba de ti contenedorDeCajas[yo.getBoxID()].y = (yo.getPosition().y - 34) / 34;//empujar caja abajo else contenedorDeCajas[yo.getBoxID()].y = (yo.getPosition().y + 34) / 34;//jalar caja bajo } else if (yo.getNextMove() == 'A' && contenedorDeCajas[yo.getBoxID()].y == yo.getPosition().y / 34) { if (yo.getPosition().x / 34 > contenedorDeCajas[yo.getBoxID()].x) //Si la caja esta a tu izquierda contenedorDeCajas[yo.getBoxID()].x = (yo.getPosition().x - 34) / 34;//empujar caa izquierda else contenedorDeCajas[yo.getBoxID()].x = (yo.getPosition().x + 34) / 34;//empujar caja derecha } else if (yo.getNextMove() == 'D' && contenedorDeCajas[yo.getBoxID()].y == yo.getPosition().y / 34) { if (yo.getPosition().x/ 34 < contenedorDeCajas[yo.getBoxID()].x) //Si la caja esta a tu derecha contenedorDeCajas[yo.getBoxID()].x = (yo.getPosition().x + 34) / 34;//empujar caja derecha else contenedorDeCajas[yo.getBoxID()].x = (yo.getPosition().x - 34) / 34;//empujar caja derecha }; }; }; window.draw(yo.getCharSprite()); break; default: break; }; window.display(); }; }; };
true
d5e94778c4789e864d501e27bc5a4e5614a0fb02
C++
sgc24/Projects
/reservation 2.cpp
UTF-8
4,654
3.671875
4
[]
no_license
#include<iostream> #include<iomanip> #include<stdlib.h> using namespace std; class Reservation{ private: string LastName; Reservation *next; friend class LinkedList; }; class LinkedList{ private: Reservation *head; Reservation *curr; public: LinkedList(); void addNode(); void cancelNode(); void printNode(); void searchNode(); }; int main() { int choice; LinkedList list; while(choice != 5) { cout << "\n1.) initialize list." << endl; cout << "2.) Print list." << endl; cout << "3.) Search list." << endl; cout << "4.) Cancel reservation." << endl; cout << "5.) Quit." << endl; cin >> choice; switch(choice) { case 1: list.addNode(); break; case 2: list.printNode(); break; case 3: list.searchNode(); break; case 4: list.cancelNode(); break; case 5: cout<<"exiting.\n"; system("pause"); exit(1); } } system("pause"); return 0; } LinkedList::LinkedList() { head = NULL; } void LinkedList::addNode() { Reservation *n = new Reservation; head = n; n->LastName = "smith"; Reservation *t = new Reservation; t->LastName = "johnson"; n->next = t; Reservation *p = new Reservation; p->LastName = "carrol"; t->next = p; Reservation *z = new Reservation; z->LastName = "gomez"; p->next = z; Reservation *j = new Reservation; j->LastName = "christ"; z->next = j; j-> next = NULL; cout << "list initialized!\n"; } void LinkedList::printNode() { if(head == NULL) { cout << "no reservations are present at this time.\n"; system("pause"); return; } curr = head; while(curr != NULL) { cout << "\nReservation for: " << curr->LastName << endl; cout << "---------------\n"; curr = curr->next; } } void LinkedList::searchNode() { if(head == NULL) { cout << "no reservations are present at this time.\n"; system("pause"); return; } string last_name; curr = head; cout << "Enter the last name under the reservation.\n"; cin >> last_name; while(curr->next != NULL && curr->LastName != last_name) { curr = curr->next; } if(curr->LastName == last_name) { cout << "\nReservation for: " << curr->LastName << endl; cout << "---------------\n"; } else { cout << "No reservation found for " << last_name << endl; system("pause"); return; } } void LinkedList::cancelNode() { if(head == NULL) { cout << "no reservations are present at this time.\n"; system("pause"); return; } string last_name; curr = head; cout << "Enter the last name of the reservation you want to cancel.\n"; cin >> last_name; while(curr->next != NULL && curr->LastName != last_name) { curr = curr->next; } if(curr->LastName == last_name) { cout << "\nReservation for: " << curr->LastName << " was found."<< endl; } else { cout << "No reservation found for " << last_name << endl; system("pause"); return; } curr = head; Reservation *d; d = head; if(head->LastName == last_name) { cout << "The reservation for " << head->LastName << " was cancelled." << endl; head = head->next; return; } while(d->LastName != last_name && d->next != NULL) { d = d->next; } while(curr->next != d) { curr = curr->next; } curr->next = d->next; cout << "The reservation for " << d->LastName << " was cancelled." << endl; }
true
e4a238e6e7eebb8c1f879e0fba0567f3c6128951
C++
zozoiiiiii/cppreflection
/sample/main.cpp
UTF-8
878
2.53125
3
[]
no_license
#include "test.h" int main() { // test1 { MetaClass* pMetaClass_Vec2Test = Point::MetaClassInstance(); MetaField* pMetaField = pMetaClass_Vec2Test->fields["x"]; Point vt; vt.x = 1.0f; vt.y = 2.0f; float* xx = (float*)pMetaField->Get(&vt); } // test2 { MetaClass* pMetaClass_Test = Test::MetaClassInstance(); MetaField* pMetaField = pMetaClass_Test->fields["position"]; // field Test tt; Point* aa = (Point*)pMetaField->Get(&tt); Point bb; bb.x=1.0f; pMetaField->Set(&tt, &bb); MetaMethod* pMetaMethod = pMetaClass_Test->methods["Set"]; float result; // method Point cc; Point* pCC = &cc; pCC->x = 1.1f; void* parameters[1]; parameters[0]=&pCC; pMetaMethod->Invoke(&result, pMetaClass_Test, parameters); } }
true
c6fbee1feb088c05ca15554ab8a89a880ca1bc14
C++
aymanrs/hammingdistancessolution
/bruteforce.cpp
UTF-8
337
2.75
3
[]
no_license
class Solution { public: int totalHammingDistance(vector<int>& nums) { unsigned long long total = 0; int i,j; for(i = 0;i < nums.size();i++){ for(j = i + 1;j < nums.size();j++){ total += __builtin_popcount(nums[i] ^ nums[j]); } } return total; } };
true
0d41d010fdde3f8ddbac98a4fdee3b14cfd95876
C++
IM-RA/MSME_Nano
/Motor_With_Individual/src/main.cpp
UTF-8
3,825
2.859375
3
[]
no_license
#include <Arduino.h> #include <Servo.h> #define NUM_MOTOR 6 uint8_t all_end_flag=0x00; uint8_t all_done=0x00; struct myservo{ Servo servo; uint8_t previous_position = 0; uint8_t working_position = 0; uint8_t target_position = 0; uint8_t call_order; }; struct myservo new_motor[NUM_MOTOR]; uint8_t posistion[NUM_MOTOR][2] = {{0,180},{0,45},{45,135},{90,0},{135,180},{80,35}}; uint8_t larger_number = 0; void motor_move(uint8_t i){ //Serial.println("Motor=>"+String(i)+"Position="+String(new_motor[i].working_position)); new_motor[i].servo.write(new_motor[i].working_position); if(new_motor[i].working_position < new_motor[i].target_position){ new_motor[i].working_position++; } else if(new_motor[i].working_position > new_motor[i].target_position){ new_motor[i].working_position--; } else{ all_end_flag = all_end_flag | (1 << i); //Serial.print("End=>"); //Serial.println(all_end_flag); if(all_end_flag == all_done){ //Serial.println("Swap"); for(int i=0;i<NUM_MOTOR;i++){ uint8_t temp; temp = new_motor[i].target_position; new_motor[i].target_position = new_motor[i].previous_position; new_motor[i].previous_position = temp; } all_end_flag =0x00; } } } void call_order(){ for(uint8_t i=1;i<=larger_number;i++){ for(uint8_t j=0;j<NUM_MOTOR;j++){ if(i%new_motor[j].call_order==0||new_motor[j].call_order==0){ motor_move(j); } } } } void call_priority(){ uint8_t smallest_number = 255; for(int i=0;i<NUM_MOTOR;i++){ new_motor[i].call_order = abs(new_motor[i].target_position-new_motor[i].previous_position); //Serial.println("MotorCallOrderSub=>"+String(i)+"=>"+String(new_motor[i].call_order)); if(smallest_number>new_motor[i].call_order && new_motor[i].call_order!=0){ smallest_number = new_motor[i].call_order; } } //Serial.println("Smallest=>"+String(smallest_number)); for(int i=0;i<NUM_MOTOR;i++){ new_motor[i].call_order = new_motor[i].call_order/smallest_number; //Serial.println("MotorCallOrderLCM=>"+String(i)+"=>"+String(new_motor[i].call_order)); if(larger_number<new_motor[i].call_order){ larger_number = new_motor[i].call_order; } } //Serial.println("Largest=>"+String(larger_number)); for(int i=0;i<NUM_MOTOR;i++){ if(new_motor[i].call_order!=0){ new_motor[i].call_order=(larger_number/new_motor[i].call_order); } //Serial.println("MotorCallOrderFinal=>"+String(i)+"=>"+String(new_motor[i].call_order)); } } void set_positions(){ for(int i=0;i<NUM_MOTOR;i++){ new_motor[i].previous_position=posistion[i][0]; new_motor[i].target_position=posistion[i][1]; new_motor[i].working_position = new_motor[i].previous_position; //Serial.println("Motor"+String(i)); //Serial.println("Pre_Pos"+String(new_motor[i].previous_position)); //Serial.println("Tar_Pos"+String(new_motor[i].target_position)); //Serial.println("Wor_Pos"+String(new_motor[i].working_position)); } } void set_pins(uint8_t pin){ for(int i=0;i<NUM_MOTOR;i++){ new_motor[i].servo.attach(pin-i); //Serial.println("Motor"+String(i)+"=>"+String(pin-i)); all_done = all_done | (1 << i); } } void setup() { Serial.begin(9600); set_pins(11); set_positions(); call_priority(); call_order(); } void loop() { call_order(); Serial.println( "Motor1:" + String(new_motor[0].working_position) + ",Motor2:" + String(new_motor[1].working_position) + ",Motor3:" + String(new_motor[2].working_position) + ",Motor4:" + String(new_motor[3].working_position) + ",Motor5:" + String(new_motor[4].working_position) + ",Motor6:" + String(new_motor[5].working_position) ); delay(50); }
true
f326100a9dabfd6cbabbbd7e8d538e446746782d
C++
FloorBroekgaarden/DCO-random-code
/code_COMPAS/COMPAS/pulsarBirthMagneticFieldDistribution.cpp
UTF-8
2,492
2.75
3
[]
no_license
#include "pulsarBirthMagneticFieldDistribution.h" double pulsarBirthMagneticFieldDistribution(programOptions options, const gsl_rng *r){ /* Return log10 of the magnetic field (in G) for a pulsar at birth Parameters ----------- options : programOptions User specified program options Returns -------- log10B : double log10 of the birth magnetic field in G */ double log10B = 0; if(boost::iequals(options.pulsarBirthMagneticFieldDistributionString, "ZERO")){ log10B = 0; } else if(boost::iequals(options.pulsarBirthMagneticFieldDistributionString, "FIXED")){ // Set to a fixed constant value std::cout << "Fixed value not yet implemented. Implement as options.pulsarBirthMagneticFieldFixedValue" << std::endl; log10B = 0; } else if(boost::iequals(options.pulsarBirthMagneticFieldDistributionString, "FLATINLOG")){ // Flat in the log distribution from Oslowski et al 2011 https://arxiv.org/abs/0903.3538 (log10B0min = , log10B0max = ) double u = gsl_rng_uniform (r); log10B = options.pulsarBirthMagneticFieldDistributionMin + (u * (options.pulsarBirthMagneticFieldDistributionMax - options.pulsarBirthMagneticFieldDistributionMin)); } else if(boost::iequals(options.pulsarBirthMagneticFieldDistributionString, "UNIFORM")){ // Flat distribution used in Kiel et al 2008 https://arxiv.org/abs/0805.0059 (log10B0min = 11, log10B0max = 13.5 see section 3.4 and Table 1.) double u = gsl_rng_uniform (r); double B = pow(10, options.pulsarBirthMagneticFieldDistributionMin) + (u * (pow(10,options.pulsarBirthMagneticFieldDistributionMax) - pow(10,options.pulsarBirthMagneticFieldDistributionMin))); log10B = log10(B); } else if(boost::iequals(options.pulsarBirthMagneticFieldDistributionString, "LOGNORMAL")){ // log normal distribution from Faucher-Giguere and Kaspi 2006 https://arxiv.org/abs/astro-ph/0512585 // Values hard-coded for now, can make them options if necessary double pulsarBirthMagneticFieldDistributionFaucherGiguereKaspi2006Mean = 12.65; double pulsarBirthMagneticFieldDistributionFaucherGiguereKaspi2006Std = 0.55; log10B = gsl_ran_gaussian (r, pulsarBirthMagneticFieldDistributionFaucherGiguereKaspi2006Std) + pulsarBirthMagneticFieldDistributionFaucherGiguereKaspi2006Mean; } else{ std::cerr << "Invalid pulsarBirthMagneticFieldDistribution provided " << std::endl; } return log10B; }
true
06af8b008aa31ce7ce142ff15e23cc818c495736
C++
memoregoing/subject
/cpp04/ex01/AWeapon.hpp
UTF-8
519
3.15625
3
[]
no_license
// // Created by namhyung kim on 2020/11/25. // #ifndef AWEAPON_HPP # define AWEAPON_HPP # include <iostream> # include <string> class AWeapon { protected: AWeapon(); std::string name; int apCost; int damage; public: AWeapon(std::string const &name, int apcost, int damage); AWeapon(AWeapon const &other); virtual ~AWeapon(); AWeapon &operator=(AWeapon const &other); std::string const &getName(void) const; int getAPCost(void) const; int getDamage(void) const; virtual void attack() const = 0; }; #endif
true
30915ea32f7ea04f7791ef341c1c86ccc68823fa
C++
mehoggan/opengl_math
/tests/check_type_point.cpp
UTF-8
10,778
3.21875
3
[]
no_license
#include "opengl_math/primitives/points/type_point_2d.h" #include "opengl_math/primitives/points/type_point_3d.h" #include "suite.h" #include <check.h> /*! \brief This is a test to see if default constructor for * 2d and 3d points itializes all of its components to 0.0f */ START_TEST(test_default_2d_point_constructor) { opengl_math::point_2d<float> p1; ck_assert(p1.x() == 0.0f); ck_assert(p1.y() == 0.0f); opengl_math::point_2d<double> p2; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.0); } END_TEST START_TEST(test_default_3d_point_constructor) { opengl_math::point_3d<float> p1; ck_assert(p1.x() == 0.0f); ck_assert(p1.y() == 0.0f); ck_assert(p1.z() == 0.0f); opengl_math::point_3d<double> p2; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.0); ck_assert(p2.z() == 0.0); } END_TEST /*! \brief This is a test to see if paramaterized constructor for * 2d and rgba points itializes all of its components correctly */ START_TEST(test_2d_point_constructor) { opengl_math::point_2d<float> p1(1.0f, 2.0f); ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 2.0f); opengl_math::point_2d<double> p2(1.0, 0.97); ck_assert(p2.x() == 1.0); ck_assert(p2.y() == 0.97); } END_TEST START_TEST(test_3d_point_constructor) { opengl_math::point_3d<float> p1(1.0f, 2.0f, 3.0f); ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 2.0f); ck_assert(p1.z() == 3.0f); opengl_math::point_3d<double> p2(1.0, 0.97, 0.2); ck_assert(p2.x() == 1.0); ck_assert(p2.y() == 0.97); ck_assert(p2.z() == 0.2); } END_TEST /*! \brief This is a test to see if the copy constructor for * 2d and rgba points initializes all of its components correctly */ START_TEST(test_point_2d_copy_constructor) { opengl_math::point_2d<float> p1(0.9f, 0.75f); opengl_math::point_2d<float> p2(p1); ck_assert(p2.x() == 0.9f); ck_assert(p2.y() == 0.75f); opengl_math::point_2d<double> p3(0.145, 0.1); opengl_math::point_2d<double> p4(p3); ck_assert(p4.x() == 0.145); ck_assert(p4.y() == 0.1); } END_TEST START_TEST(test_point_3d_copy_constructor) { opengl_math::point_3d<float> p1(0.82f, 1.0e-10f, 10.0); opengl_math::point_3d<float> p2(p1); ck_assert(p2.x() == 0.82f); ck_assert(p2.y() == 0.0000000001f); ck_assert(p2.z() == 10.0f); opengl_math::point_3d<double> p3(0.7, 1.0e-18, 1.000000001); opengl_math::point_3d<double> p4(p3); ck_assert(p4.x() == 0.7); ck_assert(p4.y() == 1.0e-18); ck_assert(p4.z() == 1.000000001); } END_TEST /*! \brief This is a test to see if the assignment operator copies * the contents of the rhs value into the lhs without modifying the * rhs. */ START_TEST(test_point_2d_assignment_operator) { opengl_math::point_2d<float> p1(0.88f, 0.0f); opengl_math::point_2d<float> p2 = p1; ck_assert(p2.x() == 0.88f); ck_assert(p2.y() == 0.0f); ck_assert(p1.x() == 0.88f); ck_assert(p1.y() == 0.0f); p2 = opengl_math::point_2d<float>(0.99f, 0.0f); ck_assert(p2.x() == 0.99f); ck_assert(p2.y() == 0.0f); ck_assert(p1.x() == 0.88f); ck_assert(p1.y() == 0.0f); opengl_math::point_2d<double> p3(0.11, 0.22); opengl_math::point_2d<double> p4 = p3; ck_assert(p4.x() == 0.11); ck_assert(p4.y() == 0.22); ck_assert(p3.x() == 0.11); ck_assert(p3.y() == 0.22); p4 = opengl_math::point_2d<double>(0.22, 0.33); ck_assert(p4.x() == 0.22); ck_assert(p4.y() == 0.33); ck_assert(p3.x() == 0.11); ck_assert(p3.y() == 0.22); } END_TEST START_TEST(test_point_3d_assignment_operator) { opengl_math::point_3d<float> p1(0.82f, 1.0f, 1.0f); opengl_math::point_3d<float> p2 = p1; ck_assert(p2.x() == 0.82f); ck_assert(p2.y() == 1.0f); ck_assert(p2.z() == 1.0f); ck_assert(p1.x() == 0.82f); ck_assert(p1.y() == 1.0f); ck_assert(p1.z() == 1.0f); p2 = opengl_math::point_3d<float>(0.83f, 0.99f, 0.98f); ck_assert(p2.x() == 0.83f); ck_assert(p2.y() == 0.99f); ck_assert(p2.z() == 0.98f); ck_assert(p1.x() == 0.82f); ck_assert(p1.y() == 1.0f); ck_assert(p1.z() == 1.0f); opengl_math::point_3d<double> p3(0.66, 0.88, 0.988); opengl_math::point_3d<double> p4 = p3; ck_assert(p4.x() == 0.66); ck_assert(p4.y() == 0.88); ck_assert(p4.z() == 0.988); ck_assert(p3.x() == 0.66); ck_assert(p3.y() == 0.88); ck_assert(p3.z() == 0.988); p4 = opengl_math::point_3d<double>(); ck_assert(p4.x() == 0.0); ck_assert(p4.y() == 0.0); ck_assert(p4.z() == 0.0); ck_assert(p3.x() == 0.66); ck_assert(p3.y() == 0.88); ck_assert(p3.z() == 0.988); } END_TEST /*! \brief This is a test to see if the setters for 2d and 3d points * set the value to a new value. */ START_TEST(test_point_2d_setters) { opengl_math::point_2d<float> p1; p1.x(1.0f); ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 0.0f); p1.y(0.5f); ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 0.5f); p1.y(0.2f); ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 0.2f); p1.x_and_y(0.0f, 0.0f); ck_assert(p1.x() == 0.0f); ck_assert(p1.y() == 0.0f); opengl_math::point_2d<double> p2; p2.x(0.5); ck_assert(p2.x() == 0.5); ck_assert(p2.y() == 0.0); p2.y(0.5); ck_assert(p2.x() == 0.5); ck_assert(p2.y() == 0.5); p2.x(0.4); ck_assert(p2.x() == 0.4); ck_assert(p2.y() == 0.5); p2.x_and_y(0.1, 0.1); ck_assert(p2.x() == 0.1); ck_assert(p2.y() == 0.1); } END_TEST START_TEST(test_point_3d_setters) { opengl_math::point_3d<float> p1; p1.x(0.01f); ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.00f); ck_assert(p1.z() == 0.00f); p1.y(0.02f); ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.02f); ck_assert(p1.z() == 0.00f); p1.z(0.05f); ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.02f); ck_assert(p1.z() == 0.05f); p1.z(0.07f); ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.02f); ck_assert(p1.z() == 0.07f); p1.x_and_y_and_z(0.09f, 0.11f, 0.15f); ck_assert(p1.x() == 0.09f); ck_assert(p1.y() == 0.11f); ck_assert(p1.z() == 0.15f); opengl_math::point_3d<double> p2; p2.x(0.0); ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.0); ck_assert(p2.z() == 0.0); p2.y(0.5); ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.0); p2.z(0.7); ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.7); p2.x(0.1); ck_assert(p2.x() == 0.1); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.7); p2.x_and_y_and_z(0.1, 0.1, 0.1); ck_assert(p2.x() == 0.1); ck_assert(p2.y() == 0.1); ck_assert(p2.z() == 0.1); } END_TEST START_TEST(test_point_2d_get_reference) { opengl_math::point_2d<float> p1; p1.xref() = 1.0f; ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 0.0f); p1.yref() = 0.5f; ck_assert(p1.x() == 1.0f); ck_assert(p1.y() == 0.5f); p1.xref() = 0.2f; ck_assert(p1.x() == 0.2f); ck_assert(p1.y() == 0.5f); opengl_math::point_2d<double> p2; p2.xref() = 0.5; ck_assert(p2.x() == 0.5); ck_assert(p2.y() == 0.0); p2.yref() = 0.5; ck_assert(p2.x() == 0.5); ck_assert(p2.y() == 0.5); p2.yref() = 0.4; ck_assert(p2.x() == 0.5); ck_assert(p2.y() == 0.4); } END_TEST START_TEST(test_point_3d_get_reference) { opengl_math::point_3d<float> p1; p1.xref() = 0.01f; ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.00f); ck_assert(p1.z() == 0.00f); p1.yref() = 0.02f; ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.02f); ck_assert(p1.z() == 0.00f); p1.zref() = 0.05f; ck_assert(p1.x() == 0.01f); ck_assert(p1.y() == 0.02f); ck_assert(p1.z() == 0.05f); opengl_math::point_3d<double> p2; p2.xref() = 0.0; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.0); ck_assert(p2.z() == 0.0); p2.yref() = 0.5; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.0); p2.zref() = 0.7; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.7); p2.zref() = 0.1; ck_assert(p2.x() == 0.0); ck_assert(p2.y() == 0.5); ck_assert(p2.z() == 0.1); } END_TEST /*! \brief This is a test to if two points can be compared for equivalence */ START_TEST(test_equivalence_type_point_2d) { opengl_math::point_2d<float> p1; opengl_math::point_2d<float> p2; ck_assert(p1 == p2); p2.x_and_y(0.0001f, 1.000001f); ck_assert(p1 != p2); opengl_math::point_2d<float> p3(1.0f, 0.5f); opengl_math::point_2d<float> p4(1.0f, 0.5f); ck_assert(p3 == p4); p3.xref() = 0.0f; ck_assert(p3 != p4); } END_TEST START_TEST(test_equivalence_type_point_3d) { opengl_math::point_3d<float> p1; opengl_math::point_3d<float> p2; ck_assert(p1 == p2); p2.x_and_y_and_z(0.0001f, 1.000001f, 0.0f); ck_assert(p1 != p2); opengl_math::point_3d<float> p3(1.0f, 0.7f, 0.8f); opengl_math::point_3d<float> p4(1.0f, 0.7f, 0.8f); ck_assert(p3 == p4); p3.yref() = 0.6f; ck_assert(p3 != p4); } END_TEST START_TEST(test_extrenuous_type_point_usecases) { opengl_math::point_2d<float> p1(1.0f, 0.9f); // Convert the raw point to an array float *raw_data = &p1.xref(); ck_assert(raw_data[1] == 0.9f); raw_data[1] = 0.8f; ck_assert(raw_data[0] == 1.0f); ck_assert(raw_data[1] == 0.8f); // Check to see if it is POD opengl_math::point_3d<float> p2(1.0f, 1.0f, 0.9f); float point_array[3]; memcpy(point_array, &p2, sizeof(p2)); ck_assert(point_array[0] == 1.0f); ck_assert(point_array[1] == 1.0f); ck_assert(point_array[2] == 0.9f); } END_TEST START_TEST(test_type_point_get_dimension) { ck_assert(2 == opengl_math::point_2d<float>::dimension); ck_assert(2 == opengl_math::point_2d<double>::dimension); ck_assert(3 == opengl_math::point_3d<float>::dimension); ck_assert(3 == opengl_math::point_3d<double>::dimension); } END_TEST int main(int argc, char *argv[]) { Suite *s; SRunner *sr; TCase *tc; int result; s = suite_create("Unit Tests"); tc = tcase_create(__FILE__); tcase_add_test(tc, test_default_2d_point_constructor); tcase_add_test(tc, test_default_3d_point_constructor); tcase_add_test(tc, test_2d_point_constructor); tcase_add_test(tc, test_3d_point_constructor); tcase_add_test(tc, test_point_2d_copy_constructor); tcase_add_test(tc, test_point_3d_copy_constructor); tcase_add_test(tc, test_point_2d_assignment_operator); tcase_add_test(tc, test_point_3d_assignment_operator); tcase_add_test(tc, test_point_2d_setters); tcase_add_test(tc, test_point_3d_setters); tcase_add_test(tc, test_point_2d_get_reference); tcase_add_test(tc, test_point_3d_get_reference); tcase_add_test(tc, test_equivalence_type_point_2d); tcase_add_test(tc, test_equivalence_type_point_3d); tcase_add_test(tc, test_extrenuous_type_point_usecases); tcase_add_test(tc, test_type_point_get_dimension); suite_add_tcase(s, tc); sr = suite_runner_create(s); result = (run_and_report(sr) == 0) ? EXIT_SUCCESS : EXIT_FAILURE; return result; }
true
357ec2756321bd833c7ca2440162b616eee5fbe5
C++
renatocron/sdl-midian-game
/midian/sources/CFPS.cpp
UTF-8
387
2.515625
3
[]
no_license
#include "CFPS.h" CTimeControl::CTimeControl() { OldTime = 0; LastTime = 0; Frames = 0; NumFrames = 0; } void CTimeControl::OnLoop() { if(OldTime + 1000 < SDL_GetTicks()) { OldTime = SDL_GetTicks(); NumFrames = Frames; Frames = 0; } LastTime = SDL_GetTicks(); Frames++; } int CTimeControl::GetFPS() { return NumFrames; }
true
31f371dd16b2b70e47f87823c350a8352226ab8f
C++
songchaow/Algorithm-Labs
/Lab4/project1/source/graph.h
UTF-8
2,012
2.625
3
[]
no_license
#include <vector> #include <map> #include <fstream> using namespace std; struct EdgeNode; typedef struct GraphNode { int id_no; void* meta; EdgeNode* fedge; GraphNode* p; // used for root-tree int rank; // used for root-tree } GNode; typedef struct EdgeNode { GNode* pointee; EdgeNode* next; } ENode; class DirectedGraph; class DFSTool { private: enum Color { WHITE, GREY, BLACK }; public: typedef struct DFSData { int time_d; int time_f; Color color; void* p; // parent } DFSNodeRecord; private: // struct cmpByTime // // we customize the compare functor, so the nodes are inserted according to `time_f` in descending order. // { // bool operator()(pair<void*,DFSTool::DFSNodeRecord> const & a,pair<void*,DFSTool::DFSNodeRecord> const & b) const // { // return (a.second.time_f != b.second.time_f)? a.second.time_f > b.second.time_f : false; // } // }; map<void*,DFSNodeRecord> DFSResult; int time = 0; DirectedGraph& g; public: typedef map<void*,DFSNodeRecord> DFSState; DFSTool(DirectedGraph& g); void clear(); DFSState getDFSResult(); void DFSVisit(GNode* node); void DFS(); void reOrderedDFS(vector<GNode*>& node_list); }; class DirectedGraph { public: //DirectedGraph(const DirectedGraph&) = default; vector<GNode> pointlist; GNode* addNode(void* meta = nullptr); void addEdge(GNode* pointer, GNode* pointee); void makeSet(GNode* node, DFSTool::DFSState&& dfs_result); //abandoned GNode* findSet(GNode* node, DFSTool::DFSState& dfs_result); void link(GNode* node1, GNode* node2); // abandoned // void union_(GNode* node1, GNode* node2) // abandoned // { // link(findSet(node1),findSet(node2)); // } pair<DirectedGraph,map<GNode*,GNode*>> transpose(); void find_scc(ofstream &scc_output); protected: int curr_index = 1; };
true
661ddafb00f69b95028c25ca4840605cb6be5b3f
C++
ambitiousCC/Work-c
/work-c/上传区/git-c++/课后练习题/2.3.cpp
GB18030
400
3.296875
3
[]
no_license
/** * Author * Date 2019/3/21 * Version 1.0 * Function ȷһfootȻ */ #include <iostream> using namespace std; int main() { double num; cout<<"Enter a value for feet: "; cin>>num; double foot = 0.305; double feet = num * foot; cout<<num<<" feet is "<<feet<<" meters"<<endl; return 0; }
true
d86f9a44bce25903ee78101b8c4cb4f436fe0c82
C++
aeremenok/a-team-777
/09/oot/epa_labs/l2/src/other/IIterator.h
WINDOWS-1251
288
2.578125
3
[]
no_license
#ifndef _IITERATOR_H #define _IITERATOR_H // template <class T> class IIterator { public: virtual T* next() = 0; virtual T* first() = 0; virtual bool hasNext() = 0; virtual int getCount() = 0; }; #endif
true
0fe4e1744173ab509f75b38725f056e6a5d85b46
C++
creator83/stm8s003
/cpp/inc/tact.h
UTF-8
583
2.5625
3
[]
no_license
#include "stm8s.h" #ifndef TACT_H #define TACT_H class Tact { //variables public: enum src_tact {HSI,HSE}; //enum frq_tact {frq4, frq8, frq12 , frq16, frq20, frq24 ,frq28 , frq32 , frq36,frq40, frq44 , frq48}; private: static uint8_t f_cpu; uint8_t src; //functions public: Tact (uint8_t frq , src_tact s ); Tact (); Tact (src_tact s); static uint8_t & get_frq (){return f_cpu;}; void init_hsi (uint8_t mdiv=0, uint8_t cdiv=0); void init_hse (); void init_lsi (); void setHsiFrq (uint8_t mdiv=0, uint8_t cdiv=0); }; #endif
true
10f40f9810a785a86edd64ea1ca2b1a4c083d9f8
C++
xiao7540916/Re-Vulkan
/Source/VulkanBackend/VulkanBase/VulkanUtil.cpp
UTF-8
778
2.578125
3
[]
no_license
#include "VulkanUtil.h" #include <Horizon/Log/LogManager.h> namespace Horizon { void HandleVkErrorCode(VkResult result, const char* vkFuntion, const char* filename, uint32 line) { if (result > 0) { LOG_ERROR("Unexpected result. Code: {}.Function : {}.File : {}.Line : {}.", (int)result, vkFuntion, filename, line); } else { LOG_ERROR("Vulkan function returns a runtime error. Code: {}. Function: {}. File: {}. Line: {}.", (int)result, vkFuntion, filename, line); } } bool IsExtensionSupported(const char* name, const std::vector<VkExtensionProperties>& supportedExtensions) { for (const auto& supportedExtension : supportedExtensions) { if (strcmp(name, supportedExtension.extensionName) == 0) { return true; } } return false; } }
true
1a9a5b9e4cd6de5867722aced55fc8f2358b65c2
C++
scikit-ika/scikit-ika
/third_party/streamDM/streamDM/core/Instance.cpp
UTF-8
2,638
2.671875
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2015 Holmes Team at HUAWEI Noah's Ark Lab. * * 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 "Instance.h" #include <string> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sstream> #include <iostream> Instance::Instance() { weight = 1; this->instanceInformation = nullptr; this->instanceInformationSaved = false; } Instance::~Instance() { if (this->instanceInformationSaved && this->instanceInformation != nullptr) { delete this->instanceInformation; } } int Instance::getNumberClasses() const { return instanceInformation->getNumberClasses(); } Attribute* Instance::getInputAttribute(int index) const { return instanceInformation->getInputAttribute(index); } Attribute* Instance::getOutputAttribute(int index) { return instanceInformation->getOutputAttribute(index); } InstanceInformation* Instance::getInstanceInformation() const { return instanceInformation; } void Instance::setInstanceInformation(InstanceInformation* ii) { this->instanceInformationSaved = false; this->instanceInformation = ii; } void Instance::saveInstanceInformation(InstanceInformation* ii) { this->instanceInformationSaved = true; this->instanceInformation = ii->clone(); } double Instance::getLabel() const { return this->getOutputAttributeValue(0); } double Instance::getWeight() const { return weight; } void Instance::setWeight(double v) { weight = v; } int Instance::getNumberInputAttributes() const { return instanceInformation->getNumberInputAttributes(); } int Instance::getNumberOutputAttributes() const { return instanceInformation->getNumberOutputAttributes(); } void Instance::addValues(const vector<double>& values) { } void Instance::addLabels(const vector<double>& values) { } void Instance::setValue(int attIdx, double value) {} void Instance::setLabel(int attIdx, double label) {} Instance* cloneInstance(const Instance* s) { Instance* temp = (Instance*) s; return temp->clone(); } vector<double> Instance::getValues() { return {}; }
true