blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
cb61d9bac898537e5a4b256efe7ccdba87092066
a008d8eed53ca796b131fabf7ad35f27f182b2cc
/include/kdtree.h
354e750c7425aa3f4d3e29fc52a986117326478c
[]
no_license
luisclaudio26/renderer
a550a3880d5d7610a20190b852a9154c58f395be
a9aed5fdbf2e89abea17207e68509c23a5e378fb
refs/heads/master
2021-01-22T22:02:59.055753
2017-08-22T03:35:22
2017-08-22T03:35:22
85,500,576
1
0
null
null
null
null
UTF-8
C++
false
false
844
h
#ifndef KDTREE_H #define KDTREE_H #include <vector> #include "Primitives/primitive.h" #include "intersection.h" #include <stack> namespace Renderer { namespace Scene { using namespace Shapes; using namespace Geometry; class kdNode { public: AABB bbox; kdNode *r, *l; int axis; float t; std::vector<int> primNum; }; class kdTree { private: mutable bool tryBackfaceCulling; public: kdNode root; int maxDepth; std::vector<Primitive*> prim; kdTree() : maxDepth(-1), tryBackfaceCulling(false) {} void build(std::vector<Primitive*>&& prim); void hit(const Ray& r, Intersection& out, bool tryBackfaceCulling) const; void hit(const kdNode& n, const Ray& r, float tmin, float tmax, Intersection& out) const; private: void buildNode(kdNode& n, int depth = 0); }; } } #endif
[ "luisclaudiogouveiarocha@gmail.com" ]
luisclaudiogouveiarocha@gmail.com
9fe0ad292567a50f5258d363c1c8f4e0a4a2ae87
c5e19b8b076ae31befe1f6eb95b1a1919f80d5a4
/sketch_jun12a.ino
7180c017c201911b24554c7f064ccd14613da781
[]
no_license
j14007/raspberry
e37e34da0643fa2987a1417405e3eb9d417ff28f
b84b9feb8bab7e1c24ac2863f98ecee55962d5d8
refs/heads/master
2021-01-13T16:50:07.611874
2017-06-26T07:24:41
2017-06-26T07:24:41
95,075,358
0
0
null
null
null
null
UTF-8
C++
false
false
246
ino
int val = 0; void setup() { // put your setup code here, to run once: Serial.begin(57600); pinMode(13, OUTPUT); } void loop() { // put your main code here, to run repeatedly: val = analogRead(0); delay(420); Serial.println(val); }
[ "j14007@sangi.jp" ]
j14007@sangi.jp
67b7e078eb22ed69ef1fc432e7d9cca595a935f2
53d50ab7e5a6069f869aa8d78486a0878e7c4afb
/GameEngine/Shader.h
6f92cf7a9396f665236b4c8ba669a6f11a2f91e3
[]
no_license
adrset/schrod
8e67efb45d17d345d3cff9d09923e1e42a1d0f8b
e0d80a13b392ccd96c6f0acff9d9959e6b7dec27
refs/heads/master
2020-03-19T10:06:19.543846
2018-06-06T14:52:15
2018-06-06T14:52:15
136,343,482
1
0
null
null
null
null
UTF-8
C++
false
false
1,240
h
#ifndef SHADER_H #define SHADER_H #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <glad/glad.h> #include <glm/matrix.hpp> #include <glm/gtc/type_ptr.hpp> #include "errors.h" namespace GameEngine { class Shader { public: // the program ID unsigned int ID; // constructor reads and builds the shader Shader(const char* vertexPath, const char* fragmentPath); Shader(){ fprintf(stderr, "%s\n", "Creating empt shader!");} // use/activate the shader void use(); // utility uniform functions void setBool(const std::string &name, bool value) const; void setInt(const std::string &name, int value) const; void setFloat(const std::string &name, float value) const; void setMat4(const std::string &name, const glm::mat4 &mat) const; void setVec4(const std::string &name, const glm::vec4 &value) const; void setVec3(const std::string &name, const glm::vec3 &value) const; void setVec3(const std::string &name, float x, float y, float z) const; void setVec2(const std::string &name, const glm::vec2 &value) const; private: int getUniformLocation(const std::string uniform) const; void checkCompileErrors(unsigned int shader, std::string type); }; } #endif
[ "274433@pw.edu.pl" ]
274433@pw.edu.pl
01ef36b542710e26230b8d8072ea12b6deb125b6
942b7b337019aa52862bce84a782eab7111010b1
/xray/utils/xrAI/graph_engine_inline.h
3cdef1b883ecd6f2c3f910c0849061946d33544a
[]
no_license
galek/xray15
338ad7ac5b297e9e497e223e0fc4d050a4a78da8
015c654f721e0fbed1ba771d3c398c8fa46448d9
refs/heads/master
2021-11-23T12:01:32.800810
2020-01-10T15:52:45
2020-01-10T15:52:45
168,657,320
0
0
null
2019-02-01T07:11:02
2019-02-01T07:11:01
null
UTF-8
C++
false
false
4,722
h
//////////////////////////////////////////////////////////////////////////// // Module : graph_engine_inline.h // Created : 21.03.2002 // Modified : 03.03.2004 // Author : Dmitriy Iassenev // Description : Graph engine inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC CGraphEngine::CGraphEngine (u32 max_vertex_count) { m_algorithm = xr_new<CAlgorithm> (max_vertex_count); m_algorithm->data_storage().set_min_bucket_value (_dist_type(0)); m_algorithm->data_storage().set_max_bucket_value (_dist_type(2000)); #ifndef AI_COMPILER m_solver_algorithm = xr_new<CSolverAlgorithm> (16*1024); #endif // AI_COMPILER } IC CGraphEngine::~CGraphEngine () { xr_delete (m_algorithm); #ifndef AI_COMPILER xr_delete (m_solver_algorithm); #endif // AI_COMPILER } #ifndef AI_COMPILER IC const CGraphEngine::CSolverAlgorithm &CGraphEngine::solver_algorithm() const { return (*m_solver_algorithm); } #endif // AI_COMPILER template < typename _Graph, typename _Parameters > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, const _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif typedef CPathManager<_Graph, CAlgorithm::CDataStorage, _Parameters, _dist_type,_index_type,_iteration_type> CPathManagerGeneric; CPathManagerGeneric path_manager; path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } template < typename _Graph, typename _Parameters > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif typedef CPathManager<_Graph, CAlgorithm::CDataStorage, _Parameters, _dist_type,_index_type,_iteration_type> CPathManagerGeneric; CPathManagerGeneric path_manager; path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } template < typename _Graph, typename _Parameters, typename _PathManager > IC bool CGraphEngine::search ( const _Graph &graph, const _index_type &start_node, const _index_type &dest_node, xr_vector<_index_type> *node_path, const _Parameters &parameters, _PathManager &path_manager ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/search") #endif path_manager.setup ( &graph, &m_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } #ifndef AI_COMPILER template < typename T1, typename T2, typename T3, typename T4, typename T5, bool T6, typename T7, typename T8, typename _Parameters > IC bool CGraphEngine::search( const CProblemSolver< T1, T2, T3, T4, T5, T6, T7, T8 > &graph, const _solver_index_type &start_node, const _solver_index_type &dest_node, xr_vector<_solver_edge_type> *node_path, const _Parameters &parameters ) { #ifndef AI_COMPILER Statistic.AI_Path.Begin(); START_PROFILE("graph_engine") START_PROFILE("graph_engine/proble_solver") #endif typedef CProblemSolver<T1,T2,T3,T4,T5,T6,T7,T8> CSProblemSolver; typedef CPathManager<CSProblemSolver,CSolverAlgorithm::CDataStorage,_Parameters,_solver_dist_type,_solver_index_type,GraphEngineSpace::_iteration_type> CSolverPathManager; CSolverPathManager path_manager; path_manager.setup ( &graph, &m_solver_algorithm->data_storage(), node_path, start_node, dest_node, parameters ); bool successfull = m_solver_algorithm->find(path_manager); #ifndef AI_COMPILER Statistic.AI_Path.End(); #endif return (successfull); #ifndef AI_COMPILER STOP_PROFILE STOP_PROFILE #endif } #endif // AI_COMPILER
[ "abramcumner@yandex.ru" ]
abramcumner@yandex.ru
80b89e43a0c094a1a26fd19dd782cac57ae86c0d
d747ba6a8c1255adda08d1681a5e72dba844b83d
/Magik Carpet/Hailey.h
b4cff05081425f54eaf0e03a877e236ac490aeb4
[]
no_license
AshleyFitness/Magik-CarpetMadeByArca
bd234bf54be655794d736d7480b41b7e68f1b516
a52ead687c8331bf3377add51912ca50faf57feb
refs/heads/master
2020-12-02T18:54:23.171785
2019-12-31T13:19:40
2019-12-31T13:19:40
231,089,101
0
0
null
null
null
null
UTF-8
C++
false
false
578
h
#pragma once #include "Personnage.h" class Hailey : public Personnage { public: void SummonTree(Personnage& cible); Hailey(std::string nom,int vie,int love,int level,int xp); ~Hailey(); void afficherEtat2() const; void Compliment(Personnage& cible) const; void Joke(Personnage& cible) const; void DrawingDogMenu() const; void LevelUp(); void Spare(Personnage &cible) const; void GetXpCustom(int XP); void DrawingNavaRobotMenu() const; void HPlifeLimit(); void DrawingRabbitMenu() const; void DrawingRustyRobot() const; private: int m_level = 1; int m_xp = 0; };
[ "57031701+AshleyFitness@users.noreply.github.com" ]
57031701+AshleyFitness@users.noreply.github.com
94ee972494c90b4f8891e71d0447a8ec3dd0b428
857ad2a52e2df470d8728815e79d7a6502d0b741
/lib/Timer/Timer.h
714720d3bffcfe2d6fb6035df5ba36807b1c81ca
[]
no_license
BriBan2-afk/Social-Distance-Device
bc05c92ce18fc900cf0803fff53da48ea7cfc3c3
2dea4aa74dea0bc5eafe2cfbd02469b866f7f9af
refs/heads/main
2023-06-13T03:10:30.237369
2021-06-23T18:29:01
2021-06-23T18:29:01
376,034,541
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
#ifndef TIMER_H #define TIMER_H #include <Arduino.h> #endif class Timer { unsigned long previousMillis; public: Timer(); bool timer (unsigned long interval); uint32_t timeIt (uint32_t prev); };
[ "banziebright2@gmail.com" ]
banziebright2@gmail.com
e252637543b25d0b952002080ddcf88bb91f7c2f
4bf2c33b5d25dc73e89a2a06c73cb3b2a911bee6
/smartweddingreception2A4/bague.cpp
10f7c8d042d359f3a364899e3bc00f9865caa659
[]
no_license
HaythemBenMechichi/smart_wedding_reception_2A4
ee15ec7271681935fb8407fb79e13851773cc2b4
07b7f88ecf532a5ac85df031321d06da05248666
refs/heads/master
2023-02-13T04:19:52.350588
2020-12-02T07:29:55
2020-12-02T07:29:55
316,033,206
1
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
#include "bague.h" bague::bague() { } bague::bague(int idb,QString nom,QString commentaire,int prix) { this->nom=nom; this->commentaire=commentaire; this->idb=idb; this->prix=prix; } bool bague::ajouter() { QSqlQuery query; query.prepare("insert into bague(nom,commentaire,idb,prix)" "values(:nom,:commentaire,:idb,:prix)"); query.bindValue(":nom",nom); query.bindValue(":commentaire",commentaire); query.bindValue(":idb",idb); query.bindValue(":prix",prix); return query.exec(); } bool bague::supprimer(QString nom) { QSqlQuery query; query.prepare("Delete from bague where nom= :nom"); query.bindValue(":nom",nom); return query.exec(); } QSqlQueryModel * bague::afficher() { QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * where nom= :nom from bague"); model->setHeaderData(0,Qt::Vertical,QObject::tr("nom")); model->setHeaderData(1,Qt::Vertical,QObject::tr("commentaire")); model->setHeaderData(2,Qt::Vertical,QObject::tr("prix")); return model; } /*bool bague::update() { QSqlQuery query; query.prepare("insert into bague where nom= :nom nom,commentaire,prix)" "values(:nom,:commentaire,:prix)"); query.bindValue(":nom",nom); query.bindValue(":commentaire",commentaire); query.bindValue(":prix",prix); return query.exec(); }*/
[ "youssefriahi63@yahoo.fr" ]
youssefriahi63@yahoo.fr
4f225436cdef6c1c1a0ac8a7d5b36de236b3b7c7
6693c202f4aa960b05d7dfd0ac8e19a0d1199a16
/COJ/eliogovea-cojAC/eliogovea-p2695-Accepted-s642467.cpp
6e19b75dbac28b0da694e9e80dd725a43d29f012
[]
no_license
eliogovea/solutions_cp
001cf73566ee819990065ea054e5f110d3187777
088e45dc48bfb4d06be8a03f4b38e9211a5039df
refs/heads/master
2020-09-11T11:13:47.691359
2019-11-17T19:30:57
2019-11-17T19:30:57
222,045,090
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
#include <iostream> #include <vector> //#include <fstream> using namespace std; int n, k; vector<int> v[25]; string str; vector<int> func(const string &s) { int i = 1, num = 0; bool menos = false; vector<int> r; r.clear(); for (int i = 0; s[i]; i++) { if (s[i] == '{') continue; if (s[i] == ',' || s[i] == '}') { if (menos) num = -num; r.push_back(num); num = 0; menos = false; } else if (s[i] == '-') menos = true; else num = 10 * num + s[i] - '0'; } return r; } int main() { ios::sync_with_stdio(false); //freopen("e.in", "r", stdin); cin >> n; while (n--) { cin >> k; int len = -1; bool sol = true; for (int i = 0; i < k; i++) { v[i].clear(); cin >> str; if (!sol) continue; v[i] = func(str); if (len == -1) len = v[i].size(); else if (len != v[i].size()) sol = false; } if (sol) { cout << '{'; for (int i = 0; i < len; i++) { int tmp = 0; for (int j = 0; j < k; j++) tmp += v[j][i]; cout << tmp; if (i < len - 1) cout << ','; } cout << "}\n"; } else cout << "No solution\n"; } }
[ "eliogovea1993@gmail.com" ]
eliogovea1993@gmail.com
e1a825ac914dec9edf1b1e361754bc165abc1baf
e0c8293982efe9b606cd256480f41bbc1db6a40b
/SketcherDoc.h
bc2de8bd250b9f14f12ecac2e0887329c45c4f72
[ "MIT" ]
permissive
chen0040/mfc-npr-interactive-ant-sketch
91a8962b6853dcbb2c50ed183cb7d6c3bbc20b84
e26d989efd3c72799dd13f153170585e640c5523
refs/heads/master
2021-01-01T17:06:32.070437
2017-07-22T00:57:44
2017-07-22T00:57:44
97,997,120
2
0
null
null
null
null
UTF-8
C++
false
false
1,603
h
// SketcherDoc.h : interface of the CSketcherDoc class // #pragma once #include "SketcherEngine.h" #include "AntColony.h" #include "AntColonyConfiguration.h" class CSketcherDoc : public CDocument { protected: // create from serialization only CSketcherDoc(); DECLARE_DYNCREATE(CSketcherDoc) // Attributes public: // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CSketcherDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() SketcherEngine m_sketcher; AntColony m_colony; AntColonyConfiguration m_configuration; BOOL m_bRedrawCanvas; public: bool Load(LPCTSTR pFileName); void Display(CDC* pDC, const CRect& rect); void OnImageDisplaysource(); afx_msg void OnSketcherSaveimage(); afx_msg void OnUpdateSketcherSaveimage(CCmdUI *pCmdUI); afx_msg void OnUpdateImageDisplaysource(CCmdUI *pCmdUI); void OnImageDisplaygradientmap(void); afx_msg void OnUpdateImageDisplaygradientmap(CCmdUI *pCmdUI); void OnImageDisplayluminancemap(void); afx_msg void OnUpdateImageDisplayluminancemap(CCmdUI *pCmdUI); void OnImageDisplaycanvas(void); afx_msg void OnUpdateImageDisplaycanvas(CCmdUI *pCmdUI); void OnSketcherSketch(void); afx_msg void OnUpdateSketcherSketch(CCmdUI *pCmdUI); afx_msg void OnSketcherOptions(); afx_msg void OnSketcherClearcanvas(); afx_msg void OnSketcherBatchrun(); afx_msg void OnUpdateSketcherBatchrun(CCmdUI *pCmdUI); };
[ "xs0040@gmail.com" ]
xs0040@gmail.com
daaa82d00057ee6efe55790bef415791a9a9188b
6870ea7fa607e314737ed7e814f22537eeb0fd0f
/Binary tree/Inorder_traversal_to_specialtree_conversion.cpp
dc95594761f36a4098a0c79ead0f4cf49ad6bd36
[]
no_license
ranjansingh119/Programming-source-code
e65b332d602a45574899d61097a46e220a67e7f2
2029be1e38f6634d287b5901ebf17e65a46fde0c
refs/heads/master
2021-01-20T20:05:24.914852
2016-06-20T18:09:52
2016-06-20T18:09:52
46,512,213
0
0
null
null
null
null
UTF-8
C++
false
false
1,457
cpp
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; struct tnode{ int data; struct tnode* left; struct tnode* right; }; struct tnode* newnode(int data); int maximum(int array[], int s, int last); struct tnode* create_special_tree(int arr[], int start, int end){ if(start>end) return NULL; int max_element_index = maximum(arr, start, end); struct tnode* root = newnode(arr[max_element_index]); if(start==end) return root; root->left = create_special_tree(arr, start, max_element_index-1); root->right = create_special_tree(arr, max_element_index+1, end); return root; } int maximum(int array[], int s, int last){ int max = array[s]; int max_index = s; for(int i=s+1; i<=last; i++){ if(array[i]>max){ max = array[i]; max_index = i; } } return max_index; } struct tnode* newnode(int data){ struct tnode* new_node = (struct tnode*) malloc (sizeof(struct tnode)); new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } void inorder_display(struct tnode* root){ if(root==NULL){ return; } inorder_display(root->left); cout<<root->data<<" "; inorder_display(root->right); } int main(){ int arr[] = {5, 10, 40, 30, 28}; int size = sizeof(arr)/ sizeof(arr[0]); struct tnode* root = create_special_tree(arr, 0, size-1); cout<<"The inorder traversal of the given tree :"<<endl; inorder_display(root); return 0; }
[ "ranjansingh119@gmail.com" ]
ranjansingh119@gmail.com
8c2ca5c460924b0a2242cf86395876a5eea9cfc7
b41db21e54e088200157105345070f01e9557ced
/AtCoderRegularContest/37/b.cpp
f208f0f833ccbc330a0fc640f134540ff09e0a78
[]
no_license
tsugupoyo/AtCoder
e6ce8692e133028264eb8f85f765d988306feb97
3b1cd63097c47bf039de87f943346fc0d787cc83
refs/heads/main
2023-06-02T06:40:34.981731
2021-06-21T02:56:36
2021-06-21T02:56:36
378,789,517
0
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; using P = pair<int,int>; #define rep(i,n) for(int i=0;i<(int)(n);i++) const int INF =1001001001; bool graph[100][100]; bool visit[100]; int n, m; bool ok; void dfs(int v, int prev) { visit[v] = true; if(prev != -1){ } rep(i,n) { if(graph[v][i] == false) continue; if(visit[i]) { if(i != prev) ok = false; continue; } dfs(i,v); } } int main() { cin >> n >> m; rep(i, m) { int a, b; cin >> a >> b; --a;--b; graph[a][b] = true; graph[b][a] = true; } int ans =0; rep(i,n) { if(visit[i]) continue; ok = true; dfs(i, -1); if(ok) ans++; } cout << ans << endl; }
[ "fujiwaratakatsugu@fujiwaratakashinoMacBook-puro.local" ]
fujiwaratakatsugu@fujiwaratakashinoMacBook-puro.local
4251d2c397175e1e2765ad7e52fe775e74da13ed
66904d7443fa6eacbd990facd0bd1c5908d89be0
/parser/header/program.h
a287698296703bdc7395f0e4661d37801280280f
[]
no_license
birgizz/regxparser
b9dc7862125c213b65fc6e6b6755d62666a91899
e18a523f542062340aa7812851f5c501466caed7
refs/heads/master
2020-07-10T12:47:24.651328
2019-08-25T08:18:54
2019-08-25T08:18:54
204,265,943
0
0
null
null
null
null
UTF-8
C++
false
false
983
h
#ifndef PROGRAM_H #define PROGRAM_H #include <iostream> #include "op.h" #include <string> extern std::vector<std::string> captures; extern std::string capture; struct program : op { std::string _id; bool eval(it &begin, it &end) override{ auto original_begin = begin; auto original_end = begin; while(begin != end){ auto current_begin = begin; if(operands[0]->eval(current_begin, end)){ if(operands[0]->id() == "OUT"){ std::cout << captures[std::stoi(capture)] << std::endl; } else if(operands[0]->id() == "EXPR") { std::cout << std::string(begin,current_begin) << std::endl; } return true; } begin++; } std::cout << "false" << std::endl; return false; } std::string id() override{ return "PROGRAM"; } }; #endif /* PROGRAM_H */
[ "birger.oberg@gmail.com" ]
birger.oberg@gmail.com
6b3baeeca3ca9a3602a9e203e66fdfea080683cb
494fc35b2dbe5705bdf81e6b5d2615d1198c8559
/Mu2eG4/inc/nestPolyhedra.hh
7e1854e300006ff28fdfe2f47eee5fafe6198f2a
[ "Apache-2.0" ]
permissive
shadowbehindthebread/Offline
36f71913ac789b9381db5143b0fc0bd7349c155e
57b5055641a4c626a695f3d83237c79758956b6a
refs/heads/master
2022-11-05T17:44:25.761755
2020-06-15T18:07:16
2020-06-15T18:07:16
273,599,835
1
0
Apache-2.0
2020-06-19T22:48:25
2020-06-19T22:48:24
null
UTF-8
C++
false
false
1,921
hh
#ifndef Mu2eG4_nestPolyhedra_hh #define Mu2eG4_nestPolyhedra_hh // // Free function to create and place a new G4Polyhedra, place inside a logical volume. // // $Id: nestPolyhedra.hh,v 1.3 2014/09/19 19:14:55 knoepfel Exp $ // $Author: knoepfel $ // $Date: 2014/09/19 19:14:55 $ // // Original author Rob Kutschke // #include <string> #include <vector> #include "G4Helper/inc/VolumeInfo.hh" class G4CSGSolid; class G4LogicalVolume; class G4Material; class G4VPhysicalVolume; // G4 includes #include "G4Polyhedra.hh" #include "G4Colour.hh" #include "G4RotationMatrix.hh" #include "G4ThreeVector.hh" namespace mu2e { class Polyhedra; class PolyhedraParams; VolumeInfo nestPolyhedra ( std::string const& name, PolyhedraParams const & polyObj, G4Material* material, G4RotationMatrix const* rot, G4ThreeVector const & offset, VolumeInfo const & parent, int copyNo, bool const isVisible, G4Colour const color, bool const forceSolid, bool const forceAuxEdgeVisible, bool const placePV, bool const doSurfaceCheck ); VolumeInfo nestPolyhedra ( std::string const& name, PolyhedraParams const & polyObj, G4Material* material, G4RotationMatrix const* rot, G4ThreeVector const & offset, VolumeInfo const & parent, int copyNo, G4Colour const color, std::string const& lookupToken ); } #endif /* Mu2eG4_nestPolyhedra_hh */
[ "david.brown@louisville.edu" ]
david.brown@louisville.edu
1838471a6af62b44930c1a1379f6c703e74261c2
1786f51414ac5919b4a80c7858e11f7eb12cb1a9
/USST/UF9div3/E.cpp
15af7f6a8d57cb6560f9f580eddfe02408e0b04b
[]
no_license
SetsunaChyan/OI_source_code
206c4d7a0d2587a4d09beeeb185765bca0948f27
bb484131e02467cdccd6456ea1ecb17a72f6e3f6
refs/heads/master
2020-04-06T21:42:44.429553
2019-12-02T09:18:54
2019-12-02T09:18:54
157,811,588
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
cpp
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> pii; char s[10][10]; int l,qaq[10][10][10],ans; void bfs() { queue<pii> q; q.emplace(0,0); while(!q.empty()) { pii p=q.front();q.pop(); if(p.second==8) { ans=1; return; } if(p.first&&qaq[p.second+1][7][p.first-1]==0&&qaq[p.second][7][p.first-1]==0) q.emplace(p.first-1,p.second+1); if(qaq[p.second+1][7][p.first]==0&&qaq[p.second][7][p.first]==0) q.emplace(p.first,p.second+1); if(p.first<7&&qaq[p.second+1][7][p.first+1]==0&&qaq[p.second][7][p.first+1]==0) q.emplace(p.first+1,p.second+1); } } int main() { for(int i=0;i<8;i++) scanf("%s",s[i]); for(int i=0;i<8;i++) for(int j=0;j<8;j++) if(s[i][j]=='S') qaq[0][i][j]=1; for(int i=1;i<9;i++) for(int j=1;j<8;j++) for(int k=0;k<8;k++) if(qaq[i-1][j-1][k]) qaq[i][j][k]=1; bfs(); if(ans) printf("WIN"); else printf("LOSE"); return 0; }
[ "ctzguozi@163.com" ]
ctzguozi@163.com
38efcb5a7064e60f0157f8a2a3cf9010dab0bc1b
b2fd89d5d9fecf54ff8fd9cf4405339e54840315
/Source/MyProject2/BPLib.h
868a02b10b3b8806f7cb1b8ecf9b65114ba82108
[]
no_license
ethosium/MyProject2
0454627d1187dd6bfbcf59377669f070418ec9bd
313aad2b31156385b0b0b95ed9170d04b077321e
refs/heads/master
2021-01-18T22:15:54.619793
2016-01-15T00:33:46
2016-01-15T00:33:46
49,684,227
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Kismet/BlueprintFunctionLibrary.h" #include "BPLib.generated.h" /** * */ UCLASS() class MYPROJECT2_API UBPLib : public UBlueprintFunctionLibrary { public: GENERATED_BODY() UFUNCTION(BlueprintCallable, meta = (FriendlyName = "md5", CompactNodeTitle = "md5", Keywords = "md5"), Category = Crypto) static FString md5(FString s); };
[ "ethosium@gmail.com" ]
ethosium@gmail.com
65bd002eba5760fb3eed8e448c9426d54f57bc5f
8134e49b7c40c1a489de2cd4e7b8855f328b0fac
/3rdparty/libbitcoin/include/bitcoin/bitcoin/message/get_blocks.hpp
5131c6e04c3eb07338b250da839787b0cc1455b5
[ "Apache-2.0" ]
permissive
BeamMW/beam
3efa193b22965397da26c1af2aebb2c045194d4d
956a71ad4fedc5130cbbbced4359d38534f8a7a5
refs/heads/master
2023-09-01T12:00:09.204471
2023-08-31T09:22:40
2023-08-31T09:22:40
125,412,400
671
233
Apache-2.0
2023-08-18T12:47:41
2018-03-15T18:49:06
C++
UTF-8
C++
false
false
3,206
hpp
/** * Copyright (c) 2011-2017 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_MESSAGE_GET_BLOCKS_HPP #define LIBBITCOIN_MESSAGE_GET_BLOCKS_HPP #include <istream> #include <memory> #include <string> #include <vector> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/math/hash.hpp> #include <bitcoin/bitcoin/utility/data.hpp> #include <bitcoin/bitcoin/utility/reader.hpp> #include <bitcoin/bitcoin/utility/writer.hpp> namespace libbitcoin { namespace message { class BC_API get_blocks { public: typedef std::shared_ptr<get_blocks> ptr; typedef std::shared_ptr<const get_blocks> const_ptr; static get_blocks factory_from_data(uint32_t version, const data_chunk& data); static get_blocks factory_from_data(uint32_t version, std::istream& stream); static get_blocks factory_from_data(uint32_t version, reader& source); get_blocks(); get_blocks(const hash_list& start, const hash_digest& stop); get_blocks(hash_list&& start, hash_digest&& stop); get_blocks(const get_blocks& other); get_blocks(get_blocks&& other); hash_list& start_hashes(); const hash_list& start_hashes() const; void set_start_hashes(const hash_list& value); void set_start_hashes(hash_list&& value); hash_digest& stop_hash(); const hash_digest& stop_hash() const; void set_stop_hash(const hash_digest& value); void set_stop_hash(hash_digest&& value); virtual bool from_data(uint32_t version, const data_chunk& data); virtual bool from_data(uint32_t version, std::istream& stream); virtual bool from_data(uint32_t version, reader& source); data_chunk to_data(uint32_t version) const; void to_data(uint32_t version, std::ostream& stream) const; void to_data(uint32_t version, writer& sink) const; bool is_valid() const; void reset(); size_t serialized_size(uint32_t version) const; // This class is move assignable but not copy assignable. get_blocks& operator=(get_blocks&& other); void operator=(const get_blocks&) = delete; bool operator==(const get_blocks& other) const; bool operator!=(const get_blocks& other) const; static const std::string command; static const uint32_t version_minimum; static const uint32_t version_maximum; private: // 10 sequential hashes, then exponential samples until reaching genesis. hash_list start_hashes_; hash_digest stop_hash_; }; } // namespace message } // namespace libbitcoin #endif
[ "strylets@gmail.com" ]
strylets@gmail.com
e521b7282ed0e84ac7a35dd95e418ac737778a00
a22d607128a696c652f47c8f98dc83fb0b541a1d
/contest 7 dslk va ngan xep/8.cpp
ea193fe9749628d4935d8b26d7c0bfb8ebc6ba4e
[]
no_license
nguyenvanhieu99/giai-thuat-
e4c4934a1eb35584b337130c80c2903ea647648d
917dcd507548a6d42eafd9f6341dcde13454a098
refs/heads/master
2022-12-24T07:47:30.319207
2020-10-01T15:00:41
2020-10-01T15:00:41
285,477,500
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
#include<iostream> #include<algorithm> //#include<bits/stdc++.h> #include<stack> using namespace std; char *chuan(string s){ int n=s.length(); int ind=0; char *t=new char(n); stack <int>a; a.push(0); for(int i=0;i<n;i++){ if(s[i]=='+'){ if(a.top()==1) t[ind++]='-'; if(a.top()==0) t[ind++]='+'; } else if(s[i]=='-'){ if(a.top()== 1 ) t[ind++]='+'; if(a.top()== 0 ) t[ind++]='-'; } else if(s[i]=='('&&i>0){ if(s[i-1]=='-'){ int x=(a.top()==1)?0:1; a.push(x); } else if(s[i-1]=='+') a.push(a.top()); } else if(s[i]==')'){ a.pop(); } else t[ind++]=s[i]; } return t; } int main(){ int bo;cin>>bo; string s; cin.ignore(); while(bo--){ getline(cin,s); cout<<chuan(s)<<endl; } return 0; }
[ "nvhieu.dev@gmail.com" ]
nvhieu.dev@gmail.com
b32cc1aeeaeebb862ccad4a74dc623496c7210bc
7446fede2d71cdb7c578fe60a894645e70791953
/src/masternode.cpp
c7fe3d439b3653940c1d911f30bc5d206434d1f5
[ "MIT" ]
permissive
ondori-project/rstr
23522833c6e28e03122d40ba663c0024677d05c9
9b3a2ef39ab0f72e8efffee257b2eccc00054b38
refs/heads/master
2021-07-12T18:03:23.480909
2019-02-25T17:51:46
2019-02-25T17:51:46
149,688,410
2
3
MIT
2019-02-14T02:19:49
2018-09-21T00:44:03
C++
UTF-8
C++
false
false
30,519
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2015-2018 The RSTR developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode.h" #include "addrman.h" #include "masternodeman.h" #include "obfuscation.h" #include "sync.h" #include "util.h" #include <boost/lexical_cast.hpp> // keep track of the scanning errors I've seen map<uint256, int> mapSeenMasternodeScanningErrors; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { if (chainActive.Tip() == NULL) return false; if (nBlockHeight == 0) nBlockHeight = chainActive.Tip()->nHeight; if (mapCacheBlockHashes.count(nBlockHeight)) { hash = mapCacheBlockHashes[nBlockHeight]; return true; } const CBlockIndex* BlockLastSolved = chainActive.Tip(); const CBlockIndex* BlockReading = chainActive.Tip(); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight) return false; int nBlocksAgo = 0; if (nBlockHeight > 0) nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight; assert(nBlocksAgo >= 0); int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nBlocksAgo) { hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } CMasternode::CMasternode() { LOCK(cs); vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternode& other) { LOCK(cs); vin = other.vin; addr = other.addr; pubKeyCollateralAddress = other.pubKeyCollateralAddress; pubKeyMasternode = other.pubKeyMasternode; sig = other.sig; activeState = other.activeState; sigTime = other.sigTime; lastPing = other.lastPing; cacheInputAge = other.cacheInputAge; cacheInputAgeBlock = other.cacheInputAgeBlock; unitTest = other.unitTest; allowFreeTx = other.allowFreeTx; nActiveState = MASTERNODE_ENABLED, protocolVersion = other.protocolVersion; nLastDsq = other.nLastDsq; nScanningErrorCount = other.nScanningErrorCount; nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight; lastTimeChecked = 0; nLastDsee = other.nLastDsee; // temporary, do not save. Remove after migration to v12 nLastDseep = other.nLastDseep; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternodeBroadcast& mnb) { LOCK(cs); vin = mnb.vin; addr = mnb.addr; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; pubKeyMasternode = mnb.pubKeyMasternode; sig = mnb.sig; activeState = MASTERNODE_ENABLED; sigTime = mnb.sigTime; lastPing = mnb.lastPing; cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = mnb.protocolVersion; nLastDsq = mnb.nLastDsq; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } // // When a new masternode broadcast is sent, update our information // bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb) { if (mnb.sigTime > sigTime) { pubKeyMasternode = mnb.pubKeyMasternode; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; sigTime = mnb.sigTime; sig = mnb.sig; protocolVersion = mnb.protocolVersion; addr = mnb.addr; lastTimeChecked = 0; int nDoS = 0; if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = mnb.lastPing; mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing)); } return true; } return false; } // // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight) { if (chainActive.Tip() == NULL) return 0; uint256 hash = 0; uint256 aux = vin.prevout.hash + vin.prevout.n; if (!GetBlockHash(hash, nBlockHeight)) { LogPrint("masternode","CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return 0; } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } void CMasternode::Check(bool forceCheck) { if (ShutdownRequested()) return; if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return; lastTimeChecked = GetTime(); //once spent, stop doing the checks if (activeState == MASTERNODE_VIN_SPENT) return; if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) { activeState = MASTERNODE_REMOVE; return; } if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { activeState = MASTERNODE_EXPIRED; return; } if(lastPing.sigTime - sigTime < MASTERNODE_MIN_MNP_SECONDS){ activeState = MASTERNODE_PRE_ENABLED; return; } if (!unitTest) { CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut(4999.99 * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { activeState = MASTERNODE_VIN_SPENT; return; } } } activeState = MASTERNODE_ENABLED; // OK } int64_t CMasternode::SecondsSincePayment() { CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); int64_t sec = (GetAdjustedTime() - GetLastPaid()); int64_t month = 60 * 60 * 24 * 30; if (sec < month) return sec; //if it's less than 30 days, give seconds CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // return some deterministic value for unknown/unpaid but force it to be more than 30 days old return month + hash.GetCompact(false); } int64_t CMasternode::GetLastPaid() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return false; CScript mnpayee; mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // use a deterministic offset to break a tie -- 2.5 minutes int64_t nOffset = hash.GetCompact(false) % 150; if (chainActive.Tip() == NULL) return false; const CBlockIndex* BlockReading = chainActive.Tip(); int nMnCount = mnodeman.CountEnabled() * 1.25; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nMnCount) { return 0; } n++; if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) { /* Search for this payee, with at least 2 votes. This will aid in consensus allowing the network to converge on the same payees quickly, then keep the same schedule. */ if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { return BlockReading->nTime + nOffset; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return 0; } std::string CMasternode::GetStatus() { switch (nActiveState) { case CMasternode::MASTERNODE_PRE_ENABLED: return "PRE_ENABLED"; case CMasternode::MASTERNODE_ENABLED: return "ENABLED"; case CMasternode::MASTERNODE_EXPIRED: return "EXPIRED"; case CMasternode::MASTERNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case CMasternode::MASTERNODE_REMOVE: return "REMOVE"; case CMasternode::MASTERNODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED"; case CMasternode::MASTERNODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } bool CMasternode::IsValidNetAddr() { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkID() == CBaseChainParams::REGTEST || (IsReachable(addr) && addr.IsRoutable()); } CMasternodeBroadcast::CMasternodeBroadcast() { vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode1 = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int protocolVersionIn) { vin = newVin; addr = newAddr; pubKeyCollateralAddress = pubKeyCollateralAddressNew; pubKeyMasternode = pubKeyMasternodeNew; sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = protocolVersionIn; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn) { vin = mn.vin; addr = mn.addr; pubKeyCollateralAddress = mn.pubKeyCollateralAddress; pubKeyMasternode = mn.pubKeyMasternode; sig = mn.sig; activeState = mn.activeState; sigTime = mn.sigTime; lastPing = mn.lastPing; cacheInputAge = mn.cacheInputAge; cacheInputAgeBlock = mn.cacheInputAgeBlock; unitTest = mn.unitTest; allowFreeTx = mn.allowFreeTx; protocolVersion = mn.protocolVersion; nLastDsq = mn.nLastDsq; nScanningErrorCount = mn.nScanningErrorCount; nLastScanningErrorBlockHeight = mn.nLastScanningErrorBlockHeight; } bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline) { CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyMasternodeNew; CKey keyMasternodeNew; //need correct blocks to send ping if (!fOffline && !masternodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode"; LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!obfuScationSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } // The service needs the correct default port to work properly if(!CheckDefaultPort(strService, strErrorRet, "CMasternodeBroadcast::Create")) return false; return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet); } bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyMasternodeNew.GetID().ToString()); CMasternodePing mnp(txin); if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION); if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address %s, masternode=%s", mnbRet.addr.ToStringIP (), txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } return true; } bool CMasternodeBroadcast::CheckDefaultPort(std::string strService, std::string& strErrorRet, std::string strContext) { CService service = CService(strService); int nDefaultPort = Params().GetDefaultPort(); if (service.GetPort() != nDefaultPort) { strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on %s-net.", service.GetPort(), strService, nDefaultPort, Params().NetworkIDString()); LogPrint("masternode", "%s - %s\n", strContext, strErrorRet); return false; } return true; } bool CMasternodeBroadcast::CheckAndUpdate(int& nDos) { // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","mnb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } // incorrect ping or its sigTime if(lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDos, false, true)) return false; if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) { LogPrint("masternode","mnb - ignoring outdated Masternode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrint("masternode","mnb - pubkey the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID()); if (pubkeyScript2.size() != 25) { LogPrint("masternode","mnb - pubkey2 the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrint("masternode","mnb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString()); return false; } std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetNewStrMessage(), errorMessage) && !obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetOldStrMessage(), errorMessage)) { // don't ban for old masternodes, their sigs could be broken because of the bug nDos = protocolVersion < MIN_PEER_MNANNOUNCE ? 0 : 100; return error("CMasternodeBroadcast::CheckAndUpdate - Got bad Masternode address signature : %s", errorMessage); } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (addr.GetPort() != 22620) return false; } else if (addr.GetPort() == 22620) return false; //search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts CMasternode* pmn = mnodeman.Find(vin); // no such masternode, nothing to update if (pmn == NULL) return true; // this broadcast is older or equal than the one that we already have - it's bad and should never happen // unless someone is doing something fishy // (mapSeenMasternodeBroadcast in CMasternodeMan::ProcessMessage should filter legit duplicates) if(pmn->sigTime >= sigTime) { return error("CMasternodeBroadcast::CheckAndUpdate - Bad sigTime %d for Masternode %20s %105s (existing broadcast is at %d)", sigTime, addr.ToString(), vin.ToString(), pmn->sigTime); } // masternode is not enabled yet/already, nothing to update if (!pmn->IsEnabled()) return true; // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if (pmn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) { //take the newest entry LogPrint("masternode","mnb - Got updated entry for %s\n", vin.prevout.hash.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); if (pmn->IsEnabled()) Relay(); } masternodeSync.AddedMasternodeList(GetHash()); } return true; } bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS) { // we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us if (fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode) return true; // incorrect ping or its sigTime if(lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDoS, false, true)) return false; // search existing Masternode list CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { // nothing to do here if we already know about this masternode and it's enabled if (pmn->IsEnabled()) return true; // if it's not enabled, remove old MN first and continue else mnodeman.Remove(pmn->vin); } CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut(4999.99 * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { //set nDos state.IsInvalid(nDoS); return false; } } LogPrint("masternode", "mnb - Accepted Masternode entry\n"); if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) { LogPrint("masternode","mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } // verify that sig time is legit in past // should be at least not earlier than block when 25000 RST tx got MASTERNODE_MIN_CONFIRMATIONS uint256 hashBlock = 0; CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, hashBlock, true); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pMNIndex = (*mi).second; // block for 1000 RSTR tx -> 1 confirmation CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS if (pConfIndex->GetBlockTime() > sigTime) { LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\n", sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime()); return false; } } LogPrint("masternode","mnb - Got NEW Masternode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime); CMasternode mn(*this); mnodeman.Add(mn); // if it matches our Masternode privkey, then we've been remotely activated if (pubKeyMasternode == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) { activeMasternode.EnableHotColdMasterNode(vin, addr); } bool isLocal = addr.IsRFC1918() || addr.IsLocal(); if (Params().NetworkID() == CBaseChainParams::REGTEST) isLocal = false; if (!isLocal) Relay(); return true; } void CMasternodeBroadcast::Relay() { CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash()); RelayInv(inv); } bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress) { std::string errorMessage; sigTime = GetAdjustedTime(); std::string strMessage; if(chainActive.Height() < Params().Zerocoin_Block_V2_Start()) strMessage = GetOldStrMessage(); else strMessage = GetNewStrMessage(); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) return error("CMasternodeBroadcast::Sign() - Error: %s", errorMessage); if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) return error("CMasternodeBroadcast::Sign() - Error: %s", errorMessage); return true; } bool CMasternodeBroadcast::VerifySignature() { std::string errorMessage; if(!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetNewStrMessage(), errorMessage) && !obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetOldStrMessage(), errorMessage)) return error("CMasternodeBroadcast::VerifySignature() - Error: %s", errorMessage); return true; } std::string CMasternodeBroadcast::GetOldStrMessage() { std::string strMessage; std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion); return strMessage; } std:: string CMasternodeBroadcast::GetNewStrMessage() { std::string strMessage; strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + boost::lexical_cast<std::string>(protocolVersion); return strMessage; } CMasternodePing::CMasternodePing() { vin = CTxIn(); blockHash = uint256(0); sigTime = 0; vchSig = std::vector<unsigned char>(); } CMasternodePing::CMasternodePing(CTxIn& newVin) { vin = newVin; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector<unsigned char>(); } bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { std::string errorMessage; std::string strMasterNodeSignMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } return true; } bool CMasternodePing::VerifySignature(CPubKey& pubKeyMasternode, int &nDos) { std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); std::string errorMessage = ""; if(!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)){ nDos = 33; return error("CMasternodePing::VerifySignature - Got bad Masternode ping signature %s Error: %s", vin.ToString(), errorMessage); } return true; } bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled, bool fCheckSigTimeOnly) { if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the past %s - %d %d \n", vin.prevout.hash.ToString(), sigTime, GetAdjustedTime()); nDos = 1; return false; } if(fCheckSigTimeOnly) { CMasternode* pmn = mnodeman.Find(vin); if(pmn) return VerifySignature(pmn->pubKeyMasternode, nDos); return true; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - New Ping - %s - %s - %lli\n", GetHash().ToString(), blockHash.ToString(), sigTime); // see if we have this Masternode CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) { if (fRequireEnabled && !pmn->IsEnabled()) return false; // LogPrint("masternode","mnping - Found corresponding mn for vin: %s\n", vin.ToString()); // update only if there is no known ping for this masternode or // last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) { if (!VerifySignature(pmn->pubKeyMasternode, nDos)) return false; BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi != mapBlockIndex.end() && (*mi).second) { if ((*mi).second->nHeight < chainActive.Height() - 24) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is too old\n", vin.prevout.hash.ToString(), blockHash.ToString()); // Do nothing here (no Masternode update, no mnping relay) // Let this node to be visible but fail to accept mnping return false; } } else { if (fDebug) LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is unknown\n", vin.prevout.hash.ToString(), blockHash.ToString()); // maybe we stuck so we shouldn't ban this node, just fail to accept it // TODO: or should we also request this block? return false; } pmn->lastPing = *this; //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) { mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this; } pmn->Check(true); if (!pmn->IsEnabled()) return false; LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping accepted, vin: %s\n", vin.prevout.hash.ToString()); Relay(); return true; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping arrived too early, vin: %s\n", vin.prevout.hash.ToString()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Couldn't find compatible Masternode entry, vin: %s\n", vin.prevout.hash.ToString()); return false; } void CMasternodePing::Relay() { CInv inv(MSG_MASTERNODE_PING, GetHash()); RelayInv(inv); }
[ "ondoricoin@gmail.com" ]
ondoricoin@gmail.com
6a50ad23e7d90a03ce7c311de07e1aec04b0d5d3
c115b2799014dc2ab63ca2626b3f0263b1339e7a
/NosePoke_Adquisicion_RA/NosePoke_Adquisicion_RA.ino
cf2094a528a52c122850e4fc468964e5100ce919
[]
no_license
Traintain/NosePoke
6409deb47072fc77aa92b30e8b3363cd1200b87c
7cf0564199464eed976851ccff136a52c097635a
refs/heads/master
2023-06-23T03:38:28.631037
2023-06-13T09:04:54
2023-06-13T09:04:54
220,561,332
0
0
null
null
null
null
UTF-8
C++
false
false
13,612
ino
//This library allows to control the stepper motor //Pin conections //Infrared sensors on the holes const int IR_Right=4; const int IR_Left=3; const int MOTOR=8; //Contecions for the LED lights const int LED_Right=6; const int LED_Left=5; const int LED_center=7; //Motor constants //120 steps per turn dispense 0.017 ml aprox. Above 120 RPM the motor get clumsy int nSpeed=120; int nSteps=150; //Number of blocks const int nBlocks=1; //Number of trials per block const int nTrials=50; //Inter trial interval, in miliseconds const int ITI=5000; int ITIsec=ITI/1000; //Maximum duration of each trial, in milisencods const int durTrial=10000; //Reward period, in case the nose enters while the trial, in miliseconds const int durReward=3000; //Output constants //Number of successful trials. Can be up to 50 por block. int success; //Time spend on impulsive responses. An impulsive response is when the animal inserts its nose during the ITI unsigned long impulsive; //Number of omissions. An omision response is when the animal doesn't inster its nose during a trial int omission; //Number of categories. A category is when a animal has 3 successes in a row. int category; //Number of right correct choices int goodRight; //Number of left correct choices int goodLeft; //mean of the latency of each block unsigned long latency; //temporal number for math double temp; //Error de seleccion: numero de errores antes del primer acierto int errSelec; //Perseveracion primaria int EPP; //Perseveracion secundaria int EPS; //Aciertos por segmento int aciertoTemprano; int aciertoIntermedio; int aciertoFinal; //Global max continious correct responses int globalMax; //Local max continious correct responses int localMax; int right; int left; int COM=-1; //Integer that counts the number of consecutives succeses int sucesiveSuccess; bool metioNariz; unsigned long tIni; unsigned long tInterm; unsigned long tLog; String msg=""; //Number between 0 and 2, that indicates the side where the animal should drink long randomSide; bool isRight; int firstCorrect; void setup() { //Setup of the different pins pinMode(IR_Right, INPUT); pinMode(IR_Left, INPUT); pinMode(LED_Right, OUTPUT); pinMode(LED_Left, OUTPUT); pinMode(LED_center, OUTPUT); pinMode(MOTOR, OUTPUT); digitalWrite(MOTOR,HIGH); randomSeed(analogRead(0)); Serial.begin(9600); //Comprobar comunicación con PC Serial.println("Transmitiendo"); //while(COM==-1){ // COM=Serial.read(); //} //To check the serial comunication the PC sends a number 6. //if(COM!=54){ //Error en caso de que no haya comunicación // Serial.println("Error"); //}else{ //Todo va bien // Serial.println("Ok"); //} } //Method to make the motor turn void motor(){ //Serial.println("Iniciando un ciclo del motor"); digitalWrite(LED_center,HIGH); digitalWrite(MOTOR,LOW); //Poner en 1000 al inicio para que llene la sonda rapidamente //Poner en 20 para dispensar una gota delay(20); digitalWrite(MOTOR,HIGH); delay(durReward); digitalWrite(LED_center,LOW); } //To initiate the protocol the PC must send a number 9 void loop() { //while(COM!=57){ // COM=Serial.read(); //} //Run two blocks for(int j=0; j<nBlocks;j++){ //Reset the output counters success=0; impulsive=0; omission=0; category=0; sucesiveSuccess=0; temp=0; goodLeft=0; goodRight=0; latency=0; firstCorrect=0; errSelec=0; EPP=0; EPS=0; aciertoTemprano=0; aciertoIntermedio=0; aciertoFinal=0; localMax=0; globalMax=0; Serial.print("Van a empezar los "); Serial.print(nTrials); Serial.println(" ensayos"); //Wait 5 seconds for habituation delay(ITI); Serial.println("Ensayo,Aciertos,Porcentaje aciertos,Tiempo total en Respuestas impulsivas,Omisiones,Porcentaje omisiones,Categorias,Latencia promedio,Errores de perseveración primarios,Porcentaje errores de perseveración primarios,Errores de perseveración secundarios,Porcentaje errores de perseveración secundarios,Errores de seleccion,Porcentaje errores de selección,Adquisicion de reglas,Establecimiento de reglas,Mantenimiento de reglas,Maximo de aciertos seguidos"); //Begin 50 trials for(int i=0; i<nTrials; i++){ trial(i); //Imprime el ensayo temp=i+1; Serial.print(temp); Serial.print(","); //Imprime los aciertos Serial.print(success); Serial.print(","); //Imprime el porcentaje de aciertos temp=(success*100/nTrials); Serial.print(temp); Serial.print(","); //Imprime el tiempo total de respuestas impulsivas temp=impulsive/1000; Serial.print(temp); Serial.print(","); //Imprime las omisiones Serial.print(omission); Serial.print(","); //Imprime el porcentaje de omisiones temp=(omission*100/nTrials); Serial.print(temp); Serial.print(","); //Imprime las categorias Serial.print(category); Serial.print(","); //Imprime la latencia promedio if(success!=0 || EPP !=0 || EPS != 0){ temp=latency/(success+EPP+EPS); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de perseveración primarios Serial.print(EPP); Serial.print(","); //Porcentaje errores de perseveración primarios if(success!=0){ temp=(EPP*100/success); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de perseveración secundarios Serial.print(EPS); Serial.print(","); //Porcentaje errores de perseveración secundarios if(EPS!=0){ temp=(EPP*100/EPS); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Errores de seleccion Serial.print(errSelec); Serial.print(","); //Porcentaje errores de selección if(firstCorrect!=0){ temp=(errSelec*100/firstCorrect); }else{ temp=0; } Serial.print(temp); Serial.print(","); //Imprime las adquisiciones de reglas temp=(aciertoTemprano*100)/17; Serial.print(temp); Serial.print(","); //Imprime el establecimiento de reglas temp=(aciertoIntermedio*100)/16; Serial.print(temp); Serial.print(","); //Imprime el mantenimiento de reglas temp=(aciertoFinal*100)/17; Serial.print(temp); Serial.print(","); //Imprime el maximo de aciertos seguidos Serial.println(globalMax); if(i==49){ Serial.println(); Serial.println("***********************************"); Serial.print("Aciertos: "); Serial.println(success); Serial.print("Porcentaje aciertos: "); temp=(success*100/nTrials); Serial.print(temp); Serial.println("%"); Serial.print("Tiempo total en Respuestas impulsivas: "); temp=impulsive/1000; Serial.print(temp); Serial.println(" s"); Serial.print("Omisiones: "); Serial.println(omission); Serial.print("Porcentaje omisiones: "); temp=(omission*100/nTrials); Serial.print(temp); Serial.println("%"); Serial.print("Categorias: "); Serial.println(category); Serial.print("La latencia promedio es de: "); if(success!=0 || EPP !=0 || EPS != 0){ temp=latency/(success+EPP+EPS); }else{ temp=0; } Serial.print(temp); Serial.println(" ms"); Serial.print("Errores de perseveración primarios: "); Serial.println(EPP); Serial.print("Porcentaje errores de perseveración primarios: "); if(success!=0){ temp=(EPP*100/success); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Errores de perseveración secundarios: "); Serial.println(EPS); Serial.print("Porcentaje errores de perseveración secundarios: "); if(EPS!=0){ temp=(EPP*100/EPS); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Errores de seleccion: "); Serial.println(errSelec); Serial.print("Porcentaje errores de selección: "); if(firstCorrect!=0){ temp=(errSelec*100/firstCorrect); }else{ temp=0; } Serial.print(temp); Serial.println("%"); Serial.print("Adquisicion de reglas: "); temp=(aciertoTemprano*100)/17; Serial.println(temp); Serial.print("Establecimiento de reglas: "); temp=(aciertoIntermedio*100)/16; Serial.println(temp); Serial.print("Mantenimiento de reglas: "); temp=(aciertoFinal*100)/17; Serial.println(temp); Serial.print("Maximo de aciertos seguidos: "); Serial.println(globalMax); if(firstCorrect!=0){ Serial.print("El primer acierto fue en el intento: "); Serial.println(firstCorrect); } } } Serial.println("Terminan bloque de 50 ensayos"); } while(true); } //The instructions for each trial void trial(int i){ metioNariz=false; randomSide=random(0,2); isRight=randomSide<1; //Serial.println("Inicia ensayo"); tIni=millis(); if(isRight){ digitalWrite(LED_Right,HIGH); //Serial.println("Se enciende la luz derecha"); }else{ digitalWrite(LED_Left,HIGH); //Serial.println("Se enciende la luz izquierda"); } //Check fot 10 seconds if the animal inserts its nose while(( (millis()-tIni) < durTrial) && metioNariz==false){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); if(right==LOW){ tLog=millis()-tIni; //Serial.print("Metio la nariz en la derecha a los: "); //Serial.println(tLog); if(isRight){ digitalWrite(LED_Right,LOW); motor(); //Exito if(firstCorrect==0){ firstCorrect=i+1; //Serial.print("Primer acierto en el intento: "); //Serial.println(firstCorrect); } success++; if(i<=16){ aciertoTemprano++; }else if(i<=32 && i>16){ aciertoIntermedio++; }else{ aciertoFinal++; } if((sucesiveSuccess%3)==2)category++; sucesiveSuccess++; localMax++; if(localMax > globalMax) globalMax = localMax; }else{ //Fallo digitalWrite(LED_Left,LOW); if(firstCorrect==0){ errSelec++; //Serial.println("Error de selección"); }else{ if(sucesiveSuccess!=0){ EPP++; //Serial.println("Error de perseveración primaria"); sucesiveSuccess=0; }else{ EPS++; //Serial.println("Error de perseveración secundaria"); } } sucesiveSuccess=0; localMax=0; } while(right==LOW){ right=digitalRead(IR_Right); } latency+=tLog; metioNariz=true; } if(left==LOW){ tLog=millis()-tIni; //Serial.print("Metio la nariz en la izquierda a los: "); //Serial.println(tLog); if(isRight){ //Fallo digitalWrite(LED_Right,LOW); if(firstCorrect==0){ errSelec++; //Serial.println("Error de selección"); }else{ if(sucesiveSuccess!=0){ EPP++; //Serial.println("Error de perseveración primaria"); sucesiveSuccess=0; }else{ EPS++; //Serial.println("Error de perseveración secundaria"); } } sucesiveSuccess=0; localMax=0; }else{ //Exito digitalWrite(LED_Left,LOW); motor(); //Exito if(firstCorrect==0){ firstCorrect=i+1; //Serial.print("Primer acierto en el intento: "); //Serial.println(firstCorrect); } success++; if(i<=16){ aciertoTemprano++; }else if(i<=32 && i>16){ aciertoIntermedio++; }else{ aciertoFinal++; } if((sucesiveSuccess%3)==2)category++; sucesiveSuccess++; localMax++; if(localMax > globalMax) globalMax = localMax; } while(left==LOW){ left=digitalRead(IR_Left); } latency+=tLog; metioNariz=true; } } //------------------------ if(metioNariz==false){ digitalWrite(LED_Right,LOW); digitalWrite(LED_Left,LOW); omission++; //Serial.print("Omision numero:"); //Serial.println(omission); sucesiveSuccess=0; } //------------------------ //El animal debe esperar 10 segundos antes de volver a meter la nariz //Si la mete antes se reinicia la cuenta //Serial.print("Fin ensayo, inician "); //Serial.print(ITIsec); //Serial.println(" s de intervalo entre estímulos"); tInterm=millis(); while((millis()-tInterm) < ITI){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); if(right==LOW || left==LOW){ //impulsive++; tIni=millis(); //Serial.println("Inicio de respuesta impulsiva"); while(right==LOW || left==LOW){ right=digitalRead(IR_Right); left=digitalRead(IR_Left); } impulsive+=millis()-tIni; tInterm = millis(); //Serial.println("Inician de nuevo "); //Serial.print(ITIsec); //Serial.println(" s de espera"); } } }
[ "jm.rivera@uniandes.edu.co" ]
jm.rivera@uniandes.edu.co
5a39832290e98aa8d43198b3c94c512c533fc812
30ddfa3cae3743090df23df96c4bfec8e757d418
/BlackJack1/BlackJack1/Card.cpp
67405d15a674d5887a4cc16fff700d1f1b9ceb6b
[]
no_license
Reza-Amani/BlackJack-Cpp
5c4c3f49ecb5fa36925a4cb532c9d39c4ab2ad8f
8ae8d3c653a47da991dcea9364faaebff1c5d55b
refs/heads/master
2020-03-31T04:26:06.062478
2018-10-21T09:55:34
2018-10-21T09:55:34
151,904,907
0
0
null
null
null
null
UTF-8
C++
false
false
197
cpp
#include "stdafx.h" #include "Card.h" Card::Card(Suits s, Ranks r) { suit = s; rank = r; rule = rule } int Card::get_value(Irule& rule) { return rule.card_value(this); } Card::~Card() { }
[ "reza.amani@gmail.com" ]
reza.amani@gmail.com
1d84795b439d4e2ba2b7dbc97628d1466d024003
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/ash/shell_port_mash.cc
3c952fb8fc1eeccc1e9459693fd35706b01d1578
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
10,192
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell_port_mash.h" #include <memory> #include <utility> #include "ash/accelerators/accelerator_controller.h" #include "ash/accelerators/accelerator_controller_registrar.h" #include "ash/display/display_synchronizer.h" #include "ash/host/ash_window_tree_host_init_params.h" #include "ash/host/ash_window_tree_host_mus.h" #include "ash/keyboard/keyboard_ui_mash.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/immersive/immersive_fullscreen_controller.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/touch/touch_transform_setter_mus.h" #include "ash/window_manager.h" #include "ash/wm/drag_window_resizer_mash.h" #include "ash/wm/immersive_handler_factory_mash.h" #include "ash/wm/tablet_mode/tablet_mode_event_handler.h" #include "ash/wm/window_cycle_event_filter.h" #include "ash/wm/window_resizer.h" #include "ash/wm/window_util.h" #include "ash/wm/workspace/workspace_event_handler_mash.h" #include "services/ui/public/interfaces/constants.mojom.h" #include "services/ui/public/interfaces/video_detector.mojom.h" #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_host_mus_init_params.h" #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/forwarding_display_delegate.h" #include "ui/display/mojo/native_display_delegate.mojom.h" #include "ui/views/mus/pointer_watcher_event_router.h" namespace ash { ShellPortMash::ShellPortMash( WindowManager* window_manager, views::PointerWatcherEventRouter* pointer_watcher_event_router) : window_manager_(window_manager), pointer_watcher_event_router_(pointer_watcher_event_router), immersive_handler_factory_( std::make_unique<ImmersiveHandlerFactoryMash>()) { DCHECK(window_manager_); DCHECK(pointer_watcher_event_router_); DCHECK_EQ(Config::MASH, GetAshConfig()); } ShellPortMash::~ShellPortMash() = default; // static ShellPortMash* ShellPortMash::Get() { const ash::Config config = ShellPort::Get()->GetAshConfig(); CHECK_EQ(Config::MASH, config); return static_cast<ShellPortMash*>(ShellPort::Get()); } void ShellPortMash::Shutdown() { display_synchronizer_.reset(); ShellPort::Shutdown(); } Config ShellPortMash::GetAshConfig() const { return Config::MASH; } std::unique_ptr<display::TouchTransformSetter> ShellPortMash::CreateTouchTransformDelegate() { return std::make_unique<TouchTransformSetterMus>( window_manager_->connector()); } void ShellPortMash::LockCursor() { // When we are running in mus, we need to keep track of state not just in the // window server, but also locally in ash because ash treats the cursor // manager as the canonical state for now. NativeCursorManagerAsh will keep // this state, while also forwarding it to the window manager for us. window_manager_->window_manager_client()->LockCursor(); } void ShellPortMash::UnlockCursor() { window_manager_->window_manager_client()->UnlockCursor(); } void ShellPortMash::ShowCursor() { window_manager_->window_manager_client()->SetCursorVisible(true); } void ShellPortMash::HideCursor() { window_manager_->window_manager_client()->SetCursorVisible(false); } void ShellPortMash::SetCursorSize(ui::CursorSize cursor_size) { window_manager_->window_manager_client()->SetCursorSize(cursor_size); } void ShellPortMash::SetGlobalOverrideCursor( base::Optional<ui::CursorData> cursor) { window_manager_->window_manager_client()->SetGlobalOverrideCursor( std::move(cursor)); } bool ShellPortMash::IsMouseEventsEnabled() { return cursor_touch_visible_; } void ShellPortMash::SetCursorTouchVisible(bool enabled) { window_manager_->window_manager_client()->SetCursorTouchVisible(enabled); } void ShellPortMash::OnCursorTouchVisibleChanged(bool enabled) { cursor_touch_visible_ = enabled; } std::unique_ptr<WindowResizer> ShellPortMash::CreateDragWindowResizer( std::unique_ptr<WindowResizer> next_window_resizer, wm::WindowState* window_state) { return std::make_unique<ash::DragWindowResizerMash>( std::move(next_window_resizer), window_state); } std::unique_ptr<WindowCycleEventFilter> ShellPortMash::CreateWindowCycleEventFilter() { // TODO: implement me, http://crbug.com/629191. return nullptr; } std::unique_ptr<wm::TabletModeEventHandler> ShellPortMash::CreateTabletModeEventHandler() { // TODO: need support for window manager to get events before client: // http://crbug.com/624157. NOTIMPLEMENTED_LOG_ONCE(); return nullptr; } std::unique_ptr<WorkspaceEventHandler> ShellPortMash::CreateWorkspaceEventHandler(aura::Window* workspace_window) { return std::make_unique<WorkspaceEventHandlerMash>(workspace_window); } std::unique_ptr<KeyboardUI> ShellPortMash::CreateKeyboardUI() { return KeyboardUIMash::Create(window_manager_->connector()); } void ShellPortMash::AddPointerWatcher(views::PointerWatcher* watcher, views::PointerWatcherEventTypes events) { // TODO: implement drags for mus pointer watcher, http://crbug.com/641164. // NOTIMPLEMENTED_LOG_ONCE drags for mus pointer watcher. pointer_watcher_event_router_->AddPointerWatcher( watcher, events == views::PointerWatcherEventTypes::MOVES); } void ShellPortMash::RemovePointerWatcher(views::PointerWatcher* watcher) { pointer_watcher_event_router_->RemovePointerWatcher(watcher); } bool ShellPortMash::IsTouchDown() { // TODO: implement me, http://crbug.com/634967. return false; } void ShellPortMash::ToggleIgnoreExternalKeyboard() { NOTIMPLEMENTED_LOG_ONCE(); } void ShellPortMash::CreatePointerWatcherAdapter() { // In Config::CLASSIC PointerWatcherAdapterClassic must be created when this // function is called (it is order dependent), that is not the case with // Config::MASH. } std::unique_ptr<AshWindowTreeHost> ShellPortMash::CreateAshWindowTreeHost( const AshWindowTreeHostInitParams& init_params) { auto display_params = std::make_unique<aura::DisplayInitParams>(); display_params->viewport_metrics.bounds_in_pixels = init_params.initial_bounds; display_params->viewport_metrics.device_scale_factor = init_params.device_scale_factor; display_params->viewport_metrics.ui_scale_factor = init_params.ui_scale_factor; display::DisplayManager* display_manager = Shell::Get()->display_manager(); display::Display mirrored_display = display_manager->GetMirroringDisplayById(init_params.display_id); if (mirrored_display.is_valid()) { display_params->display = std::make_unique<display::Display>(mirrored_display); } display_params->is_primary_display = true; display_params->mirrors = display_manager->software_mirroring_display_list(); aura::WindowTreeHostMusInitParams aura_init_params = window_manager_->window_manager_client()->CreateInitParamsForNewDisplay(); aura_init_params.display_id = init_params.display_id; aura_init_params.display_init_params = std::move(display_params); aura_init_params.use_classic_ime = !Shell::ShouldUseIMEService(); return std::make_unique<AshWindowTreeHostMus>(std::move(aura_init_params)); } void ShellPortMash::OnCreatedRootWindowContainers( RootWindowController* root_window_controller) { // TODO: To avoid lots of IPC AddActivationParent() should take an array. // http://crbug.com/682048. aura::Window* root_window = root_window_controller->GetRootWindow(); for (size_t i = 0; i < kNumActivatableShellWindowIds; ++i) { window_manager_->window_manager_client()->AddActivationParent( root_window->GetChildById(kActivatableShellWindowIds[i])); } UpdateSystemModalAndBlockingContainers(); } void ShellPortMash::UpdateSystemModalAndBlockingContainers() { std::vector<aura::BlockingContainers> all_blocking_containers; for (RootWindowController* root_window_controller : Shell::GetAllRootWindowControllers()) { aura::BlockingContainers blocking_containers; wm::GetBlockingContainersForRoot( root_window_controller->GetRootWindow(), &blocking_containers.min_container, &blocking_containers.system_modal_container); all_blocking_containers.push_back(blocking_containers); } window_manager_->window_manager_client()->SetBlockingContainers( all_blocking_containers); } void ShellPortMash::OnHostsInitialized() { display_synchronizer_ = std::make_unique<DisplaySynchronizer>( window_manager_->window_manager_client()); } std::unique_ptr<display::NativeDisplayDelegate> ShellPortMash::CreateNativeDisplayDelegate() { display::mojom::NativeDisplayDelegatePtr native_display_delegate; if (window_manager_->connector()) { window_manager_->connector()->BindInterface(ui::mojom::kServiceName, &native_display_delegate); } return std::make_unique<display::ForwardingDisplayDelegate>( std::move(native_display_delegate)); } std::unique_ptr<AcceleratorController> ShellPortMash::CreateAcceleratorController() { uint16_t accelerator_namespace_id = 0u; const bool add_result = window_manager_->GetNextAcceleratorNamespaceId(&accelerator_namespace_id); // ShellPortMash is created early on, so that GetNextAcceleratorNamespaceId() // should always succeed. DCHECK(add_result); accelerator_controller_registrar_ = std::make_unique<AcceleratorControllerRegistrar>( window_manager_, accelerator_namespace_id); return std::make_unique<AcceleratorController>( accelerator_controller_registrar_.get()); } void ShellPortMash::AddVideoDetectorObserver( viz::mojom::VideoDetectorObserverPtr observer) { // We may not have access to the connector in unit tests. if (!window_manager_->connector()) return; ui::mojom::VideoDetectorPtr video_detector; window_manager_->connector()->BindInterface(ui::mojom::kServiceName, &video_detector); video_detector->AddObserver(std::move(observer)); } } // namespace ash
[ "team@geometry.ee" ]
team@geometry.ee
24ae0e4e28f19ffef83bd74d78153ebd1502da6b
4d99749aaaf023abff4c30d4d113e63fadbb2419
/origin/math/matrix/matrix.test/matrix_1.cpp
9d1e792aa209dc1ffe585cb06a7e64c6af70f323
[ "MIT" ]
permissive
asutton/origin-google
6b6a6dd33c9677f5f5fb326f75620f4e419927b6
516482c081a357a06402e5f288d645d3e18f69fa
refs/heads/master
2021-07-24T23:00:57.341960
2017-11-03T13:24:00
2017-11-03T13:24:00
109,394,139
7
1
null
null
null
null
UTF-8
C++
false
false
2,887
cpp
// Copyright (c) 2008-2010 Kent State University // Copyright (c) 2011-2012 Texas A&M University // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #include <iostream> #include <origin/math/matrix/matrix.hpp> using namespace std; using namespace origin; // Tests for 1D use of matrices: void test_init() { // Value initialization matrix<int, 1> m1 { 1, 2, 3, 4 }; assert(m1.extent(0) == 4); assert(m1.size() == 4); cout << m1 << '\n'; // Check initialization patterns for 1D matrices (vectors). // Using parens calls the size initializer. matrix<int, 1> m2(5); assert(m2.extent(0) == 5); cout << m2 << '\n'; // Make sure that we can be completely ambiguous and still get the right // thing. That is, 3 is interpreted as a dimension and not a value. matrix<std::size_t, 1> m3(3); assert(m3.extent(0) == 3); cout << m3 << '\n'; // Using parens *always* is always a bounds initializer. matrix<std::size_t, 1> m4(2ul); cout << m4 << '\n'; // Using braces is always a value initializer. // This should emit a deleted function error since it would require // narrowing (the deleted constructor is selected). // matrix<std::size_t, 1> m5{1, 2, 3}; // But this needs to be ok since we have an exact match for value // initialization. matrix<std::size_t, 1> m6{1ul, 2ul}; cout << m6 << '\n'; } void test_access() { // Test element access. matrix<int, 1> m {0, 1, 2, 3}; assert(m(0) == 0); // Test slicing. Note that slices in 1D are proxies. assert(m[0] == 0); assert(m.row(0) == 0); // Iterators increase monotonically. auto i = m.begin(); int n = 0; for ( ; i != m.end(); ++i, ++n) assert(*i == n); } void test_slice() { cout << "--- slice ---\n"; matrix<int, 1> m {0, 1, 2, 3, 4, 5}; auto s1 = m(2); assert(s1 == 2); // FIXME: Actually implement these checks. auto s2 = m(slice(1, 3)); cout << s2 << '\n'; // 1 2 3 auto s3 = m(slice(1, 5)); // Check at the boundary. cout << s3 << '\n'; // 1 2 3 4 5 // Some identities assert(m(slice(0)) == m); assert(m(slice::all) == m); cout << "----------\n"; } void test_ops() { // Test operations matrix<int, 1> m {0, 1, 2, 3}; m[0] = 1; assert(m(0) == 1); m[0] += 1; assert(m(0) == 2); m[0] -= 1; assert(m(0) == 1); m[0] *= 10; assert(m(0) == 10); m[0] /= 5; assert(m(0) == 2); m[0] %= 2; assert(m(0) == 0); matrix<int, 1> m2 {4, 3, 2, 1}; m += m2; // 4, 4, 4, 4 cout << m << '\n'; m -= m2; // 0, 1, 2, 3 cout << m << '\n'; } int main() { test_init(); test_access(); test_slice(); test_ops(); matrix<int, 1> m {0, 1, 2, 3, 4, 5, 6 }; for (int i = 0; i != 7; ++i) { // assert(&m.s(i) == m.data() + i); } m(0); m(slice(1, 2)); }
[ "andrew.n.sutton@gmail.com" ]
andrew.n.sutton@gmail.com
4e9462bfd4f431e23a6c242cf7d2832d66c36f99
30cd1a7af92fb1243c33f9b8dde445c29118bd1a
/third_party/allwpilib_2016/wpilibc/shared/src/HLUsageReporting.cpp
bcbc6b6a34d4da7e4a6882abc83df2d2783d4fa9
[ "BSD-2-Clause" ]
permissive
FRC1296/CheezyDriver2016
3907a34fd5f8ccd2c90ab1042782106c0947c0cb
4aa95b16bb63137250d2ad2529b03b2bd56c78c0
refs/heads/master
2016-08-12T23:22:00.077919
2016-03-19T05:56:18
2016-03-19T05:56:18
51,854,487
2
0
null
2016-02-29T10:10:27
2016-02-16T17:27:07
C++
UTF-8
C++
false
false
399
cpp
#include "HLUsageReporting.h" HLUsageReportingInterface* HLUsageReporting::impl = nullptr; void HLUsageReporting::SetImplementation(HLUsageReportingInterface* i) { impl = i; } void HLUsageReporting::ReportScheduler() { if (impl != nullptr) { impl->ReportScheduler(); } } void HLUsageReporting::ReportSmartDashboard() { if (impl != nullptr) { impl->ReportSmartDashboard(); } }
[ "tkb@cheezy.usfluidtech.com" ]
tkb@cheezy.usfluidtech.com
0ae2413fc84c339218866a79093d55e70b7b9970
6a57649f5af3e5d4b9b92b0a622f43664643a073
/5/11.cpp
1180abc1774764359dabeecc0286445bf93a4e26
[]
no_license
snull/CTU-CE-BP
1602e8fcf7dc0a82a71477ce279ce3e9519f564f
3baa344f995b1fc7b80495da883cd8872b52668b
refs/heads/master
2023-03-02T08:44:10.567498
2021-02-06T00:11:41
2021-02-06T07:12:38
334,291,849
3
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
#include <iostream> using namespace std; int main(){ for(int i=1 ; i<7 ; i++ ){ for(int j=1 ; j<=i ; j++){ cout<<"* "; } cout<<endl; } return 0; }
[ "shayan.mpm@gmail.com" ]
shayan.mpm@gmail.com
c3aa1fdb85bc7db2936ac7ae0062bd7528e09d30
65702ad9670aaf0ac9da4d20477d636029d8277a
/cosim/bfmTests/srotKeyTest/c_module.cc
adafb0ded89e437897e054f6a37623f2fe1b40d7
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
animeshbchowdhury/CEP
87f3cc7c1fdf2c7b4ee2c8ce1982ec67385245e2
0eb7170a5f31aa44b6590b706d0daf0c50a49a27
refs/heads/master
2023-05-11T05:52:48.811207
2021-05-24T14:13:01
2021-05-24T14:13:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,233
cc
//************************************************************************ // Copyright 2021 Massachusetts Institute of Technology // SPDX License Identifier: MIT // // File Name: // Program: Common Evaluation Platform (CEP) // Description: // Notes: // //************************************************************************ #include "v2c_cmds.h" #include "simPio.h" // #include "shMem.h" #include "c_module.h" #include <unistd.h> #include "random48.h" #include "cep_apis.h" #include "simdiag_global.h" #include "cepSrotTest.h" // void *c_module(void *arg) { // ====================================== // Set up // ====================================== pthread_parm_t *tParm = (pthread_parm_t *)arg; int errCnt = 0; int slotId = tParm->slotId; int cpuId = tParm->cpuId; int verbose = tParm->verbose; Int32U seed = tParm->seed; int restart = tParm->restart; int offset = GET_OFFSET(slotId,cpuId); GlobalShMemory.getSlotCpuId(offset,&slotId,&cpuId); //printf("offset=%x seed=%x verbose=%x GlobalShMemory=%x\n",offset,seed, verbose,(unsigned long) &GlobalShMemory); // notify I am Alive!!! shIpc *ptr = GlobalShMemory.getIpcPtr(offset); ptr->SetAliveStatus(); sleep(1); // ====================================== // Test is Here // ====================================== simPio pio; pio.MaybeAThread(); // chec pio.EnableShIpc(1); pio.SetVerbose(verbose); // // ====================================== // Test starts here // ====================================== // MUST // wait until Calibration is done.. //int calibDone = calibrate_ddr3(50); pio.RunClk(1000); // int mask = seed; // seed is used as cpuActiveMask from c_displatch if (!errCnt) { errCnt = cepSrotTest_maxKeyTest(cpuId, verbose); } // pio.RunClk(100); // // ====================================== // Exit // ====================================== cleanup: if (errCnt != 0) { LOGI("======== TEST FAIL ========== %x\n",errCnt); } else { LOGI("======== TEST PASS ========== \n"); } // shIpc *ptr = GlobalShMemory.getIpcPtr(offset); ptr->SetError(errCnt); ptr->SetThreadDone(); pthread_exit(NULL); return ((void *)NULL); }
[ "pa25523@561195-mitll.llan.ll.mit.edu" ]
pa25523@561195-mitll.llan.ll.mit.edu
081202f0cee55f7f8d66a4ce480d30d66500133a
649d61a64e19cc44892ecad0dd8fe6164ce594a7
/Student_Cuda_Image/src/cpp/core/01_Rippling/02_provider/RipplingProvider.h
7318cf1686f1560eb58bdc2f1b388612ec7ea007
[]
no_license
thegazou/CUDA
ec2cebb4ba89679cf06d61af758d650c20508407
e2b3828cbd63314e7ddcb9d1ebb0b87f3eb4af7f
refs/heads/master
2021-01-17T21:22:16.519938
2017-05-02T15:33:19
2017-05-02T15:33:19
84,175,648
0
1
null
null
null
null
UTF-8
C++
false
false
909
h
#pragma once #include "cudaTools.h" #include "Provider_I_GPU.h" using namespace gpu; /*----------------------------------------------------------------------*\ |* Declaration *| \*---------------------------------------------------------------------*/ /*--------------------------------------*\ |* Public *| \*-------------------------------------*/ class RipplingProvider: public Provider_I<uchar4> { public: virtual ~RipplingProvider() { // Rien } /*--------------------------------------*\ |* Override *| \*-------------------------------------*/ virtual Animable_I<uchar4>* createAnimable(void); virtual Image_I* createImageGL(void); }; /*----------------------------------------------------------------------*\ |* End *| \*---------------------------------------------------------------------*/
[ "thegazou@romandie.com" ]
thegazou@romandie.com
eeb944f352166d9fa76f2aec33901ba3d9921998
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/gee4/src/linesearch.h
29452f6b3f8a6e29341a4a6d5e2b5d97eb941faf
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
1,534
h
/* Copyright 2016 The University of Manchester. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written by Yi Pan - ypan1988@gmail.com ==============================================================================*/ #ifndef LINESEARCH_H_ // NOLINT #define LINESEARCH_H_ #include <RcppArmadillo.h> #include <cmath> #include <algorithm> #include <limits> namespace dragonwell { // Line Searches and Backtracking template <typename T> class LineSearch { public: LineSearch() {} // Constructor ~LineSearch() {} // Destructor bool GetStep(T &func, double *f, arma::vec *x, const arma::vec &g, const arma::vec &p, const double stepmax); void set_message(bool message) { message_ = message; } protected: bool message_; bool IsInfOrNaN(double x); }; // class LineSearch #include "linesearch_impl.h" // NOLINT } // namespace dragonwell #endif // LINESEARCH_H_ NOLINT
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
714da659bc1678268821a5276d595b767e53a7ea
eee88a0c318799bd5ddc5bde0c3d03e989575251
/qsort.cpp
b0243f05b757bea8b5e3fdc1672459e069cb5146
[]
no_license
CATQ/Hello-world2
778f21a4bea7436d91165c6f709c1c22bc0745b6
3fdadbbc87a5f838fe7149f2e8b10a23de49de7b
refs/heads/master
2021-05-16T10:43:53.180862
2018-01-05T14:51:37
2018-01-05T14:51:37
104,815,929
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include<stdio.h> int a[200]; int qsort(int r, int l) { int mid, t; int x = r; int y = l; mid = (x+y)/2; while (x < y) { while (a[x]<a[mid]) x++; while (a[y]>a[mid]) y--; if (x<=y) { t= a[x];a[x] = a[y];a[y] = t; x++;y--; } } if (x<l) qsort(x,l); if (y>r) qsort(r,y); } int main() { int i, n; scanf("%d", &n); for (i=1; i<=n; i++) scanf("%d", &a[i]); qsort(1,n); for (i=1; i<=n; i++) printf("%d ", a[i]); }
[ "819735890@qq.com" ]
819735890@qq.com
18d0670eab4b1f80eda0ee1ba12603de101f3b5d
750395d2f5d37b1f30b8b1920e11e040cbe401c4
/FHE/Random_Coins.h
24b9b8d7ff461ac2da1f4b6240bc5741307ef578
[ "MIT", "BSD-2-Clause" ]
permissive
AlexanderViand/MP-SPDZ
b4c920e45143f710c9371cab4c37b63da5420ed7
d26a62efe496946d721b0ab49710494cea5c9652
refs/heads/master
2020-05-19T08:10:28.857168
2019-05-03T08:03:13
2019-05-03T08:03:50
184,914,569
1
0
NOASSERTION
2019-05-04T15:48:59
2019-05-04T15:48:59
null
UTF-8
C++
false
false
2,753
h
#ifndef _Random_Coins #define _Random_Coins /* Randomness used to encrypt */ #include "FHE/FHE_Params.h" #include "FHE/Rq_Element.h" #include "FHE/AddableVector.h" class FHE_PK; class Int_Random_Coins : public AddableMatrix<bigint> { const FHE_Params* params; public: Int_Random_Coins(const FHE_Params& params) : params(&params) { resize(3, params.phi_m()); } Int_Random_Coins(const FHE_PK& pk); void sample(PRNG& G) { (*this)[0].from(HalfGenerator(G)); for (int i = 1; i < 3; i++) (*this)[i].from(GaussianGenerator(params->get_DG(), G)); } }; class Random_Coins { Rq_Element uu,vv,ww; const FHE_Params *params; public: const FHE_Params& get_params() const { return *params; } Random_Coins(const FHE_Params& p) : uu(p.FFTD(),evaluation,evaluation), vv(p.FFTD(),evaluation,evaluation), ww(p.FFTD(),polynomial,polynomial) { params=&p; } Random_Coins(const FHE_PK& pk); ~Random_Coins() { ; } // Rely on default copy assignment/constructor const Rq_Element& u() const { return uu; } const Rq_Element& v() const { return vv; } const Rq_Element& w() const { return ww; } void assign(const Rq_Element& u,const Rq_Element& v,const Rq_Element& w) { uu=u; vv=v; ww=w; } template <class T> void assign(const vector<T>& u,const vector<T>& v,const vector<T>& w) { uu.from_vec(u); vv.from_vec(v); ww.from_vec(w); } void assign(const Int_Random_Coins& rc) { uu.from_vec(rc[0]); vv.from_vec(rc[1]); ww.from_vec(rc[2]); } /* Generate a standard distribution */ void generate(PRNG& G) { uu.from(HalfGenerator(G)); vv.from(GaussianGenerator(params->get_DG(), G)); ww.from(GaussianGenerator(params->get_DG(), G)); } // Generate all from Uniform in range (-B,...B) void generateUniform(PRNG& G,const bigint& B1,const bigint& B2,const bigint& B3) { if (B1 == 0) uu.assign_zero(); else uu.from(UniformGenerator(G,numBits(B1))); vv.from(UniformGenerator(G,numBits(B2))); ww.from(UniformGenerator(G,numBits(B3))); } // ans,x and y must have same params otherwise error friend void add(Random_Coins& ans, const Random_Coins& x,const Random_Coins& y); // Don't bother outputing params, assumes these are implicitly known friend ostream& operator<<(ostream& s,const Random_Coins& rc) { s << rc.uu << " " << rc.vv << " " << rc.ww; return s; } void pack(octetStream& o) const { uu.pack(o); vv.pack(o); ww.pack(o); } size_t report_size(ReportType type) { return uu.report_size(type) + vv.report_size(type) + ww.report_size(type); } }; #endif
[ "m.keller@bristol.ac.uk" ]
m.keller@bristol.ac.uk
e64fb11fa157eef645cc9f60471d1167aa1c820f
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/比赛/雅礼集训/20190107/sum_bf.cpp
2e0c8d31dcf67360aaaadaffa07f0fe4df31e9a6
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include<iostream> #include<algorithm> #include<cstdlib> #define int long long #define MAXN 77 using namespace std; int f[MAXN],fc=0,n=1,now=0,ans=0,ansnow=0; inline void judge(); signed main() { register int i=0; if(n>30) { exit(0); } for(now=0;now<(1LL<<n);++now) { judge(); } cout<<ans<<':'; for(i=0;i<n;++i) { if(ansnow>>i&1) { cout<<i+1<<' '; } } cout<<endl; ++n; main(); return 0; } inline void judge() { register int i=0,j=0; for(i=fc=0;i<n;++i) { if(now>>i&1) { f[++fc]=i+1; } } for(i=1;i<=fc;++i) { for(j=i+1;j<=fc;++j) { if(__gcd(f[i],f[j])>1) { return; } } } for(i=1,j=0;i<=fc;++i) { j+=f[i]; } if(j>ans) { ans=j; ansnow=now; } return; }
[ "3305049949@qq.com" ]
3305049949@qq.com
6e37e88e6e31bc0df0a7b7de780561fd3e60dd2a
a7764174fb0351ea666faa9f3b5dfe304390a011
/drv/MoniTool/MoniTool_CaseData.ixx
5b106e74fc341c93fbef8777f1191f6f2fb5ea6f
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
721
ixx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #include <MoniTool_CaseData.jxx> #ifndef _Standard_Type_HeaderFile #include <Standard_Type.hxx> #endif IMPLEMENT_STANDARD_TYPE(MoniTool_CaseData) IMPLEMENT_STANDARD_SUPERTYPE_ARRAY() STANDARD_TYPE(MMgt_TShared), STANDARD_TYPE(Standard_Transient), IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END() IMPLEMENT_STANDARD_TYPE_END(MoniTool_CaseData) IMPLEMENT_DOWNCAST(MoniTool_CaseData,Standard_Transient) IMPLEMENT_STANDARD_RTTI(MoniTool_CaseData)
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
e811e994c26fb180a2a00e2603351cb1258dc10b
6d6b2ad24779426fcee731602dfcff99d90bd3f8
/thrift/thrift/lib/cpp/test/gen-cpp/AnnotationTest_constants.cpp
496996a6b952f1aac746b156c146b7282e47fe52
[ "Apache-2.0" ]
permissive
XiongWD/RPC-CPP-PHP
e050dd95a06c684f4b16fab906eb15be04eb38fe
2573f240a26d3b27e6aea101171eceb9f7cfe8d9
refs/heads/master
2021-01-20T16:38:53.858121
2017-05-10T10:27:05
2017-05-10T10:27:05
90,845,780
0
0
null
null
null
null
UTF-8
C++
false
true
300
cpp
/** * Autogenerated by Thrift Compiler (1.0.0-dev) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "AnnotationTest_constants.h" const AnnotationTestConstants g_AnnotationTest_constants; AnnotationTestConstants::AnnotationTestConstants() { }
[ "hbuedxw@163.com" ]
hbuedxw@163.com
de3512ab95206c37c843ccfe9be0143f7396947c
63ade4b3fde43919e649929a8331c153d9ed7e19
/unittests/common/split.hpp
f94b9bda52d94a54fbe5eb83bd1011671baee207
[ "LLVM-exception", "Apache-2.0" ]
permissive
paulhuggett/pstore
ff33c91e953cbdf37a6f6d7874e03913788bf6e7
e6465e0d49ad317cdca9aa0914cd91a6ea9a94ee
refs/heads/main
2023-08-15T06:47:19.934465
2023-07-28T14:55:10
2023-07-28T14:55:10
321,625,810
0
0
NOASSERTION
2021-03-09T21:30:51
2020-12-15T10:00:51
C++
UTF-8
C++
false
false
1,868
hpp
//===- unittests/common/split.hpp -------------------------*- mode: C++ -*-===// //* _ _ _ * //* ___ _ __ | (_) |_ * //* / __| '_ \| | | __| * //* \__ \ |_) | | | |_ * //* |___/ .__/|_|_|\__| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/paulhuggett/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef SPLIT_HPP #define SPLIT_HPP #include <algorithm> #include <cctype> #include <cwctype> #include <iterator> #include <string> #include <vector> #include "pstore/support/ctype.hpp" template <typename StringType> std::vector<StringType> split_lines (StringType const & s) { std::vector<StringType> result; typename StringType::size_type pos = 0; for (;;) { auto const cr_pos = s.find_first_of ('\n', pos); auto count = (cr_pos == StringType::npos) ? StringType::npos : cr_pos - pos; result.emplace_back (s, pos, count); if (count == StringType::npos) { break; } pos = cr_pos + 1; } return result; } template <typename StringType> std::vector<StringType> split_tokens (StringType const & s) { std::vector<StringType> result; using char_type = typename StringType::value_type; auto is_space = [] (char_type c) { return pstore::isspace (c); }; auto it = std::begin (s); auto end = std::end (s); while (it != end) { it = std::find_if_not (it, end, is_space); // skip leading whitespace auto start = it; it = std::find_if (it, end, is_space); if (start != it) { result.emplace_back (start, it); } } return result; } #endif // SPLIT_HPP
[ "paulhuggett@mac.com" ]
paulhuggett@mac.com
0cf92815def0c9ca8cd64b870932481355252b52
b9623c82dc51f398b57dde08cf223342093f2af0
/4/4.cpp
c7144a99e0d4397a02b0056a0d443539ed241a47
[]
no_license
irinamrk02/Laba-10
b8d75237c582dc30cee17c34c3ba96cf1b5d2144
cd2ebb4092e2a547cea5b7fcaebe32ba3cbb3dc7
refs/heads/master
2023-01-31T16:37:21.747375
2020-12-08T19:44:46
2020-12-08T19:44:46
319,743,758
0
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
// 4.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include "string" #include "iostream" #include "fstream" using namespace std; int main() { setlocale(0, ""); ifstream in("f.txt"); string s, r; while (in.peek() != EOF) { getline(in, s); if (s.size() > r.size()) { r = s; } } cout << "Длина максимальной строки = " << r.size() << ". Сама строка: " << r << endl; in.close(); return 0; }
[ "irinamrk02@mail.ru" ]
irinamrk02@mail.ru
1366051be1fdb834c2a85b2f3b70cbab264c8ef2
f4bc983c8ac2fe093f90c78967a04f5bf4f0c0fd
/Final/MyWin32.cpp
556d71762bdc53a6d3c4736ea3b5bd96167755c0
[]
no_license
wyattwhiting/CS271
214be4cd1bea95cfdc42a185cf91429f6f50058f
29e2cb579aa86f49a7fa6e376bd0a31e3f88d304
refs/heads/main
2023-03-04T02:14:09.078174
2021-02-14T04:10:41
2021-02-14T04:10:41
338,722,847
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
//MyWin32 - CS271 F2020 - Wyatt Whiting #include <Windows.h> int main() { MessageBoxA(NULL, "Hello, Win32.", "Ebic :DD", MB_ICONEXCLAMATION); return 0; }
[ "wyatt.d.whiting@gmail.com" ]
wyatt.d.whiting@gmail.com
65f37ac1e86955a2286503879fe6c90954a1784c
1eb36ccc0aa5c470ed062a82953b7c2677d9d2ac
/c_and_cpp/other_projects/computer_graphics_module_labs/week07/bezier.cc
7fe269ec3d9026b9c3e12419dcf8464cce0321a5
[]
no_license
carlawarde/projects
ffaaa85fd30d64e445294af947225c839ef33f55
f11ca63ef9921530322c323bace99f834b5947b8
refs/heads/master
2021-08-03T06:45:54.409835
2021-07-30T19:04:46
2021-07-30T19:04:46
191,652,705
2
1
null
2021-07-30T19:04:47
2019-06-12T22:23:55
HTML
UTF-8
C++
false
false
6,108
cc
#include <GL/glut.h> #include <stdlib.h> #include <math.h> #include <iostream> #if !defined(GLUT_WHEEL_UP) # define GLUT_WHEEL_UP 3 # define GLUT_WHEEL_DOWN 4 #endif /* Set initial size of the display window. */ GLsizei winWidth = 600, winHeight = 600; GLsizei newWidth, newHeight; /* Set size of world-coordinate clipping window. */ GLfloat xwcMin = -50.0, xwcMax = 50.0; GLfloat ywcMin = -50.0, ywcMax = 50.0; bool leftButton = false, middleButton = false; int downX, downY; int startMouseX, startMouseY, startTransX, startTransY, curTransX, curTransY; float zoom = 1.0; class wcPt3D { public: GLfloat x, y, z; }; void init (void) { /* Set color of display window to white. */ glClearColor (1.0, 1.0, 1.0, 0.0); } void plotPoint (wcPt3D bezCurvePt) { glBegin (GL_POINTS); glVertex2f (bezCurvePt.x, bezCurvePt.y); glEnd ( ); } /* Compute binomial coefficients C for given value of n. */ void binomialCoeffs (GLint n, GLint * C) { GLint k, j; for (k = 0; k <= n; k++) { /* Compute n!/(k!(n - k)!). */ C [k] = 1; for (j = n; j >= k + 1; j--) C [k] *= j; for (j = n - k; j >= 2; j--) C [k] /= j; } } void computeBezPt (GLfloat t, wcPt3D * bezPt, GLint nCtrlPts, wcPt3D * ctrlPts, GLint * C) { GLint k, n = nCtrlPts - 1; GLfloat bezBlendFcn; bezPt->x = bezPt->y = bezPt->z = 0.0; /* Compute blending functions and blend control points. */ for (k = 0; k < nCtrlPts; k++) { bezBlendFcn = C [k] * pow (t, k) * pow (1 - t, n - k); bezPt->x += ctrlPts [k].x * bezBlendFcn; bezPt->y += ctrlPts [k].y * bezBlendFcn; bezPt->z += ctrlPts [k].z * bezBlendFcn; } } void bezier (wcPt3D * ctrlPts, GLint nCtrlPts, GLint nBezCurvePts) { wcPt3D bezCurvePt; GLfloat t; GLint *C; /* Allocate space for binomial coefficients */ C = new GLint [nCtrlPts]; binomialCoeffs (nCtrlPts - 1, C); for (int i = 0; i <= nBezCurvePts; i++) { t = GLfloat (i) / GLfloat (nBezCurvePts); computeBezPt (t, &bezCurvePt, nCtrlPts, ctrlPts, C); plotPoint (bezCurvePt); } delete [ ] C; } void displayFcn (void) { glClear (GL_COLOR_BUFFER_BIT); // Clear display window. if(leftButton){ glMatrixMode (GL_PROJECTION); glLoadIdentity ( ); double w = glutGet( GLUT_WINDOW_WIDTH ); double h = glutGet( GLUT_WINDOW_HEIGHT ); glTranslatef( curTransX / w * 2, curTransY / h * 2, 0 ); gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); } /* Set example number of control points and number of * curve positions to be plotted along the Bezier curve. */ GLint nCtrlPts = 4, nBezCurvePts = 1000; wcPt3D ctrlPts [4] = { {-40.0, -40.0, 0.0}, {-10.0, 200.0, 0.0}, {10.0, -200.0, 0.0}, {40.0, 40.0, 0.0} }; glPointSize (4); glColor3f (1.0, 0.0, 0.0); // Set point color to red. bezier (ctrlPts, nCtrlPts, nBezCurvePts); glutSwapBuffers(); } void winReshapeFcn (GLint newWidth, GLint newHeight) { /* Maintain an aspect ratio of 1.0. */ // glViewport (0, 0, newHeight, newHeight); if(newWidth >= newHeight) glViewport(0,0, newHeight, newHeight); else glViewport(0,0, newWidth, newWidth); glMatrixMode (GL_PROJECTION); glLoadIdentity ( ); gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax); glutPostRedisplay(); } void MouseCallback(int button, int state, int x, int y) { downX = x; downY = y; int mod; leftButton = ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN)); mod = glutGetModifiers(); if(leftButton) { startMouseX = x; startMouseY = glutGet(GLUT_WINDOW_HEIGHT) - y; startTransX = curTransX; startTransY = curTransY; } if(mod == GLUT_ACTIVE_CTRL && button == 3) { zoom = zoom * 0.75; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } else if(mod == GLUT_ACTIVE_CTRL && button == 4) { zoom = zoom * 1.5; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } } void MotionCallback(int x, int y) { downX = x; downY = y; int curMouseX = x; int curMouseY = glutGet( GLUT_WINDOW_HEIGHT) - y; if (leftButton) { curTransX = startTransX + (curMouseX - startMouseX ); curTransY = startTransY + (curMouseY - startMouseY ); } glutPostRedisplay(); } void keyPress(unsigned char key, int x, int y) { if(key == 'z') { zoom = zoom * 0.75; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } else if(key == 'Z') { zoom = zoom * 1.5; glLoadIdentity ( ); if(winWidth >= winHeight) gluOrtho2D ((newHeight/2) - zoom,(newHeight/2) + zoom, (newHeight/2) - zoom, (newHeight/2) + zoom); else gluOrtho2D ((newWidth/2) - zoom,(newWidth/2) + zoom, (newWidth/2) - zoom, (newWidth/2) + zoom); glutPostRedisplay(); } } int main (int argc, char** argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowPosition (50, 50); glutInitWindowSize (winWidth, winHeight); glutCreateWindow ("Bezier Curve"); init ( ); glutDisplayFunc (displayFcn); glutReshapeFunc (winReshapeFcn); glutKeyboardFunc(keyPress); glutMouseFunc(MouseCallback); glutMotionFunc(MotionCallback); glutMainLoop ( ); }
[ "carla.warde98@gmail.com" ]
carla.warde98@gmail.com
81c684ac8c56f710e42c58b0b4e3662bdbef547c
1d6f19ced2319e0674ca954a6a4d1994da32b854
/aqcore/mixcomp.h
61b36fc2af16bf0fc6b9f3e8d2d614841fe3a44f
[]
no_license
yojiyojiyoji/AQUASIM
33096096ad81cf84d7adca1afc0fad179ba3f354
83dbdfe625a428c18d1a6ec8672d8146ea2ff0e7
refs/heads/master
2023-07-13T11:58:27.884332
2018-05-09T12:20:01
2018-05-09T12:20:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,127
h
/////////////////////////////// mixcomp.h //////////////////////////////// // // date: person: comments: // // creation: 10.12.91 Peter Reichert // revisions: 26.10.92 Peter Reichert redesign of links // 11.12.92 Peter Reichert variable volume added // 17.05.04 Peter Reichert converted to ANSI C++ // ////////////////////////////////////////////////////////////////////////////// // // "mixcomp" implements a class for mixed reactor compartments // =========================================================== // ////////////////////////////////////////////////////////////////////////////// // // Concepts // ======== // // // // ////////////////////////////////////////////////////////////////////////////// // // Class hierarchy // =============== // // NODE // | // +------+ // | // FILEIO | // | | // +------+----SYMBOL // | // +----AQCOMP // | // +----MIXCOMP // ////////////////////////////////////////////////////////////////////////////// // // Classes // ======= // // The following class is implemented in this file: // // MIXCOMP: class for mixed compartments // -------- // // ////////////////////////////////////////////////////////////////////////////// // // Methods of the class MIXCOMP // ============================ // // // // // // ////////////////////////////////////////////////////////////////////////////// #ifndef MIXCOMP_H #define MIXCOMP_H #include "aqcomp.h" ////////////////////////////////////////////////////////////////////////////// class MIXCOMP : public AQCOMP { friend class COMPSYS; public: MIXCOMP(); MIXCOMP(const MIXCOMP& com); MIXCOMP(const AQCOMP* com); ~MIXCOMP(); AQCOMPTYPE Type() const { return MixComp; } const char* TypeName() const; AQVAR* SpaceVar(const VARSYS*) const { return 0; } BOOLEAN AllowedSpaceVal(REAL) const { return TRUE; } BOOLEAN AllowedProgVarType(PROGVARTYPE type) const; BOOLEAN AllowedReplaceVar(const AQVAR* oldvar, const AQVAR* newvar) const; BOOLEAN AllowedExchangeVar(const AQVAR* var1, const AQVAR* var2) const; BOOLEAN AllowedComp() const; BOOLEAN AddInitCond(const VARLIST* varlist, CARDINAL zone, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos=CARDINAL_MAX); BOOLEAN ReplaceInitCond(const VARLIST* varlist, CARDINAL zone, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos); BOOLEAN DeleteInitCond(CARDINAL pos); CARDINAL NumInitCond() const { return numinit; } CARDINAL InitZone(CARDINAL index) const; AQVAR* InitVar(CARDINAL index) const; const FORMVAR* InitVal(CARDINAL index) const; BOOLEAN Inflow(const VARLIST* varlist, const char* inpline, char* errorline); const FORMVAR* Inflow() const { return inflow; } BOOLEAN AddInput(const VARLIST* varlist, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos=CARDINAL_MAX); BOOLEAN ReplaceInput(const VARLIST* varlist, AQVAR* var, const char* inpline, char* errorline, CARDINAL& numparseerrors, CARDINAL pos); BOOLEAN DeleteInput(CARDINAL pos); CARDINAL NumInput() const { return numinput; } AQVAR* InputVar(CARDINAL index) const; const FORMVAR* InputFlux(CARDINAL index) const; CARDINAL NumGridPts() const { return 1; } BOOLEAN NumGridPts(CARDINAL n); REAL GridPt(const REAL* Y, CARDINAL index); CARDINAL NumZoneGridPts(CARDINAL zone); REAL ZoneGridPt(const REAL* Y, CARDINAL zone, CARDINAL index); CARDINAL NumEq() const; REAL RelAcc(CARDINAL i) const; REAL AbsAcc(CARDINAL i) const; EQTYPE EqType(CARDINAL i) const; BOOLEAN InitCond(VARSYS* varsys, REAL* Y, CARDINAL callnum); BOOLEAN Delta(const NUMPAR& numpar, VARSYS* varsys, const REAL* Y, const REAL* YT, REAL* DELTA); BOOLEAN GridValue(VARSYS* varsys, CARDINAL* calcnum_ptr, REAL* t_ptr, const REAL* Y, CARDINAL zone, CARDINAL pt, AQVAR* var, REAL& value); BOOLEAN SpaceValue(VARSYS* varsys, CARDINAL* calcnum_ptr, REAL* t_ptr, const REAL* Y, CARDINAL zone, REAL x, BOOLEAN xrel, AQVAR* var, REAL& value); BOOLEAN FixedVol() const { return fixedvol; } BOOLEAN FixedVol(BOOLEAN b); REAL Vol() const { return vol; } BOOLEAN Vol(REAL v); BOOLEAN Outflow(const char* inpline, const VARLIST* varlist, char* errorline, CARDINAL& numparseerrors); const FORMVAR* Outflow() { return Qout; } CARDINAL NumZones() const; const char* ZoneName(CARDINAL index) const; const char* AdvInName(CARDINAL conn) const; const char* AdvOutName(CARDINAL conn) const; const char* DiffName(CARDINAL conn) const; BOOLEAN AdvInExZ(CARDINAL conn) const; REAL AdvInZ(const REAL* Y, CARDINAL conn) const; REAL AdvOutQ(VARSYS* varsys, const REAL* Y, CARDINAL conn); REAL AdvOutJ(VARSYS* varsys, const REAL* Y, CARDINAL conn, const AQVAR* var); REAL DiffC(const REAL* Y, CARDINAL conn, const AQVAR* var) const; BOOLEAN AccQ(REAL relacc, REAL absacc); BOOLEAN AccV(REAL relacc, REAL absacc); REAL RelAccQ() const { return relaccQ; } REAL AbsAccQ() const { return absaccQ; } REAL RelAccV() const { return relaccV; } REAL AbsAccV() const { return absaccV; } JOBSTATUS Load(std::istream& in,const VARLIST* varlist, const PROCLIST* proclist); JOBSTATUS Save(std::ostream& out); JOBSTATUS Write(std::ostream& out, BOOLEAN sh=FALSE); private: CARDINAL numinit; CARDINAL* initzone; AQVAR** initvar; FORMVAR** initval; FORMVAR* inflow; CARDINAL numinput; AQVAR** inputvar; FORMVAR** inputflux; BOOLEAN fixedvol; REAL vol; FORMVAR* Qout; REAL* Cout; CARDINAL numCout; REAL relaccQ; REAL absaccQ; REAL relaccV; REAL absaccV; void ReplVar(AQVAR* oldvar, AQVAR* newvar); void ExchVar(AQVAR* var1, AQVAR* var2); BOOLEAN SetGridPts(CARDINAL n); void CalcArg(); void init(); void del(); }; ////////////////////////////////////////////////////////////////////////////// #endif //////////////////////////////////////////////////////////////////////////////
[ "jstachelek@utexas.edu" ]
jstachelek@utexas.edu
3d1116de5c6887368201f3e3b5145addecd4204c
295710c5c59ba965149c1183b8e39ea28e195738
/ToirPlus_Old_Src/LoLBot/TabTwo.cpp
bb703dc8b26e121ab7d518bd2b9022c0914bb338
[]
no_license
PrtectInt3/ToirPlus_SRC
cfeee7e10eb9a4ba415d63511c4703f887c581fb
7f2084580caffd4f0e580b55cf59ec1e07ed523c
refs/heads/main
2023-02-25T17:43:47.771388
2021-01-28T21:11:07
2021-01-28T21:11:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
873
cpp
// TabTwo.cpp : implementation file // #include "stdafx.h" #include "LoLBot.h" #include "TabTwo.h" // CTabTwo dialog IMPLEMENT_DYNAMIC(CTabTwo, CDialog) CTabTwo::CTabTwo(CWnd* pParent /*=NULL*/) : CDialog(CTabTwo::IDD, pParent) { } CTabTwo::~CTabTwo() { } void CTabTwo::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CTabTwo, CDialog) ON_CONTROL_RANGE(BN_CLICKED, LOLBOT_TAT_BAT_VE, LOLBOT_VE_ENEMY_SKILL_R, OnTab2ChecBoxStatusChanged) END_MESSAGE_MAP() // CTabTwo message handlers //#include "Commons.h" //extern HWND g_hWinAPP; void CTabTwo::OnTab2ChecBoxStatusChanged(UINT nID) { CButton *pCheckBox = (CButton *)GetDlgItem(nID); ::PostMessage(g_hWinAPP, WM_HOOK_WRITE, nID, pCheckBox->GetCheck()); //__oMsg("--------------->[%s][%d]haint--->stt check:%d;ID=%d", __FILE__, __LINE__, pCheckBox->GetCheck(), nID); }
[ "michuelhack@gmail.com" ]
michuelhack@gmail.com
3baad681e6b02de3aeb7ee83b29a16f2ef769408
f98049b004e5e452f9a5043162a1ef596870fba6
/class/car.cpp
b4664570a3304432e38d215598fc94135d403ab1
[]
no_license
JinKyuGit/CPlusPlus
3525319574373ade20a85353df2519e4969850fb
d5b14f1ab8211eab3468353a5bb48215a6e3aa58
refs/heads/master
2021-05-11T23:46:34.049510
2018-02-07T04:21:03
2018-02-07T04:21:03
117,518,786
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
#include<iostream> #include"car.h" using namespace std; void Car::Show(){ cout<<"\n == 현재상태 ==\n"; cout<<"속도 : "<<this->speed<<endl; cout<<"연료 : "<<this->fuel<<endl; cout<<" ========= \n"; cout<<"1. 가속\n"; cout<<"2. 감속\n"; } void Car::Accel(){ this->speed+=10; this->fuel-=5; } void Car::Break(){ if(this->speed < 10){ this->speed=0; cout<<" stop\n"; return; } this->speed-=10; }
[ "wlsrb8993@gmail.com" ]
wlsrb8993@gmail.com
e65f99eb47f280a3f45fc11006b8469207d57fbf
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_919.cpp
16540e7b9b94419496dceaa6350108cf22f3d561
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
case 'm': if (building_deny_info_url) break; #if USE_AUTH p = auth_user_request->denyMessage("[not available]"); #else p = "-"; #endif
[ "993273596@qq.com" ]
993273596@qq.com
b1b0cfa63a2336709ab9b95b7c3df22351be0d32
7f931e20074f464277a551ac6162aec42f9b96fb
/tva/TVS/slnTva/prjShell/shell.h
8678e2d497f98c6deda14d4093d4f43f73cb09ec
[]
no_license
yetanother/tvaSoft
6ee5c7c34ba7aaca68721c7fce29bdc4e6b054f5
41b416ec27f4c706febd96b7d2a3aff1bab64e6b
refs/heads/master
2021-01-01T16:05:53.390398
2013-07-15T13:14:43
2013-07-15T13:14:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
#pragma once #include "..\src\corelib\kernel\qobject.h" #include "..\..\slnPreProc\tvaModel.h" class MainWindow; namespace tva { class Logger; // class Shell: public QObject { Q_OBJECT private: MainWindow *mw_; Logger* logger_; tva::Model model; public: Shell():mw_(nullptr){} void setMainWnd(MainWindow*mw){mw_= mw;} void setLogger(Logger* logger){logger_=logger;} tva::Model& getModel(){return model;} public slots: void show(); void addLineToLogger(const QString& str)const; }; }
[ "std.approach@gmail.com" ]
std.approach@gmail.com
af7baadd90bb94ec036d0118f457cabd3f856347
5afb8bcb3c0edcc0266d1811d7aede7895c835f3
/src/qt/walletmodel.cpp
3aa87a397b30658edc28cb9b1afebb149ceed57d
[ "MIT" ]
permissive
CryptoHours/cryptohours
7a6b5b6a0dcffffe1c8a03aa8a348e75b7811505
b45d71bb7f34a6e39ee60024318487db2ae6573e
refs/heads/master
2021-09-03T06:14:31.357128
2018-01-06T08:29:51
2018-01-06T08:29:51
113,479,293
0
0
null
null
null
null
UTF-8
C++
false
false
25,568
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletmodel.h" #include "addresstablemodel.h" #include "guiconstants.h" #include "recentrequeststablemodel.h" #include "transactiontablemodel.h" #include "base58.h" #include "db.h" #include "keystore.h" #include "main.h" #include "spork.h" #include "sync.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include <stdint.h> #include <QDebug> #include <QSet> #include <QTimer> using namespace std; WalletModel::WalletModel(CWallet* wallet, OptionsModel* optionsModel, QObject* parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), recentRequestsTableModel(0), cachedBalance(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedZerocoinBalance(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { fHaveWatchOnly = wallet->HaveWatchOnly(); fForceCheckBalanceChanged = false; addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); recentRequestsTableModel = new RecentRequestsTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } CAmount WalletModel::getBalance(const CCoinControl* coinControl) const { if (coinControl) { CAmount nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH (const COutput& out, vCoins) if (out.fSpendable) nBalance += out.tx->vout[out.i].nValue; return nBalance; } return wallet->GetBalance(); } CAmount WalletModel::getZerocoinBalance() const { return wallet->GetZerocoinBalance(); } CAmount WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } CAmount WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } bool WalletModel::haveWatchOnly() const { return fHaveWatchOnly; } CAmount WalletModel::getWatchBalance() const { return wallet->GetWatchOnlyBalance(); } CAmount WalletModel::getWatchUnconfirmedBalance() const { return wallet->GetUnconfirmedWatchOnlyBalance(); } CAmount WalletModel::getWatchImmatureBalance() const { return wallet->GetImmatureWatchOnlyBalance(); } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if (cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { // Get required locks upfront. This avoids the GUI from getting stuck on // periodical polls if the core is holding the locks for a longer time - // for example, during a wallet rescan. TRY_LOCK(cs_main, lockMain); if (!lockMain) return; TRY_LOCK(wallet->cs_wallet, lockWallet); if (!lockWallet) return; if (fForceCheckBalanceChanged || chainActive.Height() != cachedNumBlocks || nZeromintPercentage != cachedZeromintPercentage || cachedTxLocks != nCompleteTXLocks) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed cachedNumBlocks = chainActive.Height(); cachedZeromintPercentage = nZeromintPercentage; checkBalanceChanged(); if (transactionTableModel) { transactionTableModel->updateConfirmations(); } } } void WalletModel::checkBalanceChanged() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; CAmount newBalance = getBalance(); CAmount newUnconfirmedBalance = getUnconfirmedBalance(); CAmount newImmatureBalance = getImmatureBalance(); CAmount newZerocoinBalance = getZerocoinBalance(); CAmount newWatchOnlyBalance = 0; CAmount newWatchUnconfBalance = 0; CAmount newWatchImmatureBalance = 0; if (haveWatchOnly()) { newWatchOnlyBalance = getWatchBalance(); newWatchUnconfBalance = getWatchUnconfirmedBalance(); newWatchImmatureBalance = getWatchImmatureBalance(); } if (cachedBalance != newBalance || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedZerocoinBalance != newZerocoinBalance || cachedTxLocks != nCompleteTXLocks || cachedWatchOnlyBalance != newWatchOnlyBalance || cachedWatchUnconfBalance != newWatchUnconfBalance || cachedWatchImmatureBalance != newWatchImmatureBalance) { cachedBalance = newBalance; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; cachedZerocoinBalance = newZerocoinBalance; cachedTxLocks = nCompleteTXLocks; cachedWatchOnlyBalance = newWatchOnlyBalance; cachedWatchUnconfBalance = newWatchUnconfBalance; cachedWatchImmatureBalance = newWatchImmatureBalance; emit balanceChanged(newBalance, newUnconfirmedBalance, newImmatureBalance, newZerocoinBalance, newWatchOnlyBalance, newWatchUnconfBalance, newWatchImmatureBalance); } } void WalletModel::updateTransaction() { // Balance and number of transactions might have changed fForceCheckBalanceChanged = true; } void WalletModel::updateAddressBook(const QString& address, const QString& label, bool isMine, const QString& purpose, int status) { if (addressTableModel) addressTableModel->updateEntry(address, label, isMine, purpose, status); } void WalletModel::updateAddressBook(const QString &pubCoin, const QString &isUsed, int status) { if(addressTableModel) addressTableModel->updateEntry(pubCoin, isUsed, status); } void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly) { fHaveWatchOnly = fHaveWatchonly; emit notifyWatchonlyChanged(fHaveWatchonly); } bool WalletModel::validateAddress(const QString& address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction& transaction, const CCoinControl* coinControl) { CAmount total = 0; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<std::pair<CScript, CAmount> > vecSend; if (recipients.empty()) { return OK; } if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... CAmount subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr + out.script().size()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, out.amount())); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered pivx address / amount: if (!validateAddress(rcp.address)) { return InvalidAddress; } if (rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(std::pair<CScript, CAmount>(scriptPubKey, rcp.amount)); total += rcp.amount; } } if (setAddress.size() != nAddresses) { return DuplicateAddress; } CAmount nBalance = getBalance(coinControl); if (total > nBalance) { return AmountExceedsBalance; } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); CAmount nFeeRequired = 0; std::string strFailReason; CWalletTx* newTx = transaction.getTransaction(); CReserveKey* keyChange = transaction.getPossibleKeyChange(); if (recipients[0].useSwiftTX && total > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftTX doesn't support sending values that high yet. Transactions are currently limited to %1 PIV.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl, recipients[0].inputType, recipients[0].useSwiftTX); transaction.setTransactionFee(nFeeRequired); if (recipients[0].useSwiftTX && newTx->GetValueOut() > GetSporkValue(SPORK_5_MAX_VALUE) * COIN) { emit message(tr("Send Coins"), tr("SwiftTX doesn't support sending values that high yet. Transactions are currently limited to %1 PIV.").arg(GetSporkValue(SPORK_5_MAX_VALUE)), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } if (!fCreated) { if ((total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } emit message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // reject insane fee if (nFeeRequired > ::minRelayTxFee.GetFee(transaction.getTransactionSize()) * 10000) return InsaneFee; } return SendCoinsReturn(OK); } WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction& transaction) { QByteArray transaction_array; /* store serialized transaction */ if (isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } { LOCK2(cs_main, wallet->cs_wallet); CWalletTx* newTx = transaction.getTransaction(); QList<SendCoinsRecipient> recipients = transaction.getRecipients(); // Store PaymentRequests in wtx.vOrderForm in wallet. foreach (const SendCoinsRecipient& rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { std::string key("PaymentRequest"); std::string value; rcp.paymentRequest.SerializeToString(&value); newTx->vOrderForm.push_back(make_pair(key, value)); } else if (!rcp.message.isEmpty()) // Message from normal pivx:URI (pivx:XyZ...?message=example) { newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString())); } } CReserveKey* keyChange = transaction.getPossibleKeyChange(); transaction.getRecipients(); if (!wallet->CommitTransaction(*newTx, *keyChange, (recipients[0].useSwiftTX) ? "ix" : "tx")) return TransactionCommitFailed; CTransaction* t = (CTransaction*)newTx; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *t; transaction_array.append(&(ssTx[0]), ssTx.size()); } // Add addresses / update labels that we've sent to to the address book, // and emit coinsSent signal for each recipient foreach (const SendCoinsRecipient& rcp, transaction.getRecipients()) { // Don't touch the address book when we have a payment request if (!rcp.paymentRequest.IsInitialized()) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end()) { wallet->SetAddressBook(dest, strLabel, "send"); } else if (mi->second.name != strLabel) { wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } emit coinsSent(wallet, rcp, transaction_array); } checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits return SendCoinsReturn(OK); } OptionsModel* WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel* WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel* WalletModel::getTransactionTableModel() { return transactionTableModel; } RecentRequestsTableModel* WalletModel::getRecentRequestsTableModel() { return recentRequestsTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if (!wallet->IsCrypted()) { return Unencrypted; } else if (wallet->fWalletUnlockAnonymizeOnly) { return UnlockedForAnonymizationOnly; } else if (wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString& passphrase) { if (encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString& passPhrase, bool anonymizeOnly) { if (locked) { // Lock wallet->fWalletUnlockAnonymizeOnly = false; return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase, anonymizeOnly); } } bool WalletModel::isAnonymizeOnlyUnlocked() { return wallet->fWalletUnlockAnonymizeOnly; } bool WalletModel::changePassphrase(const SecureString& oldPass, const SecureString& newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString& filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel* walletmodel, CCryptoKeyStore* wallet) { qDebug() << "NotifyKeyStoreStatusChanged"; QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel* walletmodel, CWallet* wallet, const CTxDestination& address, const std::string& label, bool isMine, const std::string& purpose, ChangeType status) { QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString()); QString strLabel = QString::fromStdString(label); QString strPurpose = QString::fromStdString(purpose); qDebug() << "NotifyAddressBookChanged : " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + strPurpose + " status=" + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, strAddress), Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(QString, strPurpose), Q_ARG(int, status)); } // queue notifications to show a non freezing progress dialog e.g. for rescan static bool fQueueNotifications = false; static std::vector<std::pair<uint256, ChangeType> > vQueueNotifications; static void NotifyTransactionChanged(WalletModel* walletmodel, CWallet* wallet, const uint256& hash, ChangeType status) { if (fQueueNotifications) { vQueueNotifications.push_back(make_pair(hash, status)); return; } QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection /*, Q_ARG(QString, strHash), Q_ARG(int, status)*/); } static void ShowProgress(WalletModel* walletmodel, const std::string& title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyWatchonlyChanged(WalletModel* walletmodel, bool fHaveWatchonly) { QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); } static void NotifyZerocoinChanged(WalletModel* walletmodel, CWallet* wallet, const std::string& hexString, const std::string& isUsed, ChangeType status) { QString HexStr = QString::fromStdString(hexString); QString isUsedStr = QString::fromStdString(isUsed); qDebug() << "NotifyZerocoinChanged : " + HexStr + " " + isUsedStr + " status= " + QString::number(status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, HexStr), Q_ARG(QString, isUsedStr), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.connect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyZerocoinChanged.connect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5, _6)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); wallet->NotifyWatchonlyChanged.disconnect(boost::bind(NotifyWatchonlyChanged, this, _1)); wallet->NotifyZerocoinChanged.disconnect(boost::bind(NotifyZerocoinChanged, this, _1, _2, _3, _4)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock(bool relock) { bool was_locked = getEncryptionStatus() == Locked; if (!was_locked && isAnonymizeOnlyUnlocked()) { setWalletLocked(true); wallet->fWalletUnlockAnonymizeOnly = false; was_locked = getEncryptionStatus() == Locked; } if (was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(valid, relock); // return UnlockContext(this, valid, was_locked && !isAnonymizeOnlyUnlocked()); } WalletModel::UnlockContext::UnlockContext(bool valid, bool relock) : valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { /* if (valid && relock) { wallet->setWalletLocked(true); } */ } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { LOCK2(cs_main, wallet->cs_wallet); BOOST_FOREACH (const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vOutputs.push_back(out); } } bool WalletModel::isSpent(const COutPoint& outpoint) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsSpent(outpoint.hash, outpoint.n); } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector<COutPoint> vLockedCoins; wallet->ListLockedCoins(vLockedCoins); // add locked coins BOOST_FOREACH (const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); if (outpoint.n < out.tx->vout.size() && wallet->IsMine(out.tx->vout[outpoint.n]) == ISMINE_SPENDABLE) vCoins.push_back(out); } BOOST_FOREACH (const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true); } CTxDestination address; if (!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[QString::fromStdString(CBitcoinAddress(address).ToString())].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { LOCK2(cs_main, wallet->cs_wallet); return wallet->IsLockedCoin(hash, n); } void WalletModel::lockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->LockCoin(output); } void WalletModel::unlockCoin(COutPoint& output) { LOCK2(cs_main, wallet->cs_wallet); wallet->UnlockCoin(output); } void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts) { LOCK2(cs_main, wallet->cs_wallet); wallet->ListLockedCoins(vOutpts); } void WalletModel::listZerocoinMints(std::list<CZerocoinMint>& listMints, bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus) { listMints.clear(); CWalletDB walletdb(wallet->strWalletFile); listMints = walletdb.ListMintedCoins(fUnusedOnly, fMaturedOnly, fUpdateStatus); } void WalletModel::loadReceiveRequests(std::vector<std::string>& vReceiveRequests) { LOCK(wallet->cs_wallet); BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) BOOST_FOREACH (const PAIRTYPE(std::string, std::string) & item2, item.second.destdata) if (item2.first.size() > 2 && item2.first.substr(0, 2) == "rr") // receive request vReceiveRequests.push_back(item2.second); } bool WalletModel::saveReceiveRequest(const std::string& sAddress, const int64_t nId, const std::string& sRequest) { CTxDestination dest = CBitcoinAddress(sAddress).Get(); std::stringstream ss; ss << nId; std::string key = "rr" + ss.str(); // "rr" prefix = "receive request" in destdata LOCK(wallet->cs_wallet); if (sRequest.empty()) return wallet->EraseDestData(dest, key); else return wallet->AddDestData(dest, key, sRequest); } bool WalletModel::isMine(CBitcoinAddress address) { return IsMine(*wallet, address.Get()); }
[ "ivan.helmot@yahoo.com" ]
ivan.helmot@yahoo.com
0e115863a7a2a9339c80a116d758ce7717d5c2e2
f9d7775bef11d1621c5e8417046b9161e63eacb7
/include/ipv6_address.h
25357512455b7e2133bbe532f7895a0730393d0f
[]
no_license
sdeming/spirit-parsers
43d6269402a99eae1119d00d2bdc97201ce435ab
98b4b6f671b59d0d33af6bc68091b61ce33714c5
refs/heads/master
2020-05-19T10:34:49.890303
2016-08-25T14:32:13
2016-08-25T14:32:13
546,967
1
0
null
null
null
null
UTF-8
C++
false
false
2,684
h
#ifndef __ipv6_parser_h__ #define __ipv6_parser_h__ #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include "ipv4_address.h" #include <iostream> #include <string> namespace uri { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace phoenix = boost::phoenix; /** * Implementation of an ipv6 IP address parser */ template <typename Iterator> struct ipv6_address : qi::grammar<Iterator, std::string()> { ipv6_address() : ipv6_address::base_type(start) { using qi::repeat; using qi::raw; using ascii::xdigit; qi::on_error<qi::fail> ( start, std::cerr << phoenix::val("Error! Expecting") << qi::_4 << phoenix::val(" here: \"") << phoenix::construct<std::string>(qi::_3, qi::_2) << phoenix::val("\"") << std::endl ); h16 = repeat(1,4)[xdigit]; ls32 = h16 >> ':' >> h16 | ipv4 ; ipv6_attr = repeat(6)[h16 >> ':'] >> ls32 | "::" >> repeat(5)[h16 >> ':'] >> ls32 | - h16 >> "::" >> repeat(4)[h16 >> ':'] >> ls32 | -(h16 >> -( ':' >> h16) ) >> "::" >> repeat(3)[h16 >> ':'] >> ls32 | -(h16 >> -repeat(1,2)[':' >> h16] ) >> "::" >> repeat(2)[h16 >> ':'] >> ls32 | -(h16 >> -repeat(1,3)[':' >> h16] ) >> "::" >> h16 >> ':' >> ls32 | -(h16 >> -repeat(1,4)[':' >> h16] ) >> "::" >> ls32 | -(h16 >> -repeat(1,5)[':' >> h16] ) >> "::" >> h16 | -(h16 >> -repeat(1,6)[':' >> h16] ) >> "::" ; start = raw[ipv6_attr]; h16.name("h16"); ls32.name("ls32"); ipv6_attr.name("ipv6_attr"); start.name("start"); } ipv4_address<Iterator> ipv4; qi::rule<Iterator> h16, ls32; qi::rule<Iterator, std::string()> ipv6_attr; qi::rule<Iterator, std::string()> start; }; } // namespace uri #endif // __ipv6_parser_h__
[ "sdeming@makefile.com" ]
sdeming@makefile.com
7799c1916b8a5834d3be6ecbb6374bde9a0893b7
dc1b29c1041ee98d882751a53c49c1044ea272eb
/src/blockchain_utilities/blockchain_export.cpp
8db4fe5e6cf2cc648b0d9b4b44d55bd5750aea9c
[ "BSD-3-Clause" ]
permissive
XtendCash/XtendCash
ed3bcf5fd52eff151821f33f63b47de55792f2ff
f82de0b9e0f0ba4893713dc5021ff87de9943212
refs/heads/master
2020-05-05T00:16:17.280894
2019-09-15T03:03:13
2019-09-15T03:03:13
179,569,723
3
3
NOASSERTION
2019-08-25T23:41:29
2019-04-04T20:10:26
C++
UTF-8
C++
false
false
7,369
cpp
// Copyright (c) 2014-2018, The Monero Project // Copyright (c) 2018, The Loki Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "bootstrap_file.h" #include "blocksdat_file.h" #include "common/command_line.h" #include "cryptonote_core/cryptonote_core.h" #include "blockchain_objects.h" #include "blockchain_db/db_types.h" #include "version.h" #undef XTEND_DEFAULT_LOG_CATEGORY #define XTEND_DEFAULT_LOG_CATEGORY "bcutil" namespace po = boost::program_options; using namespace epee; int main(int argc, char* argv[]) { TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); std::string default_db_type = "lmdb"; std::string available_dbs = cryptonote::blockchain_db_types(", "); available_dbs = "available: " + available_dbs; uint32_t log_level = 0; uint64_t block_stop = 0; bool blocks_dat = false; tools::on_startup(); boost::filesystem::path output_file_path; po::options_description desc_cmd_only("Command line options"); po::options_description desc_cmd_sett("Command line options and settings options"); const command_line::arg_descriptor<std::string> arg_output_file = {"output-file", "Specify output file", "", true}; const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""}; const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop}; const command_line::arg_descriptor<std::string> arg_database = { "database", available_dbs.c_str(), default_db_type }; const command_line::arg_descriptor<bool> arg_blocks_dat = {"blocksdat", "Output in blocks.dat format", blocks_dat}; command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir); command_line::add_arg(desc_cmd_sett, arg_output_file); command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on); command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on); command_line::add_arg(desc_cmd_sett, arg_log_level); command_line::add_arg(desc_cmd_sett, arg_database); command_line::add_arg(desc_cmd_sett, arg_block_stop); command_line::add_arg(desc_cmd_sett, arg_blocks_dat); command_line::add_arg(desc_cmd_only, command_line::arg_help); po::options_description desc_options("Allowed options"); desc_options.add(desc_cmd_only).add(desc_cmd_sett); po::variables_map vm; bool r = command_line::handle_error_helper(desc_options, [&]() { po::store(po::parse_command_line(argc, argv, desc_options), vm); po::notify(vm); return true; }); if (! r) return 1; if (command_line::get_arg(vm, command_line::arg_help)) { std::cout << "Xtend '" << XTEND_RELEASE_NAME << "' (v" << XTEND_VERSION_FULL << ")" << ENDL << ENDL; std::cout << desc_options << std::endl; return 1; } mlog_configure(mlog_get_default_log_path("xtend-blockchain-export.log"), true); if (!command_line::is_arg_defaulted(vm, arg_log_level)) mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); block_stop = command_line::get_arg(vm, arg_block_stop); LOG_PRINT_L0("Starting..."); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on); if (opt_testnet && opt_stagenet) { std::cerr << "Can't specify more than one of --testnet and --stagenet" << std::endl; return 1; } bool opt_blocks_dat = command_line::get_arg(vm, arg_blocks_dat); std::string m_config_folder; m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir); std::string db_type = command_line::get_arg(vm, arg_database); if (!cryptonote::blockchain_valid_db_type(db_type)) { std::cerr << "Invalid database type: " << db_type << std::endl; return 1; } if (command_line::has_arg(vm, arg_output_file)) output_file_path = boost::filesystem::path(command_line::get_arg(vm, arg_output_file)); else output_file_path = boost::filesystem::path(m_config_folder) / "export" / BLOCKCHAIN_RAW; LOG_PRINT_L0("Export output file: " << output_file_path.string()); LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); blockchain_objects_t blockchain_objects = {}; Blockchain *core_storage = &blockchain_objects.m_blockchain; BlockchainDB *db = new_db(db_type); if (db == NULL) { LOG_ERROR("Attempted to use non-existent database type: " << db_type); throw std::runtime_error("Attempting to use non-existent database type"); } LOG_PRINT_L0("database: " << db_type); boost::filesystem::path folder(m_config_folder); folder /= db->get_db_name(); const std::string filename = folder.string(); LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); try { db->open(filename, DBF_RDONLY); } catch (const std::exception& e) { LOG_PRINT_L0("Error opening database: " << e.what()); return 1; } r = core_storage->init(db, opt_testnet ? cryptonote::TESTNET : opt_stagenet ? cryptonote::STAGENET : cryptonote::MAINNET); if (core_storage->get_blockchain_pruning_seed()) { LOG_PRINT_L0("Blockchain is pruned, cannot export"); return 1; } CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); LOG_PRINT_L0("Source blockchain storage initialized OK"); LOG_PRINT_L0("Exporting blockchain raw data..."); if (opt_blocks_dat) { BlocksdatFile blocksdat; r = blocksdat.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } else { BootstrapFile bootstrap; r = bootstrap.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop); } CHECK_AND_ASSERT_MES(r, 1, "Failed to export blockchain raw data"); LOG_PRINT_L0("Blockchain raw data exported OK"); return 0; CATCH_ENTRY("Export error", 1); }
[ "49289946+XtendCash@users.noreply.github.com" ]
49289946+XtendCash@users.noreply.github.com
b52d6a1c29108ecd018b55ce4d32f9a4bcd3ab1a
20d024bd04ace59987ba05f864d6d9dece72fbab
/CQU Summer/西南弱校联萌训练赛(1)/G - Problem G.cpp
9974244ba0fe5231af5c5e6bbd61c7919fa74942
[]
no_license
Yeluorag/ACM-ICPC-Code-Library
8837688c23bf487d4374a76cf0656cb7adc751b0
77751c79549ea8ab6f790d55fac3738d5b615488
refs/heads/master
2021-01-20T20:18:43.366920
2016-08-12T08:08:38
2016-08-12T08:08:38
64,487,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
cpp
// Header. #include <set> #include <map> #include <queue> #include <stack> #include <cmath> #include <cstdio> #include <vector> #include <string> #include <sstream> #include <cstring> #include <iostream> #include <algorithm> using namespace std; // Macro typedef long long LL; #define mem(a, n) memset(a, n, sizeof(a)) #define rep(i, n) for(int i = 0; i < (n); i ++) #define REP(i, t, n) for(int i = (t); i < (n); i ++) #define FOR(i, t, n) for(int i = (t); i <= (n); i ++) #define ALL(v) v.begin(), v.end() #define Min(a, b) a = min(a, b) #define Max(a, b) a = max(a, b) #define put(a) printf("%d\n", a) #define ss(a) scanf("%s", a) #define si(a) scanf("%d", &a) #define sii(a, b) scanf("%d%d", &a, &b) #define siii(a, b, c) scanf("%d%d%d", &a, &b, &c) #define VI vector<int> #define pb push_back const int inf = 0x3f3f3f3f, N = 3e5 + 5, MOD = 1e9 + 7; // Macro end int T, cas = 0; int n, m, a[N]; // Imp #define LOCAL int main(){ #ifdef LOCAL freopen("/Users/apple/input.txt", "r", stdin); // freopen("/Users/apple/out.txt", "w", stdout); #endif si(n); FOR(i, 1, n) si(a[i]); int l, r, dv = inf; FOR(i, 1, n) { int tmp = dv; Min(tmp, a[i]); if(a[i] % tmp) } return 0; }
[ "yeluorag@gmail.com" ]
yeluorag@gmail.com
f941f8877abd3f27028b006fb49d212fcc0dd30c
1d1f79a08c9c23582501f0afaff3e98952a731be
/Runtime/Src/External.hpp
8be537ab9fe1d1559c75ed4691d2214f3f47fdd4
[]
no_license
smorel/Cheezy
65fab8dc9f05d6a7d4f92369a86f048507d90d27
9cab8f0165f3cb1681472317190db0984e1ffe9b
refs/heads/master
2021-01-20T10:10:55.200685
2019-01-16T23:33:30
2019-01-16T23:33:30
2,325,685
0
0
null
null
null
null
UTF-8
C++
false
false
79
hpp
#pragma once #include "Core/Src/Public.hpp" #include "UnitTest/Src/Public.hpp"
[ "sebastien.morel@autodesk.com" ]
sebastien.morel@autodesk.com
2efd53f5a1010222a98ad3e82893066d90a3fc41
2ed96334b80d8aada5026e9ee8b3633e42d7064c
/Platformer/src/game/state_stack.cpp
870e922409b9e759bce632afe91dddc940f9c1c5
[]
no_license
matt4682/platformer
0e0c8a9f667d482e2752c62afa09a7e66880d819
2b756ee9a2d4b04e0106463ace46fa2a8ae818e6
refs/heads/master
2021-01-23T06:21:04.311802
2017-03-27T17:18:26
2017-03-27T17:18:26
86,359,806
0
0
null
null
null
null
UTF-8
C++
false
false
3,355
cpp
#include "./state_stack.h" #include "../ui/states/play_state.h" #include "../ui/states/pause_state.h" #include "../ui/states/level_select_state.h" #include "../ui/states/world_select_state.h" #include "../ui/states/level_loading_state.h" #include "../ui/states/level_completion_state.h" #include "../ui/states/menu_state.h" #include "../ui/states/option_state.h" #include "../ui/states/help_state.h" StateStack::StateStack(State::Context context) : mContext(context) {} void StateStack::update(sf::Time deltaTime) { for (auto i = mStack.rbegin(); i != mStack.rend(); ++i) { if (!i->get()->update(deltaTime)) break; } applyPendingChanges(); } void StateStack::draw() { for (auto i = mStack.begin(); i != mStack.end(); ++i) { i->get()->draw(); } } void StateStack::handleEvent(const sf::Event &event) { for (auto i = mStack.rbegin(); i != mStack.rend(); ++i) { if (!i->get()->handleEvent(event)) break; } } State::Ptr StateStack::createState(State::ID stateID, const std::string &map) { switch (stateID) { case(State::ID::Play) : return std::unique_ptr<PlayState>(new PlayState(*this, mContext, map)); case(State::ID::Pause) : return std::unique_ptr<PauseState>(new PauseState(*this, mContext, map)); case(State::ID::WorldSelect) : return std::unique_ptr<WorldSelectState>(new WorldSelectState(*this, mContext, map)); case(State::ID::LevelSelect) : return std::unique_ptr<LevelSelectState>(new LevelSelectState(*this, mContext, map)); case(State::ID::LevelCompletion) : return std::unique_ptr<LevelCompletionState>(new LevelCompletionState(*this, mContext)); case(State::ID::LoadingWorld) : return std::unique_ptr<LevelSelectState>(new LevelSelectState(*this, mContext, map)); case(State::ID::Loading) : return std::unique_ptr<LevelLoadingState>(new LevelLoadingState(*this, mContext, map)); case(State::ID::Menu) : return std::unique_ptr<MenuState>(new MenuState(*this, mContext)); case(State::ID::Option) : return std::unique_ptr<OptionState>(new OptionState(*this, mContext)); case(State::ID::Help) : return std::unique_ptr<HelpState>(new HelpState(*this, mContext)); default: return std::unique_ptr<MenuState>(new MenuState(*this, mContext)); } } void StateStack::pushState(State::ID stateID, const std::string &map) { mPendingList.push_back(PendingChange(Push, stateID, map)); } void StateStack::popState() { mPendingList.push_back(PendingChange(Pop)); } void StateStack::clearStates() { mPendingList.push_back(PendingChange(Clear)); } void StateStack::onResolutionChange() { mPendingList.push_back(PendingChange(Resolution)); } bool StateStack::isEmpty() const { return mStack.empty(); } void StateStack::applyPendingChanges() { for (auto &change : mPendingList) { switch (change.action) { case(Action::Push) : mStack.push_back(std::move(createState(change.stateID, change.map))); break; case(Action::Pop) : mStack.pop_back(); break; case(Action::Clear) : mStack.clear(); break; case(Action::Resolution) : for (auto &state : mStack) state->onResolutionChange(); break; } } mPendingList.clear(); } State::Context StateStack::getContext() const { return mContext; }
[ "m_wilmink@fanshaweonline.ca" ]
m_wilmink@fanshaweonline.ca
5c3d69a602773d6ae6795969fe1bce3709c93fb2
eff63d54d63acf878b013342fc43c222be535164
/maths/euler_tot.cpp
9661882e4a94f8277f2e5d2ab7ac9ec03df733da
[]
no_license
viv-india/Viv_lib
526753e0fbf0143fe2fea9ac5bf2c848eb09b4fb
360515ca3a009521e55d258d299fb28789545855
refs/heads/master
2023-05-15T08:12:39.313302
2023-05-03T16:48:43
2023-05-03T16:48:43
85,391,925
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
/*************What doesn't kills you makes you stronger************************/ #include<bits/stdc++.h> #include<algorithm> using namespace std; #define ld long double #define ll long long #define mod 1000000007 #define f(i,n) for( ll (i)= 0;(i)<(n);(i)++) #define faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define lp pair<ll,ll> #define maxn 1000000 //ll gcd(ll a ,ll b) {return(a==0?b:gcd(b%a,a));} ll tot(ll n) {ll ans=n; if(n%2==0) ans=(n/2); while(n%2==0) {n/=2;} ll sq=sqrt(n); for(ll i=3;i<=sq;i+=2) { if(n%i==0) ans=(ans/i)*(i-1); while(n%i==0) {n/=i;} } if(n>1) ans=(ans/n)*(n-1); return ans;} int main() {faster; ll n,x; cin>>n; while(n--) {cin>>x;cout<<tot(x)<<endl;} }
[ "vivek.singh9022@gmail.com" ]
vivek.singh9022@gmail.com
a02b0f3f2b2f2c94424a5a3e5503bb1909105a22
6cabb3a28013758e71c3cfab530762d49b89785b
/贪心/F - 1838 鎕鎕鎕(构造法).cpp
19d563c32b941fcb8000b0890758268bba48ae32
[]
no_license
TreeYD/Code
2caeccbebd1330fd51373fc46aafd6804c9446bf
1e16ccc80cf36af3728f3ca172e4ab86402e4d8e
refs/heads/master
2020-04-01T22:47:06.318221
2018-10-31T11:37:19
2018-10-31T11:37:19
153,726,191
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include<bits/stdc++.h> using namespace std; #define M 200005 struct Node{ int a,b,id; bool operator<(const Node &x)const{ return a<x.a; } }A[M<<1]; int n; int main(){ scanf("%d",&n); for(int i=1;i<=n*2+1;i++){ scanf("%d%d",&A[i].a,&A[i].b); A[i].id=i; } sort(A+1,A+1+n*2+1); for(int i=1;i<=n;i++){ int a=2*i-1,b=2*i; if(A[a].b>A[b].b)printf("%d\n",A[a].id); else printf("%d\n",A[b].id); } printf("%d\n",A[n*2+1].id); return 0; }
[ "treeYd@qq.com" ]
treeYd@qq.com
f1e2db1971355d10830c5f3be053050855364587
a79d9f2e9626bb428f2f322cafd0fbf800bcdc2f
/src/EC/Item_component.cpp
6b35d684b741b9c35d6005d9ead47ba8d6a953d0
[ "GLWTPL" ]
permissive
marcintaton/Be-hidin
d2bae4ff10ad88a2fad6ec37af93a64d9c972e78
2d3dfce5bd3ec7d613e018a8f1626e77662fc7ea
refs/heads/master
2022-09-30T06:18:21.448676
2018-06-18T08:38:35
2018-06-18T08:38:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include "Item_component.h" #include "../Collision.h" #include "../Singletons/Player.h" Item_component::Item_component() { } Item_component::Item_component(Item* _item) { item = _item; } Item_component::~Item_component() { } void Item_component::update() { if (Collision::aabb( parent_entity->get_component<Collider_component>().collider, Player::Get_instance() ->get_component<Collider_component>() .collider)) { Player::Get_instance()->get_component<Inventory_component>().add_item( item); parent_entity->set_inactive(); } }
[ "tatonmarcinpr@gmail.com" ]
tatonmarcinpr@gmail.com
379e08eeb1421210da657e5cc41c9828747a763f
33e560cfbc2cbd17610ac9a76df203eb8d923399
/leetcode/153insert-interval.cpp
b64a464fc704caef046f6d5319911e7a611024b7
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
gaobaoru/code_day
935b4d63ff0c7a5d8d25a55069d8af5db21ec67f
c00aab4ea56309b4c000f3ef7056e8aa4d9ff7ec
refs/heads/master
2020-04-10T03:28:49.439274
2017-01-21T14:37:09
2017-01-21T14:37:09
62,032,328
0
1
null
2016-11-14T12:54:16
2016-06-27T06:55:35
C++
UTF-8
C++
false
false
1,443
cpp
题目描述 Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals[1,3],[6,9], insert and merge[2,5]in as[1,5],[6,9]. Example 2: Given[1,2],[3,5],[6,7],[8,10],[12,16], insert and merge[4,9]in as[1,2],[3,10],[12,16]. This is because the new interval[4,9]overlaps with[3,5],[6,7],[8,10]. /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: //时间复杂度O(n),空间复杂度O(1) vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval>::iterator it = intervals.begin(); while(it != intervals.end()){ if(newInterval.end < it->start){ intervals.insert(it, newInterval); return intervals; }else if(newInterval.start > it->end){ it++; continue; }else{ newInterval.start = min(newInterval.start, it->start); newInterval.end = max(newInterval.end, it->end); it = intervals.erase(it); } } intervals.insert(intervals.end(), newInterval); return intervals; } };
[ "gaobaoru2010@126.com" ]
gaobaoru2010@126.com
cd8615af3009ae01419d82014abbf06c1c90160a
ca334a387940ab68fea3eef4aa9705540d725ec4
/homework3/bt10+11.cpp
6716f988c1cc8399a25483f0c851eba5280de02d
[]
no_license
minhtblaser/homeworkcodeC
878330e90b1306b3f867da542bbc72ccc775763f
c31d22c128eb78ed634254ea2e1d6490ac5564f6
refs/heads/main
2023-02-06T03:54:25.008790
2020-12-30T14:21:36
2020-12-30T14:21:36
315,014,739
0
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
#include <stdio.h> #define MAX 1000 void NhapMang(int a[], int n){ for(int i = 0;i < n; i++){ printf("Nhap so thu %d: ", i); scanf("%d", &a[i]); } } void XuatMang(int a[], int n){ for(int i = 0;i < n; i++){ printf("%4d", a[i]); } } void ThemPhanTu(int a[], int &n, int val, int pos){ // Mang da day, khong the them. if(n >= MAX){ return; } // Neu pos <= 0 => Them vao dau if(pos < 0){ pos = 0; } // Neu pos >= n => Them vao cuoi else if(pos > n){ pos = n; } // Dich chuyen mang de tao o trong truoc khi them. for(int i = n; i > pos; i--){ a[i] = a[i-1]; } // Chen val tai pos a[pos] = val; // Tang so luong phan tu sau khi chen. ++n; } void XoaPhanTu(int a[], int &n, int pos){ // Mang rong, khong the xoa. if(n <= 0){ return; } // Neu pos <= 0 => Xoa dau if(pos < 0){ pos = 0; } // Neu pos >= n => Xoa cuoi else if(pos >= n){ pos = n-1; } // Dich chuyen mang for(int i = pos; i < n - 1; i++){ a[i] = a[i+1]; } // Giam so luong phan tu sau khi xoa. --n; } int main(){ int a[MAX]; int n; printf("\nNhap so luong phan tu: "); scanf("%d", &n); NhapMang(a, n); XuatMang(a, n); printf("\n=======THEM PHAN TU======\n"); int val, pos; printf("\nNhap so can them: "); scanf("%d", &val); printf("\nNhap vi tri muon chen: "); scanf("%d", &pos); ThemPhanTu(a, n, val, pos); printf("\nMang sau khi them: "); XuatMang(a, n); printf("\n=======XOA PHAN TU======\n"); printf("\nNhap vi tri muon xoa: "); scanf("%d", &pos); XoaPhanTu(a, n, pos); printf("\nMang sau khi xoa: "); XuatMang(a, n); printf("\nDone!"); }
[ "trinhngocminh,9a1@gmail.com" ]
trinhngocminh,9a1@gmail.com
76c6718de738397ead6b0222486a428f14a1b25d
e61f5b7a23c3b1ca014e4809e487e95a65fc3e2c
/Source/SBansheeEditor/Source/BsScriptGizmos.cpp
c3a73a3f86956e1ddb2973a7745c3119d1593541
[]
no_license
ketoo/BansheeEngine
83568cb22f2997162905223013f3f6d73ae4227e
1ce5ec1bb46329695dd7cc13c0556b5bf7278e39
refs/heads/master
2021-01-02T08:49:09.416072
2017-08-01T15:46:42
2017-08-01T15:46:42
99,069,699
1
0
null
2017-08-02T03:48:06
2017-08-02T03:48:06
null
UTF-8
C++
false
false
6,423
cpp
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #include "BsScriptGizmos.h" #include "BsScriptMeta.h" #include "BsMonoClass.h" #include "BsScriptSpriteTexture.h" #include "BsGizmoManager.h" #include "BsMonoUtil.h" #include "BsScriptFont.h" #include "BsScriptRendererMeshData.generated.h" namespace bs { void ScriptGizmos::initRuntimeData() { metaData.scriptClass->addInternalCall("Internal_SetColor", &ScriptGizmos::internal_SetColor); metaData.scriptClass->addInternalCall("Internal_GetColor", &ScriptGizmos::internal_GetColor); metaData.scriptClass->addInternalCall("Internal_SetTransform", &ScriptGizmos::internal_SetTransform); metaData.scriptClass->addInternalCall("Internal_GetTransform", &ScriptGizmos::internal_GetTransform); metaData.scriptClass->addInternalCall("Internal_DrawCube", &ScriptGizmos::internal_DrawCube); metaData.scriptClass->addInternalCall("Internal_DrawSphere", &ScriptGizmos::internal_DrawSphere); metaData.scriptClass->addInternalCall("Internal_DrawCone", &ScriptGizmos::internal_DrawCone); metaData.scriptClass->addInternalCall("Internal_DrawDisc", &ScriptGizmos::internal_DrawDisc); metaData.scriptClass->addInternalCall("Internal_DrawWireCube", &ScriptGizmos::internal_DrawWireCube); metaData.scriptClass->addInternalCall("Internal_DrawWireSphere", &ScriptGizmos::internal_DrawWireSphere); metaData.scriptClass->addInternalCall("Internal_DrawWireCapsule", &ScriptGizmos::internal_DrawWireCapsule); metaData.scriptClass->addInternalCall("Internal_DrawWireCone", &ScriptGizmos::internal_DrawWireCone); metaData.scriptClass->addInternalCall("Internal_DrawWireDisc", &ScriptGizmos::internal_DrawWireDisc); metaData.scriptClass->addInternalCall("Internal_DrawWireArc", &ScriptGizmos::internal_DrawWireArc); metaData.scriptClass->addInternalCall("Internal_DrawWireMesh", &ScriptGizmos::internal_DrawWireMesh); metaData.scriptClass->addInternalCall("Internal_DrawLine", &ScriptGizmos::internal_DrawLine); metaData.scriptClass->addInternalCall("Internal_DrawLineList", &ScriptGizmos::internal_DrawLineList); metaData.scriptClass->addInternalCall("Internal_DrawFrustum", &ScriptGizmos::internal_DrawFrustum); metaData.scriptClass->addInternalCall("Internal_DrawIcon", &ScriptGizmos::internal_DrawIcon); metaData.scriptClass->addInternalCall("Internal_DrawText", &ScriptGizmos::internal_DrawText); } void ScriptGizmos::internal_SetColor(Color* color) { GizmoManager::instance().setColor(*color); } void ScriptGizmos::internal_GetColor(Color* color) { *color = GizmoManager::instance().getColor(); } void ScriptGizmos::internal_SetTransform(Matrix4* transform) { GizmoManager::instance().setTransform(*transform); } void ScriptGizmos::internal_GetTransform(Matrix4* transform) { *transform = GizmoManager::instance().getTransform(); } void ScriptGizmos::internal_DrawCube(Vector3* position, Vector3* extents) { GizmoManager::instance().drawCube(*position, *extents); } void ScriptGizmos::internal_DrawSphere(Vector3* position, float radius) { GizmoManager::instance().drawSphere(*position, radius); } void ScriptGizmos::internal_DrawCone(Vector3* base, Vector3* normal, float height, float radius, Vector2* scale) { GizmoManager::instance().drawCone(*base, *normal, height, radius, *scale); } void ScriptGizmos::internal_DrawDisc(Vector3* position, Vector3* normal, float radius) { GizmoManager::instance().drawDisc(*position, *normal, radius); } void ScriptGizmos::internal_DrawWireCube(Vector3* position, Vector3* extents) { GizmoManager::instance().drawWireCube(*position, *extents); } void ScriptGizmos::internal_DrawWireSphere(Vector3* position, float radius) { GizmoManager::instance().drawWireSphere(*position, radius); } void ScriptGizmos::internal_DrawWireCapsule(Vector3* position, float height, float radius) { GizmoManager::instance().drawWireCapsule(*position, height, radius); } void ScriptGizmos::internal_DrawWireCone(Vector3* base, Vector3* normal, float height, float radius, Vector2* scale) { GizmoManager::instance().drawWireCone(*base, *normal, height, radius, *scale); } void ScriptGizmos::internal_DrawLine(Vector3* start, Vector3* end) { GizmoManager::instance().drawLine(*start, *end); } void ScriptGizmos::internal_DrawLineList(MonoArray* linePoints) { ScriptArray lineArray(linePoints); UINT32 numElements = lineArray.size(); Vector<Vector3> points(numElements); for (UINT32 i = 0; i < numElements; i++) points[i] = lineArray.get<Vector3>(i); GizmoManager::instance().drawLineList(points); } void ScriptGizmos::internal_DrawWireDisc(Vector3* position, Vector3* normal, float radius) { GizmoManager::instance().drawWireDisc(*position, *normal, radius); } void ScriptGizmos::internal_DrawWireArc(Vector3* position, Vector3* normal, float radius, float startAngle, float amountAngle) { GizmoManager::instance().drawWireArc(*position, *normal, radius, Degree(startAngle), Degree(amountAngle)); } void ScriptGizmos::internal_DrawWireMesh(ScriptRendererMeshData* meshData) { if (meshData != nullptr) { SPtr<MeshData> nativeMeshData = meshData->getInternal()->getData(); GizmoManager::instance().drawWireMesh(nativeMeshData); } } void ScriptGizmos::internal_DrawFrustum(Vector3* position, float aspect, Degree* FOV, float near, float far) { GizmoManager::instance().drawFrustum(*position, aspect, *FOV, near, far); } void ScriptGizmos::internal_DrawIcon(Vector3* position, MonoObject* image, bool fixedScale) { HSpriteTexture nativeTexture; if (image != nullptr) nativeTexture = ScriptSpriteTexture::toNative(image)->getHandle(); GizmoManager::instance().drawIcon(*position, nativeTexture, fixedScale); } void ScriptGizmos::internal_DrawText(Vector3* position, MonoString* text, ScriptFont* font, int size) { WString nativeText = MonoUtil::monoToWString(text); HFont fontHandle; if (font != nullptr) fontHandle = font->getHandle(); GizmoManager::instance().drawText(*position, nativeText, fontHandle, size); } }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
3e9358a615d2a5aa49654c998b93134ed91cbcbb
360f38378f4e515be0ff700964e4fadf3374ade5
/cs1400Final/cs1400Final/tom.cpp
cc9543a409c0016bb9d18cc00f24590764feb15f
[]
no_license
jenniferballing/CS1400Final
89b526b26a27c01a77eaa957221133ef6266ee3b
fa8ce7f5250c63f073a87196a52e10850c44ed1b
refs/heads/master
2016-09-10T12:07:53.076600
2013-11-30T04:47:29
2013-11-30T04:47:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
#include "tom.h" #include <cmath> #include <iostream> void tom::Place(int minR,int maxR,int minC,int maxC, SitRep sitrep){ bool done=false; int tr,tc; Dir td; while(!done){ tr=minR+rand()%(maxR-minR); tc=minC+rand()%(maxC-minC); if(sitrep.thing[tr][tc].what==space)done=true; } int rdist=ROWS/2-tr; int cdist=COLS/2-tc; if(abs(rdist)<abs(cdist)){ if(cdist>0)td=rt; else td=lt; }else{ if(rdist>0)td=up; else td=dn; } r=tr; c=tc; dir=td; } // tell someone what you want to do Action tom::Recommendation(SitRep sitrep){ // this code is provided as an example only // use at your own risk Action a; // first, try to attack in front of you int tr=r,tc=c; switch(dir){ case up: tr--; break; case dn: tr++; break; case rt: tc++; break; case lt: tc--; break; case none: break; } if(tr>=0&&tr<ROWS&&tc>=0&&tc<COLS){ if(sitrep.thing[tr][tc].what==unit){ if(sitrep.thing[tr][tc].tla!=tla){ a.action=attack; a.ar=tr; a.ac=tc; return a; } } } // there is not an enemy in front of me // so head to the nearest enemy if(dir==sitrep.nearestEnemy.dirFor){ a.action=fwd; a.maxDist=1; if(rank==knight||rank==crown)a.maxDist=HORSESPEED; return a; } else { a.action=turn; a.dir=sitrep.nearestEnemy.dirFor; return a; } a.action=nothing; return a; }
[ "jenniferballing@gmail.com" ]
jenniferballing@gmail.com
95b57abbe732ccc9f9df77b4cabadccc730feae7
84dd2490c7b5dda1fa01ba4bd5530dca00b3e8e7
/src/sick_reader/CSICK.h
dfad4defd062dcae7b7294ecf855aa45862733a8
[]
no_license
eglrp/laser_slam
2c6e58f7a8bbf5c94f7024d2aebae3eca69de4fa
83e980848e029a6addd937956b6e524b6d89c632
refs/heads/master
2020-04-07T04:52:49.104644
2017-04-15T20:55:23
2017-04-15T20:55:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,156
h
/* * CSICK.h * * Created on: Nov 26, 2012 * Author: liu */ #ifndef CSICK_H_ #define CSICK_H_ #include "CObs2DScan.h" #include "CClientSocket.h" #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <pthread.h> #define APPERTURE 4.712385 // in radian <=> 270° using namespace std; class CSICK { public: /** Constructor. * Note that there is default arguments, here you can customize IP Adress and TCP Port of your device. */ CSICK(std::string _ip=string("192.168.0.1"), unsigned int _port=2111); /** Destructor. * Close communcation with the device, and free memory. */ virtual ~CSICK(); /** This function acquire a laser scan from the device. If an error occured, hardwareError will be set to true. * The new laser scan will be stored in the outObservation argument. * * \exception This method throw exception if the frame received from the LMS 100 contain the following bad parameters : * * Status is not OK * * Data in the scan aren't DIST1 (may be RSSIx or DIST2). */ void doProcessSimple(bool &outThereIsObservation, CObs2DScan &outObservation, bool &hardwareError); //new for dual sick void doProcessSimple( ); bool setSick_A(string, unsigned int); bool setSick_B(string, unsigned int); void runSick_A(); void runSick_B(); //static int getScan_A(float* , TTimeStamp& ); static int getScan_A_SLAM(float* , TTimeStamp& ); static int getScan_A_OD(float* , TTimeStamp& ); //static int getScan_B(float* , TTimeStamp& ); static int getScan_B_SLAM(float* , TTimeStamp& ); static int getScan_B_OD(float* , TTimeStamp& ); CObs2DScan m_scan_A; CObs2DScan m_scan_B; CClientSocket m_client_A; CClientSocket m_client_B; bool m_connected_A; bool m_connected_B; pthread_mutex_t mutex_read_A_SLAM; pthread_mutex_t mutex_read_A_OD; pthread_mutex_t mutex_read_B_SLAM; pthread_mutex_t mutex_read_B_OD; float* m_pScan_A_SLAM; // for SLAM float* m_pScan_A_OD; // for obstacle detection float* m_pScan_B_SLAM; // for SLAM float* m_pScan_B_OD; // for obstacle detection bool bFirst_A; bool bFirst_B; int scan_A_num; int scan_B_num; bool scan_A_Ready_SLAM; bool scan_A_Ready_OD; bool scan_B_Ready_SLAM; bool scan_B_Ready_OD; TTimeStamp scan_A_t_SLAM; TTimeStamp scan_A_t_OD; TTimeStamp scan_B_t_SLAM; TTimeStamp scan_B_t_OD; /** This method must be called before trying to get a laser scan. */ bool turnOn(); /** This method could be called manually to stop communication with the device. Method is also called by destructor. */ bool turnOff(); /** A method to set the sensor pose on the robot. * Equivalent to setting the sensor pose via loading it from a config file. */ void setSensorPose(const CPose3D& _pose); void setSensorLabel(string ); /** This method should be called periodically. Period depend on the process_rate in the configuration file. */ void doProcess(); /** Initialize the sensor according to the parameters previously read in the configuration file. */ void initialize(); static CSICK * m_pCSICK; private : string m_ip; unsigned int m_port; CClientSocket m_client; bool m_turnedOn; string m_cmd; bool m_connected; unsigned int m_scanFrequency; // en hertz double m_angleResolution; // en degrés double m_startAngle; // degrés double m_stopAngle; // degrés //CPose3D m_sensorPose; double m_maxRange; double m_beamApperture; std::string m_sensorLabel; CObs2DScan m_scan; bool m_hdErr; bool m_obsErr; void generateCmd(const char *cmd); bool checkIsConnected(); bool decodeScan(char *buf, CObs2DScan& outObservation); void sendCommand(const char *cmd); void roughPrint( char *msg ); pthread_mutex_t mutex_read; protected: /** Load sensor pose on the robot, or keep the default sensor pose. */ /* void loadConfig_sensorSpecific(const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ); */ }; #endif /* CSICK_H_ */
[ "hxzhang1@ualr.edu" ]
hxzhang1@ualr.edu
1feb2d84deb8047e0a9fa590d0a258b588c837b8
bd2f117637be64d13d7b94093c537d346ca3257f
/Examples/Game/DiceWar/Sources/Server/server_game_player_collection.h
5d77c620aef1d91807b32163a392fd9ff218d02f
[ "Zlib" ]
permissive
animehunter/clanlib-2.3
e6d6a09ff58016809d687c101b64ed4da1467562
7013c39f4cd1f25b0dad3bedfdb7a5cf593b1bb7
refs/heads/master
2016-09-10T12:56:23.015390
2011-12-15T20:58:59
2011-12-15T20:58:59
3,001,221
1
1
null
null
null
null
UTF-8
C++
false
false
711
h
#pragma once class Server; class ServerGame; class ServerGamePlayer; class ServerGamePlayerCollection { public: ServerGamePlayerCollection(Server *server, ServerGame *game); ~ServerGamePlayerCollection(); void add_player(ServerGamePlayer *player); void remove_player(ServerGamePlayer *player); bool contains_player(ServerGamePlayer *player); ServerGamePlayer *get_player(int player_id); std::vector<ServerGamePlayer *> &get_players() { return players; } int get_count() const { return players.size(); } void transfer_players(); void send_event(const CL_NetGameEvent &game_event); private: Server *server; ServerGame *game; std::vector<ServerGamePlayer *> players; int next_visual_id; };
[ "rombust@cc39f7f4-b520-0410-a30f-b56705a9c917" ]
rombust@cc39f7f4-b520-0410-a30f-b56705a9c917
393389b47bef5882dadfb34182e9d2b0145c9d36
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_patch_hunk_4960.cpp
bd1f9a440749066d5064028e6922712c3537d341
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
674
cpp
rv = file_cache_el_final(conf, &dobj->hdrs, r); } if (APR_SUCCESS == rv) { rv = file_cache_el_final(conf, &dobj->vary, r); } if (APR_SUCCESS == rv) { - rv = file_cache_el_final(conf, &dobj->data, r); + if (!dobj->disk_info.header_only) { + rv = file_cache_el_final(conf, &dobj->data, r); + } + else if (dobj->data.file){ + rv = apr_file_remove(dobj->data.file, dobj->data.pool); + } } /* remove the cached items completely on any failure */ if (APR_SUCCESS != rv) { remove_url(h, r); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00736)
[ "993273596@qq.com" ]
993273596@qq.com
09751f8e9e58d8a40a3478d408b88cee5d63630e
0bf1f7b901118b5cbe3d51bbc5885fcb634419c5
/Cpp/SDK/UMG_MobHealthBar_parameters.h
9783d194d299eadb242986463ef38c9738bfa376
[]
no_license
zH4x-SDK/zMCDungeons-SDK
3a90a959e4a72f4007fc749c53b8775b7155f3da
ab9d8f0ab04b215577dd2eb067e65015b5a70521
refs/heads/main
2023-07-15T15:43:17.217894
2021-08-27T13:49:22
2021-08-27T13:49:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,448
h
#pragma once // Name: DBZKakarot, Version: 1.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UMG_MobHealthBar.UMG_MobHealthBar_C.UpdateScaling struct UUMG_MobHealthBar_C_UpdateScaling_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.setHighlighted struct UUMG_MobHealthBar_C_setHighlighted_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetWidthScaling struct UUMG_MobHealthBar_C_SetWidthScaling_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.UpdateGraphics struct UUMG_MobHealthBar_C_UpdateGraphics_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetHealthBar struct UUMG_MobHealthBar_C_SetHealthBar_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.SetMob struct UUMG_MobHealthBar_C_SetMob_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.Tick struct UUMG_MobHealthBar_C_Tick_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.PreConstruct struct UUMG_MobHealthBar_C_PreConstruct_Params { }; // Function UMG_MobHealthBar.UMG_MobHealthBar_C.ExecuteUbergraph_UMG_MobHealthBar struct UUMG_MobHealthBar_C_ExecuteUbergraph_UMG_MobHealthBar_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
1ae800acf1efbe4ed47cfd454787e8ab03773ffe
1faf78259839977b53a1d7b9fc954e6a7cf5c887
/include/Transport_system.h
48a5ad55b81aff6b08406ed1f3211d8532661b17
[]
no_license
DeadBread/Tickets
28f18046a3cfd3711a13a612462b32eb0a99e8e2
c247efdd0ac1a2eddecde232b0b241325f1e818d
refs/heads/master
2021-01-10T18:02:46.813616
2016-04-08T16:02:02
2016-04-08T16:02:02
55,857,095
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
h
#ifndef TRANSPORT_SYSTEM_H #define TRANSPORT_SYSTEM_H #include <memory> #include <iostream> #include "Train.h" #include "Plain.h" #include "Bus.h" using namespace std; class Transport_system { public: //Transport_system(); //virtual ~Transport_system(); static Transport_system& get_transport_system() { static Transport_system tmp; return tmp; } void add_plain(Plain &&pl) { all_plains.push_back(pl); } void add_train(Train &&tr) { all_trains.push_back(tr); } void add_bus(Bus &&bs) { all_buses.push_back(bs); } void print_all() const; void print_plains() const; void print_trains() const; void print_buses() const; const Vectr<Train> & get_trains() const { return all_trains; } const Vectr<Plain> & get_plains() const { return all_plains; } const Vectr<Bus> & get_buses() const { return all_buses; } protected: private: Transport_system(); Vectr<Train> all_trains; Vectr<Plain> all_plains; Vectr<Bus> all_buses; }; #endif // TRANSPORT_SYSTEM_H
[ "zhikov_n1@mail.ru" ]
zhikov_n1@mail.ru
1f9af01f411e7170e7a94cbd911e0404564730d9
dd80a584130ef1a0333429ba76c1cee0eb40df73
/frameworks/av/media/libstagefright/omx/GraphicBufferSource.cpp
44f0be7a9b640913a7ce2ccd3bdbf65659a2f857
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
26,608
cpp
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ #define LOG_TAG "GraphicBufferSource" //#define LOG_NDEBUG 0 #include <utils/Log.h> #include "GraphicBufferSource.h" #include <OMX_Core.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <media/hardware/MetadataBufferType.h> #include <ui/GraphicBuffer.h> namespace android { static const bool EXTRA_CHECK = true; GraphicBufferSource::GraphicBufferSource(OMXNodeInstance* nodeInstance, uint32_t bufferWidth, uint32_t bufferHeight, uint32_t bufferCount) : mInitCheck(UNKNOWN_ERROR), mNodeInstance(nodeInstance), mExecuting(false), mSuspended(false), mNumFramesAvailable(0), mEndOfStream(false), mEndOfStreamSent(false), mRepeatAfterUs(-1ll), mMaxTimestampGapUs(-1ll), mPrevOriginalTimeUs(-1ll), mPrevModifiedTimeUs(-1ll), mRepeatLastFrameGeneration(0), mRepeatLastFrameTimestamp(-1ll), mLatestSubmittedBufferId(-1), mLatestSubmittedBufferFrameNum(0), mLatestSubmittedBufferUseCount(0), mRepeatBufferDeferred(false) { ALOGV("GraphicBufferSource w=%u h=%u c=%u", bufferWidth, bufferHeight, bufferCount); if (bufferWidth == 0 || bufferHeight == 0) { ALOGE("Invalid dimensions %ux%u", bufferWidth, bufferHeight); mInitCheck = BAD_VALUE; return; } String8 name("GraphicBufferSource"); mBufferQueue = new BufferQueue(); mBufferQueue->setConsumerName(name); mBufferQueue->setDefaultBufferSize(bufferWidth, bufferHeight); mBufferQueue->setConsumerUsageBits(GRALLOC_USAGE_HW_VIDEO_ENCODER | GRALLOC_USAGE_HW_TEXTURE); mInitCheck = mBufferQueue->setMaxAcquiredBufferCount(bufferCount); if (mInitCheck != NO_ERROR) { ALOGE("Unable to set BQ max acquired buffer count to %u: %d", bufferCount, mInitCheck); return; } // Note that we can't create an sp<...>(this) in a ctor that will not keep a // reference once the ctor ends, as that would cause the refcount of 'this' // dropping to 0 at the end of the ctor. Since all we need is a wp<...> // that's what we create. wp<BufferQueue::ConsumerListener> listener = static_cast<BufferQueue::ConsumerListener*>(this); sp<BufferQueue::ProxyConsumerListener> proxy = new BufferQueue::ProxyConsumerListener(listener); mInitCheck = mBufferQueue->consumerConnect(proxy, false); if (mInitCheck != NO_ERROR) { ALOGE("Error connecting to BufferQueue: %s (%d)", strerror(-mInitCheck), mInitCheck); return; } CHECK(mInitCheck == NO_ERROR); } GraphicBufferSource::~GraphicBufferSource() { ALOGV("~GraphicBufferSource"); if (mBufferQueue != NULL) { status_t err = mBufferQueue->consumerDisconnect(); if (err != NO_ERROR) { ALOGW("consumerDisconnect failed: %d", err); } } } void GraphicBufferSource::omxExecuting() { Mutex::Autolock autoLock(mMutex); ALOGV("--> executing; avail=%d, codec vec size=%zd", mNumFramesAvailable, mCodecBuffers.size()); CHECK(!mExecuting); mExecuting = true; // Start by loading up as many buffers as possible. We want to do this, // rather than just submit the first buffer, to avoid a degenerate case: // if all BQ buffers arrive before we start executing, and we only submit // one here, the other BQ buffers will just sit until we get notified // that the codec buffer has been released. We'd then acquire and // submit a single additional buffer, repeatedly, never using more than // one codec buffer simultaneously. (We could instead try to submit // all BQ buffers whenever any codec buffer is freed, but if we get the // initial conditions right that will never be useful.) while (mNumFramesAvailable) { if (!fillCodecBuffer_l()) { ALOGV("stop load with frames available (codecAvail=%d)", isCodecBufferAvailable_l()); break; } } ALOGV("done loading initial frames, avail=%d", mNumFramesAvailable); // If EOS has already been signaled, and there are no more frames to // submit, try to send EOS now as well. if (mEndOfStream && mNumFramesAvailable == 0) { submitEndOfInputStream_l(); } if (mRepeatAfterUs > 0ll && mLooper == NULL) { mReflector = new AHandlerReflector<GraphicBufferSource>(this); mLooper = new ALooper; mLooper->registerHandler(mReflector); mLooper->start(); if (mLatestSubmittedBufferId >= 0) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } } void GraphicBufferSource::omxIdle() { ALOGV("omxIdle"); Mutex::Autolock autoLock(mMutex); if (mExecuting) { // We are only interested in the transition from executing->idle, // not loaded->idle. mExecuting = false; } } void GraphicBufferSource::omxLoaded(){ Mutex::Autolock autoLock(mMutex); if (!mExecuting) { // This can happen if something failed very early. ALOGW("Dropped back down to Loaded without Executing"); } if (mLooper != NULL) { mLooper->unregisterHandler(mReflector->id()); mReflector.clear(); mLooper->stop(); mLooper.clear(); } ALOGV("--> loaded; avail=%d eos=%d eosSent=%d", mNumFramesAvailable, mEndOfStream, mEndOfStreamSent); // Codec is no longer executing. Discard all codec-related state. mCodecBuffers.clear(); // TODO: scan mCodecBuffers to verify that all mGraphicBuffer entries // are null; complain if not mExecuting = false; } void GraphicBufferSource::addCodecBuffer(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (mExecuting) { // This should never happen -- buffers can only be allocated when // transitioning from "loaded" to "idle". ALOGE("addCodecBuffer: buffer added while executing"); return; } ALOGV("addCodecBuffer h=%p size=%lu p=%p", header, header->nAllocLen, header->pBuffer); CodecBuffer codecBuffer; codecBuffer.mHeader = header; mCodecBuffers.add(codecBuffer); } void GraphicBufferSource::codecBufferEmptied(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (!mExecuting) { return; } int cbi = findMatchingCodecBuffer_l(header); if (cbi < 0) { // This should never happen. ALOGE("codecBufferEmptied: buffer not recognized (h=%p)", header); return; } ALOGV("codecBufferEmptied h=%p size=%lu filled=%lu p=%p", header, header->nAllocLen, header->nFilledLen, header->pBuffer); CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); // header->nFilledLen may not be the original value, so we can't compare // that to zero to see of this was the EOS buffer. Instead we just // see if the GraphicBuffer reference was null, which should only ever // happen for EOS. if (codecBuffer.mGraphicBuffer == NULL) { if (!(mEndOfStream && mEndOfStreamSent)) { // This can happen when broken code sends us the same buffer // twice in a row. ALOGE("ERROR: codecBufferEmptied on non-EOS null buffer " "(buffer emptied twice?)"); } // No GraphicBuffer to deal with, no additional input or output is // expected, so just return. return; } if (EXTRA_CHECK) { // Pull the graphic buffer handle back out of the buffer, and confirm // that it matches expectations. OMX_U8* data = header->pBuffer; buffer_handle_t bufferHandle; memcpy(&bufferHandle, data + 4, sizeof(buffer_handle_t)); if (bufferHandle != codecBuffer.mGraphicBuffer->handle) { // should never happen ALOGE("codecBufferEmptied: buffer's handle is %p, expected %p", bufferHandle, codecBuffer.mGraphicBuffer->handle); CHECK(!"codecBufferEmptied: mismatched buffer"); } } // Find matching entry in our cached copy of the BufferQueue slots. // If we find a match, release that slot. If we don't, the BufferQueue // has dropped that GraphicBuffer, and there's nothing for us to release. int id = codecBuffer.mBuf; if (mBufferSlot[id] != NULL && mBufferSlot[id]->handle == codecBuffer.mGraphicBuffer->handle) { ALOGV("cbi %d matches bq slot %d, handle=%p", cbi, id, mBufferSlot[id]->handle); if (id == mLatestSubmittedBufferId) { CHECK_GT(mLatestSubmittedBufferUseCount--, 0); } else { mBufferQueue->releaseBuffer(id, codecBuffer.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } } else { ALOGV("codecBufferEmptied: no match for emptied buffer in cbi %d", cbi); } // Mark the codec buffer as available by clearing the GraphicBuffer ref. codecBuffer.mGraphicBuffer = NULL; if (mNumFramesAvailable) { // Fill this codec buffer. CHECK(!mEndOfStreamSent); ALOGV("buffer freed, %d frames avail (eos=%d)", mNumFramesAvailable, mEndOfStream); fillCodecBuffer_l(); } else if (mEndOfStream) { // No frames available, but EOS is pending, so use this buffer to // send that. ALOGV("buffer freed, EOS pending"); submitEndOfInputStream_l(); } else if (mRepeatBufferDeferred) { bool success = repeatLatestSubmittedBuffer_l(); if (success) { ALOGV("deferred repeatLatestSubmittedBuffer_l SUCCESS"); } else { ALOGV("deferred repeatLatestSubmittedBuffer_l FAILURE"); } mRepeatBufferDeferred = false; } return; } void GraphicBufferSource::codecBufferFilled(OMX_BUFFERHEADERTYPE* header) { Mutex::Autolock autoLock(mMutex); if (mMaxTimestampGapUs > 0ll && !(header->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) { ssize_t index = mOriginalTimeUs.indexOfKey(header->nTimeStamp); if (index >= 0) { ALOGV("OUT timestamp: %lld -> %lld", header->nTimeStamp, mOriginalTimeUs[index]); header->nTimeStamp = mOriginalTimeUs[index]; mOriginalTimeUs.removeItemsAt(index); } else { // giving up the effort as encoder doesn't appear to preserve pts ALOGW("giving up limiting timestamp gap (pts = %lld)", header->nTimeStamp); mMaxTimestampGapUs = -1ll; } if (mOriginalTimeUs.size() > BufferQueue::NUM_BUFFER_SLOTS) { // something terribly wrong must have happened, giving up... ALOGE("mOriginalTimeUs has too many entries (%d)", mOriginalTimeUs.size()); mMaxTimestampGapUs = -1ll; } } } void GraphicBufferSource::suspend(bool suspend) { Mutex::Autolock autoLock(mMutex); if (suspend) { mSuspended = true; while (mNumFramesAvailable > 0) { BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == BufferQueue::NO_BUFFER_AVAILABLE) { // shouldn't happen. ALOGW("suspend: frame was not available"); break; } else if (err != OK) { ALOGW("suspend: acquireBuffer returned err=%d", err); break; } --mNumFramesAvailable; mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, item.mFence); } return; } mSuspended = false; if (mExecuting && mNumFramesAvailable == 0 && mRepeatBufferDeferred) { if (repeatLatestSubmittedBuffer_l()) { ALOGV("suspend/deferred repeatLatestSubmittedBuffer_l SUCCESS"); mRepeatBufferDeferred = false; } else { ALOGV("suspend/deferred repeatLatestSubmittedBuffer_l FAILURE"); } } } bool GraphicBufferSource::fillCodecBuffer_l() { CHECK(mExecuting && mNumFramesAvailable > 0); if (mSuspended) { return false; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { // No buffers available, bail. ALOGV("fillCodecBuffer_l: no codec buffers, avail now %d", mNumFramesAvailable); return false; } ALOGV("fillCodecBuffer_l: acquiring buffer, avail=%d", mNumFramesAvailable); BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == BufferQueue::NO_BUFFER_AVAILABLE) { // shouldn't happen ALOGW("fillCodecBuffer_l: frame was not available"); return false; } else if (err != OK) { // now what? fake end-of-stream? ALOGW("fillCodecBuffer_l: acquireBuffer returned err=%d", err); return false; } mNumFramesAvailable--; // Wait for it to become available. err = item.mFence->waitForever("GraphicBufferSource::fillCodecBuffer_l"); if (err != OK) { ALOGW("failed to wait for buffer fence: %d", err); // keep going } // If this is the first time we're seeing this buffer, add it to our // slot table. if (item.mGraphicBuffer != NULL) { ALOGV("fillCodecBuffer_l: setting mBufferSlot %d", item.mBuf); mBufferSlot[item.mBuf] = item.mGraphicBuffer; } err = submitBuffer_l(item, cbi); if (err != OK) { ALOGV("submitBuffer_l failed, releasing bq buf %d", item.mBuf); mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } else { ALOGV("buffer submitted (bq %d, cbi %d)", item.mBuf, cbi); setLatestSubmittedBuffer_l(item); } return true; } bool GraphicBufferSource::repeatLatestSubmittedBuffer_l() { CHECK(mExecuting && mNumFramesAvailable == 0); if (mLatestSubmittedBufferId < 0 || mSuspended) { return false; } if (mBufferSlot[mLatestSubmittedBufferId] == NULL) { // This can happen if the remote side disconnects, causing // onBuffersReleased() to NULL out our copy of the slots. The // buffer is gone, so we have nothing to show. // // To be on the safe side we try to release the buffer. ALOGD("repeatLatestSubmittedBuffer_l: slot was NULL"); mBufferQueue->releaseBuffer( mLatestSubmittedBufferId, mLatestSubmittedBufferFrameNum, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); mLatestSubmittedBufferId = -1; mLatestSubmittedBufferFrameNum = 0; return false; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { // No buffers available, bail. ALOGV("repeatLatestSubmittedBuffer_l: no codec buffers."); return false; } BufferQueue::BufferItem item; item.mBuf = mLatestSubmittedBufferId; item.mFrameNumber = mLatestSubmittedBufferFrameNum; item.mTimestamp = mRepeatLastFrameTimestamp; status_t err = submitBuffer_l(item, cbi); if (err != OK) { return false; } ++mLatestSubmittedBufferUseCount; /* repeat last frame up to kRepeatLastFrameCount times. * in case of static scene, a single repeat might not get rid of encoder * ghosting completely, refresh a couple more times to get better quality */ if (--mRepeatLastFrameCount > 0) { mRepeatLastFrameTimestamp = item.mTimestamp + mRepeatAfterUs * 1000; if (mReflector != NULL) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } return true; } void GraphicBufferSource::setLatestSubmittedBuffer_l( const BufferQueue::BufferItem &item) { ALOGV("setLatestSubmittedBuffer_l"); if (mLatestSubmittedBufferId >= 0) { if (mLatestSubmittedBufferUseCount == 0) { mBufferQueue->releaseBuffer( mLatestSubmittedBufferId, mLatestSubmittedBufferFrameNum, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, Fence::NO_FENCE); } } mLatestSubmittedBufferId = item.mBuf; mLatestSubmittedBufferFrameNum = item.mFrameNumber; mRepeatLastFrameTimestamp = item.mTimestamp + mRepeatAfterUs * 1000; mLatestSubmittedBufferUseCount = 1; mRepeatBufferDeferred = false; mRepeatLastFrameCount = kRepeatLastFrameCount; if (mReflector != NULL) { sp<AMessage> msg = new AMessage(kWhatRepeatLastFrame, mReflector->id()); msg->setInt32("generation", ++mRepeatLastFrameGeneration); msg->post(mRepeatAfterUs); } } status_t GraphicBufferSource::signalEndOfInputStream() { Mutex::Autolock autoLock(mMutex); ALOGV("signalEndOfInputStream: exec=%d avail=%d eos=%d", mExecuting, mNumFramesAvailable, mEndOfStream); if (mEndOfStream) { ALOGE("EOS was already signaled"); return INVALID_OPERATION; } // Set the end-of-stream flag. If no frames are pending from the // BufferQueue, and a codec buffer is available, and we're executing, // we initiate the EOS from here. Otherwise, we'll let // codecBufferEmptied() (or omxExecuting) do it. // // Note: if there are no pending frames and all codec buffers are // available, we *must* submit the EOS from here or we'll just // stall since no future events are expected. mEndOfStream = true; if (mExecuting && mNumFramesAvailable == 0) { submitEndOfInputStream_l(); } return OK; } int64_t GraphicBufferSource::getTimestamp(const BufferQueue::BufferItem &item) { int64_t timeUs = item.mTimestamp / 1000; if (mMaxTimestampGapUs > 0ll) { /* Cap timestamp gap between adjacent frames to specified max * * In the scenario of cast mirroring, encoding could be suspended for * prolonged periods. Limiting the pts gap to workaround the problem * where encoder's rate control logic produces huge frames after a * long period of suspension. */ int64_t originalTimeUs = timeUs; if (mPrevOriginalTimeUs >= 0ll) { if (originalTimeUs < mPrevOriginalTimeUs) { // Drop the frame if it's going backward in time. Bad timestamp // could disrupt encoder's rate control completely. ALOGW("Dropping frame that's going backward in time"); return -1; } int64_t timestampGapUs = originalTimeUs - mPrevOriginalTimeUs; timeUs = (timestampGapUs < mMaxTimestampGapUs ? timestampGapUs : mMaxTimestampGapUs) + mPrevModifiedTimeUs; } mPrevOriginalTimeUs = originalTimeUs; mPrevModifiedTimeUs = timeUs; mOriginalTimeUs.add(timeUs, originalTimeUs); ALOGV("IN timestamp: %lld -> %lld", originalTimeUs, timeUs); } return timeUs; } status_t GraphicBufferSource::submitBuffer_l( const BufferQueue::BufferItem &item, int cbi) { ALOGV("submitBuffer_l cbi=%d", cbi); int64_t timeUs = getTimestamp(item); if (timeUs < 0ll) { return UNKNOWN_ERROR; } CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); codecBuffer.mGraphicBuffer = mBufferSlot[item.mBuf]; codecBuffer.mBuf = item.mBuf; codecBuffer.mFrameNumber = item.mFrameNumber; OMX_BUFFERHEADERTYPE* header = codecBuffer.mHeader; CHECK(header->nAllocLen >= 4 + sizeof(buffer_handle_t)); OMX_U8* data = header->pBuffer; const OMX_U32 type = kMetadataBufferTypeGrallocSource; buffer_handle_t handle = codecBuffer.mGraphicBuffer->handle; memcpy(data, &type, 4); memcpy(data + 4, &handle, sizeof(buffer_handle_t)); status_t err = mNodeInstance->emptyDirectBuffer(header, 0, 4 + sizeof(buffer_handle_t), OMX_BUFFERFLAG_ENDOFFRAME, timeUs); if (err != OK) { ALOGW("WARNING: emptyDirectBuffer failed: 0x%x", err); codecBuffer.mGraphicBuffer = NULL; return err; } ALOGV("emptyDirectBuffer succeeded, h=%p p=%p bufhandle=%p", header, header->pBuffer, handle); return OK; } void GraphicBufferSource::submitEndOfInputStream_l() { CHECK(mEndOfStream); if (mEndOfStreamSent) { ALOGV("EOS already sent"); return; } int cbi = findAvailableCodecBuffer_l(); if (cbi < 0) { ALOGV("submitEndOfInputStream_l: no codec buffers available"); return; } // We reject any additional incoming graphic buffers, so there's no need // to stick a placeholder into codecBuffer.mGraphicBuffer to mark it as // in-use. CodecBuffer& codecBuffer(mCodecBuffers.editItemAt(cbi)); OMX_BUFFERHEADERTYPE* header = codecBuffer.mHeader; if (EXTRA_CHECK) { // Guard against implementations that don't check nFilledLen. size_t fillLen = 4 + sizeof(buffer_handle_t); CHECK(header->nAllocLen >= fillLen); OMX_U8* data = header->pBuffer; memset(data, 0xcd, fillLen); } uint64_t timestamp = 0; // does this matter? status_t err = mNodeInstance->emptyDirectBuffer(header, /*offset*/ 0, /*length*/ 0, OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_EOS, timestamp); if (err != OK) { ALOGW("emptyDirectBuffer EOS failed: 0x%x", err); } else { ALOGV("submitEndOfInputStream_l: buffer submitted, header=%p cbi=%d", header, cbi); mEndOfStreamSent = true; } } int GraphicBufferSource::findAvailableCodecBuffer_l() { CHECK(mCodecBuffers.size() > 0); for (int i = (int)mCodecBuffers.size() - 1; i>= 0; --i) { if (mCodecBuffers[i].mGraphicBuffer == NULL) { return i; } } return -1; } int GraphicBufferSource::findMatchingCodecBuffer_l( const OMX_BUFFERHEADERTYPE* header) { for (int i = (int)mCodecBuffers.size() - 1; i>= 0; --i) { if (mCodecBuffers[i].mHeader == header) { return i; } } return -1; } // BufferQueue::ConsumerListener callback void GraphicBufferSource::onFrameAvailable() { Mutex::Autolock autoLock(mMutex); ALOGV("onFrameAvailable exec=%d avail=%d", mExecuting, mNumFramesAvailable); if (mEndOfStream || mSuspended) { if (mEndOfStream) { // This should only be possible if a new buffer was queued after // EOS was signaled, i.e. the app is misbehaving. ALOGW("onFrameAvailable: EOS is set, ignoring frame"); } else { ALOGV("onFrameAvailable: suspended, ignoring frame"); } BufferQueue::BufferItem item; status_t err = mBufferQueue->acquireBuffer(&item, 0); if (err == OK) { // If this is the first time we're seeing this buffer, add it to our // slot table. if (item.mGraphicBuffer != NULL) { ALOGV("fillCodecBuffer_l: setting mBufferSlot %d", item.mBuf); mBufferSlot[item.mBuf] = item.mGraphicBuffer; } mBufferQueue->releaseBuffer(item.mBuf, item.mFrameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, item.mFence); } return; } mNumFramesAvailable++; mRepeatBufferDeferred = false; ++mRepeatLastFrameGeneration; if (mExecuting) { fillCodecBuffer_l(); } } // BufferQueue::ConsumerListener callback void GraphicBufferSource::onBuffersReleased() { Mutex::Autolock lock(mMutex); uint32_t slotMask; if (mBufferQueue->getReleasedBuffers(&slotMask) != NO_ERROR) { ALOGW("onBuffersReleased: unable to get released buffer set"); slotMask = 0xffffffff; } ALOGV("onBuffersReleased: 0x%08x", slotMask); for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) { if ((slotMask & 0x01) != 0) { mBufferSlot[i] = NULL; } slotMask >>= 1; } } status_t GraphicBufferSource::setRepeatPreviousFrameDelayUs( int64_t repeatAfterUs) { Mutex::Autolock autoLock(mMutex); if (mExecuting || repeatAfterUs <= 0ll) { return INVALID_OPERATION; } mRepeatAfterUs = repeatAfterUs; return OK; } status_t GraphicBufferSource::setMaxTimestampGapUs(int64_t maxGapUs) { Mutex::Autolock autoLock(mMutex); if (mExecuting || maxGapUs <= 0ll) { return INVALID_OPERATION; } mMaxTimestampGapUs = maxGapUs; return OK; } void GraphicBufferSource::onMessageReceived(const sp<AMessage> &msg) { switch (msg->what()) { case kWhatRepeatLastFrame: { Mutex::Autolock autoLock(mMutex); int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation != mRepeatLastFrameGeneration) { // stale break; } if (!mExecuting || mNumFramesAvailable > 0) { break; } bool success = repeatLatestSubmittedBuffer_l(); if (success) { ALOGV("repeatLatestSubmittedBuffer_l SUCCESS"); } else { ALOGV("repeatLatestSubmittedBuffer_l FAILURE"); mRepeatBufferDeferred = true; } break; } default: TRESPASS(); } } } // namespace android
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
9347605b8c0ffd6857fe85c8efd69bf9fec2568e
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/pc/dtls_transport_unittest.cc
f80d99b05ec7525b7bf5d10e5afa8e79a8baa20f
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "MIT" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
C++
false
false
5,756
cc
/* * Copyright 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "pc/dtls_transport.h" #include <utility> #include <vector> #include "absl/memory/memory.h" #include "p2p/base/fake_dtls_transport.h" #include "rtc_base/gunit.h" #include "test/gmock.h" #include "test/gtest.h" constexpr int kDefaultTimeout = 1000; // milliseconds constexpr int kNonsenseCipherSuite = 1234; using cricket::FakeDtlsTransport; using ::testing::ElementsAre; namespace webrtc { class TestDtlsTransportObserver : public DtlsTransportObserverInterface { public: void OnStateChange(DtlsTransportInformation info) override { state_change_called_ = true; states_.push_back(info.state()); info_ = info; } void OnError(RTCError error) override {} DtlsTransportState state() { if (states_.size() > 0) { return states_[states_.size() - 1]; } else { return DtlsTransportState::kNew; } } bool state_change_called_ = false; DtlsTransportInformation info_; std::vector<DtlsTransportState> states_; }; class DtlsTransportTest : public ::testing::Test { public: DtlsTransport* transport() { return transport_.get(); } DtlsTransportObserverInterface* observer() { return &observer_; } void CreateTransport(rtc::FakeSSLCertificate* certificate = nullptr) { auto cricket_transport = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); if (certificate) { cricket_transport->SetRemoteSSLCertificate(certificate); } cricket_transport->SetSslCipherSuite(kNonsenseCipherSuite); transport_ = rtc::make_ref_counted<DtlsTransport>(std::move(cricket_transport)); } void CompleteDtlsHandshake() { auto fake_dtls1 = static_cast<FakeDtlsTransport*>(transport_->internal()); auto fake_dtls2 = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); auto cert1 = rtc::RTCCertificate::Create( rtc::SSLIdentity::Create("session1", rtc::KT_DEFAULT)); fake_dtls1->SetLocalCertificate(cert1); auto cert2 = rtc::RTCCertificate::Create( rtc::SSLIdentity::Create("session1", rtc::KT_DEFAULT)); fake_dtls2->SetLocalCertificate(cert2); fake_dtls1->SetDestination(fake_dtls2.get()); } rtc::scoped_refptr<DtlsTransport> transport_; TestDtlsTransportObserver observer_; }; TEST_F(DtlsTransportTest, CreateClearDelete) { auto cricket_transport = std::make_unique<FakeDtlsTransport>( "audio", cricket::ICE_CANDIDATE_COMPONENT_RTP); auto webrtc_transport = rtc::make_ref_counted<DtlsTransport>(std::move(cricket_transport)); ASSERT_TRUE(webrtc_transport->internal()); ASSERT_EQ(DtlsTransportState::kNew, webrtc_transport->Information().state()); webrtc_transport->Clear(); ASSERT_FALSE(webrtc_transport->internal()); ASSERT_EQ(DtlsTransportState::kClosed, webrtc_transport->Information().state()); } TEST_F(DtlsTransportTest, EventsObservedWhenConnecting) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state_change_called_, kDefaultTimeout); EXPECT_THAT( observer_.states_, ElementsAre( // FakeDtlsTransport doesn't signal the "connecting" state. // TODO(hta): fix FakeDtlsTransport or file bug on it. // DtlsTransportState::kConnecting, DtlsTransportState::kConnected)); } TEST_F(DtlsTransportTest, CloseWhenClearing) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); } TEST_F(DtlsTransportTest, CertificateAppearsOnConnect) { rtc::FakeSSLCertificate fake_certificate("fake data"); CreateTransport(&fake_certificate); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); EXPECT_TRUE(observer_.info_.remote_ssl_certificates() != nullptr); } TEST_F(DtlsTransportTest, CertificateDisappearsOnClose) { rtc::FakeSSLCertificate fake_certificate("fake data"); CreateTransport(&fake_certificate); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); EXPECT_TRUE(observer_.info_.remote_ssl_certificates() != nullptr); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); EXPECT_FALSE(observer_.info_.remote_ssl_certificates()); } TEST_F(DtlsTransportTest, CipherSuiteVisibleWhenConnected) { CreateTransport(); transport()->RegisterObserver(observer()); CompleteDtlsHandshake(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kConnected, kDefaultTimeout); ASSERT_TRUE(observer_.info_.ssl_cipher_suite()); EXPECT_EQ(kNonsenseCipherSuite, *observer_.info_.ssl_cipher_suite()); transport()->Clear(); ASSERT_TRUE_WAIT(observer_.state() == DtlsTransportState::kClosed, kDefaultTimeout); EXPECT_FALSE(observer_.info_.ssl_cipher_suite()); } } // namespace webrtc
[ "wuhaiyang1213@gmail.com" ]
wuhaiyang1213@gmail.com
6077cd3a58794f87542013047bfcfe70e474e8b5
69a525172319cfb3fe1d5200dd67d8793820531c
/Software/iROB_EA/copia/iROB_EA.ino
a5e1e6b90383738915eaa0a8b508ade21d415a10
[]
no_license
Baphomet2015/iROB-EA
efcd8fd36b33cd3a0cd028447609c5416ea1eb12
d58e078bd40f239fee59d5e8e81c3a032002de24
refs/heads/master
2021-12-08T22:50:17.717175
2021-12-05T19:07:24
2021-12-05T19:07:24
51,265,231
2
0
null
null
null
null
UTF-8
C++
false
false
32,401
ino
//! --------------------------------------------------------- //! //! @mainpage //! //! @brief Proyecto: iROB-EA //! @date Fecha: Enero 2021 //! @author AAL //! //! @remarks Hardware Arduino MEGA 2560\n //! //! @version Versión de SW 1.0 //! @version Versión de IDE Arduino: 1.8.12 //! //! @brief <b>Leitmotiv:</b>\n //! "Toda Bestia necesita un Cerebro...", Dr. Frankenstein, en su laboratorio\n //! "¡Larga y próspera vida!.", Sr. Spock\n //! //! --------------------------------------------------------- //! --------------------------------------------------------- //! //! @brief Funcionalidad: Modulo principal de la Aplicacion //! //! @warning REVISADO --/--/---- //! --------------------------------------------------------- #include <Arduino.h> #include <stdlib.h> #include <WString.h> #include <avr/pgmspace.h> #include <Wire.h> #include <Servo.h> #include <EEPROM.h> #include <LedDisplay.h> #include "iROB_EA.h" #include "UF_SYS.h" #include "MOTOR_FDS5672.h" #include "SENSOR_USS.h" #include "SENSOR_GPS.h" #include "SENSOR_EMC.h" #include "SENSOR_RAZOR.h" #include <Gescom_MEGA2560_V3.h> #include <Gescom_MEGA2560_V3_CMD.h> // --------------------------------------------------------- // // Definicion de Clases y variables GLOBALES // // // . uf_sys Objeto de manejo de funcionalidades basicas // . mDer Objeto de manejo del motor derecho // . mIzq Objeto de manejo del motor izquierdo // . myDisplay Objeto para manejear el display de estado // . sensor_USS Objeto para manejo de los sensores de US // . sensor_EMC Objeto para manejo de la estacion climatica // . sensor_GPS Objeto para manejo del GPS // . sensor_RAZOR Objeto para manejo del RAZOR // . sensor_mlx Objeto para manejar el sensor MLX90614 // . rtc Objeto para manejar el reloj de tiempo real // . gc Objeto que implementa el gestor de comandos // // . GLOBAL_FlgDebug Flag para control del modo DEBUG // . GLOBAL_FlgStatusPC Flag con el estado del PC // . GLOBAL_Timer_Ctrl_PC Timer asociado a los procesos de // encendido/apagado del PC // --------------------------------------------------------- UF_SYS uf_sys = UF_SYS(); // Implementa la funcionalidad relacionada con la UF_SYS MOTOR_FDS5672 mDer = MOTOR_FDS5672( PIN_HW_MTD_DIR , // Implementa el control del motor derecho PIN_HW_MTD_RST , PIN_HW_MTD_PWM ); MOTOR_FDS5672 mIzq = MOTOR_FDS5672( PIN_HW_MTI_DIR , // Implementa el control del motor izquierdo PIN_HW_MTI_RST , PIN_HW_MTI_PWM ); LedDisplay myDisplay = LedDisplay( PIN_HW_HCMS_DATA , // Implementa el control del display PIN_HW_HCMS_RS , PIN_HW_HCMS_CLK , PIN_HW_HCMS_CE , PIN_HW_HCMS_RESET , 4 ); SENSOR_USS sensor_USS = SENSOR_USS( PIN_HW_USR_DER_TRIGGER , // Implementa el control de los sensores de deteccion de objetos PIN_HW_USR_IZQ_TRIGGER , PIN_HW_USR_DER_ECHO , PIN_HW_USR_IZQ_ECHO , PIN_HW_SUPERFICIE ); SENSOR_EMC sensor_EMC = SENSOR_EMC( PIN_HW_SEN_MET_LUZ); // Implementa el control de los sensores de la estacion climatica SENSOR_GPS sensor_GPS; // Implementa el modulo de GPS SENSOR_RAZOR sensor_RAZOR; // Implementa el modulo de sensores AHRS GESCOM3 gc = GESCOM3( IDE_SERIAL_0 , false , IDE_DISPOSITIVO_R00 , IDE_SERIAL_TRX_PC ); // Gestor de comandos byte GLOBAL_FlgDebug; // Flag global que indica si se deben generar trazas por el puerto de Debug o no byte GLOBAL_FlgStatusPC; // Flag para control del proceso de encendido/Apagado byte GLOBAL_FlgModoAvance; // Flag que indica el modo de avance, ver defines IDE_MODO_AVANCE_xx byte GLOBAL_FlgModoAvanceEvento; // Flag que indica eventos detectados cuando la variable GLOBAL_FlgModoAvance = IDE_MODO_AVANCE_CON_PROTECCION unsigned long int GLOBAL_Timer_Ctrl_PC; // Timer asociado a los procesos de encendido/apagado del PC int GLOBAL_Timer_DispD_PC; // Timer asociado a los procesos de encendido/apagado del PC, para mostrar en el display int GLOBAL_Timer_DispF_PC; // Timer asociado a los procesos de encendido/apagado del PC, para mostrar en el display // --------------------------------------------------------- // // void setup() // Funcion para inicializar todos los sistemas del // iROB-EA // // --------------------------------------------------------- void setup(void) { // --------------------------------------------------------- // // ATENCIÓN: // // . Los pines de control de los motores NO se inicializan // aqui porque ya lo hace el constructor de la clase // MOTOR_FDS5672 // // . Los pines de control del display NO se inicializan // aqui porque ya lo hace el constructor de la clase // ledDisplay // // . Los pines de control de los sensores de ultrasonidos // NO se inicializan aqui porque ya lo hace el constructor // de la clase SENSOR_US // // . El pin PIN_HW_OFF_PETICION es la entrada de INT 0, no // es necesario inicializar este pin con pinMode // // --------------------------------------------------------- // --------------------------------------------------------- // // Inicializacion de los pines I/O (MODO) // Los pines que NO se inicializan expresamente aqui es debido // a que se inicializan en los objetos definidos para su // utilizacion, sensor_USS, mDer, MIzq etc // --------------------------------------------------------- pinMode( PIN_HW_MIC_01 ,INPUT); pinMode( PIN_HW_SEN_MET_LUZ ,INPUT); pinMode( PIN_HW_MTDI_INFO ,INPUT); pinMode( PIN_HW_ICC_SENSE_12P,INPUT); pinMode( PIN_HW_ICC_SENSE_5VP,INPUT); pinMode( PIN_HW_INT_OFF_PETICION,INPUT); pinMode( PIN_HW_INT_SQW ,INPUT); pinMode( PIN_HW_POW_CNX_A0,OUTPUT); pinMode( PIN_HW_POW_CNX_A1,OUTPUT); pinMode( PIN_HW_POW_CNX_A2,OUTPUT); pinMode( PIN_HW_DTMF_D0,INPUT); pinMode( PIN_HW_DTMF_D1,INPUT); pinMode( PIN_HW_DTMF_D2,INPUT); pinMode( PIN_HW_DTMF_D3,INPUT); pinMode( PIN_HW_DTMF_DV,INPUT); pinMode( PIN_HW_CNX_DEBUG,INPUT); pinMode( PIN_HW_BAT_N25 ,INPUT); pinMode( PIN_HW_BAT_N50 ,INPUT); pinMode( PIN_HW_BAT_N75 ,INPUT); pinMode( PIN_HW_BAT_N100 ,INPUT); pinMode( PIN_HW_SERVO_HOR,OUTPUT); pinMode( PIN_HW_SERVO_VER,OUTPUT); pinMode( PIN_HW_FAN,OUTPUT); pinMode( PIN_HW_LED_POS ,OUTPUT); pinMode( PIN_HW_LED_DER ,OUTPUT); pinMode( PIN_HW_LED_IZQ ,OUTPUT); pinMode( PIN_HW_LED_FOCO,OUTPUT); pinMode( PIN_HW_MTI_DIR,OUTPUT); pinMode( PIN_HW_MTI_RST,OUTPUT); pinMode( PIN_HW_MTI_PWM,OUTPUT); pinMode( PIN_HW_MTD_DIR,OUTPUT); pinMode( PIN_HW_MTD_RST,OUTPUT); pinMode( PIN_HW_MTD_PWM,OUTPUT); pinMode( PIN_HW_MTDI_SEL_A,OUTPUT); pinMode( PIN_HW_MTDI_SEL_B,OUTPUT); pinMode( PIN_HW_MTDI_SEL_C,OUTPUT); pinMode( PIN_HW_POW_PC_1,OUTPUT); // --------------------------------------------------------- // // !!! Estas variables se INICIALIZAN AQUI !!! // // --------------------------------------------------------- GLOBAL_FlgDebug = false; GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_ON; GLOBAL_FlgModoAvance = IDE_MODO_AVANCE_CON_PROTECCION; GLOBAL_FlgModoAvanceEvento = IDE_EVENTO_OK; GLOBAL_Timer_Ctrl_PC = 0L; GLOBAL_Timer_DispD_PC = 0; GLOBAL_Timer_DispF_PC = true; // --------------------------------------------------------- // // Inicializacion de variables, objetos Globales y elementos // // // --------------------------------------------------------- analogReference(DEFAULT); // --------------------------------------------------------- // // --------------------------------------------------------- Wire.begin(); mDer.begin(); mIzq.begin(); myDisplay.begin(); myDisplay.setBrightness(15); sensor_USS.begin(); sensor_GPS.begin(); sensor_EMC.begin(); sensor_RAZOR.begin(); gc.begin(); // --------------------------------------------------------- // Interrupciones: // // INT 0: Boton Power OFF // Funcion: INT_power_OFF() // Variable: GLOBAL_FlgPower_OFF // Variable actualizada por esta funcion // // INT 1: Señal generada desde el RTC // Funcion: INT_rtc_SQW() // // --------------------------------------------------------- attachInterrupt(0, INT_power_OFF, RISING); attachInterrupt(1, INT_rtc_SQW , RISING); // --------------------------------------------------------- // // Inicializacion de puertos serie // // . Serial0 Gestor de comandos, se inicializa en gc->begin() // Comunicacion entre Arduino y PC // . Serial1 GPS , se inicializa en sensor_GPS.begin() // . Serial2 RAZOR, se inicializa en sensor_RAZOR.begin() // . Serial3 9600 , puerto de DEBUG, 9600 // // --------------------------------------------------------- Serial3.begin(IDE_SERIAL_TRX_DEBUG); // Puerto de DEBUG, ver comentario de la variable GLOBAL_FlgDebug // --------------------------------------------------------- // IMPORTANTE // !!! NO mover de aqui estas inicializaciones // Para version Funcional, comentar todas las lineas que // puedan aparecer debajo de este comentario y dejar SOLO: // // uf_sys.begin(); // // --------------------------------------------------------- uf_sys.begin(); // --------------------------------------------------------- // Utilidad para escanear el bus I2C // DESCOMENTAR para probar los sensore conectados por I2C // --------------------------------------------------------- // UTIL_Scanner_I2C(); // --------------------------------------------------------- // Atencion: // Cuando se instala un nuevo Arduino MEGA, es conveniente // descomentar esta llamada UNA SOLA VEZ para iniciar la // Variable EEPROM a un valor conocido, despues se DEBE // dejar comentada // --------------------------------------------------------- // uf_sys.set_NUM_RC(1); } // --------------------------------------------------------- // // void loop() // Funcion principal para mantener funcionando iROB-EA // // --------------------------------------------------------- void loop(void) { // --------------------------------------------------------- // Actualizacion de Timers etc de uf_sys // --------------------------------------------------------- uf_sys.timers(); // ------------------------------------------------------- // // BLOQUE GENERAL DE PROGRAMA // // ------------------------------------------------------- // ------------------------------------------------------- // // GESTOR DE COMANDOS // // La funcion exeGesComando ejecuta el gestor de comandos. // Si se ha recibido algo en el puerto serie lo procesa y // envia el resultado obtenido. // TODAS las funciones asociadas a comandos se encuentran // en el fichero iROB-EA_CMD.ino // // Si no se ha recibido nada retorna inmediatamente. // // Esta funcion retorna: // . IDE_BUFF_RX_OK Se ha recibdo algo valido ( un // comando y se ha ejecutado ) // . IDE_BUFF_RX_ER Se ha recibido algo erroneo. // . IDE_BUFF_RX_VACIO NO se ha recibido nada // // Estos defines se encuentran en Gescom_MEGA2560_V3.h // // ------------------------------------------------------- gc.exeGesComando(); // ------------------------------------------------------- // // Proceso de encendido/apagado/Bucle activo // // - Si el proceso de encendido finaliza correctamente: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK = procesoActivo() // // - Si el proceso de apagado se solicita actuando sobre // el pulsador: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_OFF // // ------------------------------------------------------- switch( GLOBAL_FlgStatusPC ) { case ( IDE_STATUS_PC_INI_ON ): { // ---------------------------------------- // El PC esta apagado, se acaba de // arrancar el Robot // // Se inicia el proceso de encendido. // La funcion pc_ON() inicia el encendido y // cambia el valor de GLOBAL_FlgStatusPC a // GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_WAIT,0); pc_ON(); break; } case ( IDE_STATUS_PC_START ): { // ---------------------------------------- // El PC esta arrancando // Temporiza esperando respuesta desde el // PC. // // . Si el PC se inicializa correctamente // se recibira un comando desde el PC en // la funcion de comandos cmd_Comando_C_STPC() // con el cnv_Param01 = IDE_PARAM_ACT y esa // funcion cambiara el estado de la // variable // GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON // // . Si se agota el tiempo de espera se pasa // GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON_ERROR // // ---------------------------------------- if ( (unsigned long int)(millis()-GLOBAL_Timer_Ctrl_PC)>=IDE_PC_POWER_ON_TIMEOUT ) { // ------------------------------------------ // Superado el tiempo maximo de espera para // que el PC comunique que se ha encendido, // NO se ha recibido desde el PC el comando // #####1001070000E0001 que indicaria que ha // arrancado correctamente, se indica error y // se cambia GLOBAL_FlgStatusPC // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_ER_000,0); GLOBAL_FlgStatusPC = IDE_STATUS_PC_ON_ERROR; } else { // ------------------------------------------ // Muestra tiempo de espera restante // ------------------------------------------ displayTimerInicio_PC(); } break; } case ( IDE_STATUS_PC_ON ): { // ---------------------------------------- // Se ha recibido desde el PC la // confirmacion de encendido correcto. // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_OK ,(IDE_PAUSA_GENERAL*4)); FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_CLS,0); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OK; break; } case ( IDE_STATUS_PC_OK ): { // ---------------------------------------- // Finalizado correctamente el proceso de // encendido del PC. // Bucle Activo // Aqui se deben incluir todas las cosas // que se deben ejecutar en el modo normal // de funcionamiento. // ---------------------------------------- procesoActivo(); break; } case ( IDE_STATUS_PC_INI_OFF ): { // ---------------------------------------- // Se ha pulsado el boton de // encendido/apagado // Se inicia el proceso de apagado del PC // Independientemente del resultado del // proceso de apagado del PC , se pasara a // GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF // ---------------------------------------- FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_DOWN,0); pc_OFF(); break; } case ( IDE_STATUS_PC_DOWN ): { // ---------------------------------------- // Proceso de apagado del Robot // // ---------------------------------------- if ( (unsigned long int)(millis()-GLOBAL_Timer_Ctrl_PC)>=IDE_PC_POWER_OFF_TIMEOUT ) { // ------------------------------------------ // Superado el tiempo maximo de espera para // detectar el apagado del PC. // Se indica error y se cambia GLOBAL_FlgStatusPC // para apagar fisicamente el Robot , aunque // el PC no se haya apagado correctamente // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_ER_001,(IDE_PAUSA_GENERAL*5)); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF; } else { // ------------------------------------------ // Mide la corriente consumida por el PC para // detectar cuando se apaga // ------------------------------------------ if ( getIcc5VP()==false ) { // ------------------------------------------ // La corriente medida con el sensor asociado // a la alimentacion del PC determina que se // ha apagado. // Se indica ok y se cambia GLOBAL_FlgStatusPC // para apagar fisicamente el Robot // ------------------------------------------ FNG_DisplayMsgPROGMEM(IDE_MSG_DISPLAY_OK,(IDE_PAUSA_GENERAL*5)); GLOBAL_FlgStatusPC = IDE_STATUS_PC_OFF; } } break; } case ( IDE_STATUS_PC_OFF ): { // ---------------------------------------- // Apagado fisico del Robot -) // ---------------------------------------- uf_sys.power_OFF(); break; } case ( IDE_STATUS_PC_ON_ERROR ): { // ---------------------------------------- // El PC no ha podido encenderse, se debe // dejar la alimentacion conectada para que // desde el exterior , via teclado/Raton se // pueda determinar el fallo // ---------------------------------------- break; } } } // --------------------------------------------------------- // // void pc_ON(void) // Efectua las operaciones necesarias para encender el PC y // cambia el estado de la variable global GLOBAL_FlgStatusPC // al valor: // GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // // --------------------------------------------------------- void pc_ON(void) { unsigned long int t; // --------------------------------------------------------- // 1 - Conecta el rele de alimentacion (5VP) // 2 - Espera x segundos a que el PC se estabilice. // 3 - Activa el pulsador de encendido, durante x seg // 4 - Cambia el estado de GLOBAL_FlgStatusPC = IDE_STATUS_PC_START // 5 - Inicia la variable de Timer que se actualiza con la // interruptor del RTC // 6 - Inicializa los Timers de espera a que el PC comunique // que ha arrancado, enviado el comando #####1001070000E0001 // al Arduino // --------------------------------------------------------- uf_sys.rele(IDE_RELE_5VP,IDE_RELE_ACTIVAR); t = millis(); while( (millis()-t)<IDE_PC_POWER_INICIO ) { // ------------------------------------------ // Bucle de espera para que el HW del PC se // inicie correctamente antes de solicitar su // encendido con el pulsador // ------------------------------------------ } uf_sys.pulsador_PC(IDE_PC_POWER_PULSADOR_ON); GLOBAL_FlgStatusPC = IDE_STATUS_PC_START; GLOBAL_Timer_DispD_PC = int(IDE_PC_POWER_ON_TIMEOUT / 1000); GLOBAL_Timer_DispF_PC = true; GLOBAL_Timer_Ctrl_PC = millis(); } // --------------------------------------------------------- // // void pc_OFF(void) // Efectua las operaciones necesarias para apagar el PC. // 1 - Activa el pulsador de encendido/apagado del PC, SOLO // si se determina que el PC esta encendido // 2 - Cambia el estado de GLOBAL_FlgStatusPC = IDE_STATUS_PC_DOWN // 3 - Inicializa el Timer de espera a que el PC se apague // --------------------------------------------------------- void pc_OFF(void) { if ( getIcc5VP()==true ) { // ---------------------------------------------------- // Hay consumo de corriente, luego el PC esta encendido // se actua sobre el pulsador del PC para apagarlo pero // SOLO se debe actuar sobre este pulsador cuando el // PC esta encendido porque sino lo que se consigue es // lo contrario, encenderlo -) // Esto se hace asi porque existe la posibilidad de que // el PC se pueda apagar directamente por intervencion // del usuario que remotamente esta controlando el Robot // actuando desde alguna de las aplicaciones que ejecuta // ( web, apps etc) // ---------------------------------------------------- uf_sys.pulsador_PC(IDE_PC_POWER_PULSADOR_OFF); } GLOBAL_FlgStatusPC = IDE_STATUS_PC_DOWN; GLOBAL_Timer_Ctrl_PC = millis(); } // --------------------------------------------------------- // // void procesoActivo(void) // // Funcion para manter activas las o peraciones precisas // durante el funcionamiento del Robot // // // --------------------------------------------------------- void procesoActivo(void) { unsigned int sup; int obj; if ( GLOBAL_FlgModoAvance==IDE_MODO_AVANCE_CON_PROTECCION ) { // ------------------------------------------------------- // El modo de proteccion esta activado, esto implica: // // 1 - Deteccion de suelo en modo avance // Paro si existe peligro // // 2 - Deteccion de objetos (ultrasonidos) en modo avance // Paro si existe peligro // // 2 - Deteccion de obstaculos (por sobreconsumo) en modo // avance // Paro si existe peligro // // Al activar este modo, la velocidad esta LIMITADA permanentemente // ver el comando cmd_Comando_CM_CTR(GESCOM_DATA* gd), en // iROB-EA_CMD.ino // // ------------------------------------------------------ sup = sensor_USS.get_Superficie(); if ( sup<IDE_EVENTO_TRIGGER_SUELO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_SUELO); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_SUELO); } obj = sensor_USS.get_DER(); if ( obj<IDE_EVENTO_TRIGGER_OBJETO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_DERECHA); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_DERECHA); } obj = sensor_USS.get_IZQ(); if ( obj<IDE_EVENTO_TRIGGER_OBJETO ) { bitSet (GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_IZQUIERDA); } else { bitClear(GLOBAL_FlgModoAvanceEvento, IDE_EVENTO_OBJETO_IZQUIERDA); } if ( GLOBAL_FlgModoAvanceEvento!=IDE_EVENTO_OK ) { // ------------------------------------------------- // Detectada alguna incidencia, para los motores // ------------------------------------------------- mDer.paro(); mIzq.paro(); } } } // --------------------------------------------------------- // // byte getIcc5VP(void) // Mide la corriente consumida por el PC para determinar si // esta encendido o no. // Retrona: // . true El PC esta encendido // . false El PC esta apagado // // Notas: // . Cuando el PC Stick esta APAGADO, su consumo es inferior // a 100mA ( 68mA medidos con multimetro), situacion de // standby. // // . Cuando el PC Stick esta funcionando, su consumo es de // entorno a 500 ... 800mA // // --------------------------------------------------------- byte getIcc5VP(void) { float iccMedida; byte resultado; iccMedida = uf_sys.get_Corriente(IDE_ICC_5VP); if ( iccMedida<IDE_PC_POWER_ICC_OFF ) { resultado = false; } else { resultado = true; } return(resultado ); } // --------------------------------------------------------- // // void INT_power_OFF(void) // Funcion conectada a la interrupcion 0 para capturar la // pulsacion del pulsador ON/OFF, que se actua para iniciar // y apagar el Robot. // La interrupcion se conecta al iniciar el arduino para poder // capturar la pulsacion del pulsador y poder APAGAR el Robot // cuando el Robot esta apagado el pulsador ENCIENDE el Robot // via Hardware. // Hay que mantener el pulsador actuado durante unos 10 seg // para iniciar el apagado del Robot. // --------------------------------------------------------- void INT_power_OFF(void) { if ( (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_INI_ON) && (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_START) && (GLOBAL_FlgStatusPC!=IDE_STATUS_PC_ON) ) { // ------------------------------------------------------- // solo se permite si NO se esta inicializando el PC Stick // ------------------------------------------------------- GLOBAL_FlgStatusPC = IDE_STATUS_PC_INI_OFF; } } // --------------------------------------------------------- // // void INT_rtc_SQW(void) // Funcion conectada a la interrupcion 1 para capturar la // señal que genera el reloj de tiempo real, modulo // // --------------------------------------------------------- void INT_rtc_SQW(void) { GLOBAL_Timer_DispF_PC = true; } // --------------------------------------------------------- // // void displayTimerInicio_PC(void) // Actualiza y visualiza en el dsipaly el valor de la variable // GLOBAL_Timer_INI_PC // --------------------------------------------------------- void displayTimerInicio_PC(void) { char sBuff[IDE_MAX_DISPLAY_CAR+1]; if ( (GLOBAL_Timer_DispF_PC==true) && (GLOBAL_Timer_DispD_PC>0) ) { GLOBAL_Timer_DispF_PC = false; sprintf(sBuff,"T%3d",GLOBAL_Timer_DispD_PC); FNG_DisplayMsg(sBuff,0); GLOBAL_Timer_DispD_PC--; } } // --------------------------------------------------------- // // byte FNG_DisplayMsgPROGMEM(const char* msg,unsigned int pausa) // // Funcion para mostrar mensajes en el display cuando los // mensajes son CONSTANTES de memoria // // Ver "https://www.arduino.cc/en/Reference/PROGMEM" // // --------------------------------------------------------- byte FNG_DisplayMsgPROGMEM( const char* msgP,unsigned int pausa) { byte resultado; char buff [IDE_MAX_DISPLAY_CAR+1]; char c; byte ind; byte max; resultado = false; max = strlen_P(msgP); ind = 0; if ( max<=IDE_MAX_DISPLAY_CAR) { for ( ;ind<max; ) { c = pgm_read_byte_near(msgP); buff[ind++] = c; buff[ind ] = '\0'; msgP++; } myDisplay.home(); myDisplay.print(buff); resultado = true; if ( pausa>0 ) { FNG_Pausa(pausa); } } return (resultado) ; } // --------------------------------------------------------- // // byte FNG_DisplayMsg(char* msg,unsigned int pausa) // // Funcion para mostrar mensajes en el display cuando los // mensajes son creados dinamicamente durante la ejecucion // // --------------------------------------------------------- byte FNG_DisplayMsg(char* msg,unsigned int pausa) { byte resultado; resultado = false; if ( strlen(msg)<=IDE_MAX_DISPLAY_CAR) { myDisplay.home(); myDisplay.print(msg); resultado = true; if ( pausa>0 ) { FNG_Pausa(pausa); } } return (resultado) ; } // --------------------------------------------------------- // // void FNG_Pausa(unsigned int pausa) // Genera una pausa de los milisegundos indicados // // --------------------------------------------------------- void FNG_Pausa(unsigned int pausa) { unsigned long int tIni; tIni = millis(); while ( 1 ) { if ( (unsigned int)(millis()-tIni)>= pausa ) { break; } } } // --------------------------------------------------------- // // void UTIL_Scanner_I2C (void) // Utilidad para descubrir dispositivos conecatados al bus // I2C // --------------------------------------------------------- void UTIL_Scanner_I2C (void) { byte error; byte address; int nDevices; Serial3.println("Scanning I2C..."); while ( true ) { nDevices = 0; for ( address = 1; address < 127; address++ ) { // Uses the return value of the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if ( error==0 ) { Serial3.print("I2C Device found at address 0x"); if (address<16) { Serial3.print("0"); } Serial3.println(address,HEX); nDevices++; } else if ( error==4 ) { Serial3.print("Unknown error at address 0x"); if (address<16) { Serial3.print("0"); } Serial3.println(address,HEX); } } if (nDevices == 0) { Serial3.println("No I2C devices found\n"); } else { Serial3.println("Done\n"); } delay(3000); } }
[ "antonio.arnaizlago@gmail.com" ]
antonio.arnaizlago@gmail.com
8ba16b70c536b1e4f340995daca952ca65f6ab98
5fb4409abe9e4796c8dc17cc51233c779b9e24bc
/app/src/main/cpp/wechat/zxing/common/binarizer/simple_adaptive_binarizer.cpp
bde11680a18a4d65bf5e5885235e89a2500e468a
[]
no_license
BlackSuns/LearningAndroidOpenCV
6be52f71cd9f3a1d5546da31f71c04064f0c7cac
79dc25e383c740c73cae67f36027abf13ab17922
refs/heads/master
2023-07-10T02:08:10.923992
2021-08-09T02:09:19
2021-08-09T02:09:34
297,529,216
0
0
null
2021-08-09T14:06:05
2020-09-22T03:52:46
C++
UTF-8
C++
false
false
5,405
cpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #include "../../../precomp.hpp" #include "simple_adaptive_binarizer.hpp" using zxing::SimpleAdaptiveBinarizer; SimpleAdaptiveBinarizer::SimpleAdaptiveBinarizer(Ref<LuminanceSource> source) : GlobalHistogramBinarizer(source) { filtered = false; } SimpleAdaptiveBinarizer::~SimpleAdaptiveBinarizer() {} // Applies simple sharpening to the row data to improve performance of the 1D // readers. Ref<BitArray> SimpleAdaptiveBinarizer::getBlackRow(int y, Ref<BitArray> row, ErrorHandler &err_handler) { // First call binarize image in child class to get matrix0_ and binCache if (!matrix0_) { binarizeImage0(err_handler); if (err_handler.ErrCode()) return Ref<BitArray>(); } // Call parent getBlackMatrix to get current matrix return Binarizer::getBlackRow(y, row, err_handler); } // Does not sharpen the data, as this call is intended to only be used by 2D // readers. Ref<BitMatrix> SimpleAdaptiveBinarizer::getBlackMatrix(ErrorHandler &err_handler) { // First call binarize image in child class to get matrix0_ and binCache if (!matrix0_) { binarizeImage0(err_handler); if (err_handler.ErrCode()) return Ref<BitMatrix>(); } // First call binarize image in child class to get matrix0_ and binCache // Call parent getBlackMatrix to get current matrix return Binarizer::getBlackMatrix(err_handler); } using namespace std; int SimpleAdaptiveBinarizer::binarizeImage0(ErrorHandler &err_handler) { LuminanceSource &source = *getLuminanceSource(); Ref<BitMatrix> matrix(new BitMatrix(width, height, err_handler)); if (err_handler.ErrCode()) return -1; ArrayRef<char> localLuminances = source.getMatrix(); unsigned char *src = (unsigned char *) localLuminances->data(); unsigned char *dst = matrix->getPtr(); qrBinarize(src, dst); matrix0_ = matrix; return 0; } /*A simplified adaptive thresholder. This compares the current pixel value to the mean value of a (large) window surrounding it.*/ int SimpleAdaptiveBinarizer::qrBinarize(const unsigned char *src, unsigned char *dst) { unsigned char *mask = dst; if (width > 0 && height > 0) { unsigned *col_sums; int logwindw; int logwindh; int windw; int windh; int y0offs; int y1offs; unsigned g; int x; int y; /*We keep the window size fairly large to ensure it doesn't fit completely inside the center of a finder pattern of a version 1 QR code at full resolution.*/ for (logwindw = 4; logwindw < 8 && (1 << logwindw) < ((width + 7) >> 3); logwindw++); for (logwindh = 4; logwindh < 8 && (1 << logwindh) < ((height + 7) >> 3); logwindh++); windw = 1 << logwindw; windh = 1 << logwindh; int logwinds = (logwindw + logwindh); col_sums = (unsigned *) malloc(width * sizeof(*col_sums)); /*Initialize sums down each column.*/ for (x = 0; x < width; x++) { g = src[x]; col_sums[x] = (g << (logwindh - 1)) + g; } for (y = 1; y < (windh >> 1); y++) { y1offs = min(y, height - 1) * width; for (x = 0; x < width; x++) { g = src[y1offs + x]; col_sums[x] += g; } } for (y = 0; y < height; y++) { unsigned m; int x0; int x1; /*Initialize the sum over the window.*/ m = (col_sums[0] << (logwindw - 1)) + col_sums[0]; for (x = 1; x < (windw >> 1); x++) { x1 = min(x, width - 1); m += col_sums[x1]; } int offset = y * width; for (x = 0; x < width; x++) { /*Perform the test against the threshold T = (m/n)-D, where n=windw*windh and D=3.*/ g = src[offset + x]; mask[offset + x] = ((g + 3) << (logwinds) < m); /*Update the window sum.*/ if (x + 1 < width) { x0 = max(0, x - (windw >> 1)); x1 = min(x + (windw >> 1), width - 1); m += col_sums[x1] - col_sums[x0]; } } /*Update the column sums.*/ if (y + 1 < height) { y0offs = max(0, y - (windh >> 1)) * width; y1offs = min(y + (windh >> 1), height - 1) * width; for (x = 0; x < width; x++) { col_sums[x] -= src[y0offs + x]; col_sums[x] += src[y1offs + x]; } } } free(col_sums); } return 1; } Ref<Binarizer> SimpleAdaptiveBinarizer::createBinarizer(Ref<LuminanceSource> source) { return Ref<Binarizer>(new SimpleAdaptiveBinarizer(source)); }
[ "onlyloveyd@gmail.com" ]
onlyloveyd@gmail.com
0a340b69167678d0f8b2318c987c570828022d1c
e7f4c25dc251fd6b74efa7014c3d271724536797
/test/encodings/unicode_group_Mn_u_encoding_policy_fail.re
823edc273b26407fa5143e2721172590a3905502
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
nightlark/re2c
163cc308e9023b290e08cc82cc704a8ae5b90114
96104a652622c63ca2cc0b1d2b1d3dad8c34aae6
refs/heads/master
2023-08-08T18:35:31.715463
2023-07-21T21:23:56
2023-07-21T21:29:45
100,122,233
1
0
null
2017-08-12T15:51:24
2017-08-12T15:51:24
null
UTF-8
C++
false
false
11,325
re
// re2c $INPUT -o $OUTPUT -u --encoding-policy fail #include <stdio.h> #define YYCTYPE unsigned int bool scan(const YYCTYPE * start, const YYCTYPE * const limit) { __attribute__((unused)) const YYCTYPE * YYMARKER; // silence compiler warnings when YYMARKER is not used # define YYCURSOR start Mn: /*!re2c re2c:yyfill:enable = 0; Mn = [\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf-\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7-\u05c7\u0610-\u061a\u064b-\u065f\u0670-\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711-\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u07fd-\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0902\u093a-\u093a\u093c-\u093c\u0941-\u0948\u094d-\u094d\u0951-\u0957\u0962-\u0963\u0981-\u0981\u09bc-\u09bc\u09c1-\u09c4\u09cd-\u09cd\u09e2-\u09e3\u09fe-\u09fe\u0a01-\u0a02\u0a3c-\u0a3c\u0a41-\u0a42\u0a47-\u0a48\u0a4b-\u0a4d\u0a51-\u0a51\u0a70-\u0a71\u0a75-\u0a75\u0a81-\u0a82\u0abc-\u0abc\u0ac1-\u0ac5\u0ac7-\u0ac8\u0acd-\u0acd\u0ae2-\u0ae3\u0afa-\u0aff\u0b01-\u0b01\u0b3c-\u0b3c\u0b3f-\u0b3f\u0b41-\u0b44\u0b4d-\u0b4d\u0b56-\u0b56\u0b62-\u0b63\u0b82-\u0b82\u0bc0-\u0bc0\u0bcd-\u0bcd\u0c00-\u0c00\u0c04-\u0c04\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56\u0c62-\u0c63\u0c81-\u0c81\u0cbc-\u0cbc\u0cbf-\u0cbf\u0cc6-\u0cc6\u0ccc-\u0ccd\u0ce2-\u0ce3\u0d00-\u0d01\u0d3b-\u0d3c\u0d41-\u0d44\u0d4d-\u0d4d\u0d62-\u0d63\u0dca-\u0dca\u0dd2-\u0dd4\u0dd6-\u0dd6\u0e31-\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1-\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0f18-\u0f19\u0f35-\u0f35\u0f37-\u0f37\u0f39-\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6-\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074\u1082-\u1082\u1085-\u1086\u108d-\u108d\u109d-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5\u17b7-\u17bd\u17c6-\u17c6\u17c9-\u17d3\u17dd-\u17dd\u180b-\u180d\u1885-\u1886\u18a9-\u18a9\u1920-\u1922\u1927-\u1928\u1932-\u1932\u1939-\u193b\u1a17-\u1a18\u1a1b-\u1a1b\u1a56-\u1a56\u1a58-\u1a5e\u1a60-\u1a60\u1a62-\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f-\u1a7f\u1ab0-\u1abd\u1b00-\u1b03\u1b34-\u1b34\u1b36-\u1b3a\u1b3c-\u1b3c\u1b42-\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6-\u1be6\u1be8-\u1be9\u1bed-\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced-\u1ced\u1cf4-\u1cf4\u1cf8-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u20d0-\u20dc\u20e1-\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f-\u2d7f\u2de0-\u2dff\u302a-\u302d\u3099-\u309a\ua66f-\ua66f\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1\ua802-\ua802\ua806-\ua806\ua80b-\ua80b\ua825-\ua826\ua8c4-\ua8c5\ua8e0-\ua8f1\ua8ff-\ua8ff\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3-\ua9b3\ua9b6-\ua9b9\ua9bc-\ua9bd\ua9e5-\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43-\uaa43\uaa4c-\uaa4c\uaa7c-\uaa7c\uaab0-\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1-\uaac1\uaaec-\uaaed\uaaf6-\uaaf6\uabe5-\uabe5\uabe8-\uabe8\uabed-\uabed\ufb1e-\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\U000101fd-\U000101fd\U000102e0-\U000102e0\U00010376-\U0001037a\U00010a01-\U00010a03\U00010a05-\U00010a06\U00010a0c-\U00010a0f\U00010a38-\U00010a3a\U00010a3f-\U00010a3f\U00010ae5-\U00010ae6\U00010d24-\U00010d27\U00010f46-\U00010f50\U00011001-\U00011001\U00011038-\U00011046\U0001107f-\U00011081\U000110b3-\U000110b6\U000110b9-\U000110ba\U00011100-\U00011102\U00011127-\U0001112b\U0001112d-\U00011134\U00011173-\U00011173\U00011180-\U00011181\U000111b6-\U000111be\U000111c9-\U000111cc\U0001122f-\U00011231\U00011234-\U00011234\U00011236-\U00011237\U0001123e-\U0001123e\U000112df-\U000112df\U000112e3-\U000112ea\U00011300-\U00011301\U0001133b-\U0001133c\U00011340-\U00011340\U00011366-\U0001136c\U00011370-\U00011374\U00011438-\U0001143f\U00011442-\U00011444\U00011446-\U00011446\U0001145e-\U0001145e\U000114b3-\U000114b8\U000114ba-\U000114ba\U000114bf-\U000114c0\U000114c2-\U000114c3\U000115b2-\U000115b5\U000115bc-\U000115bd\U000115bf-\U000115c0\U000115dc-\U000115dd\U00011633-\U0001163a\U0001163d-\U0001163d\U0001163f-\U00011640\U000116ab-\U000116ab\U000116ad-\U000116ad\U000116b0-\U000116b5\U000116b7-\U000116b7\U0001171d-\U0001171f\U00011722-\U00011725\U00011727-\U0001172b\U0001182f-\U00011837\U00011839-\U0001183a\U000119d4-\U000119d7\U000119da-\U000119db\U000119e0-\U000119e0\U00011a01-\U00011a0a\U00011a33-\U00011a38\U00011a3b-\U00011a3e\U00011a47-\U00011a47\U00011a51-\U00011a56\U00011a59-\U00011a5b\U00011a8a-\U00011a96\U00011a98-\U00011a99\U00011c30-\U00011c36\U00011c38-\U00011c3d\U00011c3f-\U00011c3f\U00011c92-\U00011ca7\U00011caa-\U00011cb0\U00011cb2-\U00011cb3\U00011cb5-\U00011cb6\U00011d31-\U00011d36\U00011d3a-\U00011d3a\U00011d3c-\U00011d3d\U00011d3f-\U00011d45\U00011d47-\U00011d47\U00011d90-\U00011d91\U00011d95-\U00011d95\U00011d97-\U00011d97\U00011ef3-\U00011ef4\U00016af0-\U00016af4\U00016b30-\U00016b36\U00016f4f-\U00016f4f\U00016f8f-\U00016f92\U0001bc9d-\U0001bc9e\U0001d167-\U0001d169\U0001d17b-\U0001d182\U0001d185-\U0001d18b\U0001d1aa-\U0001d1ad\U0001d242-\U0001d244\U0001da00-\U0001da36\U0001da3b-\U0001da6c\U0001da75-\U0001da75\U0001da84-\U0001da84\U0001da9b-\U0001da9f\U0001daa1-\U0001daaf\U0001e000-\U0001e006\U0001e008-\U0001e018\U0001e01b-\U0001e021\U0001e023-\U0001e024\U0001e026-\U0001e02a\U0001e130-\U0001e136\U0001e2ec-\U0001e2ef\U0001e8d0-\U0001e8d6\U0001e944-\U0001e94a\U000e0100-\U000e01ef]; Mn { goto Mn; } * { return YYCURSOR == limit; } */ } static const unsigned int chars_Mn [] = {0x300,0x36f, 0x483,0x487, 0x591,0x5bd, 0x5bf,0x5bf, 0x5c1,0x5c2, 0x5c4,0x5c5, 0x5c7,0x5c7, 0x610,0x61a, 0x64b,0x65f, 0x670,0x670, 0x6d6,0x6dc, 0x6df,0x6e4, 0x6e7,0x6e8, 0x6ea,0x6ed, 0x711,0x711, 0x730,0x74a, 0x7a6,0x7b0, 0x7eb,0x7f3, 0x7fd,0x7fd, 0x816,0x819, 0x81b,0x823, 0x825,0x827, 0x829,0x82d, 0x859,0x85b, 0x8d3,0x8e1, 0x8e3,0x902, 0x93a,0x93a, 0x93c,0x93c, 0x941,0x948, 0x94d,0x94d, 0x951,0x957, 0x962,0x963, 0x981,0x981, 0x9bc,0x9bc, 0x9c1,0x9c4, 0x9cd,0x9cd, 0x9e2,0x9e3, 0x9fe,0x9fe, 0xa01,0xa02, 0xa3c,0xa3c, 0xa41,0xa42, 0xa47,0xa48, 0xa4b,0xa4d, 0xa51,0xa51, 0xa70,0xa71, 0xa75,0xa75, 0xa81,0xa82, 0xabc,0xabc, 0xac1,0xac5, 0xac7,0xac8, 0xacd,0xacd, 0xae2,0xae3, 0xafa,0xaff, 0xb01,0xb01, 0xb3c,0xb3c, 0xb3f,0xb3f, 0xb41,0xb44, 0xb4d,0xb4d, 0xb56,0xb56, 0xb62,0xb63, 0xb82,0xb82, 0xbc0,0xbc0, 0xbcd,0xbcd, 0xc00,0xc00, 0xc04,0xc04, 0xc3e,0xc40, 0xc46,0xc48, 0xc4a,0xc4d, 0xc55,0xc56, 0xc62,0xc63, 0xc81,0xc81, 0xcbc,0xcbc, 0xcbf,0xcbf, 0xcc6,0xcc6, 0xccc,0xccd, 0xce2,0xce3, 0xd00,0xd01, 0xd3b,0xd3c, 0xd41,0xd44, 0xd4d,0xd4d, 0xd62,0xd63, 0xdca,0xdca, 0xdd2,0xdd4, 0xdd6,0xdd6, 0xe31,0xe31, 0xe34,0xe3a, 0xe47,0xe4e, 0xeb1,0xeb1, 0xeb4,0xebc, 0xec8,0xecd, 0xf18,0xf19, 0xf35,0xf35, 0xf37,0xf37, 0xf39,0xf39, 0xf71,0xf7e, 0xf80,0xf84, 0xf86,0xf87, 0xf8d,0xf97, 0xf99,0xfbc, 0xfc6,0xfc6, 0x102d,0x1030, 0x1032,0x1037, 0x1039,0x103a, 0x103d,0x103e, 0x1058,0x1059, 0x105e,0x1060, 0x1071,0x1074, 0x1082,0x1082, 0x1085,0x1086, 0x108d,0x108d, 0x109d,0x109d, 0x135d,0x135f, 0x1712,0x1714, 0x1732,0x1734, 0x1752,0x1753, 0x1772,0x1773, 0x17b4,0x17b5, 0x17b7,0x17bd, 0x17c6,0x17c6, 0x17c9,0x17d3, 0x17dd,0x17dd, 0x180b,0x180d, 0x1885,0x1886, 0x18a9,0x18a9, 0x1920,0x1922, 0x1927,0x1928, 0x1932,0x1932, 0x1939,0x193b, 0x1a17,0x1a18, 0x1a1b,0x1a1b, 0x1a56,0x1a56, 0x1a58,0x1a5e, 0x1a60,0x1a60, 0x1a62,0x1a62, 0x1a65,0x1a6c, 0x1a73,0x1a7c, 0x1a7f,0x1a7f, 0x1ab0,0x1abd, 0x1b00,0x1b03, 0x1b34,0x1b34, 0x1b36,0x1b3a, 0x1b3c,0x1b3c, 0x1b42,0x1b42, 0x1b6b,0x1b73, 0x1b80,0x1b81, 0x1ba2,0x1ba5, 0x1ba8,0x1ba9, 0x1bab,0x1bad, 0x1be6,0x1be6, 0x1be8,0x1be9, 0x1bed,0x1bed, 0x1bef,0x1bf1, 0x1c2c,0x1c33, 0x1c36,0x1c37, 0x1cd0,0x1cd2, 0x1cd4,0x1ce0, 0x1ce2,0x1ce8, 0x1ced,0x1ced, 0x1cf4,0x1cf4, 0x1cf8,0x1cf9, 0x1dc0,0x1df9, 0x1dfb,0x1dff, 0x20d0,0x20dc, 0x20e1,0x20e1, 0x20e5,0x20f0, 0x2cef,0x2cf1, 0x2d7f,0x2d7f, 0x2de0,0x2dff, 0x302a,0x302d, 0x3099,0x309a, 0xa66f,0xa66f, 0xa674,0xa67d, 0xa69e,0xa69f, 0xa6f0,0xa6f1, 0xa802,0xa802, 0xa806,0xa806, 0xa80b,0xa80b, 0xa825,0xa826, 0xa8c4,0xa8c5, 0xa8e0,0xa8f1, 0xa8ff,0xa8ff, 0xa926,0xa92d, 0xa947,0xa951, 0xa980,0xa982, 0xa9b3,0xa9b3, 0xa9b6,0xa9b9, 0xa9bc,0xa9bd, 0xa9e5,0xa9e5, 0xaa29,0xaa2e, 0xaa31,0xaa32, 0xaa35,0xaa36, 0xaa43,0xaa43, 0xaa4c,0xaa4c, 0xaa7c,0xaa7c, 0xaab0,0xaab0, 0xaab2,0xaab4, 0xaab7,0xaab8, 0xaabe,0xaabf, 0xaac1,0xaac1, 0xaaec,0xaaed, 0xaaf6,0xaaf6, 0xabe5,0xabe5, 0xabe8,0xabe8, 0xabed,0xabed, 0xfb1e,0xfb1e, 0xfe00,0xfe0f, 0xfe20,0xfe2f, 0x101fd,0x101fd, 0x102e0,0x102e0, 0x10376,0x1037a, 0x10a01,0x10a03, 0x10a05,0x10a06, 0x10a0c,0x10a0f, 0x10a38,0x10a3a, 0x10a3f,0x10a3f, 0x10ae5,0x10ae6, 0x10d24,0x10d27, 0x10f46,0x10f50, 0x11001,0x11001, 0x11038,0x11046, 0x1107f,0x11081, 0x110b3,0x110b6, 0x110b9,0x110ba, 0x11100,0x11102, 0x11127,0x1112b, 0x1112d,0x11134, 0x11173,0x11173, 0x11180,0x11181, 0x111b6,0x111be, 0x111c9,0x111cc, 0x1122f,0x11231, 0x11234,0x11234, 0x11236,0x11237, 0x1123e,0x1123e, 0x112df,0x112df, 0x112e3,0x112ea, 0x11300,0x11301, 0x1133b,0x1133c, 0x11340,0x11340, 0x11366,0x1136c, 0x11370,0x11374, 0x11438,0x1143f, 0x11442,0x11444, 0x11446,0x11446, 0x1145e,0x1145e, 0x114b3,0x114b8, 0x114ba,0x114ba, 0x114bf,0x114c0, 0x114c2,0x114c3, 0x115b2,0x115b5, 0x115bc,0x115bd, 0x115bf,0x115c0, 0x115dc,0x115dd, 0x11633,0x1163a, 0x1163d,0x1163d, 0x1163f,0x11640, 0x116ab,0x116ab, 0x116ad,0x116ad, 0x116b0,0x116b5, 0x116b7,0x116b7, 0x1171d,0x1171f, 0x11722,0x11725, 0x11727,0x1172b, 0x1182f,0x11837, 0x11839,0x1183a, 0x119d4,0x119d7, 0x119da,0x119db, 0x119e0,0x119e0, 0x11a01,0x11a0a, 0x11a33,0x11a38, 0x11a3b,0x11a3e, 0x11a47,0x11a47, 0x11a51,0x11a56, 0x11a59,0x11a5b, 0x11a8a,0x11a96, 0x11a98,0x11a99, 0x11c30,0x11c36, 0x11c38,0x11c3d, 0x11c3f,0x11c3f, 0x11c92,0x11ca7, 0x11caa,0x11cb0, 0x11cb2,0x11cb3, 0x11cb5,0x11cb6, 0x11d31,0x11d36, 0x11d3a,0x11d3a, 0x11d3c,0x11d3d, 0x11d3f,0x11d45, 0x11d47,0x11d47, 0x11d90,0x11d91, 0x11d95,0x11d95, 0x11d97,0x11d97, 0x11ef3,0x11ef4, 0x16af0,0x16af4, 0x16b30,0x16b36, 0x16f4f,0x16f4f, 0x16f8f,0x16f92, 0x1bc9d,0x1bc9e, 0x1d167,0x1d169, 0x1d17b,0x1d182, 0x1d185,0x1d18b, 0x1d1aa,0x1d1ad, 0x1d242,0x1d244, 0x1da00,0x1da36, 0x1da3b,0x1da6c, 0x1da75,0x1da75, 0x1da84,0x1da84, 0x1da9b,0x1da9f, 0x1daa1,0x1daaf, 0x1e000,0x1e006, 0x1e008,0x1e018, 0x1e01b,0x1e021, 0x1e023,0x1e024, 0x1e026,0x1e02a, 0x1e130,0x1e136, 0x1e2ec,0x1e2ef, 0x1e8d0,0x1e8d6, 0x1e944,0x1e94a, 0xe0100,0xe01ef, 0x0,0x0}; static unsigned int encode_utf32 (const unsigned int * ranges, unsigned int ranges_count, unsigned int * s) { unsigned int * const s_start = s; for (unsigned int i = 0; i < ranges_count; i += 2) for (unsigned int j = ranges[i]; j <= ranges[i + 1]; ++j) *s++ = j; return s - s_start; } int main () { unsigned int * buffer_Mn = new unsigned int [1827]; YYCTYPE * s = (YYCTYPE *) buffer_Mn; unsigned int buffer_len = encode_utf32 (chars_Mn, sizeof (chars_Mn) / sizeof (unsigned int), buffer_Mn); /* convert 32-bit code units to YYCTYPE; reuse the same buffer */ for (unsigned int i = 0; i < buffer_len; ++i) s[i] = buffer_Mn[i]; if (!scan (s, s + buffer_len)) printf("test 'Mn' failed\n"); delete [] buffer_Mn; return 0; }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
988fba82c03ff63cb837ef88daeda9d94bbd9e2c
a7413d9ce83654f1f34cacb09c20deeb6bd523ea
/toolboxes/operators/cpu/hoMotionCompensation2DTOperator.h
6508ba48d569d42b5285c898789ca5d117128f3a
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hansenms/gadgetron
1e40b1a6265a96cc6f518d0a28cecb0a1d65d292
10531591411fea4e16a074a574cd449a60d28ef8
refs/heads/master
2022-02-01T23:52:52.993704
2021-12-10T23:31:52
2021-12-10T23:31:52
28,053,346
3
1
NOASSERTION
2021-12-21T23:41:07
2014-12-15T19:54:00
C++
UTF-8
C++
false
false
1,859
h
/** \file hoMotionCompensation2DTOperator.h \brief Implement motion compensation operator for 2DT cases \author Hui Xue */ #pragma once #include "cpuOperatorExport.h" #include "hoNDArray_linalg.h" #include "hoImageRegContainer2DRegistration.h" namespace Gadgetron { template <typename T, typename CoordType> class EXPORTCPUOPERATOR hoMotionCompensation2DTOperator { public: typedef typename realType<T>::Type value_type; typedef hoNDArray<T> ARRAY_TYPE; hoMotionCompensation2DTOperator(); virtual ~hoMotionCompensation2DTOperator(); /// x: [RO E1 CHA N] /// y: [RO E1 CHA N] /// apply forward deformation Mx virtual void mult_M(ARRAY_TYPE* x, ARRAY_TYPE* y, bool accumulate = false); /// appy adjoint deformation M'x virtual void mult_MH(ARRAY_TYPE* x, ARRAY_TYPE* y, bool accumulate = false); /// compute gradient of ||Mx||1 virtual void gradient(ARRAY_TYPE* x, ARRAY_TYPE* g, bool accumulate = false); /// compute cost value of L1 norm ||Mx||1 virtual value_type magnitude(ARRAY_TYPE* x); T bg_value_; Gadgetron::GT_BOUNDARY_CONDITION bc_; hoNDArray<CoordType> dx_; hoNDArray<CoordType> dy_; hoNDArray<CoordType> adj_dx_; hoNDArray<CoordType> adj_dy_; protected: // warp the 2D+T image arrays // im : complex image [RO E1 CHA N] // dx, dy : [RO E1 N] deformation fields // the image domain warpping is performed virtual void warp_image(const hoNDArray<T>& im, const hoNDArray<CoordType>& dx, const hoNDArray<CoordType>& dy, hoNDArray<T>& warpped, T bgValue=0, Gadgetron::GT_BOUNDARY_CONDITION bh=GT_BOUNDARY_CONDITION_FIXEDVALUE); // helper memory ARRAY_TYPE moco_im_; ARRAY_TYPE adj_moco_im_; ARRAY_TYPE grad_im_; hoNDArray<value_type> moco_im_Norm_; hoNDArray<value_type> moco_im_Norm_approx_; }; }
[ "hui.xue@nih.gov" ]
hui.xue@nih.gov
858e1edd5e1ac04de74bfbfd2437a6a6fa0b0e86
d45b17e2cdc712de1a2907b59d69a05ba2dc9533
/Xngine/ResourceModel.cpp
34632ce78e2f09270125fe1c54dc3abdc19b1507
[ "MIT" ]
permissive
FrancPS/Xngine
9e7738799492485327ebaec549e7d75d436a38f2
3eb031eb43a8c7fcfea0638f19347797783633b2
refs/heads/master
2023-01-24T22:02:11.140529
2020-11-29T12:32:45
2020-11-29T12:32:45
313,328,017
0
0
null
null
null
null
UTF-8
C++
false
false
3,135
cpp
#include "Globals.h" #include "Application.h" #include "ResourceModel.h" #include "ResourceMesh.h" #include "ModuleTexture.h" #include "assimp/scene.h" #include "assimp/cimport.h" #include "assimp/postprocess.h" #include "GL/glew.h" void AssimpCallback(const char* message, char* userData) { if (message) LOG("Assimp Message: %s", message); } ResourceModel::ResourceModel() { struct aiLogStream stream; stream.callback = AssimpCallback; aiAttachLogStream(&stream); } ResourceModel::~ResourceModel() { UnLoad(); } void ResourceModel::Load(const char* const file_name) { const aiScene* scene; scene = aiImportFile(file_name, aiProcessPreset_TargetRealtime_MaxQuality); if (scene) { UnLoad(); LoadMaterials(scene, file_name); LoadMeshes(scene); LOG("Scene loaded correctly"); } else { // the file was not a model, but it can be a texture! UnLoadMaterials(); unsigned int texID = App->textures->LoadTexture(file_name, file_name); if (texID) modelMaterials.push_back(texID); else LOG("Error loading %s: %s", file_name, aiGetErrorString()); } } void ResourceModel::LoadMaterials(const aiScene* const scene, const char* const file_name) { aiString file; modelMaterials.reserve(scene->mNumMaterials); for (unsigned i = 0; i < scene->mNumMaterials; ++i) { if (scene->mMaterials[i]->GetTexture(aiTextureType_DIFFUSE, 0, &file) == AI_SUCCESS) { // Populate materials list modelMaterials.push_back(App->textures->LoadTexture(file.data, file_name)); } } LOG("Materials loaded correctly"); } void ResourceModel::LoadMeshes(const aiScene* const scene) { aiString file; modelMeshes.reserve(scene->mNumMeshes); for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { // Populate meshes list modelMeshes.push_back(new ResourceMesh(scene->mMeshes[i])); numMeshes++; } // get total size of all meshes for (unsigned int i = 0; i < modelMeshes.size(); i++) { if (modelMeshes[i]->maxX > maxX) maxX = modelMeshes[i]->maxX; if (modelMeshes[i]->minX < minX) minX = modelMeshes[i]->minX; if (modelMeshes[i]->maxY > maxY) maxY = modelMeshes[i]->maxY; if (modelMeshes[i]->minY < minY) minY = modelMeshes[i]->minY; if (modelMeshes[i]->maxZ > maxZ) maxZ = modelMeshes[i]->maxZ; if (modelMeshes[i]->minZ < minZ) minZ = modelMeshes[i]->minZ; } sizeX = maxX - minX; sizeY = maxY - minY; sizeZ = maxZ - minZ; LOG("Meshes loaded correctly"); } void ResourceModel::Draw() { for (unsigned int i = 0; i < numMeshes; ++i) { modelMeshes[i]->Draw(modelMaterials); } } void ResourceModel::UnLoad() { LOG("Unloading the current module"); // destroy objects from mesh list for (unsigned int i = 0; i < modelMeshes.size(); i++) { delete modelMeshes[i]; } numMeshes = 0; modelMeshes.clear(); // erase modelMaterials UnLoadMaterials(); ResetSizes(); } void ResourceModel::UnLoadMaterials() { for (unsigned int i = 0; i < modelMaterials.size(); i++) { glDeleteTextures(1, &modelMaterials[i]); } modelMaterials.clear(); } void ResourceModel::ResetSizes() { maxX = maxY = maxZ = 0; minX = minY = minZ = 3.40282e+038; // MAXFLOAT* sizeX = sizeY = sizeZ = 0; }
[ "f_xeski94@hotmail.com" ]
f_xeski94@hotmail.com
915281d52c80e957156a133d370d104799a2c665
4d0a3d58bd66e588a50b834a8b8a65a5dac81170
/Exam/Piscine_cpp/d07/ex02/sources/main.cpp
6513dd584c7d330645ee338fbd20b8f0e27316ba
[]
no_license
fredatgithub/42
0384b35529a42cf09bbe6dc9362b6ad5c5b3e044
7c1352ab9c8dda4a381ce5a11cd3bbbfad078841
refs/heads/master
2023-03-17T09:47:48.850239
2019-12-15T18:13:13
2019-12-15T18:13:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include <iostream> #include "Array.hpp" int main(void) { try { Array<std::string> array(5); for (int i = 0; i < array.size(); i++) { array[i] = "t1"; std::cout << array[i] << std::endl; } Array<std::string> sarray(2); std::cout << std::endl; for (int i = 0; i < sarray.size(); i++) { sarray[i] = "t2"; std::cout << sarray[i] << std::endl; } sarray = array; std::cout << std::endl; for (int i = 0; i < sarray.size(); i++) { std::cout << sarray[i] << std::endl; } std::cout << array[6] << std::endl; } catch (std::exception & e) { std::cout << e.what() << std::endl; } return (0); }
[ "julien.balestrieri@gmail.com" ]
julien.balestrieri@gmail.com
97896ed28071f5ec47fdcc336625498c8f73bfc3
7d7301514d34006d19b2775ae4f967a299299ed6
/leetcode/interview/05.01.insertBits.cpp
2d88373160668ada1ea8fcf96e09854d71d12ff1
[]
no_license
xmlb88/algorithm
ae83ff0e478ea01f37bc686de14f7d009d45731b
cf02d9099569e2638e60029b89fd7b384f3c1a68
refs/heads/master
2023-06-16T00:21:27.922428
2021-07-17T03:46:50
2021-07-17T03:46:50
293,984,271
1
0
null
2020-12-02T09:08:28
2020-09-09T02:44:20
C++
UTF-8
C++
false
false
220
cpp
#include <iostream> using namespace std; int insertBits(int N, int M, int i, int j) { for (int k = i; k <= j; k++) { if (N & (1 << k)) { N -= (1 << k); } } return N | (M << i); }
[ "xmlb@gmail.com" ]
xmlb@gmail.com
c5baad7e1a3b5102f914421e114c61bc6842c2d2
ea53dfce2ddc7c3eb16381932fe8b2e80018cc0e
/indra/llui/llradiogroup.h
0588900600484c9bd843044191450eb593d951c2
[]
no_license
otwstephanie/hpa2oar
7a1ac9a1502c5a09f946c303ecaf0a9c61f2e409
0660c6a8d66d3ab40a5b034f2ff86ff4b356b15b
refs/heads/master
2021-01-20T22:35:31.868166
2010-12-15T09:52:21
2010-12-15T09:52:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,794
h
/** * @file llradiogroup.h * @brief LLRadioGroup base class * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #ifndef LL_LLRADIOGROUP_H #define LL_LLRADIOGROUP_H #include "lluictrl.h" #include "llcheckboxctrl.h" #include "llctrlselectioninterface.h" /* * An invisible view containing multiple mutually exclusive toggling * buttons (usually radio buttons). Automatically handles the mutex * condition by highlighting only one button at a time. */ class LLRadioGroup : public LLUICtrl, public LLCtrlSelectionInterface { public: struct ItemParams : public LLInitParam::Block<ItemParams, LLCheckBoxCtrl::Params> { Optional<LLSD> value; ItemParams(); }; struct Params : public LLInitParam::Block<Params, LLUICtrl::Params> { Optional<bool> has_border; Multiple<ItemParams, AtLeast<1> > items; Params(); }; protected: LLRadioGroup(const Params&); friend class LLUICtrlFactory; public: /*virtual*/ void initFromParams(const Params&); virtual ~LLRadioGroup(); virtual BOOL postBuild(); virtual BOOL handleMouseDown(S32 x, S32 y, MASK mask); virtual BOOL handleKeyHere(KEY key, MASK mask); void setIndexEnabled(S32 index, BOOL enabled); // return the index value of the selected item S32 getSelectedIndex() const { return mSelectedIndex; } // set the index value programatically BOOL setSelectedIndex(S32 index, BOOL from_event = FALSE); // Accept and retrieve strings of the radio group control names virtual void setValue(const LLSD& value ); virtual LLSD getValue() const; // Update the control as needed. Userdata must be a pointer to the button. void onClickButton(LLUICtrl* clicked_radio); //======================================================================== LLCtrlSelectionInterface* getSelectionInterface() { return (LLCtrlSelectionInterface*)this; }; // LLCtrlSelectionInterface functions /*virtual*/ S32 getItemCount() const { return mRadioButtons.size(); } /*virtual*/ BOOL getCanSelect() const { return TRUE; } /*virtual*/ BOOL selectFirstItem() { return setSelectedIndex(0); } /*virtual*/ BOOL selectNthItem( S32 index ) { return setSelectedIndex(index); } /*virtual*/ BOOL selectItemRange( S32 first, S32 last ) { return setSelectedIndex(first); } /*virtual*/ S32 getFirstSelectedIndex() const { return getSelectedIndex(); } /*virtual*/ BOOL setCurrentByID( const LLUUID& id ); /*virtual*/ LLUUID getCurrentID() const; // LLUUID::null if no items in menu /*virtual*/ BOOL setSelectedByValue(const LLSD& value, BOOL selected); /*virtual*/ LLSD getSelectedValue(); /*virtual*/ BOOL isSelected(const LLSD& value) const; /*virtual*/ BOOL operateOnSelection(EOperation op); /*virtual*/ BOOL operateOnAll(EOperation op); private: const LLFontGL* mFont; S32 mSelectedIndex; typedef std::vector<class LLRadioCtrl*> button_list_t; button_list_t mRadioButtons; BOOL mHasBorder; }; #endif
[ "hazim.gazov@gmail.com" ]
hazim.gazov@gmail.com
b7b46f2fb6a11ef25d8cea66cefb4e7bd16f888b
e8f16f6b2fb53bb52088e96ddbc6ceeb39cb00ea
/CLICalendarServer/src/Note.cpp
1805ec7671e16a1c2f3ffa1c0575c7345ec990c4
[]
no_license
MasterElijah97/CLICalendar
0a9b4776ff6a06227ab2c354401abef7a641fa4e
1f452b3b84307b2488ef734a09a453fd4eb62189
refs/heads/master
2023-02-17T19:07:09.070081
2021-01-17T12:03:13
2021-01-17T12:03:13
297,442,990
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
cpp
#include "Note.h" bool operator==(const Note& left, const Note& right) { return (left.label_ == right.label_) && (left.name_ == right.name_) && (left.description_ == right.description_) && (left.version_ == right.version_); } Note::Note() { this->label_ = "Buffer"; this->name_ = "New Task"; this->description_ = "New Task"; this->id_ = -1; this->version_ = 1; } Note::Note(std::string name, std::string description = "New Note", std::string label = "Buffer") { this->label_ = label; this->name_ = name; this->description_ = description; this->id_ = -1; this->version_ = 1; } Note::Note(const Note& right) { this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; } Note::Note(Note&& right) { this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; } Note::~Note() { } Note& Note::operator=(const Note& other) { if (this == &other) { return *this; } this->label_ = other.label_; this->name_ = other.name_; this->description_ = other.description_; this->version_ = other.version_; this->id_ = other.id_; return *this; } Note& Note::operator=(Note&& right) { if (this == &right) { return *this; } this->label_ = right.label_; this->name_ = right.name_; this->description_ = right.description_; this->version_ = right.version_; this->id_ = right.id_; return *this; } std::string Note::concatenate() { return label_ +SEPARATOR+ name_ +SEPARATOR+ std::to_string(version_) +SEPARATOR+ std::to_string(id_) +SEPARATOR+ description_; } void Note::deconcatenate(std::string msg) { std::vector<std::string> v = split(msg, SEPARATOR.c_str()[0]); label_ = v[0]; name_ = v[1]; version_ = std::stoi(v[2]); id_ = std::stoi(v[3]); description_ = v[4]; }
[ "morozov97@mail.ru" ]
morozov97@mail.ru
444d586fde259af5249a30d3c8a7a84ab104ca69
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_4213.cpp
55ac7e050c5fabeb82190ebc99c14390022efca8
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
* X-CACHE-MISS entry should tell us who. */ httpHeaderPutStrf(&rep->header, HDR_X_SQUID_ERROR, "%s %d", name, xerrno); + +#if USE_ERR_LOCALES + /* + * If error page auto-negotiate is enabled in any way, send the Vary. + * RFC 2616 section 13.6 and 14.44 says MAY and SHOULD do this. + * We have even better reasons though: + * see http://wiki.squid-cache.org/KnowledgeBase/VaryNotCaching + */ + if(!Config.errorDirectory) { + /* We 'negotiated' this ONLY from the Accept-Language. */ + httpHeaderDelById(&rep->header, HDR_VARY); + httpHeaderPutStrf(&rep->header, HDR_VARY, "Accept-Language"); + } + + /* add the Content-Language header according to RFC section 14.12 */ + if(err_language) { + httpHeaderPutStrf(&rep->header, HDR_CONTENT_LANGUAGE, "%s", err_language); + } + else +#endif /* USE_ERROR_LOCALES */ + { + /* default templates are in English */ + /* language is known unless error_directory override used */ + if(!Config.errorDirectory) + httpHeaderPutStrf(&rep->header, HDR_CONTENT_LANGUAGE, "en"); + } + httpBodySet(&rep->body, content); /* do not memBufClean() or delete the content, it was absorbed by httpBody */ }
[ "993273596@qq.com" ]
993273596@qq.com
7ef445eab03e60b296417fa903dda17f9f7d6708
a3d5c0f4b5d036659aa4c735f65f2ac6d43454d1
/Preoblem_treasure/dp.cpp
d58f28247366ec190e4a99753d6ab6e2188e24eb
[]
no_license
GoFire2000/CPulsPuls-create-test-problems
4bbf191286ca5cd6b945da249914a96e7da4b7d3
6ccd1fd8e0aa5b47651561cb3155ed6b33118e1a
refs/heads/main
2023-09-04T23:28:55.029152
2021-11-14T09:21:40
2021-11-14T09:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define LL long long #define Inf 1e9 const int maxn=1010; void Init(); int main(){ while(true) Init(); return 0; } void Init(){ system("DateMake.exe"); system("Trick.exe"); system("Std.exe"); if(system("fc Std.out Trick.out")) system("pause");; }
[ "xuzikang@bupt.edu.cn" ]
xuzikang@bupt.edu.cn
e2a30a1262a1a01b8296fa7c5fad506e89da3e39
cd470ad61c4dbbd37ff004785fd6d75980987fe9
/Codeforces/1213E Two Small Strings/暴力/std.cpp
0f4350f512d992ea4e58989a865cf03b4aea56f4
[]
no_license
AutumnKite/Codes
d67c3770687f3d68f17a06775c79285edc59a96d
31b7fc457bf8858424172bc3580389badab62269
refs/heads/master
2023-02-17T21:33:04.604104
2023-02-17T05:38:57
2023-02-17T05:38:57
202,944,952
3
1
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <cstdio> #include <cstring> #include <algorithm> int n; char s[5], t[5], c[5]; bool check(char a, char b){ if (a == s[0] && b == s[1]) return 0; if (a == t[0] && b == t[1]) return 0; return 1; } int main(){ scanf("%d%s%s", &n, s, t); c[0] = 'a', c[1] = 'b', c[2] = 'c'; while (1){ if (check(c[0], c[1]) && check(c[1], c[2])){ if (n == 1) return printf("YES\n%s", c), 0; if (check(c[2], c[0])){ puts("YES"); for (register int i = 1; i <= n; ++i) printf("%s", c); return 0; } if (check(c[0], c[0]) && check(c[1], c[1]) && check(c[2], c[2])){ puts("YES"); for (register int i = 1; i <= n; ++i) putchar(c[0]); for (register int i = 1; i <= n; ++i) putchar(c[1]); for (register int i = 1; i <= n; ++i) putchar(c[2]); return 0; } } if (!std :: next_permutation(c, c + 3)) break; } puts("NO"); }
[ "1790397194@qq.com" ]
1790397194@qq.com
b2a8455595e3c5d49d127659ea39a9740904502e
680440f5e59eb2157c1ecb41fd891880ac47c459
/XJOI/CONTEST/xjoi.net/1293/nichijou/nichijou.cpp
60d3ed4b9e85d3435ac7eaa81a6f5449a0f479f5
[]
no_license
Skywt2003/codes
a705dc3a4f5f79d47450179fc597bd92639f3d93
0e09198dc84e3f6907a11b117a068f5e0f55ca68
refs/heads/master
2020-03-29T09:29:54.014364
2019-11-15T12:39:47
2019-11-15T12:39:47
149,760,952
6
0
null
null
null
null
UTF-8
C++
false
false
3,489
cpp
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int ret=0,f=1; char ch=getchar(); while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar(); return ret*f; } const int maxn=1e6+5,maxe=2e6+5,maxm=1e6+5; int n,m; int tot=0,lnk[maxn],nxt[maxe],to[maxe]; int deep[maxn],f[maxn][22]; void add_edge(int x,int y){ tot++; to[tot]=y; nxt[tot]=lnk[x];lnk[x]=tot; } void build_tree(int x){ for (int i=1;i<22;i++) f[x][i]=f[f[x][i-1]][i-1]; for (int i=lnk[x];i;i=nxt[i]) if (to[i]!=f[x][0]){ f[to[i]][0]=x; deep[to[i]]=deep[x]+1; build_tree(to[i]); } } int get_lca(int x,int y){ if (deep[x]<deep[y]) swap(x,y); for (int i=21;i>=0;i--) if (deep[f[x][i]] >= deep[y]) x=f[x][i]; if (x==y) return x; for (int i=21;i>=0;i--) if (f[x][i] != f[y][i]) x=f[x][i],y=f[y][i]; return f[x][0]; } int get_dist(int x,int y){ int lca=get_lca(x,y); return deep[x]-deep[lca]+deep[y]-deep[lca]; } bool is_subtask3=true; bool is_subtask5=true; struct query{ int x,y,d; }; query q[maxm]; namespace subtask3{ signed main(){ #ifdef DEBUG printf("subtask3::main() | start\n"); #endif puts("1"); return 0; } }; namespace subtask5{ int sum[maxn],ans=-1; void find_answer(int x,int now){ if (ans!=-1) return; if (now==m){ans=x;return;} for (int i=lnk[x];i;i=nxt[i]) if (to[i]!=f[x][0]) find_answer(to[i],now+sum[to[i]]); } signed main(){ #ifdef DEBUG printf("subtask5::main() | start\n"); #endif for (int i=1;i<=m;i++){ int lca=get_lca(q[i].x,q[i].y); sum[lca]++; if (lca!=q[i].x) for (int j=lnk[q[i].x];j;j=nxt[j]) if (to[j]!=f[q[i].x][0]) sum[to[j]]--; if (lca!=q[i].y) for (int j=lnk[q[i].y];j;j=nxt[j]) if (to[j]!=f[q[i].y][0]) sum[to[j]]--; if (lca==q[i].x && lca==q[i].y) for (int j=lnk[q[i].y];j;j=nxt[j]) if (to[j]!=f[q[i].y][0]) sum[to[j]]--; } find_answer(1,sum[1]); if (ans==-1) printf("NO\n"); else printf("%lld\n",ans); return 0; } }; bool now_vis[maxn]; int cnt[maxn]; void make_now_tag(int x,int y){ if (deep[x] < deep[y]) swap(x,y); while (deep[x]>deep[y]) now_vis[x]=true,x=f[x][0]; while (x!=y) now_vis[x]=now_vis[y]=true,x=f[x][0],y=f[y][0]; now_vis[x]=true; } void exDFS(int x,int lft){ now_vis[x]=true; if (lft==0) return; for (int i=lnk[x];i;i=nxt[i]) if (!now_vis[to[i]]) exDFS(to[i],lft-1); } signed main(){ #ifdef DEBUG freopen("data.in","r",stdin); #endif n=read(); m=read(); for (int i=1;i<n;i++){ int x=read(),y=read(); add_edge(x,y); add_edge(y,x); } deep[1]=1; build_tree(1); for (int i=1;i<=m;i++){ q[i].x=read(),q[i].y=read(),q[i].d=read(); if (q[i].d != 2e6) is_subtask3=false; if (is_subtask5){ int dist=get_dist(q[i].x,q[i].y); if (q[i].d != dist) is_subtask5=false; } } if (is_subtask3) return subtask3::main(); if (is_subtask5) return subtask5::main(); #ifdef DEBUG printf("main() | Other subtask\n"); #endif for (int i=1;i<=m;i++){ int dist=get_dist(q[i].x,q[i].y); int ext=(q[i].d-dist)/2; for (int j=1;j<=n;j++) now_vis[j]=false; make_now_tag(q[i].x,q[i].y); int xx=q[i].x,yy=q[i].y; if (deep[xx] < deep[yy]) swap(xx,yy); while (deep[xx] > deep[yy]) exDFS(xx,ext),xx=f[xx][0]; while (xx!=yy) exDFS(xx,ext),exDFS(yy,ext),xx=f[xx][0],yy=f[yy][0]; exDFS(xx,ext); for (int j=1;j<=n;j++) cnt[j]+=now_vis[j]; } for (int i=1;i<=n;i++) if (cnt[i]==m){ printf("%lld\n",i); return 0; } printf("NO\n"); return 0; }
[ "skywt2003@gmail.com" ]
skywt2003@gmail.com
b184e9fcb818b548db391f7b01117bc08b50144b
3985c19fecd6d2b805d5d45217402336d9b7b0fa
/gamewindow.h
40e7431169f32c43954827b011df7aa4ac62382f
[]
no_license
sh0dan/QTetris
5ed39d3d32ff7ea92f0bda4a311ffab596780939
d0fde85aeffc89359fd06ec8bd2ec768733ae68b
refs/heads/master
2020-06-01T11:23:03.186260
2012-05-14T14:11:03
2012-05-14T14:11:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
#ifndef GAMEWINDOW_H #define GAMEWINDOW_H /* #include <QFrame> #include <QWidget> QT_BEGIN_NAMESPACE class QLCDNumber; class QLabel; class QPushButton; QT_END_NAMESPACE */ #include <QtGui> class GameBoard; class GameWindow : public QWidget { Q_OBJECT public: GameWindow(); private: QLabel *nextBlockLabel; QLabel *playerScoresLabel; QLabel *linesLabel; QLabel *currentLevelLabel; GameBoard *gameBoard; QPushButton *startBtn; QPushButton *pauseBtn; QPushButton *exitBtn; QLabel *createLabel(const QString &text); }; #endif // GAMEWINDOW_H
[ "ruslan.sazonov@postindustria.com" ]
ruslan.sazonov@postindustria.com
e536899b44c5932ffc9bc3baae5007bea80df57a
10b85163837c1c1976d4de6e179d53cf6e371478
/third_party/common/include/RE/ExtraHealthPerc.h
2af139fff5b0ab928bbaf17a69bfe722913c7f88
[ "ISC", "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
rethesda/alchemy
8e02352240bfb295e1fe7c6682acabe93fc11aa6
fe6897fa8c065eccc49b61c8c82eda223d865d51
refs/heads/master
2023-03-15T19:10:10.132829
2020-05-12T05:02:33
2020-05-12T05:02:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
654
h
#pragma once #include "RE/BSExtraData.h" #include "RE/ExtraDataTypes.h" namespace RE { class ExtraHealthPerc : public BSExtraData { public: inline static const void* RTTI = RTTI_ExtraHealthPerc; enum { kExtraTypeID = ExtraDataType::kHealthPerc }; virtual ~ExtraHealthPerc(); // 00 // override (BSExtraData) virtual ExtraDataType GetType() const override; // 01 - { return kHealthPerc; } virtual bool IsNotEqual(const BSExtraData* a_rhs) const override; // 02 - { return unk10 != a_rhs->unk10; } // members UInt32 unk10; // 10 UInt32 pad14; // 14 }; static_assert(sizeof(ExtraHealthPerc) == 0x18); }
[ "alexej.h@xiphos.de" ]
alexej.h@xiphos.de
e986708d4a1f7b1834747912c08821f9ac9f4ae0
f84a142a0891022ef44d0f6b6e80b9c7163cc9e4
/.history/src/person_20200716233728.cpp
9ad70eb584eae335ac07a50cfc71b2484b6ea15e
[ "MIT" ]
permissive
zoedsy/LibManage
046b3749cc089355e0d3a9fe0f13b9a042b8ec85
590311fb035d11daa209301f9ce76f53ccae7643
refs/heads/master
2022-11-17T09:44:26.432808
2020-07-17T06:45:50
2020-07-17T06:45:50
279,246,675
1
0
null
null
null
null
GB18030
C++
false
false
17,248
cpp
/* * @Author: DuShiyi * @Date: 2020-07-15 17:56:32 * @LastEditTime: 2020-07-16 23:37:26 * @LastEditors: Please set LastEditors * @Description: about person(admin ,visitor,reader) * @FilePath: \LibManage\src\person.cpp */ #include"../include/person.h" #include"../include/library.h" // logs = new Logs(); //具体功能等待完善 using LibSys::library; // LibSys::library* lib1= LibSys::library::getLibrary(); /* |函 数 名|:apply10 |功能描述|:管理员登陆后显示所有书籍 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:马晓晨 ========================================================================================*/ void Admin::apply10(){ //显示所有内容 LibSys::library* lib1= LibSys::library::getLibrary(); system("cls"); lib1->list(true); system("pause"); //back admin function menu // apply1(); } // Logs* Person::ls = new Logs(); // library* Person::lib = new library(); /*============================================================================== |函 数 名|:apply11 |功能描述|:管理员登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply11(){ //search LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"未找到相应书籍"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"未找到相应书籍"<<endl; } break; } system("pause"); //back admin function menu } /*============================================================================== |函 数 名|:apply12 |功能描述|:管理员登陆后的修改书籍数据界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply12(){ //INFORMATION MODIFY LibSys::library* lib1= LibSys::library::getLibrary(); string _isbn; string newname; cout<<"请输入书的ISBN:"; cin>>_isbn; cout<<"请输入书的新名字:"; cin>>newname; lib1->changeBookName(*this,_isbn,newname); // cout<<"successfully change book name!"<<endl; //返回功能主页 system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply13 |功能描述|:管理员登陆后的插入书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply13(){ //information insert LibSys::library* lib1= LibSys::library::getLibrary(); string n;string isbn;string author;string press;int count;string cg; cout<<"请按照示例格式输入所录入书的信息(书名 ISBN 出版社 库存量 上架类型):"<<endl; cin>>n;cin>>isbn;cin>>author;cin>>press;cin>>count;cin>>cg; LibSys::Book b(n,isbn,author,press,count,LibSys::StringToCategory(cg)); lib1->buy(*this,b); // cout<<"successfully insert book"<<endl; system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply14 |功能描述|:管理员登陆后的书籍信息删除界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply14(){ //information delete LibSys::library* lib1= LibSys::library::getLibrary(); string n;string isbn;string author;string press;int count;string cg; cout<<"请按照示例格式输入所删除书的信息(书名 ISBN 出版社 数量 上架类型):"<<endl; cin>>n;cin>>isbn;cin>>author;cin>>press;cin>>count;cin>>cg; LibSys::Book b(n,isbn,author,press,count,LibSys::StringToCategory(cg)); lib1->discard(*this,b); // cout<<"successfully delete book"<<endl; system("pause"); // apply1(); } /*============================================================================== |函 数 名|:apply11 |功能描述|:管理员登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply15(){ //look up borrowlog LibSys::library* lib1= LibSys::library::getLibrary(); lib1->listBorrowTrace(); system("pause"); // apply1(); } /* |函 数 名|:apply10 |功能描述|:管理员登陆后显示所有书籍 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:马晓晨 ========================================================================================*/ void Reader::apply20(){ //显示所有内容 LibSys::library* lib1= LibSys::library::getLibrary(); system("cls"); lib1->list(1); system("pause"); //back admin function menu // apply2(); } /*============================================================================== |函 数 名|:apply21 |功能描述|:读者登陆后的search界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply21(){ //search LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"can not find the book"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"can not find the book"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"can not find the book"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"can not find the book"<<endl; } break; } system("pause"); //back admin function menu // apply2(); } /*============================================================================== |函 数 名|:apply22 |功能描述|:读者登陆后的借阅界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply22(){ //borrow LibSys::library* lib1= LibSys::library::getLibrary(); string isbn; cout<<"please input the isbn of the book:"<<endl; cin>>isbn; lib1->borrow(*this,isbn); system("pause"); } /*============================================================================== |函 数 名|:apply11 |功能描述|:读者登陆后的归还界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply23(){ //return LibSys::library* lib1= LibSys::library::getLibrary(); int flag=0; do{ char a; string isbn; cout<<"Do you wannna return all the books?(Y/N):"; cin>>a; if(a=='Y'){ lib1->retAllBook(*this); flag=0; // cout<<"successfully return all the books!"<<endl; }else if(a=='N'){ cout<<"input isbn of the book you wanna return:"; cin>>isbn; lib1->ret(*this,isbn); flag=0; // cout<<"successfully return the book!"<<endl; }else{ cout<<"input error!"<<endl; flag=1; } }while(flag); system("pause"); } /*============================================================================== |函 数 名|:apply25 |功能描述|:读者登陆后的查阅个人借书信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply25(){ //look up borrowlog LibSys::library* lib1= LibSys::library::getLibrary(); lib1->personalBorrowTrace(*this); system("pause"); } /*============================================================================== |函 数 名|:apply31 |功能描述|:游客查阅所有书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply31(){ //look up all the information LibSys::library* lib1= LibSys::library::getLibrary(); lib1->list(true); system("pause"); } /*============================================================================== |函 数 名|:apply32 |功能描述|:游客搜索书籍信息的界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply32(){ //search information LibSys::library* lib1= LibSys::library::getLibrary(); string s1; char c; system("cls"); cout<<"您希望通过哪种方式来搜索书籍,"<<endl; cout<<"书名请输入‘N’,ISBN请输入‘I’,作者名请输入‘A’,出版社名请输入‘P’:"; cin>>c; cout<<"请输入其关键词:"; cin>>s1; switch(c){ case 'N': if(lib1->search(s1,LibSys::library::field::NAME)){ }else{ cout<<"can not find the book"<<endl; } break; case 'I': if(lib1->search(s1,LibSys::library::field::ISBN)){ }else{ cout<<"can not find the book"<<endl; } break; case 'A': if(lib1->search(s1,LibSys::library::field::AUTHOR)){ }else{ cout<<"can not find the book"<<endl; } break; case 'P': if(lib1->search(s1,LibSys::library::field::PRESS)){ }else{ cout<<"can not find the book"<<endl; } break; } system("pause"); //back admin function menu } /*============================================================================== |函 数 名|:apply1 |功能描述|:管理员登陆后功能选项界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Admin::apply1() { while(1){ int i; system("cls"); cout<<"----管理员界面----"<<endl; cout<<"0.显示所有书籍" <<endl; cout<<"1.书籍查询"<<endl; cout<<"2.书籍修改"<<endl; cout<<"3.书籍信息增加"<<endl; cout<<"4.书籍信息删除"<<endl; cout<<"5.查看用户借阅记录"<<endl; cout<<"6.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(0-6):"; cin>>i; system("cls"); switch(i){ case 0: //显示所有书籍的接口 apply10(); break; case 1: //录入信息的接口 apply11(); break; case 2: //数据修改接口 apply12(); break; case 3: //数据插入接口 apply13(); break; case 4: //数据删除接口 apply14(); break; case 5: //借阅信息查看接口 apply15(); break; case 6: //last page return; break; default: cout<<"输入错误!"<<endl; } // system("pause"); } } /*============================================================================== |函 数 名|:apply2 |功能描述|:读者登陆后功能界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Reader::apply2() //读者功能 { while(1){ int i; system("cls"); cout<<"-----读者界面-----"<<endl; cout<<"0.显示所有书籍" <<endl; cout<<"1.书籍查询"<<endl; cout<<"2.书籍借阅"<<endl; cout<<"3.书籍归还"<<endl; // cout<<"4.modify personal informatin"<<endl; cout<<"4.查看个人借阅日志"<<endl; cout<<"5.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(0-5):"; cin>>i; system("cls"); switch(i){ case 0: apply20(); break; case 1: apply21(); break; case 2: apply22(); break; case 3: apply23(); break; case 4: apply25(); break; case 5: return; break; default: cout<<"输入错误!"<<endl; } } } /*============================================================================== |函 数 名|:apply3 |功能描述|:游客功能界面 |输入参数|:无 |输出参数|:无 |返 回 值|:无 |创建日期|:2020年7月14日 |修改日期|:2020年7月16日 |作 者|:杜诗仪 ========================================================================================*/ void Visitor::apply3() { //游客功能 while(1){ system("cls"); int i; cout<<"-----游客界面-----"<<endl; cout<<"1.查询所有馆藏书籍"<<endl; cout<<"2.查询书籍"<<endl; cout<<"3.返回上一页"<<endl; cout<<"请输入您要使用的功能选项(1-3):"<<endl; cin>>i; switch(i){ case 1: apply31(); break; case 2: apply32(); break; case 3: return; //last page default: cout<<"输入错误!"<<endl; } } }
[ "1246906787@qq.com" ]
1246906787@qq.com
a284a0e7243b7f4c66a25132ec6b4209a6c1bd57
6c9146e5b2b973f4ecd43ddcbd79b59c86a7590b
/CppWindowsServices-RemoteConsole/socket-client.cpp
7b779cf11c208ff0ec3cb86aca2a7e02f5266f21
[]
no_license
Gewery/CppWindowsServices-RemoteConsole
822a192e7e381fafa470013141c15ab8c29f3cef
ede295e4f1bb512c620e188761b26e5d0ac0acca
refs/heads/master
2020-12-21T05:20:15.097357
2020-06-01T10:47:57
2020-06-01T10:47:57
236,319,273
0
0
null
null
null
null
UTF-8
C++
false
false
5,132
cpp
#define WIN32_LEAN_AND_MEAN #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib #pragma comment (lib, "Ws2_32.lib") #pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "AdvApi32.lib") #define DEFAULT_BUFLEN 512 #define DEFAULT_OUTPUT_PORT "27015" #define DEFAULT_INPUT_PORT "27016" DWORD WINAPI sendingMessages(LPVOID sOutputSocket) { char sendbuf[1024]; //char* sendbuf; int iResult; // Send until the connection closes do { //scanf("%s", sendbuf); fgets(sendbuf, 1024, stdin); //sendbuf = (char*)"dir\n"; // Send a buffer iResult = send((SOCKET)(sOutputSocket), sendbuf, (int)strlen(sendbuf), 0); if (iResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); closesocket((SOCKET)(sOutputSocket)); WSACleanup(); return 1; } //printf("Bytes Sent: %ld\n", iResult); } while (iResult > 0); return 0; } DWORD WINAPI recievingMessages(LPVOID sInputSocket) { char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; int iResult; //printf("receiving starting...\n"); // Receive until the peer closes the connection do { iResult = recv((SOCKET)(sInputSocket), recvbuf, recvbuflen, 0); //printf("received something...\n"); if (iResult == 0) printf("Connection closed\n"); else if (iResult < 0) printf("recv failed with error: %d\n", WSAGetLastError()); for (int i = 0; i < iResult; i++) printf("%c", recvbuf[i]); } while (iResult > 0); //printf("receiving finished\n"); return 0; } int establishConnection(SOCKET &ConnectSocket, char* ip, char* port_number) { WSADATA wsaData; struct addrinfo* result = NULL, * ptr = NULL, hints; int iResult; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port iResult = getaddrinfo(ip, port_number, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Attempt to connect to an address until one succeeds for (ptr = result; ptr != NULL; ptr = ptr->ai_next) { // Create a SOCKET for connecting to server ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } // Connect to server. iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen); if (iResult == SOCKET_ERROR) { closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; continue; } break; } freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) { printf("Unable to connect to server!\n"); WSACleanup(); return 1; } } int socket_client(int argc, char* argv[]) { SOCKET sOutputSocket = INVALID_SOCKET; establishConnection(sOutputSocket, argv[1], (char*)DEFAULT_OUTPUT_PORT); SOCKET sInputSocket = INVALID_SOCKET; establishConnection(sInputSocket, argv[1], (char*)DEFAULT_INPUT_PORT); DWORD dwSendingThreadId; HANDLE hSendingThread = CreateThread( NULL, // no security attribute 0, // default stack size sendingMessages, // thread proc (LPVOID)(sOutputSocket), // thread parameter 0, // not suspended &dwSendingThreadId); // returns thread ID if (hSendingThread == NULL) { printf("CreateThread for sending failed, GLE=%d.\n", GetLastError()); return -1; } DWORD dwRecievingThreadId; HANDLE hRecievingThread = CreateThread( NULL, // no security attribute 0, // default stack size recievingMessages, // thread proc (LPVOID)(sInputSocket), // thread parameter 0, // not suspended &dwRecievingThreadId); // returns thread ID if (hRecievingThread == NULL) { printf("CreateThread for recieving failed, GLE=%d.\n", GetLastError()); return -1; } // Wait for threads stops WaitForSingleObject(hRecievingThread, INFINITE); WaitForSingleObject(hSendingThread, INFINITE); CloseHandle(hRecievingThread); CloseHandle(hSendingThread); // cleanup closesocket(sOutputSocket); closesocket(sInputSocket); WSACleanup(); return 0; }
[ "gewery@mail.ru" ]
gewery@mail.ru
6b286cce858d36f2fee3e6267ac2fdaa4bc66063
d7909b07bbfcbfa6c066fa8db8fe3a7ecfbf220a
/TumTum_First/Demo/SourceCode/LHSceneCameraFollowDemo.h
9d22aad149820ccfa70b89d64e1dbdc24f017937
[]
no_license
tigerwoods1206/TumTumCopy
bd43a0973eb3478f65aa430b7521b1a69e17d0d2
3d50889ffa5ee0aeb7ff15ed9e08a4be4952bc91
refs/heads/master
2016-09-05T12:04:44.961195
2014-11-11T08:38:04
2014-11-11T08:38:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
576
h
#ifndef __LH_SCENE_CAMERA_FOLLOW_DEMO_H__ #define __LH_SCENE_CAMERA_FOLLOW_DEMO_H__ #include "cocos2d.h" #include "LHSceneDemo.h" class LHSceneCameraFollowDemo : public LHSceneDemo { public: static LHSceneCameraFollowDemo* create(); LHSceneCameraFollowDemo(); virtual ~LHSceneCameraFollowDemo(); virtual bool initWithContentOfFile(const std::string& plistLevelFile); virtual std::string className(); virtual bool onTouchBegan(Touch* touch, Event* event); private: bool didChangeX; }; #endif // __LH_SCENE_CAMERA_FOLLOW_DEMO_H__
[ "ohtaisao@square-enix.com" ]
ohtaisao@square-enix.com
d9136c404d12cf09747d66845420feae5a71da28
7a7c54ff72cfcb42d1c47f69662820e999775e8f
/c++/232.cpp
0f2a69cc09303e53f6e3d5b814a37a09c050cea8
[]
no_license
manito-ming/leetcode
d46da165db835de4c98b2153a4f451ec88e965c2
709b482866d86febf242ed56daab5244f4587c98
refs/heads/master
2020-04-10T15:17:30.187074
2019-03-07T16:10:29
2019-03-07T16:10:29
161,104,459
1
0
null
null
null
null
UTF-8
C++
false
false
1,114
cpp
#include <iostream> #include <queue> #include <vector> #include <stack> using namespace std; class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { p.push(x); } //获得队首元素的时候,必须先将栈反转,把先进入的元素放在栈顶,这样就符合了队列的先进先出 /** Removes the element from in front of queue and returns that element. */ int pop() { if (q.empty()) { while (!p.empty()) { q.push(p.top()); p.pop(); } } int x= q.top(); q.pop(); return x; } /** Get the front element. */ int peek() { if (q.empty()) { while (!p.empty()) { q.push(p.top()); p.pop(); } } return q.top(); } /** Returns whether the queue is empty. */ bool empty() { return p.empty()&&q.empty(); } private: stack<int>p,q; }; int main() { return 0; }
[ "1315915230@qq.com" ]
1315915230@qq.com
02bb95f36eb22eaff025a7f9a8a6ef48feb004de
1d64c085dd71c84689768a9aa3aa9a0c7c40548f
/games/my_read.cpp
c392523c8b8ee164f0eb77fb04f0b5f71cf82861
[ "MIT" ]
permissive
NicolasG31/cpp_arcade
a5265dc699e9e8a22828577cbea3f39f3108cb4e
c6a9dc54ed10ea5300d7bf972c5ee2bee2e58116
refs/heads/master
2022-06-04T11:01:36.810774
2019-05-10T10:24:17
2019-05-10T10:24:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
498
cpp
// // my_read.cpp for in /home/doremi/rendu/cpp/cpp_arcade/games // // Made by Guillaume // Login <doremi@epitech.net> // // Started on Tue Apr 4 13:18:09 2017 Guillaume // Last update Tue Apr 4 13:29:42 2017 Guillaume // #include "my_read.hpp" my_read::my_read() { } my_read::~my_read() { } int my_read::my_read_mouli(int fd, void *core, long size) { return (read(fd, core, size)); } int my_read::my_write_mouli(int fd, void *core, long size) { return (write(fd, core, size)); }
[ "nicolas.guillon@epitech.eu" ]
nicolas.guillon@epitech.eu
bcb965aa4fd0ec64872e656f72201a07c0d2f5de
1ef627be7b987c195f8201f1a75d7f8ea2fbd102
/arreglos/8c.cpp
4866c4a5cc963c8ca0594db3e8138672a2c21f3b
[]
no_license
Alberto-Arias-x64/Segundo_cpp
bf0dfd35cd160a95a95058352619677f6693b5ff
4170ea47d45dbd9c7bff325f1a4e5140dd7e2d80
refs/heads/main
2023-05-04T01:53:36.600725
2021-05-28T00:00:51
2021-05-28T00:00:51
371,406,211
1
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
#include<iostream> #include<math.h> using namespace std; main() { int fmax[10],n,x; int i; n=999; for(i=1;i<=10;i++) { cout<<"ingrese el numero #"<<i<<" "; cin>>fmax[i]; if(fmax[i]<n) { n=fmax[i]; x=i; } } cout<<"el numero menor es "<<n<<endl; cout<<"este es el elemento numero #"<<x<<" en la lista de numeros"; }
[ "yugipoi@gmail.com" ]
yugipoi@gmail.com
bcdbf2b3dca2211c32223e631c780aa087af4346
29a4c1e436bc90deaaf7711e468154597fc379b7
/modules/reduction/include/nt2/toolbox/reduction/function/second.hpp
1bd06b9b8b93d0359bbfee9e17a238e88a3aa446
[ "BSL-1.0" ]
permissive
brycelelbach/nt2
31bdde2338ebcaa24bb76f542bd0778a620f8e7c
73d7e8dd390fa4c8d251c6451acdae65def70e0b
refs/heads/master
2021-01-17T12:41:35.021457
2011-04-03T17:37:15
2011-04-03T17:37:15
1,263,345
1
0
null
null
null
null
UTF-8
C++
false
false
1,013
hpp
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_REDUCTION_FUNCTION_SECOND_HPP_INCLUDED #define NT2_TOOLBOX_REDUCTION_FUNCTION_SECOND_HPP_INCLUDED #include <nt2/include/simd.hpp> #include <nt2/include/functor.hpp> #include <nt2/toolbox/reduction/include.hpp> namespace nt2 { namespace tag { struct second_ {}; } NT2_FUNCTION_IMPLEMENTATION(tag::second_, second, 1) } #include <nt2/toolbox/reduction/function/scalar/second.hpp> #include NT2_REDUCTION_INCLUDE(second.hpp) #endif // modified by jt the 25/12/2010
[ "jtlapreste@gmail.com" ]
jtlapreste@gmail.com
5f008f9698fae0baff763c05b0fa03de3d08bc76
df1e1faeb6a66cdf6e2c39d0a61225d8c7c486f8
/include/message.h
28492e7367a11852f2887813f64f5f781964510a
[]
no_license
GBernardo07/DiaryProject
5ce6dc82b64bda4d41f8822e198016a97bfdb5bd
d5dd86526b4f5462e25150152673c7e449d18082
refs/heads/master
2022-11-14T03:12:45.307916
2020-07-02T11:22:23
2020-07-02T11:22:23
272,705,794
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
#ifndef MESSAGE_H #define MESSAGE_h #include <string> #include "timing.h" #include "date.h" struct Message { std::string content; Date date; Time time; bool compare_messages(); }; #endif
[ "gbernardoreis@outlook.com" ]
gbernardoreis@outlook.com
c9e2fda72504009b2c7dc7b92e8ccd633bc8b051
1c34dce890845531443f50c309cb14b8803ad1ce
/CHC_Thesis.cxx
9c42dd167e14759ae5f74d093df9b3d61041ca19
[]
no_license
kbeick/CHC_Thesis
703c93b28f42760d13e3013c1a533df71bb12b5b
66e74f0a6ffe9391a3715a5c776cca96b81b4290
refs/heads/master
2021-01-19T20:21:52.114885
2014-12-11T03:19:16
2014-12-11T03:19:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,603
cxx
// Kevin Beick's Clark Honors College Thesis Project - 2014 // Author: Kevin Beick /* Main.cxx - Run command line interface - Set parameters - Construct BVH - Ray Tracing - streams evaluation data - produce image file */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <vtkDataSet.h> #include <vtkImageData.h> #include <vtkPNGWriter.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataReader.h> #include <vtkPoints.h> #include <vtkUnsignedCharArray.h> #include <vtkFloatArray.h> #include <vtkCellArray.h> #include <vtkImageCast.h> #include <numeric> #include <cmath> #include <vector> #include <string> #include "globals.h" #include "BVH.h" #include "BVH_BottomUpConstructor.h" #include "BVH_TopDownConstructor.h" #include "BBox.h" #include "Ray.h" #include "Shading.h" #include "Triangle.h" #include "utils.h" #include "objLoader.h" #include "Stopwatch.h" #include "Camera.h" using std::cerr; using std::cout; using std::endl; /* ----------------------------------------------------------------------------- */ /* ---------- PARAMETERIZATION ---------- */ /* ----------------------------------------------------------------------------- */ void print_params() { cerr << "~~~~read in params:" << endl; cerr << "~~~~constr method is: " << construction_method << endl; cerr << "~~~~got camera pos: " << campos[0] << ", " << campos[1] << ", " << campos[2] << endl; } int SetConstructionMethod(char* input) { int construction_method = -1; if(strcmp(input, "td")==0) construction_method = TOPDOWN; else if(strcmp(input, "bu")==0) construction_method = BOTTOMUP; else{ // cerr << input << endl; throw std::invalid_argument( "ERROR: Construction method must be either td or bu (top down or bottom up)\n" ); } return construction_method; } Camera* SetUpCamera() { Camera *c = new Camera(); c->near = 1; c->far = 200; c->angle = M_PI/6; c->focus = new Vec3f(0,0,0); c->up = new Vec3f(0,-1,0); return c; } /* ----------------------------------------------------------------------------- */ /* ---------- IMAGE PRODUCTION ---------- */ /* ----------------------------------------------------------------------------- */ class Screen { public: unsigned char *buffer; double *depthBuffer; int width, height; // return the element number of buffer corresponding to pixel at (c,r) int pixel(int c, int r){ return 3*( (IMAGE_WIDTH*r)+c ); } }; vtkImageData * NewImage(int width, int height) { vtkImageData *image = vtkImageData::New(); image->SetDimensions(width, height, 1); image->SetWholeExtent(0, width-1, 0, height-1, 0, 0); image->SetUpdateExtent(0, width-1, 0, height-1, 0, 0); image->SetNumberOfScalarComponents(3); image->SetScalarType(VTK_UNSIGNED_CHAR); image->AllocateScalars(); return image; } void WriteImage(vtkImageData *img, const char *filename) { std::string full_filename = filename; full_filename += ".png"; vtkPNGWriter *writer = vtkPNGWriter::New(); writer->SetInput(img); writer->SetFileName(full_filename.c_str()); writer->Write(); writer->Delete(); } /* ----------------------------------------------------------------------------- */ /* ---------- MAIN ---------- */ /* ----------------------------------------------------------------------------- */ int main(int argc, char** argv) { Stopwatch* stopwatch = new Stopwatch(); /* PREFATORY DATA LOG STUFF */ ofstream data_log; data_log.open("log_data_output_-_3.txt", ios_base::app); data_log << "___________________________________\n"; data_log << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; /* SET UP CAMERA */ c = SetUpCamera(); /* HANDLE AND SET PARAMETERS */ if (argc != 9 && argc != 10){ cerr << USAGE_MSG; exit(0);} cerr << "PROCESSING " << argv[1] << endl; try{ objReader = new ObjReader(argv[1]); branching_factor = atoi( argv[2] ); construction_method = SetConstructionMethod(argv[3]); c->position = new Vec3f(atof(argv[4]),atof(argv[5]),atof(argv[6])); depthOfTrace = atof(argv[7]); opacity = atof(argv[8]); }catch (const std::exception &exc){ // catch anything thrown within try block that derives from std::exception std::cerr << exc.what(); cerr << USAGE_MSG; exit(0); } data_log << "File: " << argv[1] << " Branching Factor: " << branching_factor << " Constr Method: " << argv[3] << " Campos: " << *c->position << " Depth of Trace: " << depthOfTrace << " Opacity: " << opacity << endl; char *outFileName; if(argv[9]){ outFileName = argv[9]; } else{ outFileName = (char*)"myOutput"; } EMPTY_NODE_BBOX = new BBox(*c->position * 1.1, *c->position * 1.1); vtkImageData *image; Screen* screen = new Screen; if (PRODUCE_IMAGE){ image = NewImage(IMAGE_WIDTH, IMAGE_HEIGHT); unsigned char *buffer = (unsigned char *) image->GetScalarPointer(0,0,0); int npixels = IMAGE_WIDTH*IMAGE_HEIGHT; //Initialize buffer to be all black for (int i = 0 ; i < npixels*3 ; i++) buffer[i] = 0; screen->buffer = buffer; screen->width = IMAGE_WIDTH; screen->height = IMAGE_HEIGHT; } /* GET RAW DATA FROM objReader */ objReader->extractNormals(); numTriangles = objReader->totalTriangles; data_log << "NUMBER OF TRIANGLES: " << numTriangles << endl; float* verts; float* normals; objReader->getRawData(verts, normals); tris = new Triangle[numTriangles]; CreateTriangleArray(tris, numTriangles, verts, normals); /* INITIALIZE BVH */ BVH_Node *root = new BVH_Node(); root->id = 0; root->parent = NULL; /* START TIMER */ stopwatch->reset(); /* CALL SPECIFIED BVH CONSTRUCTOR */ if (construction_method == TOPDOWN){ BuildBVH_topdown(tris, root, root->parent, numTriangles, 0); } else if (construction_method == BOTTOMUP){ BuildBVH_bottomup(tris, &root, numTriangles); if(branching_factor!=2){ BVH_Bottomup_Collapser(root); } } data_log << "BUILD TIME " << stopwatch->read() << endl; //cerr << "\nFINISHED BUILDING TREE " << (construction_method == TOPDOWN ? "top down" : "bottom up" ) << endl; /* GENERATE FLAT ARRAY REP OF BVH */ int flat_array_len; flat_array = bvhToFlatArray(root, &flat_array_len, branching_factor); // cerr << "flat_array_len " << flat_array_len << endl; /* PRINT FLAT ARRAY TO COMMAND LINE */ // for(int a=0; a<flat_array_len; a++){ // if(flat_array[a]==LEAF_FLAG){ cerr << "idx " << a << ": "; } // cerr << flat_array[a] << endl; // } /* ----------------------------------------------------------------------------- */ /* ---------- DO RAY TRACING ---------- */ /* ----------------------------------------------------------------------------- */ printf("\n~~~~~~ RAY TRACING ~~~~~~\n"); int npixels = IMAGE_WIDTH*IMAGE_HEIGHT; double traversal_times[npixels]; std::vector<int> node_visit_data (npixels, 0); /* PREP WORK */ Ray* look = RayFromPoints(*c->position, *c->focus); Vec3f* u = crossProductNormalized(look->unitDir, *c->up); Vec3f* v = crossProductNormalized(look->unitDir, *u); Vec3f x = (*u) * (2*tan((c->angle)/2)/IMAGE_WIDTH); Vec3f y = (*v) * (2*tan((c->angle)/2)/IMAGE_HEIGHT); /* FOR EACH PIXEL... */ for (int h = 0; h < IMAGE_HEIGHT; h++) { for (int w = 0; w < IMAGE_WIDTH; w++) { int pixel = screen->pixel(w,h); Vec3f x_comp = x*((2*w+1-IMAGE_WIDTH)/2); Vec3f y_comp = y*((2*h+1-IMAGE_HEIGHT)/2); /* ---- CALCULATE THE RAY FROM CAMERA TO PIXEL ---- */ Vec3f rayVector = look->unitDir + x_comp + y_comp; Ray* curRay = new Ray(*c->position, rayVector); // cerr << "\n\npixel " << w << "," << h << " :: "; /* ---- TRAVERSE THE BVH ---- */ Vec3f* color = new Vec3f(0,0,0); /* Pixel Color */ stopwatch->reset(); /* Start Timer */ traverseFlatArray(flat_array, 0, curRay, color, depthOfTrace, &node_visit_data[pixel/3]); /* Record Traversal Time */ traversal_times[w*IMAGE_HEIGHT + h] = stopwatch->read(); // cerr << "traversal complete" <<endl; if(PRODUCE_IMAGE){ // Assign colors to pixel screen->buffer[pixel] = color->x; screen->buffer[pixel+1] = color->y; screen->buffer[pixel+2] = color->z; } delete color; delete curRay; } } /* LOG EVAL METRICS TO DATA FILE */ double avg_time = std::accumulate(traversal_times,traversal_times+npixels,0.0) / npixels; data_log << "AVG TRAVERSAL TIME PER PIXEL: " << avg_time << endl; double avg_num_visits = std::accumulate(node_visit_data.begin(),node_visit_data.end(),0.0) / npixels; data_log << "AVG # NODES VISTED PER PIXEL: " << avg_num_visits << endl; if(construction_method == BOTTOMUP){ data_log << "AVG # CHILDREN PER INNER NODE: " << (double)branching_factor - ((double)emptyNodeCount/(double)inner_node_counter) << endl; } if( PRODUCE_IMAGE ) WriteImage(image, outFileName) ; data_log.close(); }
[ "kbeick@zoho.com" ]
kbeick@zoho.com
7450ef5d7da5c56e448a9cf69fa3dd89c9b86c91
72e59a47eb012891b84b10f9b1bd738f02aa5a9a
/ESEMPI_rseba/STRUCT/prova.cc
3c0fae93c3e8c6eff3f6e0b81d370bd1f4038504
[]
no_license
Leonelli/C-plus-plus-works
8a366f9716284ef804de5c707c5a0904afb217a7
f4a9971b5391d5864ffcf208a2845c4a224969fe
refs/heads/master
2020-03-29T17:22:53.737281
2019-02-13T16:50:48
2019-02-13T16:50:48
150,159,156
1
0
null
null
null
null
UTF-8
C++
false
false
490
cc
using namespace std; #include <iostream> #include <cstring> const int Nmax = 1000; struct myarray { double v[Nmax]; int nelem; }; double somma (myarray a,int n) { double res; if (n==0) res = a.v[0]; else res = a.v[n]+somma(a,n-1); return res; } int main () { myarray a; // inizializza Myarray a.nelem=Nmax; for (int i=0;i<a.nelem;i++) { a.v[i]=double(i+1.0); } cout << "La somma degli elementi dell'array e' " << somma(a,a.nelem-1) << endl; }
[ "matteoleonelli99@gmail.com" ]
matteoleonelli99@gmail.com
e5aacfe0c12881506d801e034d5e9d3b51538ef0
5b9a1720d88be1ba9b18a0adb2d0ac2bd76c5e42
/Coba-coba/Code 5.cpp
5925dc92b81b19f5fa3b1f15e2fcd08b25898878
[]
no_license
asianjack19/Cpp
7affaa765c5e5b246e21e4b9df239334362ca470
acc2cac32921fff56c8d76a43d18ba740a9ed26f
refs/heads/master
2023-08-14T15:33:29.487550
2021-09-18T10:58:27
2021-09-18T10:58:27
378,959,808
0
0
null
null
null
null
UTF-8
C++
false
false
155
cpp
#include <stdio.h> #include <stdlib.h> int main() { char line[0]; gets (line); printf("Hello,World\n"); printf("%s",line); return 0; }
[ "michaeladriel080801@gmail.com" ]
michaeladriel080801@gmail.com
a028f3bc61b8a49a132f039d86baeb7634a33862
6e9b20902f4e232d12e865f192ea5128ae253ba7
/Fluid/2.1/pointDisplacement
d618c0c834cfb708698a96cec31c72db046ddefe
[]
no_license
abarcaortega/FSI_3
1de5ed06ca7731016e5136820aecdc0a74042723
016638757f56e7b8b33af4a1af8e0635b88ffbbc
refs/heads/master
2020-08-03T22:28:04.707884
2019-09-30T16:33:31
2019-09-30T16:33:31
211,905,379
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class pointVectorField; location "2.1"; object pointDisplacement; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 0 0 0 0 0]; internalField uniform (0 0 0); boundaryField { inlet { type fixedValue; value uniform (0 0 0); } outlet { type fixedValue; value uniform (0 0 0); } flap { type fixedValue; value uniform (0 0 0); } upperWall { type slip; } lowerWall { type slip; } frontAndBack { type empty; } } // ************************************************************************* //
[ "aldo.abarca.ortega@gmail.com" ]
aldo.abarca.ortega@gmail.com
6cdc32fd851461aaacae4b06b1c9a4267293164c
0c557860627c2025919fc0871dc29e9cba4d36f1
/src/data/data_normalization.h
185059652472b41019cbbdf00c09e2d3acde593c
[ "MIT" ]
permissive
m-colombo/ML.cpp
c6b58d7fae2665f7db40f54c61606bf1a45ce481
2f1b3b5ab3487ea47263fbd774af9d5a17779c96
refs/heads/master
2021-01-10T07:41:59.773348
2016-02-10T13:50:01
2016-02-10T13:50:01
50,877,606
1
1
null
null
null
null
UTF-8
C++
false
false
1,864
h
// // data_normalization.h // XAA1 // // Created by Michele Colombo on 16/12/2015. // Copyright (c) 2015 Michele Colombo. All rights reserved. // #ifndef __XAA1__data_normalization__ #define __XAA1__data_normalization__ #include "samples.h" #include "../selection/model_info.h" //TODO extend for 1-of-k class DataNormalizer : public ModelInfo{ public: virtual double normalize(double value) = 0; virtual double denormalize(double value) = 0; virtual void setDataSource(Doubles const& values)=0; virtual ~DataNormalizer()=default; }; typedef std::shared_ptr<DataNormalizer> DataNormalizerSP; class MinMaxNormalizer : public DataNormalizer{ public: MinMaxNormalizer(double min_target, double max_target); void setDataSource(Doubles const& values) override; double normalize(double value) override; double denormalize(double value) override; std::string getInfo() override {return "MinMax["+std::to_string(min_target)+","+std::to_string(max_target)+"]";} protected: double min_target, max_target; double min_value, max_value; }; class IdentityNormalizer : public DataNormalizer{ public: IdentityNormalizer(){}; void setDataSource(Doubles const& values) override {} double normalize(double value) override {return value;} double denormalize(double value) override {return value;} std::string getInfo() override {return "Identity";} }; class ZNormalizer : public DataNormalizer{ public: ZNormalizer()=default; void setDataSource(Doubles const& values) override; double normalize(double value) override { return (value - mean) / sd;} double denormalize(double value) override { return (value * sd) + mean;} std::string getInfo() override {return "Z";} protected: double mean, sd; }; #endif /* defined(__XAA1__data_normalization__) */
[ "mr.michele.colombo@gmail.com" ]
mr.michele.colombo@gmail.com
cd558d89ecce96dfdd7c48e05f0d17fb75383feb
8a2fb4d3076f008db245efae540041fc3eace4d6
/HawkUtil/HawkWebSocket.h
9197fdb476c0b0a3738b147b53d5dd18b37dd04f
[]
no_license
hawkproject/hawkproject
f536953ef6df199b2b93cee5672fa4a4cca23c36
e781fd463f24e5a4c54cbd8c2bf34f4d36906ae4
refs/heads/master
2021-01-22T09:26:32.063606
2014-07-23T10:22:43
2014-07-23T10:22:43
13,612,604
6
5
null
null
null
null
GB18030
C++
false
false
995
h
#ifndef HAWK_WEBSOCKET_H #define HAWK_WEBSOCKET_H #include "HawkSocket.h" #include "HawkOctetsStream.h" namespace Hawk { /************************************************************************/ /* WebSocket封装 */ /************************************************************************/ class UTIL_API HawkWebSocket : public HawkSocket { public: //构造 HawkWebSocket(); //析构 virtual ~HawkWebSocket(); public: //握手协议生成(依据请求信息生成握手的相应信息) static Bool HandShake(const OctetsStream* pHttpReq, OctetsStream* pHttpRep); protected: //获取Sec-WebSocket-Key("Sec-WebSocket-Key1: " | "Sec-WebSocket-Key2: ") static Bool GetSecWebSocketKey(const OctetsStream* pHttpReq, const AString& sKeyType, AString& sSecKey, UChar cFlag = '\r'); //获取8-byte security key static Bool Get8ByteSecurityKey(const OctetsStream* pHttpReq, UChar* pSecKey); }; } #endif
[ "380269273@qq.com" ]
380269273@qq.com
0d5d503d08603d1e6c0b6f23fe90cc60c2326b85
c2658b5a3b4e00d836287f22e47af2f4241278bd
/Fraction/Fraction.h
3b2021ebb89e6c160a004c1a8e36d076c7ac9d5e
[]
no_license
ahmad1598/C-plus-plus
2fdeac3686e5d33bb46b27968816194369cca816
25fb17f62abe946064500eb55839507b6fc5623c
refs/heads/master
2020-04-27T04:59:58.091937
2019-03-06T06:39:23
2019-03-06T06:39:23
174,070,189
0
0
null
null
null
null
UTF-8
C++
false
false
1,212
h
/***************************************** * * Project : M5 - Fraction Class * File : Fraction.h * Name : Ahmad Rasoulpour * Professor : Robert Baird * Date : 07 / 06 / 18 ******************************************/ class Fraction { friend Fraction operator+(const Fraction& f1, const Fraction& f2); friend Fraction operator-(const Fraction& f1, const Fraction& f2); friend Fraction operator*(const Fraction& f1, const Fraction& f2); friend Fraction operator/(const Fraction& f1, const Fraction& f2); public: Fraction(); // Set numerator = 1, denominator = 1. Fraction(int n, int d=1); // constructor with parameters // acts as conversion constructor // standard input/output routines void Input(); // input a fraction from keyboard. void Show() const; // Display a fraction on screen // accessors int GetNumerator() const; int GetDenominator() const; // mutator bool SetValue(int n, int d=1); // set the fraction's value through parameters double Evaluate() const; // Return the decimal value of a fraction private: int numerator; // may be any integer int denominator; // should always be positive };
[ "ahmad.raman83@yahoo.com" ]
ahmad.raman83@yahoo.com
5de5c136681f1a29ba49125753376e83b858dcc1
239994fd79fdec7a4184db3e230828b8347dd997
/Frost/Vector2f.h
8eea3b31e974de69e4642790014c69a5b0d48ef3
[]
no_license
ClericX/Projects
bd0944c6994658b539b61ae90580ee0db440f84c
9c705315cb16d42a0116f88f156fb748ca46ccfc
refs/heads/master
2021-01-01T19:42:21.981590
2013-03-16T15:49:00
2013-03-16T15:49:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
186
h
#pragma once #include "DLL.h" class FROSTAPI Vector2f { public: float x; float y; Vector2f(void); Vector2f(float _x, float _y); void Set(float _x, float _y); ~Vector2f(void); };
[ "clericx@clericx.net" ]
clericx@clericx.net
c4e976384cacd38e0a82e7b95555555bd2ab94b4
b0dd7779c225971e71ae12c1093dc75ed9889921
/boost/geometry/algorithms/append.hpp
9a4e082aed67bb4fbdf69f2e2df150c28aacbb5b
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
6,693
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP #define BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP #include <boost/range.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/mutable_range.hpp> #include <boost/geometry/core/point_type.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/algorithms/num_interior_rings.hpp> #include <boost/geometry/algorithms/detail/convert_point_to_point.hpp> #include <boost/geometry/geometries/concepts/check.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace append { template <typename Geometry, typename Point> struct append_no_action { static inline void apply(Geometry& , Point const& , int = 0, int = 0) { } }; template <typename Geometry, typename Point> struct append_point { static inline void apply(Geometry& geometry, Point const& point, int = 0, int = 0) { typename geometry::point_type<Geometry>::type copy; geometry::detail::conversion::convert_point_to_point(point, copy); traits::push_back<Geometry>::apply(geometry, copy); } }; template <typename Geometry, typename Range> struct append_range { typedef typename boost::range_value<Range>::type point_type; static inline void apply(Geometry& geometry, Range const& range, int = 0, int = 0) { for (typename boost::range_iterator<Range const>::type it = boost::begin(range); it != boost::end(range); ++it) { append_point<Geometry, point_type>::apply(geometry, *it); } } }; template <typename Polygon, typename Point> struct point_to_polygon { typedef typename ring_type<Polygon>::type ring_type; static inline void apply(Polygon& polygon, Point const& point, int ring_index, int = 0) { if (ring_index == -1) { append_point<ring_type, Point>::apply( exterior_ring(polygon), point); } else if (ring_index < int(num_interior_rings(polygon))) { append_point<ring_type, Point>::apply( interior_rings(polygon)[ring_index], point); } } }; template <typename Polygon, typename Range> struct range_to_polygon { typedef typename ring_type<Polygon>::type ring_type; static inline void apply(Polygon& polygon, Range const& range, int ring_index, int ) { if (ring_index == -1) { append_range<ring_type, Range>::apply( exterior_ring(polygon), range); } else if (ring_index < int(num_interior_rings(polygon))) { append_range<ring_type, Range>::apply( interior_rings(polygon)[ring_index], range); } } }; }} // namespace detail::append #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { namespace splitted_dispatch { template <typename Tag, typename Geometry, typename Point> struct append_point : detail::append::append_no_action<Geometry, Point> {}; template <typename Geometry, typename Point> struct append_point<linestring_tag, Geometry, Point> : detail::append::append_point<Geometry, Point> {}; template <typename Geometry, typename Point> struct append_point<ring_tag, Geometry, Point> : detail::append::append_point<Geometry, Point> {}; template <typename Polygon, typename Point> struct append_point<polygon_tag, Polygon, Point> : detail::append::point_to_polygon<Polygon, Point> {}; template <typename Tag, typename Geometry, typename Range> struct append_range : detail::append::append_no_action<Geometry, Range> {}; template <typename Geometry, typename Range> struct append_range<linestring_tag, Geometry, Range> : detail::append::append_range<Geometry, Range> {}; template <typename Geometry, typename Range> struct append_range<ring_tag, Geometry, Range> : detail::append::append_range<Geometry, Range> {}; template <typename Polygon, typename Range> struct append_range<polygon_tag, Polygon, Range> : detail::append::range_to_polygon<Polygon, Range> {}; } // Default: append a range (or linestring or ring or whatever) to any geometry template < typename Geometry, typename RangeOrPoint, typename TagRangeOrPoint = typename tag<RangeOrPoint>::type > struct append : splitted_dispatch::append_range<typename tag<Geometry>::type, Geometry, RangeOrPoint> {}; // Specialization for point to append a point to any geometry template <typename Geometry, typename RangeOrPoint> struct append<Geometry, RangeOrPoint, point_tag> : splitted_dispatch::append_point<typename tag<Geometry>::type, Geometry, RangeOrPoint> {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH /*! \brief Appends one or more points to a linestring, ring, polygon, multi-geometry \ingroup append \tparam Geometry \tparam_geometry \tparam RangeOrPoint Either a range or a point, fullfilling Boost.Range concept or Boost.Geometry Point Concept \param geometry \param_geometry \param range_or_point The point or range to add \param ring_index The index of the ring in case of a polygon: exterior ring (-1, the default) or interior ring index \param multi_index Reserved for multi polygons or multi linestrings \qbk{[include reference/algorithms/append.qbk]} } */ template <typename Geometry, typename RangeOrPoint> inline void append(Geometry& geometry, RangeOrPoint const& range_or_point, int ring_index = -1, int multi_index = 0) { concept::check<Geometry>(); dispatch::append < Geometry, RangeOrPoint >::apply(geometry, range_or_point, ring_index, multi_index); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_APPEND_HPP
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
cb24f1981bb5642106dfe3259fa696823b846051
3fd747b340e5ea8c59ac733abd335c5d033cf812
/src/gui/daq/coord.h
2c6d712cc855a318c3f4d970e27f02cf4513cd5e
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
hgamber/qpx-gamma
dd6e2817d744d1415d9022c3f70272f8ad43dfd6
4af4dd783e618074791674a018a3ba21c9b9aab1
refs/heads/master
2021-10-27T11:50:46.578617
2019-04-17T01:24:07
2019-04-17T01:24:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
h
/******************************************************************************* * * This software was developed at the National Institute of Standards and * Technology (NIST) by employees of the Federal Government in the course * of their official duties. Pursuant to title 17 Section 105 of the * United States Code, this software is not subject to copyright protection * and is in the public domain. NIST assumes no responsibility whatsoever for * its use by other parties, and makes no guarantees, expressed or implied, * about its quality, reliability, or any other characteristic. * * Author(s): * Martin Shetty (NIST) * * Description: * Marker - for marking a channel or energt in a plot * ******************************************************************************/ #pragma once #include "calibration.h" class Coord { public: Coord() : bits_(0), energy_(nan("")), bin_(nan("")) {} void set_energy(double nrg, Qpx::Calibration cali); void set_bin(double bin, uint16_t bits, Qpx::Calibration cali); uint16_t bits() const {return bits_;} double energy() const; double bin(const uint16_t to_bits) const; bool null() { return ((bits_ == 0) && std::isnan(bin_) && std::isnan(energy_) ); } bool operator!= (const Coord& other) const { return (!operator==(other)); } bool operator== (const Coord& other) const { if (energy_ != other.energy_) return false; if (bin(bits_) != other.bin(bits_)) return false; return true; } private: double energy_; double bin_; uint16_t bits_; };
[ "martukas@gmail.com" ]
martukas@gmail.com
ae50ba56f78e3175d378f2ae4999c56d8316a689
76d72c6a16a715239729c2b548ca832b7e8bd35e
/LibFFmpegPlayer/LibFFmpegPlayer/FFmpegAudioSpeaker.h
51718671341ffa9a4798c99d138b80f1443286e2
[]
no_license
naturehome/C-Test
a4a120b6862e3d4076f28452a7f9e0d3a83c7cd4
218f4d899579049017a6bf25cc12eb8fb2fd0168
refs/heads/master
2021-01-20T08:22:02.131967
2019-01-09T11:31:38
2019-01-09T11:31:38
90,137,637
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
#pragma once class FFmpegSynchronizer; class FFmpegFrameProvider; class FFmpegAudioSpeaker { public: FFmpegAudioSpeaker(FFmpegFrameProvider& FrameProvider, FFmpegSynchronizer& Synchronizer); ~FFmpegAudioSpeaker(); private: FFmpegFrameProvider& m_FrameProvider; FFmpegSynchronizer& m_Synchronizer; };
[ "zhangyabin@jiandan100.cn" ]
zhangyabin@jiandan100.cn
fd506a86a89c3d4277e4e8bb0315f89d42cf4f89
4da55187c399730f13c5705686f4b9af5d957a3f
/resources/languages/cpp/Motor.cpp
6881a4b479d17026cf0e033f4436b1114ae3ff22
[ "Apache-2.0" ]
permissive
Ewenwan/webots
7111c5587100cf35a9993ab923b39b9e364e680a
6b7b773d20359a4bcf29ad07384c5cf4698d86d3
refs/heads/master
2020-04-17T00:23:54.404153
2019-01-16T13:58:12
2019-01-16T13:58:12
166,048,591
2
0
Apache-2.0
2019-01-16T13:53:50
2019-01-16T13:53:50
null
UTF-8
C++
false
false
3,941
cpp
// Copyright 1996-2018 Cyberbotics Ltd. // // 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. #define WB_ALLOW_MIXING_C_AND_CPP_API #include <webots/device.h> #include <webots/motor.h> #include <webots/Brake.hpp> #include <webots/Motor.hpp> #include <webots/PositionSensor.hpp> #include <webots/Robot.hpp> using namespace webots; void Motor::setAcceleration(double acceleration) { wb_motor_set_acceleration(getTag(), acceleration); } void Motor::setVelocity(double vel) { wb_motor_set_velocity(getTag(), vel); } void Motor::setControlPID(double p, double i, double d) { wb_motor_set_control_pid(getTag(), p, i, d); } // Force void Motor::setForce(double force) { wb_motor_set_force(getTag(), force); } void Motor::setAvailableForce(double availableForce) { wb_motor_set_available_force(getTag(), availableForce); } void Motor::enableForceFeedback(int sampling_period) { wb_motor_enable_force_feedback(getTag(), sampling_period); } void Motor::disableForceFeedback() { wb_motor_disable_force_feedback(getTag()); } int Motor::getForceFeedbackSamplingPeriod() const { return wb_motor_get_force_feedback_sampling_period(getTag()); } double Motor::getForceFeedback() const { return wb_motor_get_force_feedback(getTag()); } // Torque void Motor::setTorque(double torque) { wb_motor_set_force(getTag(), torque); } void Motor::setAvailableTorque(double availableTorque) { wb_motor_set_available_force(getTag(), availableTorque); } double Motor::getTorqueFeedback() const { return wb_motor_get_force_feedback(getTag()); } void Motor::enableTorqueFeedback(int sampling_period) { wb_motor_enable_force_feedback(getTag(), sampling_period); } void Motor::disableTorqueFeedback() { wb_motor_disable_force_feedback(getTag()); } int Motor::getTorqueFeedbackSamplingPeriod() const { return wb_motor_get_force_feedback_sampling_period(getTag()); } void Motor::setPosition(double position) { wb_motor_set_position(getTag(), position); } Motor::Type Motor::getType() const { return Type(wb_motor_get_type(getTag())); } double Motor::getTargetPosition() const { return wb_motor_get_target_position(getTag()); } double Motor::getMinPosition() const { return wb_motor_get_min_position(getTag()); } double Motor::getMaxPosition() const { return wb_motor_get_max_position(getTag()); } double Motor::getVelocity() const { return wb_motor_get_velocity(getTag()); } double Motor::getMaxVelocity() const { return wb_motor_get_max_velocity(getTag()); } double Motor::getAcceleration() const { return wb_motor_get_acceleration(getTag()); } double Motor::getAvailableForce() const { return wb_motor_get_available_force(getTag()); } double Motor::getMaxForce() const { return wb_motor_get_max_force(getTag()); } double Motor::getAvailableTorque() const { return wb_motor_get_available_torque(getTag()); } double Motor::getMaxTorque() const { return wb_motor_get_max_torque(getTag()); } Brake *Motor::getBrake() { if (brake == NULL) brake = dynamic_cast<Brake *>(Robot::getDevice(getBrakeTag())); return brake; } int Motor::getBrakeTag() const { return wb_motor_get_brake(getTag()); } PositionSensor *Motor::getPositionSensor() { if (positionSensor == NULL) positionSensor = dynamic_cast<PositionSensor *>(Robot::getDevice(getPositionSensorTag())); return positionSensor; } int Motor::getPositionSensorTag() const { return wb_motor_get_position_sensor(getTag()); }
[ "David.Mansolino@cyberbotics.com" ]
David.Mansolino@cyberbotics.com
39fdffe4d02e0f07df1992f66ad7987fc0fc7d5d
048df2b4dc5ad153a36afad33831017800b9b9c7
/atcoder/joisc2007/joisc2007_mall.cc
d43cb1f10e338dd286f69dd0d5c55733f20189d6
[]
no_license
fluffyowl/past-submissions
a73e8f5157c647634668c200cd977f4428c6ac7d
24706da1f79e5595b2f9f2583c736135ea055eb7
refs/heads/master
2022-02-21T06:32:43.156817
2019-09-16T00:17:50
2019-09-16T00:17:50
71,639,325
0
0
null
null
null
null
UTF-8
C++
false
false
2,048
cc
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for (int i=0;i<(n);i++) #define REP2(i,m,n) for (int i=m;i<(n);i++) typedef long long ll; int H, W, X, Y; ll A[1010][1010]; ll B[1010][1010]; ll sum1(int i, int j, int h, int w) { return A[i + h][j + w] - A[i][j + w] + A[i][j] - A[i + h][j]; } ll sum2(int i, int j, int h, int w) { return B[i + h][j + w] - B[i][j + w] + B[i][j] - B[i + h][j]; } int main() { ios::sync_with_stdio(false); cin.tie(0); memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B)); cin >> W >> H >> Y >> X; REP(i, H) REP(j, W) cin >> A[i+1][j+1]; REP(i, H) REP(j, W) B[i+1][j+1] = A[i+1][j+1] == -1; REP(i, H+1) REP(j, W) A[i][j+1] += A[i][j]; REP(i, H) REP(j, W+1) A[i+1][j] += A[i][j]; REP(i, H+1) REP(j, W) B[i][j+1] += B[i][j]; REP(i, H) REP(j, W+1) B[i+1][j] += B[i][j]; ll ans = 1LL << 59; REP(i, H-X+1) REP(j, W-Y+1) if (sum2(i, j, X, Y) == 0) { ans = min(ans, sum1(i, j, X, Y)); } cout << ans << endl; } #include <bits/stdc++.h> using namespace std; #define REP(i,n) for (int i=0;i<(n);i++) #define REP2(i,m,n) for (int i=m;i<(n);i++) typedef long long ll; int H, W, X, Y; ll A[1010][1010]; ll B[1010][1010]; ll sum1(int i, int j, int h, int w) { return A[i + h][j + w] - A[i][j + w] + A[i][j] - A[i + h][j]; } ll sum2(int i, int j, int h, int w) { return B[i + h][j + w] - B[i][j + w] + B[i][j] - B[i + h][j]; } int main() { ios::sync_with_stdio(false); cin.tie(0); memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B)); cin >> W >> H >> Y >> X; REP(i, H) REP(j, W) cin >> A[i+1][j+1]; REP(i, H) REP(j, W) B[i+1][j+1] = A[i+1][j+1] == -1; REP(i, H+1) REP(j, W) A[i][j+1] += A[i][j]; REP(i, H) REP(j, W+1) A[i+1][j] += A[i][j]; REP(i, H+1) REP(j, W) B[i][j+1] += B[i][j]; REP(i, H) REP(j, W+1) B[i+1][j] += B[i][j]; ll ans = 1LL << 59; REP(i, H-X+1) REP(j, W-Y+1) if (sum2(i, j, X, Y) == 0) { ans = min(ans, sum1(i, j, X, Y)); } cout << ans << endl; }
[ "nebukuro09@gmail.com" ]
nebukuro09@gmail.com
0340fd2ab349815015527bdf694a041b86f88d3d
cf7537721caf499b46be56b9932fabb4500b2274
/include/GCutG.h
ca63b691f0b875fb92bbd0679026b1696c2a29bc
[]
no_license
placebosarah/GRUTinizer
f95c2a93ffb2f55f4a96e28037ecfc019144dddd
62b1156c6bd39d3bb80283e479f7a6968149a550
refs/heads/master
2021-01-11T10:59:45.819686
2016-11-02T19:47:30
2016-11-02T19:47:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,055
h
#ifndef GCUTG_H_ #define GCUTG_H_ #include <TCutG.h> #include <TClass.h> #include <TString.h> class GCutG : public TCutG { public: GCutG() : TCutG() { } GCutG(const TCutG &cutg) : TCutG(cutg) { } GCutG(const char *name,Int_t n=0) : TCutG(name,n) { } GCutG(const char *name,Int_t n,const Float_t *x,const Float_t *y) : TCutG(name,n,x,y) { } GCutG(const char *name,Int_t n,const Double_t *x,const Double_t *y) : TCutG(name,n,x,y) { } ~GCutG() { } virtual void Print(Option_t *opt="") const; int SaveTo(const char *cutname="",const char* filename="",Option_t* option="update"); // *MENU* void SetGateMethod(const char* xclass,const char* xmethod, const char* yclass,const char* ymethod); bool IsInside(TObject *objx,TObject *objy=0); Int_t IsInside(Double_t x,Double_t y) const { return TCutG::IsInside(x,y); } private: TString fXGateClass; TString fYGateClass; TString fXGateMethod; TString fYGateMethod; ClassDef(GCutG,1) }; #endif
[ "pcbend@gmail.com" ]
pcbend@gmail.com
cd8fefa22be8cecf89a1389a60bb2870a1c51191
f268ef85eb335af1794a669e7f69e3c94d3b3cb0
/Client/source/feint/pane/markdown/html/headerpraser.h
4ca943a6daaec44f00968837bcf00e73c000371b
[]
no_license
feint123/Emoji
a67a9a6f7cc2e61bba16f9cb75a18c61c8b5d428
9929171c9eb74b9799fd3ab23e35d68c059dcfbf
refs/heads/master
2020-06-16T18:30:49.915832
2017-02-02T07:33:09
2017-02-02T07:33:09
75,077,349
3
0
null
null
null
null
UTF-8
C++
false
false
239
h
#ifndef HEADERPRASER_H #define HEADERPRASER_H #include <QString> class HeaderPraser { public: HeaderPraser(); static QString praser(QString text); private: QString hOneReg; QString hTwoReg; }; #endif // HEADERPRASER_H
[ "13479399352zyf@gmail.com" ]
13479399352zyf@gmail.com
866011ecf098ce7a8107eebb0fc68ddc8c13a731
9b48da12e8d70fb3d633b988b9c7d63a954434bf
/ECC8.1/Server/kennel/Ecc_Common/opens/snmp++/snmp++/Snmp++/include/snmp_pp/oid_def.h
d898440c7939ea231e84b633b3959779ce4c0d7f
[]
no_license
SiteView/ECC8.1.3
446e222e33f37f0bb6b67a9799e1353db6308095
7d7d8c7e7d7e7e03fa14f9f0e3ce5e04aacdb033
refs/heads/master
2021-01-01T18:07:05.104362
2012-08-30T08:58:28
2012-08-30T08:58:28
4,735,167
1
3
null
null
null
null
UTF-8
C++
false
false
3,938
h
/*_############################################################################ _## _## oid_def.h _## _## SNMP++v3.2.15 _## ----------------------------------------------- _## Copyright (c) 2001-2004 Jochen Katz, Frank Fock _## _## This software is based on SNMP++2.6 from Hewlett Packard: _## _## Copyright (c) 1996 _## Hewlett-Packard Company _## _## ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS. _## Permission to use, copy, modify, distribute and/or sell this software _## and/or its documentation is hereby granted without fee. User agrees _## to display the above copyright notice and this license notice in all _## copies of the software and any documentation of the software. User _## agrees to assume all liability for the use of the software; _## Hewlett-Packard and Jochen Katz make no representations about the _## suitability of this software for any purpose. It is provided _## "AS-IS" without warranty of any kind, either express or implied. User _## hereby grants a royalty-free license to any and all derivatives based _## upon this software code base. _## _## Stuttgart, Germany, Tue Jan 4 21:42:42 CET 2005 _## _##########################################################################*/ /*=================================================================== Copyright (c) 1999 Hewlett-Packard Company ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS. Permission to use, copy, modify, distribute and/or sell this software and/or its documentation is hereby granted without fee. User agrees to display the above copyright notice and this license notice in all copies of the software and any documentation of the software. User agrees to assume all liability for the use of the software; Hewlett-Packard makes no representations about the suitability of this software for any purpose. It is provided "AS-IS" without warranty of any kind,either express or implied. User hereby grants a royalty-free license to any and all derivatives based upon this software code base. SNMP++ O I D _ D E F . H OID_DEF DEFINITIONS DESCRIPTION: Some common Oid definitions. DESIGN + AUTHOR: Peter E Mellquist LANGUAGE: ANSI C++ OPERATING SYSTEMS: DOS / Windows 3.1 BSD UNIX =====================================================================*/ // $Id: oid_def.h,v 1.4 2004/03/03 23:11:21 katz Exp $ #ifndef _OID_DEF #define _OID_DEF #include "snmp_pp/oid.h" #ifdef SNMP_PP_NAMESPACE namespace Snmp_pp { #endif /** SMI trap oid def */ class snmpTrapsOid: public Oid { public: DLLOPT snmpTrapsOid() : Oid("1.3.6.1.6.3.1.1.5") {}; }; /** SMI Enterprose Oid */ class snmpTrapEnterpriseOid: public Oid { public: DLLOPT snmpTrapEnterpriseOid() : Oid("1.3.6.1.6.3.1.1.4.3.0") {}; }; /** SMI Cold Start Oid */ class coldStartOid: public snmpTrapsOid { public: DLLOPT coldStartOid() { *this+=".1"; }; }; /** SMI WarmStart Oid */ class warmStartOid: public snmpTrapsOid { public: DLLOPT warmStartOid() { *this+=".2"; }; }; /** SMI LinkDown Oid */ class linkDownOid: public snmpTrapsOid { public: DLLOPT linkDownOid() { *this+=".3"; }; }; /** SMI LinkUp Oid */ class linkUpOid: public snmpTrapsOid { public: DLLOPT linkUpOid() { *this+=".4"; }; }; /** SMI Authentication Failure Oid */ class authenticationFailureOid: public snmpTrapsOid { public: DLLOPT authenticationFailureOid() { *this+=".5"; }; }; /** SMI egpneighborloss Oid */ class egpNeighborLossOid: public snmpTrapsOid { public: DLLOPT egpNeighborLossOid() { *this+=".6"; }; }; #ifdef SNMP_PP_NAMESPACE }; // end of namespace Snmp_pp #endif #endif // _OID_DEF
[ "136122085@163.com" ]
136122085@163.com