blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
26bb6298a5db0e9f0d2dd9402a2235b9290defdb
aaad762cd1d72e7dc46052e3112d148137c8f741
/lab_5q15.cpp
0c6cb997ab427770663054aa4b9f4c6947e30a1b
[]
no_license
Ashwinak2000/Project-1
a0c1bfc9d376e66849c452dc89256238c8ccd9a9
0a0a91926ef5ba999098f00bbf8858aef576203a
refs/heads/master
2021-07-24T04:34:32.804530
2018-11-18T14:40:55
2018-11-18T14:40:55
143,856,396
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include<iostream> using namespace std; /* ***** * * * * ** * */ int main() { //Find number of rows int n=5; cout<<"Enter value of rows(n)"<<endl; cin>>n; int star=0;//Position of star per row. // for loop for the rows for(int i=0;i<n;i++) { //For loop for the columns for(int j=0;j<n;j++) { if(i!=0) { if(star==j||(j==n-1)) cout<<"*"; else cout<<" "; } else cout<<"*"; } cout<<endl; star++; } }
[ "noreply@github.com" ]
noreply@github.com
5392392a6f4518205c4d24f705044210c3e24f7e
f87ffdde15f1c2bb42220e73b283b17f15342363
/Test_IPC/BaseLayer.cpp
3c7ae15b5608f7a9a9a3d1b4a99e14dcd4b366c9
[]
no_license
dbstn1369/IPC
ab5a1cfb8d8070374cdbcb03b4fdb5e341494b30
66c9bcbbdf0030271c822b2d3f23a00702909076
refs/heads/master
2020-04-24T10:51:14.869267
2019-02-21T16:37:08
2019-02-21T16:37:08
171,907,394
0
0
null
null
null
null
UTF-8
C++
false
false
2,749
cpp
// BaseLayer.cpp: implementation of the CBaseLayer class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Test_IPC.h" #include "BaseLayer.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBaseLayer::CBaseLayer( char* pName ) : m_nUpperLayerCount( 0 ), mp_UnderLayer( NULL ) { m_pLayerName = pName ; } CBaseLayer::~CBaseLayer() { } void CBaseLayer::SetUnderUpperLayer(CBaseLayer *pUULayer) { if ( !pUULayer ) // if the pointer is null, { #ifdef _DEBUG TRACE( "[CBaseLayer::SetUnderUpperLayer] The variable , 'pUULayer' is NULL" ) ; #endif return ; } //////////////////////// fill the blank /////////////////////////////// /////////////////////////////////////////////////////////////////////// } void CBaseLayer::SetUpperUnderLayer(CBaseLayer *pUULayer) { if ( !pUULayer ) // if the pointer is null, { #ifdef _DEBUG TRACE( "[CBaseLayer::SetUpperUnderLayer] The variable , 'pUULayer' is NULL" ) ; #endif return ; } //////////////////////// fill the blank /////////////////////////////// SetUpperLayer(pUULayer); pUULayer->SetUnderLayer(this); /////////////////////////////////////////////////////////////////////// } void CBaseLayer::SetUpperLayer(CBaseLayer *pUpperLayer ) { if ( !pUpperLayer ) // if the pointer is null, { #ifdef _DEBUG TRACE( "[CBaseLayer::SetUpperLayer] The variable , 'pUpperLayer' is NULL" ) ; #endif return ; } // UpperLayer is added.. this->mp_aUpperLayer[ m_nUpperLayerCount++ ] = pUpperLayer ; } void CBaseLayer::SetUnderLayer(CBaseLayer *pUnderLayer) { if ( !pUnderLayer ) // if the pointer is null, { #ifdef _DEBUG TRACE( "[CBaseLayer::SetUnderLayer] The variable , 'pUnderLayer' is NULL\n" ) ; #endif return ; } // UnderLayer assignment.. this->mp_UnderLayer = pUnderLayer ; } CBaseLayer* CBaseLayer::GetUpperLayer(int nindex) { if ( nindex < 0 || nindex > m_nUpperLayerCount || m_nUpperLayerCount < 0 ) { #ifdef _DEBUG TRACE( "[CBaseLayer::GetUpperLayer] There is no UpperLayer in Array..\n" ) ; #endif return NULL ; } return mp_aUpperLayer[ nindex ] ; } CBaseLayer* CBaseLayer::GetUnderLayer() { if ( !mp_UnderLayer ) { #ifdef _DEBUG TRACE( "[CBaseLayer::GetUnderLayer] There is not a UnerLayer..\n" ) ; #endif return NULL ; } return mp_UnderLayer ; } char* CBaseLayer::GetLayerName() { return m_pLayerName ; }
[ "dbstn1369@gmail.com" ]
dbstn1369@gmail.com
1fe286046b6c7dfcd1fa19ba09d8969740d12f51
b301ab714ad4d4625d4a79005a1bda6456a283ec
/POJ/1905.cpp
643a019710c27e262d98f47370a0eb51009be896
[]
no_license
askeySnip/OJ_records
220fd83d406709328e8450df0f6da98ae57eb2d9
4b77e3bb5cf19b98572fa6583dff390e03ff1a7c
refs/heads/master
2022-06-26T02:14:34.957580
2022-06-11T13:56:33
2022-06-11T13:56:33
117,955,514
1
0
null
null
null
null
UTF-8
C++
false
false
637
cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cstdio> #include <cstring> #include <set> #include <map> #include <cmath> using namespace std; double esp = 1e-5; int main() { ios::sync_with_stdio(false); cin.tie(0); double l, d, c; while(cin >> l >> d >> c){ if(l < 0 && d < 0 && c < 0) break; double ll = (1+d*c)*l; double low, high; double mid, r; low = 0; high = l/2; while(high - low > esp){ mid = (high + low) / 2; r = (4*mid*mid+l*l)/(8*mid); if(2*r*asin(l/(2*r)) < ll){ low = mid; }else { high = mid; } } printf("%.3f\n", mid); } return 0; }
[ "296181278@qq.com" ]
296181278@qq.com
b193f6ad403b970986689c58db11c9190a227866
3bbd76064ee4549228d7fc89c0666493c93bae4d
/code/01_points/model.cpp
4e7ace84d4b91e0931a8fddd70f5529b58f4c6f7
[]
no_license
Ant-Play/tinyrender
4a5594de84d533ea6a320c0d5f6c1546fefc587f
7f5f8e7226e77f152e69e10f8696022b2986344a
refs/heads/master
2023-04-13T03:16:32.949249
2021-01-03T01:17:40
2021-01-03T01:17:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
686
cpp
#include <iostream> #include <fstream> #include <sstream> #include "model.h" Model::Model(const char *filename): verts_() { std::ifstream in(filename, std::ifstream::in); if (in.is_open()) { std::string line; while (std::getline(in,line)) { char trash; std::istringstream iss(line); if(line.substr(0,2) == "v "){ iss >> trash; Vec3f v; for (int i = 0; i < 3; i++) iss >> v[i]; verts_.push_back(v); } } in.close(); } std::cout << "# v#" << verts_.size() << std::endl; } Model::~Model(){} int Model::nverts(){ return (int)verts_.size(); } Vec3f Model::vert(int i){ return verts_[i]; }
[ "abcyuxue123@126.com" ]
abcyuxue123@126.com
5869be1731883c8c43e1a1a05aad4872f13076e1
63a8dc03928ac350f578b4fece4cb581f1ba8fc4
/include/caffe/layers/anno_data_layer.hpp
7ca59fcf730a8c5886ec1bc18035b99f310db17c
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
bigning/caffe
8d43cc55e9baa6c215b24a34cc3daeb747a75f92
aa0e2477ff9091a00cd58e4708a076aaf3a4b940
refs/heads/master
2020-12-07T06:26:21.411494
2016-05-06T02:28:00
2016-05-06T02:28:00
56,088,184
0
0
null
2016-04-12T18:33:22
2016-04-12T18:33:21
null
UTF-8
C++
false
false
1,487
hpp
#ifndef ANNO_DATA_LAYER_HPP_ #define ANNO_DATA_LAYER_HPP_ #include <vector> #include <string> #include <map> #include "caffe/blob.hpp" #include "caffe/data_reader.hpp" #include "caffe/data_transformer.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" namespace caffe { template <typename Dtype> class AnnoDataLayer: public BasePrefetchingDataLayer<Dtype> { public: explicit AnnoDataLayer(const LayerParameter& param); virtual ~AnnoDataLayer(); virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // DataLayer uses DataReader instead for sharing for parallelism virtual inline bool ShareInParallel() const { return false; } virtual inline const char* type() const { return "AnnoData"; } virtual inline int ExactNumBottomBlobs() const { return 0; } virtual inline int MinTopBlobs() const { return 1; } virtual inline int MaxTopBlobs() const { return 2; } protected: virtual void load_batch(Batch<Dtype>* batch); //DataReader reader_; std::vector<std::vector<float> > read_and_transform_img(std::string& img_id, cv::Mat& img); // newly added member variable std::vector<std::string> list_vec_; int img_fetch_index_; //std::map<std::string, std::vector<std::vector<float> > > labels_; int ready_to_load_; }; } // namespace caffe #endif // CAFFE_AnnoDATA_LAYER_HPP_
[ "bigning1118@gmail.com" ]
bigning1118@gmail.com
ac32dbbe8f0fefde1ff6d9dfdc7b926693d108a3
a72a2e6a96adef9d7f6ad4b913f386c9a4a8e0a4
/lec-18/BinarySearchUsingRecursion.Cpp
5c7183e9ef35ec580ab254a9977eeb7ad959c6ae
[]
no_license
Mohit29061999/StAndrews-Cpp
dc9d5e022e7ce351682525974da7445e000c28fe
84025f53a2473ab3142f508fcbdd74e57662b0e8
refs/heads/master
2023-02-26T00:06:09.938805
2021-01-29T07:32:09
2021-01-29T07:32:09
298,160,687
18
6
null
null
null
null
UTF-8
C++
false
false
694
cpp
#include <iostream> using namespace std; int bs(int arr[],int n,int start,int end,int x){ if(start>end){ //ye case tab aayega jab saari values search ho return -1; //gyi hogi } // [1,2,3,4,5,6,7,8,9,10] int mid = (start+end)/2; //mid ka index nikala h if(arr[mid]==x){ return mid; } else if(arr[mid]>x){ //[1,2,3,4,5] return bs(arr,n,start,mid-1,x); //ignore the right half } else{ //[1,2,3,4,5] return bs(arr,n,mid+1,end,x); ////ignore the right half } } int main(){ int arr[]={1,2,3,4,5}; int n=5; //[1,2,3,4,5] cout << bs(arr,5,0,4,0); return 0; }
[ "noreply@github.com" ]
noreply@github.com
7b025ab0b608962813448fff9c6724ec07551806
a511497ea715c06a26c830fb230bf023db84aff5
/Communication.h
48b65f0c7807614187cf70cbc912a7af277438ee
[]
no_license
amirhammad/wireless433MHz
b0bc1609fa1bec82d65ed6a674989b2c6cfaa597
84c6ed0cc1829725623aa7f630daa34366e62249
refs/heads/master
2021-01-19T00:52:35.283506
2016-06-13T07:04:37
2016-06-13T07:04:37
61,014,595
0
0
null
null
null
null
UTF-8
C++
false
false
316
h
#pragma once #include <QObject> class Communication : public QObject { Q_OBJECT int m_fd; QByteArray m_buffer; int m_index; int m_sendIndex; void sendSync(); void parse(); public: Communication(QObject *parent = 0); private slots: void on_socketNotifier_activated(int fd); void on_timer_timeout(); };
[ "amir.hammad@hotmail.com" ]
amir.hammad@hotmail.com
bcf2f02e9b536061846d2ec4508e16de21e2e073
a4d8cb480cbdb196e79ce482f5f9221fc74855e2
/2009/20090728_appline_onestream.cpp
d653b2765503873be0283292980fe4476044d86e
[]
no_license
bonly/exercise
96cd21e5aa65e2f4c8ba18adda63c28a5634c033
dccf193a401c386719b8dcd7440d1f3bb74cb693
refs/heads/master
2020-05-06T13:51:29.957349
2018-02-10T16:14:52
2018-02-10T16:14:52
3,512,855
1
0
null
null
null
null
UTF-8
C++
false
false
794
cpp
#include <fstream> using namespace std; int main() { fstream fs; fs.open("/tmp/tek.txt",ios::out|ios::binary); fs << "line 333333333\n"; fs << "444444\n"; //fs.flush(); //fs.seekg(ios::beg); fs.close(); fs.open("/tmp/tek.txt",ios::in); ofstream is; is.open("/tmp/tekret.txt",ios::out); is << "over write 111111\n"; is << "write 2222 end\n"; char c=0; while(fs.get(c).good()) { is << c; } fs.close(); is.close(); return 0; } /* 写完后关闭文件再重新读入并补到另一文件中 flush()了再读不起作用,需close开open 来读 int get(); istream& get ( char& c ); istream& get ( char* s, streamsize n ); istream& get ( char* s, streamsize n, char delim ); istream& get ( streambuf& sb); istream& get ( streambuf& sb, char delim ); */
[ "bonly@163.com" ]
bonly@163.com
4e1e17bf42eed4453f56b0c1541a1c7b17c82537
6e9f140ae0ab51bfcb4a2238dacea893de39f22b
/src/UnitTestPRD/UnitTestPRD.cpp
18d38f879edc64db898d365b256c760a3d7ee2f4
[]
no_license
YohanDerenne/PRD-Operational-Research
cf55e6965500cdd753c753d9d9aec72e50e45109
0db264536e585dc340a7fa52863ba6bc0b02a8ae
refs/heads/main
2023-04-14T00:57:58.886194
2021-04-14T15:53:51
2021-04-14T15:53:51
316,169,441
0
0
null
null
null
null
ISO-8859-1
C++
false
false
17,621
cpp
#include "pch.h" #include "CppUnitTest.h" #include "../PRD/Instance.h" #include "../PRD/Instance.cpp" #include <string> #include "../PRD/Result.h" #include "../PRD/Result.cpp" #include "../PRD/SolverControler.h" #include "../PRD/SolverControler.cpp" #include "../PRD/Solver.h" #include "../PRD/Solver.cpp" #include "../PRD/Solution.h" #include "../PRD/Solution.cpp" #include "../PRD/SolutionPSO.h" #include "../PRD/SolutionPSO.cpp" #include "../PRD/PSO.h" #include "../PRD/PSO.cpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTestPRD { /// <summary> /// Tests de la classe Instance /// </summary> TEST_CLASS(UnitTestInstance) { public: /// <summary> /// Test si le parseur fonctionne bien /// </summary> TEST_METHOD(TestParseur) { Instance instance = Instance(); try { bool result = instance.Parse("../UnitTestPRD/instanceTest/I_n6_id2.txt"); Assert::AreEqual(true, result,L"Aucun problème n'est attendu"); // Premiers parametres Assert::AreEqual(6, instance.n); Assert::AreEqual(5, instance.m); Assert::AreEqual(4000, instance.c_V); Assert::AreEqual(2, instance.id); vector<pair<int, int>> coord; // Coordonnées producteur coord.push_back({ 122,281 }); // Coordonnées livreur coord.push_back({ 119,88 }); // Commande 0 int numCmd = 0; Assert::AreEqual(51.0, instance.p[0][numCmd]); Assert::AreEqual(24.0, instance.p[1][numCmd]); Assert::AreEqual(85.0, instance.p[2][numCmd]); Assert::AreEqual(45.0, instance.p[3][numCmd]); Assert::AreEqual(17.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(2, instance.h_WIP[1][numCmd]); Assert::AreEqual(4, instance.h_WIP[2][numCmd]); Assert::AreEqual(6, instance.h_WIP[3][numCmd]); Assert::AreEqual(7, instance.h_WIP[4][numCmd]); Assert::AreEqual(9, instance.h_FIN[numCmd]); Assert::AreEqual(71, instance.d[numCmd]); Assert::AreEqual(9, instance.p_M[numCmd]); coord.push_back({ 149,154 }); // Commande 1 numCmd = 1; Assert::AreEqual(1.0, instance.p[0][numCmd]); Assert::AreEqual(99.0, instance.p[1][numCmd]); Assert::AreEqual(35.0, instance.p[2][numCmd]); Assert::AreEqual(64.0, instance.p[3][numCmd]); Assert::AreEqual(7.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(1, instance.h_WIP[1][numCmd]); Assert::AreEqual(2, instance.h_WIP[2][numCmd]); Assert::AreEqual(4, instance.h_WIP[3][numCmd]); Assert::AreEqual(5, instance.h_WIP[4][numCmd]); Assert::AreEqual(6, instance.h_FIN[numCmd]); Assert::AreEqual(91, instance.d[numCmd]); Assert::AreEqual(9, instance.p_M[numCmd]); coord.push_back({ 128,129 }); // Commande 2 numCmd = 2; Assert::AreEqual(53.0, instance.p[0][numCmd]); Assert::AreEqual(94.0, instance.p[1][numCmd]); Assert::AreEqual(8.0, instance.p[2][numCmd]); Assert::AreEqual(79.0, instance.p[3][numCmd]); Assert::AreEqual(78.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(1, instance.h_WIP[1][numCmd]); Assert::AreEqual(3, instance.h_WIP[2][numCmd]); Assert::AreEqual(4, instance.h_WIP[3][numCmd]); Assert::AreEqual(6, instance.h_WIP[4][numCmd]); Assert::AreEqual(7, instance.h_FIN[numCmd]); Assert::AreEqual(123, instance.d[numCmd]); Assert::AreEqual(10, instance.p_M[numCmd]); coord.push_back({ 153,283 }); // Commande 3 numCmd = 3; Assert::AreEqual(13.0, instance.p[0][numCmd]); Assert::AreEqual(8.0, instance.p[1][numCmd]); Assert::AreEqual(84.0, instance.p[2][numCmd]); Assert::AreEqual(76.0, instance.p[3][numCmd]); Assert::AreEqual(52.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(1, instance.h_WIP[1][numCmd]); Assert::AreEqual(2, instance.h_WIP[2][numCmd]); Assert::AreEqual(3, instance.h_WIP[3][numCmd]); Assert::AreEqual(5, instance.h_WIP[4][numCmd]); Assert::AreEqual(6, instance.h_FIN[numCmd]); Assert::AreEqual(441, instance.d[numCmd]); Assert::AreEqual(9, instance.p_M[numCmd]); coord.push_back({ 103,234 }); // Commande 4 numCmd = 4; Assert::AreEqual(86.0, instance.p[0][numCmd]); Assert::AreEqual(54.0, instance.p[1][numCmd]); Assert::AreEqual(67.0, instance.p[2][numCmd]); Assert::AreEqual(21.0, instance.p[3][numCmd]); Assert::AreEqual(27.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(2, instance.h_WIP[1][numCmd]); Assert::AreEqual(3, instance.h_WIP[2][numCmd]); Assert::AreEqual(5, instance.h_WIP[3][numCmd]); Assert::AreEqual(6, instance.h_WIP[4][numCmd]); Assert::AreEqual(8, instance.h_FIN[numCmd]); Assert::AreEqual(449, instance.d[numCmd]); Assert::AreEqual(7, instance.p_M[numCmd]); coord.push_back({ 239,138 }); // Commande 5 numCmd = 5; Assert::AreEqual(47.0, instance.p[0][numCmd]); Assert::AreEqual(25.0, instance.p[1][numCmd]); Assert::AreEqual(4.0, instance.p[2][numCmd]); Assert::AreEqual(66.0, instance.p[3][numCmd]); Assert::AreEqual(20.0, instance.p[4][numCmd]); Assert::AreEqual(0, instance.h_WIP[0][numCmd]); Assert::AreEqual(1, instance.h_WIP[1][numCmd]); Assert::AreEqual(3, instance.h_WIP[2][numCmd]); Assert::AreEqual(5, instance.h_WIP[3][numCmd]); Assert::AreEqual(6, instance.h_WIP[4][numCmd]); Assert::AreEqual(7, instance.h_FIN[numCmd]); Assert::AreEqual(536, instance.d[numCmd]); Assert::AreEqual(5, instance.p_M[numCmd]); coord.push_back({ 215,228 }); // Distances vector<vector<double>> t; for (size_t i = 0; i < coord.size() ; i++) { vector<double> row; for (size_t j = 0; j < coord.size(); j++) { row.push_back(sqrt(pow(coord[i].first - coord[j].first, 2) + pow(coord[i].second - coord[j].second, 2))); } t.push_back(row); } // Check for (int i = 0; i < instance.n + 1; i++) { for (int j = 0; j < instance.n + 1; j++) { Assert::AreEqual(t[i][j], instance.t[i][j]); } } } catch (const std::exception& exc) { Assert::Fail(L"Exception non attendue"); } } /// <summary> /// Test du parseur avec un chemin invalide /// </summary> TEST_METHOD(TestInvalidPathParse) { Instance instance = Instance(); try { bool result = instance.Parse("../UnitTestPRD/instanceTest/unknow.txt"); Assert::Fail(L"Une exception d'argument invalide est attendu"); } catch (const std::invalid_argument& ia) { } catch (const std::exception&) { Assert::Fail(L"Une exception d'argument invalide est attendu"); } } /// <summary> /// Test si le parseur releve bien une exception sur des fichiers ou le format n'est pas bon /// </summary> TEST_METHOD(TestBadInstanceParse) { Instance instance = Instance(); try { bool result = instance.Parse("../UnitTestPRD/badInstanceTest/I_n6_id2.txt"); Assert::Fail(L"Une exception est attendu"); } catch (const std::invalid_argument& ia) { Assert::Fail(L"Une autre exception est attendu"); } catch (const std::exception& exc) { cerr << exc.what(); } try { bool result = instance.Parse("../UnitTestPRD/badInstanceTest/I_n8_id4.txt"); Assert::Fail(L"Une exception est attendu"); } catch (const std::invalid_argument& ia) { Assert::Fail(L"Une autre exception est attendu"); } catch (const std::exception& exc) { cerr << exc.what(); } } /// <summary> /// Test le constructeur de copie de la classe Instance /// </summary> TEST_METHOD(TestCopyInstance) { Instance* inst1 = new Instance(); try { bool result = inst1->Parse("../UnitTestPRD/instanceTest/I_n6_id2.txt"); Instance* inst2 = new Instance(*inst1); Assert::AreEqual(51.0, inst2->p[0][0]); delete inst1; Assert::AreEqual(1.0, inst2->p[0][1]); delete inst2; } catch (exception exc) { //cerr << exc.what(); } } }; /// <summary> /// Test les elements de la classe Result /// </summary> TEST_CLASS(UnitTestResult) { public: /// <summary> /// Test le constructeur de copie de la classe Result /// </summary> TEST_METHOD(TestCopyResult) { Instance* instance = new Instance(); try { bool result = instance->Parse("../UnitTestPRD/instanceTest/I_n6_id2.txt"); Result* res1 = new Result(*instance); Result* res2 = new Result(*res1); //Assert::AreNotEqual(res1, res2); Assert::AreEqual(51.0, res2->inst.p[0][0]); Assert::AreEqual(res1->IC_WIP, res2->IC_WIP); delete res1; Assert::AreEqual(1.0, res2->inst.p[0][1]); delete res2; } catch (exception exc) { //cerr << exc.what(); } delete instance; } }; /// <summary> /// Test les elements de la classe SolverControler /// </summary> TEST_CLASS(UnitTestSolverControler) { public: TEST_METHOD(TestImportDirectory) { SolverControler control = SolverControler(); Assert::AreEqual(true,control.ImportInstances("../UnitTestPRD/instanceTest")); list<Instance> list = control.getInstances(); auto it = list.begin(); std::advance(it, 0); Instance inst = *it; size_t expected_size = 3; Assert::AreEqual(expected_size, control.getInstances().size()); Assert::AreEqual(51.0, inst.p[0][0]); std::advance(it, 1); inst = *it; Assert::AreEqual(47.0, inst.p[0][0]); } TEST_METHOD(TestExportResults) { remove("../UnitTestPRD/resultTest/resultat.txt"); // Init SolverControler control = SolverControler(); control.ImportInstances("../UnitTestPRD/instanceTest"); list<Instance> list = control.getInstances(); auto it = list.begin(); std::advance(it, 0); Instance inst = *it; Result res1 = Result(inst); std::advance(it, 1); inst = *it; Result res2 = Result(inst); res1.IC_FIN = 123; res1.PPC_M = 456; res1.cout_total = 626; res1.IC_WIP = 47; res1.nb_part = 15; res1.cout_ref = 700; res1.dureeSec = 20; res2.IC_FIN = 78; res2.PPC_M = 98; res2.cout_total = 231; res2.IC_WIP = 55; res2.nb_part = 5; res2.cout_ref = 800; res2.dureeSec = 25; control.AddResult(res1); control.AddResult(res2); // Export Assert::AreEqual(true,control.ExportResults("../UnitTestPRD/resultTest/resultat.txt")); // Check ifstream file; file.open("../UnitTestPRD/resultTest/resultat.txt"); if (!file) { Assert::Fail(L"Ne retrouve pas le fichier résultat"); } int n; int id; int nb_p; double cr; double cs; double t; // Skip header string header; for (int i = 0; i < 6; i++) { file >> header; } file >> n; file >> id; file >> nb_p; file >> cr; file >> cs; file >> t; Assert::AreEqual(2,id); Assert::AreEqual(6, n); Assert::AreEqual(15, nb_p); Assert::AreEqual(700.0, cr); Assert::AreEqual(626.0, cs); Assert::AreEqual(20.0, t); file >> n; file >> id; file >> nb_p; file >> cr; file >> cs; file >> t; Assert::AreEqual(8, n); Assert::AreEqual(4, id); Assert::AreEqual(5, nb_p); Assert::AreEqual(800.0, cr); Assert::AreEqual(231.0, cs); Assert::AreEqual(25.0, t); file.close(); } TEST_METHOD(TestExportResultsBadPath) { SolverControler control = SolverControler(); Instance inst = Instance(); Result res1 = Result(inst); control.AddResult(res1); try { Assert::AreEqual(false, control.ExportResults("../UnitTestPRD/resultTest/resultat.data")); Assert::Fail(L"Une exception est attendue"); } catch (exception exc) { } try { Assert::AreEqual(false, control.ExportResults("../UnitTestPRD/resultTest/resultat")); Assert::Fail(L"Une exception est attendue"); } catch (exception exc) { } try { Assert::AreEqual(false, control.ExportResults("../UnitTestPRD/resultTest/")); Assert::Fail(L"Une exception est attendue"); } catch (exception exc) { } Assert::AreEqual(true, control.ExportResults("../UnitTestPRD/resultTest/resTmp.txt")); try { Assert::AreEqual(false, control.ExportResults("../UnitTestPRD/resultTest/resTmp.txt")); Assert::Fail(L"Une exception est attendue"); } catch (exception exc) { } remove("../UnitTestPRD/resultTest/resTmp.txt"); } TEST_METHOD(TestImportDirWithBadFormat) { SolverControler control = SolverControler(); try { control.ImportInstances("../UnitTestPRD/BadInstanceTest"); Assert::Fail(L"Une exception est attendue"); } catch (exception exc) { } } }; TEST_CLASS(UnitTestSolution) { public: TEST_METHOD(TestDecode) { // === INSTANCE Instance inst = Instance(); inst.m = 3; inst.n = 5; inst.p = vector<vector<double>>(inst.m, vector<double>(inst.n, 1)); inst.d = vector<int>(inst.n, 13); inst.h_WIP = vector<vector<int>>(inst.m, vector<int>(inst.n, 1)); inst.t = vector<vector<double>>(inst.n+2, vector<double>(inst.n+2, 1)); inst.p_M = vector<int>(inst.n, 3); inst.h_FIN = vector<int>(inst.n, 2); inst.c_V = 5; // === SOLUTION Solution sol = Solution(inst); sol.sv1.push_back(-0.8); sol.sv1.push_back(3.7); sol.sv1.push_back(-1.5); sol.sv1.push_back(2.3); sol.sv1.push_back(1.1); sol.sv2.push_back(0.2); sol.sv2.push_back(1.8); sol.sv2.push_back(2.7); sol.sv2.push_back(0.6); sol.sv2.push_back(1.2); sol.sv3 = vector<vector<double>>(inst.m, vector<double>(inst.n, 1)); // === RESULT sol.Decode(); sol.DecodeXY(); Result res = sol.resultatDecode; Assert::AreEqual(2, sol.ordre[0]); Assert::AreEqual(0, sol.ordre[1]); Assert::AreEqual(4, sol.ordre[2]); Assert::AreEqual(3, sol.ordre[3]); Assert::AreEqual(1, sol.ordre[4]); Assert::AreEqual(0, sol.affectV[0]); Assert::AreEqual(2, sol.affectV[1]); Assert::AreEqual(3, sol.affectV[2]); Assert::AreEqual(1, sol.affectV[3]); Assert::AreEqual(1, sol.affectV[4]); Assert::AreEqual(10.0, res.C[0][1]); Assert::AreEqual(14.0, res.C[2][1]); Assert::AreEqual(10.0, res.IC_WIP); Assert::AreEqual(4.0, res.IC_FIN); Assert::AreEqual(8.0, res.F[0]); Assert::AreEqual(12.0, res.F[1]); Assert::AreEqual(14.0, res.F[2]); Assert::AreEqual(6.0, res.F[3]); Assert::AreEqual(14.0, res.IC); Assert::AreEqual(9.0, res.PPC_M); Assert::AreEqual(20, res.VC); Assert::AreEqual(43.0, res.cout_total); Assert::AreEqual(true,res.VerificationContraintes()); } TEST_METHOD(TestDecode2) { // === INSTANCE Instance inst = Instance(); inst.m = 3; inst.n = 5; inst.p = vector<vector<double>>(inst.m, vector<double>(inst.n, 1)); inst.d = vector<int>(inst.n, 13); inst.h_WIP = vector<vector<int>>(inst.m, vector<int>(inst.n, 1)); inst.t = vector<vector<double>>(inst.n+2, vector<double>(inst.n+2, 1)); inst.p_M = vector<int>(inst.n, 1); inst.h_FIN = vector<int>(inst.n, 2); inst.c_V = 5; // modif inst.h_WIP[1][0] = 2; inst.p[1][2] = 3; inst.d[0] = 7; inst.t[3 + 2][4 + 2] = 3; inst.t[4 + 2][3 + 2] = 3; inst.t[0][0 + 2] = 2; inst.t[0 + 2][0] = 2; inst.p_M[1] = 4; inst.h_FIN[4] = 1; // === SOLUTION Solution sol = Solution(inst); sol.sv1.push_back(-0.8); sol.sv1.push_back(3.7); sol.sv1.push_back(-1.5); sol.sv1.push_back(2.3); sol.sv1.push_back(1.1); sol.sv2.push_back(0.2); sol.sv2.push_back(1.8); sol.sv2.push_back(2.7); sol.sv2.push_back(0.6); sol.sv2.push_back(1.2); sol.sv3 = vector<vector<double>>(inst.m, vector<double>(inst.n, 0)); // Modif sol.sv3[0][2] = 1; sol.sv3[1][2] = 2; sol.sv3[2][2] = 1; sol.sv3[1][0] = 1; // === RESULT Result res = sol.Decode(); Assert::AreEqual(2, sol.ordre[0]); Assert::AreEqual(0, sol.ordre[1]); Assert::AreEqual(4, sol.ordre[2]); Assert::AreEqual(3, sol.ordre[3]); Assert::AreEqual(1, sol.ordre[4]); Assert::AreEqual(10.0, res.F[0]); Assert::AreEqual(12.0, res.F[1]); Assert::AreEqual(13.0, res.F[2]); Assert::AreEqual(9.0, res.F[3]); Assert::AreEqual(-1.0, res.F[4]); Assert::AreEqual(28.0, res.IC_WIP); Assert::AreEqual(1.0, res.IC_FIN); Assert::AreEqual(29.0, res.IC); Assert::AreEqual(12.0, res.PPC_M); Assert::AreEqual(20, res.VC); Assert::AreEqual(29.0+12.0+20.0, res.cout_total); sol.DecodeXY(); Assert::AreEqual(true, sol.resultatDecode.VerificationContraintes()); } }; TEST_CLASS(UnitTestPSO) { public: TEST_METHOD(TestPSO) { Instance inst = Instance("../UnitTestPRD/I_n20_id0.txt"); PSO solver = PSO(inst, 5, 20); Result res = solver.Solve(); Result ref = solver.GetReference(); string log = "Durée résolution : " + std::to_string(res.dureeSec); log += "\nDernieres particules : " + std::to_string(solver.particules[2].resultatDecode.cout_total); log += "\nBest particule : " + std::to_string(res.cout_total); log += "\nRef : " + std::to_string(ref.cout_total); Logger::WriteMessage(log.c_str()); Assert::AreEqual(true, res.VerificationContraintes()); //Assert::AreEqual(true, res.cout_total < solver.GetReference().cout_total); } TEST_METHOD(TestReference) { Instance inst = Instance("../UnitTestPRD/I_n5_id0.txt"); PSO solver = PSO(inst, 200, 40); Result ref = solver.GetReference(); string log = "Cout total ref : " + std::to_string(ref.cout_total); Logger::WriteMessage(log.c_str()); Assert::AreEqual(true, ref.VerificationContraintes()); } }; }
[ "yohan.derenne@gmail.com" ]
yohan.derenne@gmail.com
be1b8757573badebddbfbe533ddce6baa76e4d2b
ddc2551fa7665a63cf26291442ed409e03b5e218
/.Sincrono/Report/paper.cpp
9e0eeb5c075612db7f3e6787d613271859ade1b8
[]
no_license
kapyderi/recoverdrake-v3
41052a7c86e3f25d7cde174e1269e60ed9528164
e75375b692d5d7cc7dc224d55cd3c8329d4956b0
refs/heads/master
2020-06-08T16:26:57.305002
2015-02-14T01:34:41
2015-02-14T01:34:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,353
cpp
#include "paper.h" #include "sectioneditordlg.h" #include <QKeyEvent> struct _size { double width; double heigth; }; _size StandarSizes [] = { {841 , 1189},{594 , 841},{420 , 594},{297 , 420}, {210 , 297}, {148 , 210},{105 , 148},{74 , 105}, {52 , 74}, {37 , 52}, {1000 , 1414}, {707 , 1000}, {500 , 707}, {353 , 500}, {250 , 353}, {176 , 250}, {125 , 176}, {88 , 125}, {62 , 88}, {33 , 62}, {31 , 44}, {163 , 229}, {105 , 241}, {110 , 220}, {190.5 , 254}, {210 , 330}, {431.8 , 279.4},{215.9 , 355.6}, {215.9 , 279.4},{279.4 , 431.8 } }; Paper::Paper(QGraphicsItem *parent) : QGraphicsRectItem(parent) { _inserting = false; mySize = A4; m_orientacion = Retrato; CFondo = Qt::NoBrush; } QRectF Paper::margin() { return QRectF(cmToPx(margenSuperior()), cmToPx(margenSuperior()), this->rect().width() - cmToPx(margenSuperior()) - cmToPx(margenSuperior())- 5, this->rect().height()- cmToPx(margenSuperior()) - cmToPx(margenSuperior())- 5); } QRectF Paper::paper() { return QRectF(0, 0, this->rect().width() - 5, this->rect().height()- 5); } Paper::_Sizes Paper::StandartSize() { return mySize; } Paper::_Orientacion Paper::Orientacion() const { return m_orientacion; } void Paper::setOrientacion(Paper::_Orientacion arg) { if (m_orientacion != arg) { QRectF r = this->rect(); this->setRect(0,0, r.height(),r.width()); m_orientacion = arg; emit orientacionChanged(arg); } } void Paper::setMargen(double arg) { setmargenDerecho(arg); setmargenIzquierdo(arg); setmargenSuperior(arg); setmargenInferior(arg); } void Paper::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QRectF r = this->rect(); painter->fillRect(5,5,r.width()-5,r.height()-5,Qt::black); painter->fillRect(0,0,r.width()-5,r.height()-5,Qt::white); painter->fillRect(margin(),CFondo); painter->drawRect(0,0,r.width()-5,r.height()-5); painter->setPen(Qt::DotLine); painter->drawRect(margin()); } void Paper::Fondo(QBrush fondo) { CFondo = fondo; CFondo.setColor(Qt::gray); } void Paper::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(_inserting) { if(margin().contains(event->pos())) { if(seccionPool.isEmpty()) { QMessageBox::warning(qApp->activeWindow(),tr("Sin secciones seleccionadas"),tr("Inserta una seccion desde el menu o doble click en el area de trabajo.")); emit itemInserted(); return; } _insertingPoint = event->pos(); QList<Section*>::Iterator it; Section * target; for(it = seccionPool.begin();it!= seccionPool.end();++it) { target = (*it); if( mapRectToItem(this,QRectF(target->pos(),target->rect().size())).contains( mapToItem(this,_insertingPoint) )) break; } switch (_insertingType) { case Paper::Campo: insertCampo(target); break; case Paper::Imagen: insertImagen(target); break; case Paper::Linea: insertLinea(target); break; case Paper::Label: insertLabel(target); break; case RoundRectIt: insertRoundRect(target); break; case Paper::CodeBarIt: insertCodeBar(target); break; case Paper::CampoRelacional: insertCampoRelacional(target); break; case Paper::Acumulador: insertAcumulador(target); break; case Paper::Parametro: insertParametro(target); break; default: break; } emit itemInserted(); } } else { QList<QGraphicsItem*> list = this->scene()->selectedItems(); for(int i=0; i<list.size();i++) list.at(i)->setSelected(false); } } void Paper::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event); SectionEditorDlg dlg(this,qApp->activeWindow()); dlg.exec(); } void Paper::Seccion() { SectionEditorDlg dlg(this,qApp->activeWindow()); dlg.exec(); } qreal Paper::cmToPx(double cm) { double inch = cm * 0.3937008; return inch * 96.0; } qreal Paper::pxTocm(int px) { double inch = px/96.0; return inch/0.3937008; } void Paper::insertRoundRect(Section * sec) { QString name = QString("rect_%1").arg(qrand()); RoundedRect * rect = new RoundedRect(name,this); rect->setMargins(this->margin()); rect->setSize(100,100); rect->setPos(_insertingPoint.x()-50,_insertingPoint.y()-50); connect(rect,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(rect); itemPool.append(rect); } void Paper::insertLabel(Section * sec) { QString name = QString("txt_%1").arg(qrand()); CustomLabel * rect = new CustomLabel(name,this); rect->setMargins(this->margin()); rect->setSize(100,15); rect->setPos(_insertingPoint.x()-20,_insertingPoint.y()-7); rect->setText(tr("Prueba de texto: Tamaño, orientacion, tipo de letra, color, posicion, negrita, cursiva, subrayado, centrada, etc.")); rect->setfontSize(10); connect(rect,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(rect); itemPool.append(rect); } void Paper::insertLinea(Section * sec) { QString name = QString("lin_%1").arg(qrand()); ReportLine * line = new ReportLine (name,this); line->setMargins(this->margin()); line->setSize(200,15); line->setPos(_insertingPoint.x()-100,_insertingPoint.y()-7); connect(line,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(line); itemPool.append(line); } void Paper::insertImagen(Section * sec ) { QString name = QString("img_%1").arg(qrand()); ReportImage * img = new ReportImage(name,this); img->setruta("/usr/share/RecoverDrake/logo.png"); img->setMargins(this->margin()); img->setPos(_insertingPoint.x()-50,_insertingPoint.y()-7); connect(img,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(img); itemPool.append(img); } void Paper::insertCampo(Section * sec) { QString name = QString("cam_%1").arg(qrand()); ReportField * fld = new ReportField(name,this); fld->setMargins(this->margin()); fld->setSize(100,20); fld->setPos(_insertingPoint.x()-50,_insertingPoint.y()-7); connect(fld,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(fld); itemPool.append(fld); } void Paper::insertCodeBar(Section * sec) { QString name = QString("cod_%1").arg(qrand()); CodeBar* code = new CodeBar(name,this); code->setMargins(this->margin()); code->setcode("*123456789*"); code->setvisibleCode(true); code->setPos(_insertingPoint.x()-100,_insertingPoint.y()-7); connect(code,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(code); itemPool.append(code); } void Paper::insertCampoRelacional(Section * sec) { QString name = QString("rel_%1").arg(qrand()); RelationalField * fld = new RelationalField(name,this) ; fld->setMargins(this->margin()); fld->setSize(150,20); fld->setPos(_insertingPoint.x()-50,_insertingPoint.y()-7); connect(fld,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(fld); itemPool.append(fld ); } void Paper::insertParametro(Section *sec) { QString name = QString("para_%1").arg(qrand()); reportParama * fld = new reportParama(name,this) ; fld->setMargins(this->margin()); fld->setSize(150,20); fld->setText(":fecha"); fld->setPos(_insertingPoint.x()-50,_insertingPoint.y()-7); connect(fld,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(fld); itemPool.append(fld ); } void Paper::insertAcumulador(Section *sec) { QString name = QString("acum_%1").arg(qrand()); ReportAcumulator * fld = new ReportAcumulator(name,this) ; fld->setMargins(this->margin()); fld->setSize(150,20); fld->setPos(_insertingPoint.x()-50,_insertingPoint.y()-7); connect(fld,SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); sec->_items.append(fld); itemPool.append(fld ); } double Paper::margenSuperior() const { return m_margenSuperior; } int Paper::SFondo() const { if (CFondo.style() == Qt::NoBrush) return 0; else return 1; } void Paper::setSize(double w, double h) { this->setRect(0,0,cmToPx(w)+5,cmToPx(h)+5); scene()->setSceneRect(-10,-10,rect().width()+200,rect().height()+15); } void Paper::_insertSection(Section *sec) { if(seccionPool.isEmpty()) seccionPool.append(sec); else { bool inserted = false; Section::SectionType type = sec->sectionType(); for(int i=0;i<seccionPool.size();i++) { if(seccionPool.at(i)->sectionType() > type) { seccionPool.insert(i,sec); inserted = true; break; } } if(!inserted) seccionPool.append(sec); } } void Paper::reCalculateSeccion(Section * secSender) { int position = margin().top(); int final = 0; QPair<Section *,int> maxHeigth; QListIterator<Section*> it(seccionPool); while (it.hasNext()) { Section* sec = it.next(); qreal oldP = sec->pos().ry(); qreal diff = position-oldP; sec->setvPos(position); position += sec->Height()+1; QList<Container *>::Iterator itemIt; for(itemIt = sec->_items.begin();itemIt != sec->_items.end();++itemIt) (*itemIt)->setPos((*itemIt)->pos().rx(),(*itemIt)->pos().ry()+diff); if(sec->Height() > maxHeigth.second) { maxHeigth.first = sec; maxHeigth.second = sec->Height(); } if(!it.hasNext()) final = position ; } if (final > margin().bottom()) { int diff = final - margin().bottom(); if(secSender->Height() > diff) { secSender->setOnMaxsize(true); secSender->setHeight(secSender->Height() - diff); int position = margin().top(); QListIterator<Section*> it(seccionPool); while(it.hasNext()) { Section* sec = it.next(); sec->setvPos(position); position += sec->Height()+1; } } else { maxHeigth.first->setHeight(maxHeigth.second - diff); int position = margin().top(); QListIterator<Section*> it(seccionPool); while(it.hasNext()) { Section* sec = it.next(); sec->setvPos(position); position += sec->Height()+1; } } } } void Paper::itemMoved(Container * cont) { QPointF pos = cont->pos(); QList<Section *>::Iterator it; Section * oldSection = 0; Section * newSection = 0; for(it = seccionPool.begin();it != seccionPool.end(); ++it) { Section * aux = *it; if(aux->_items.contains(cont)) oldSection = aux; if(mapRectToItem(this,QRectF(aux->pos(),aux->rect().size())).contains(pos)) newSection = aux; } if(oldSection == newSection) return; if(oldSection) oldSection->_items.removeOne(cont); if(newSection) newSection->_items.append(cont); } void Paper::setSize(_Sizes siz, double w, double h, _Orientacion o) { Q_UNUSED(w); Q_UNUSED(h); mySize = siz; if(siz != QPrinter::Custom) { if(o== Retrato) this->setSize(StandarSizes[siz].width/10 , StandarSizes[siz].heigth/10); else this->setSize(StandarSizes[siz].heigth/10 , StandarSizes[siz].width/10); } } bool Paper::addSection(QString nombre, Section::SectionType type) { bool valid = true; QListIterator<Section*> it(seccionPool); while (it.hasNext()) { if(it.next()->SectionName() == nombre) { valid = false; break; } } if(!valid) return false; if(type != Section::Detail && type!= Section::PageHeader && type!=Section::PageFooter) { Section * seccion = new Section(this); seccion->setType(type); seccion->setSectionName(nombre); seccion->setMargin(margin()); if(seccionPool.isEmpty()) { seccionPool.append(seccion); seccion->setvPos(margin().top()); } else { switch (type) { case Section::ReportHeader: seccionPool.prepend(seccion); break; case Section::PageFooter: case Section::Detail: _insertSection(seccion); break; default: seccionPool.append(seccion); break; } reCalculateSeccion(seccion); } connect(seccion,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } else if(type==Section::Detail) { DetailSection * seccion = new DetailSection(this); seccion->setType(type); seccion->setSectionName(nombre); seccion->setMargin(margin()); if(seccionPool.isEmpty()) { seccionPool.append(seccion); seccion->setvPos(margin().top()); } else { _insertSection(seccion); reCalculateSeccion(seccion); } connect(seccion,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } else if(type==Section::PageFooter) { PageHeaderSection * seccion = new PageHeaderSection(this); seccion->setType(type); seccion->setSectionName(nombre); seccion->setMargin(margin()); if(seccionPool.isEmpty()) { seccionPool.append(seccion); seccion->setvPos(margin().top()); } else { _insertSection(seccion); reCalculateSeccion(seccion); } connect(seccion,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } else { PageHeaderSection * seccion = new PageHeaderSection(this); seccion->setType(type); seccion->setSectionName(nombre); seccion->setMargin(margin()); if(seccionPool.isEmpty()) { seccionPool.append(seccion); seccion->setvPos(margin().top()); } else { _insertSection(seccion); reCalculateSeccion(seccion); } connect(seccion,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } return true; } void Paper::removeSection(QString nombre) { QListIterator<Section*> it(seccionPool); while (it.hasNext()) { Section* sec = it.next(); if(sec->SectionName() == nombre) { seccionPool.removeOne(sec); sec->deleteLater(); } } reCalculateSeccion(); } void Paper::prepareItemInsert(itemType type) { _insertingType = type; _inserting = true; } void Paper::stopInsertingItems() { _inserting = false; } bool Paper::parseXML(QString xml, QString & error) { QListIterator<Section*> secIt(seccionPool); QListIterator<Container*> itemIt(itemPool); while(secIt.hasNext()) secIt.next()->deleteLater(); while(itemIt.hasNext()) itemIt.next()->deleteLater(); seccionPool.clear(); itemPool.clear(); QString errorStr; int errorLine; int errorColumn; QDomDocument doc; if (!doc.setContent(xml, false, &errorStr, &errorLine, &errorColumn)) { error = QString(tr("Error: Error de analisis en linea %1, columna %2 : %3")).arg(errorLine).arg(errorColumn).arg(errorStr); return false; } else { QDomElement root = doc.documentElement(); if (root.tagName() != "RDReports") { error = tr("Error: No es un archivo RDReports valido"); return false; } else { QDomNode child = root.firstChild(); while (!child.isNull()) { QDomNode sections = child.firstChild(); while (!sections.isNull()) { QDomElement secEle = sections.toElement(); if(secEle.tagName() == "Size") this->setSize(secEle.attribute("w").toDouble(),secEle.attribute("h").toDouble()); if(secEle.tagName() == "Size") this->m_orientacion = secEle.attribute("type") == "V" ? Retrato : Apaisado; else if(secEle.tagName() == "Margin") { this->setmargenDerecho(secEle.attribute("rigth").toDouble()); this->setmargenIzquierdo(secEle.attribute("left").toDouble()); this->setmargenSuperior(secEle.attribute("top").toDouble()); this->setmargenInferior(secEle.attribute("bottom").toDouble()); } else if(secEle.tagName() == "Section") { int typeOfSection = secEle.attribute("id").toDouble(); Section::SectionType type = static_cast<Section::SectionType>(typeOfSection); if(type != Section::Detail && type != Section::PageHeader && type != Section::PageFooter) { Section * sec = new Section(this); sec->setHeight(secEle.attribute("size").toDouble()); sec->setSectionName(secEle.attribute("name")); sec->setMargin(margin()); sec->setType(type); _insertSection(sec); reCalculateSeccion(sec); sec->parseXml(secEle.firstChild().toElement(), itemPool); connect(sec,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } else if(type == Section::Detail) { DetailSection* sec = new DetailSection(this); sec->setHeight(secEle.attribute("size").toDouble()); sec->setSectionName(secEle.attribute("name")); sec->setType(type); sec->setMargin(margin()); sec->setSqlGlobal(secEle.attribute("SqlGlobal")); sec->setSqlInterno(secEle.attribute("SqlInterno")); sec->setClausulaInterna(secEle.attribute("ClausulaInterna")); sec->setcolorear(secEle.attribute("colored").toDouble()); sec->setcolor1(sec->ColorFromString(secEle.attribute("color1"))); sec->setuse2Colors(secEle.attribute("alternative").toDouble()); sec->setcolor2(sec->ColorFromString(secEle.attribute("color2"))); _insertSection(sec); reCalculateSeccion(sec); connect(sec,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); sec->parseXml(secEle.firstChild().toElement(), itemPool); } else { PageHeaderSection * sec = new PageHeaderSection(this); sec->setOnFisrtPage(secEle.attribute("OnFistPage").toDouble()); sec->setHeight(secEle.attribute("size").toDouble()); sec->setSectionName(secEle.attribute("name")); sec->setMargin(margin()); sec->setType(type); _insertSection(sec); reCalculateSeccion(sec); sec->parseXml(secEle.firstChild().toElement(), itemPool); connect(sec,SIGNAL(resized(Section*)),this,SLOT(reCalculateSeccion(Section*))); } } sections = sections.nextSibling(); } child = child.nextSibling(); } } } for(int i= 0;i < itemPool.size();i++) connect(itemPool.at(i),SIGNAL(moved(Container*)),this,SLOT(itemMoved(Container*))); return true; } int Paper::save(QString file) { QFile f(file); if(f.open(QFile::WriteOnly)) { QTextStream out(&f); const int Indent = 4; QDomDocument doc; QDomElement root = doc.createElement("RDReports"); QDomElement paperNode = doc.createElement("Paper"); QDomElement siz = doc.createElement("Size"); siz.setAttribute("w", QString::number( pxTocm(this->paper().width ()), 'f', 2)); siz.setAttribute("h", QString::number( pxTocm(this->paper().height()), 'f', 2)); QDomElement din = doc.createElement("StandartSize"); din.setAttribute("type",this->mySize); QDomElement orientacion = doc.createElement("Orientation"); orientacion.setAttribute("type",this->m_orientacion == Retrato ? "V" : "H"); QDomElement margin = doc.createElement("Margin"); margin.setAttribute("top",QString::number(this->margenSuperior(), 'f', 2)); margin.setAttribute("bottom",QString::number(this->margenInferior(), 'f', 2)); margin.setAttribute("left",QString::number(this->margenIzquierdo(), 'f', 2)); margin.setAttribute("rigth",QString::number(this->margenDerecho(), 'f', 2)); doc.appendChild(root); root.appendChild(paperNode); paperNode.appendChild(siz); paperNode.appendChild(din); paperNode.appendChild(orientacion); paperNode.appendChild(margin); QList<Section*>::Iterator it; QList<Container*> usedItems; QMap<QString,bool> querys; for(it=seccionPool.begin();it!=seccionPool.end();++it) paperNode.appendChild((*it)->xml(doc,usedItems,querys,seccionPool)); QMapIterator<QString,bool> mIt(querys); while(mIt.hasNext()) { QString s = mIt.next().key(); if(!s.isEmpty()) { QDomElement sql = doc.createElement("SQL"); sql.setAttribute("target",s); paperNode.appendChild(sql); } } QDomNode xmlNode = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"ISO-8859-1\""); doc.insertBefore(xmlNode, doc.firstChild()); doc.save(out, Indent); f.close(); if (usedItems.size() < itemPool.size()) return -2; else return 1; } else return -1; } QDomDocument Paper::preview() { QDomDocument doc; QDomElement root = doc.createElement("RDReports"); QDomElement paperNode = doc.createElement("Paper"); QDomElement siz = doc.createElement("Size"); siz.setAttribute("w", QString::number( pxTocm(this->paper().width ()), 'f', 2)); siz.setAttribute("h", QString::number( pxTocm(this->paper().height()), 'f', 2)); QDomElement din = doc.createElement("StandartSize"); din.setAttribute("type",this->mySize); QDomElement orientacion = doc.createElement("Orientation"); orientacion.setAttribute("type",this->m_orientacion == Retrato ? "V" : "H"); QDomElement margin = doc.createElement("Margin"); margin.setAttribute("top",QString::number(this->margenSuperior(), 'f', 2)); margin.setAttribute("bottom",QString::number(this->margenInferior(), 'f', 2)); margin.setAttribute("left",QString::number(this->margenIzquierdo(), 'f', 2)); margin.setAttribute("rigth",QString::number(this->margenDerecho(), 'f', 2)); doc.appendChild(root); root.appendChild(paperNode); paperNode.appendChild(siz); paperNode.appendChild(din); paperNode.appendChild(orientacion); paperNode.appendChild(margin); QList<Section*>::Iterator it; QList<Container*> usedItems; QMap<QString,bool> querys; for(it=seccionPool.begin();it!=seccionPool.end();++it) paperNode.appendChild((*it)->xml(doc,usedItems,querys,seccionPool)); QMapIterator<QString,bool> mIt(querys); while(mIt.hasNext()) { QString s = mIt.next().key(); if(!s.isEmpty()) { QDomElement sql = doc.createElement("SQL"); sql.setAttribute("target",s); paperNode.appendChild(sql); } } QDomNode xmlNode = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"ISO-8859-1\""); doc.insertBefore(xmlNode, doc.firstChild()); QFile f("/usr/share/RecoverDrake/pre.xml"); if(f.open(QFile::WriteOnly)) { QTextStream t(&f); doc.save(t,4); } f.close(); return doc; } void Paper::setmargenSuperior(double arg) { if (m_margenSuperior != arg) { m_margenSuperior = arg; emit margenSuperiorChanged(arg); } } double Paper::margenInferior() const { return m_margenInferiro; } double Paper::margenIzquierdo() const { return m_margenIzquierdo; } double Paper::margenDerecho() const { return m_margenDerecho; } void Paper::setmargenInferior(double arg) { if (m_margenInferiro != arg) { m_margenInferiro = arg; emit margenInferiroChanged(arg); } } void Paper::setmargenIzquierdo(double arg) { if (m_margenIzquierdo != arg) { m_margenIzquierdo = arg; emit margenIzquierdoChanged(arg); } } void Paper::setmargenDerecho(double arg) { if (m_margenDerecho != arg) { m_margenDerecho = arg; emit margenDerechoChanged(arg); } } QList<Section *> Paper::getSeccionPool() const { return seccionPool; } void Paper::removeItems(QList<QGraphicsItem *> items) { QListIterator<Container*> it(itemPool); while(it.hasNext()) { Container * cont = it.next(); QList<Section *>::Iterator it; for(it = seccionPool.begin();it != seccionPool.end(); ++it) { Section * aux = *it; if(aux->_items.contains(cont)) { aux->_items.removeOne(cont); break; } } if(items.contains(cont)) { itemPool.removeOne(cont); cont->deleteLater(); } } } void Paper::insertSection(Section *sec) { _insertSection(sec); } void Paper::subirSeccion(QString name) { int i = 0; for (;i< seccionPool.size();i++) { if(seccionPool.at(i)->SectionName() == name) { if(i!= 0) { seccionPool.swap(i,i-1); break; } } } reCalculateSeccion(seccionPool.at(i-1)); } void Paper::bajarSeccion(QString name) { int i = 0; for (;i< seccionPool.size();i++) { if(seccionPool.at(i)->SectionName() == name) { if(i!= seccionPool.size()-1) { seccionPool.swap(i,i+1); break; } } } reCalculateSeccion(seccionPool.at(i+1)); } void Paper::borrarSeccion(QString name) { int i = 0; for (;i< seccionPool.size();i++) { if(seccionPool.at(i)->SectionName() == name) { Section * sec = seccionPool.takeAt(i); sec->deleteLater(); break; } } if(!seccionPool.isEmpty()) reCalculateSeccion(seccionPool.at(0)); } void Paper::updatePaper() { for(int i=0;i<seccionPool.size();i++) { seccionPool.at(i)->setWidth(this->rect().width()); seccionPool.at(i)->setMargin(this->margin()); } for(int a = 0;a<itemPool.size();a++) itemPool.at(a)->setMargins(this->margin()); this->scene()->setSceneRect(-15,-15,this->rect().width()+100,this->rect().height()+30); } void Paper::newDoc() { this->setOrientacion(Paper::Retrato); this->updatePaper(); QListIterator<Section*> secIt(seccionPool); QListIterator<Container*> itemIt(itemPool); while(secIt.hasNext()) secIt.next()->deleteLater(); while(itemIt.hasNext()) itemIt.next()->deleteLater(); seccionPool.clear(); itemPool.clear(); this->scene()->update(); }
[ "juanjo.kapyderi@gmail.com" ]
juanjo.kapyderi@gmail.com
34645084023a466a1f7ce99615eb47e247e95bcb
199db94b48351203af964bada27a40cb72c58e16
/lang/mk/gen/Bible50.h
57ca415187cd3fc6307bc551ca4c30df452fee77
[]
no_license
mkoldaev/bible50cpp
04bf114c1444662bb90c7e51bd19b32e260b4763
5fb1fb8bd2e2988cf27cfdc4905d2702b7c356c6
refs/heads/master
2023-04-05T01:46:32.728257
2021-04-01T22:36:06
2021-04-01T22:36:06
353,830,130
0
0
null
null
null
null
UTF-8
C++
false
false
21,495
h
#include <map> #include <string> class Bible50 { struct mk1 { int val; const char *msg; }; struct mk2 { int val; const char *msg; }; struct mk3 { int val; const char *msg; }; struct mk4 { int val; const char *msg; }; public: static void view1() { struct mk1 poems[] = { {1, "1 Павле и Тимотеј, слуги на Христос Исус, до сите светии во Христос Исус, кои се во Вилипи, заедно со надзорниците и ѓаконите: "}, {2, "2 благодат вам и мир од Бог нашиот Татко и од Господ Исус Христос. "}, {3, "3 Му благодарам на својот Бог секогаш кога си спомнувам за вас; "}, {4, "4 секогаш во секоја своја молитва се молам за сите вас со радост, "}, {5, "5 заради вашето учество во Евангелието од првиот ден досега. "}, {6, "6 Уверен сум во тоа, дека Оној Кој го започна доброто дело во вас, ќе го доврши до Денот на Христос Исус. "}, {7, "7 А и исправно е да го мислам тоа за сите вас, зашто ве имам во срцето сите вас кои сте соучесници со мене во благодатта - како во моите окови, така и во одбраната и утврдувањето на Евангелието. "}, {8, "8 Зашто Бог ми е сведок колку копнеам по сите вас со срдечната љубов на Христос Исус. "}, {9, "9 И затоа се молам вашата љубов да изобилува сè повеќе и повеќе во целосно познавање и во секакво расудување, "}, {10, "10 за да можете да го распознавате она што е подобро; за да бидете искрени и беспрекорни за Христовиот ден, "}, {11, "11 исполнети со плодот на праведноста, кој е преку Исус Христос, за слава и пофалба на Бог. "}, {12, "12 А сакам да знаете, браќа, дека ова што се случува со мене помогна за поголем напредок на Евангелието, "}, {13, "13 така што им стана јасно на целата царска стража и на сите други, дека сум во окови заради Христос, "}, {14, "14 и дека повеќето од браќата во Господ, охрабрени од моите окови, се осмелуваат сè повеќе без страв да го проповедаат Божјото слово. "}, {15, "15 Навистина, едни Го проповедаат Христос од завист и соперништво, а други од добра волја; "}, {16, "16 едни од љубов, знаејќи дека сум поставен за одбрана на Евангелието, "}, {17, "17 а други Го навестуваат Христос од себични пориви, не со чиста намера, мислејќи да ми нанесат тага во моите окови. "}, {18, "18 Но што тогаш? Само тоа: дека на секаков начин, било дволично или искрено, Христос се навестува. На тоа му се радувам и ќе се радувам, "}, {19, "19 зашто знам дека ова - преку вашата молитва и помошта на Духот на Исус Христос - ќе ми биде за избавување, "}, {20, "20 сходно со моето цврсто очекување и надеж, дека во ништо нема да се засрамам, туку како и секогаш во сета смелост, така и сега, Христос ќе е возвишен во моето тело, било преку живот или преку смрт. "}, {21, "21 Зашто за мене да живеам е Христос, а да умрам - придобивка. "}, {22, "22 Но ако и натаму живеам во телото, тоа за мене значи плодна работа - и не знам што да изберам. "}, {23, "23 Притиснат сум од две страни, имам желба да си заминам и да бидам со Христос, што е далеку подобро, "}, {24, "24 но заради вас е попотребно да останам во телото. "}, {25, "25 И наполно уверен во тоа, знам дека ќе останам и ќе продолжам со сите вас, за ваш напредок и за радост во верата. "}, {26, "26 А вашата пофалба преку мене да биде уште поизобилна во Христос Исус, заради моето повторно доаѓање кај вас."}, {27, "27 Само однесувајте се достојно на Христовото Евангелие, за да можам јас - било да дојдам и да ве видам, било да сум отсутен - да чујам за вас дека стоите цврсто во еден дух, дека еднодушно се борите за евангелската вера, "}, {28, "28 и дека воопшто не се вознемирувате од противниците, што е знак за нивна погибел, а спасение за вас, и тоа од Бог. "}, {29, "29 Зашто вам ви беше дадено заради Христос не само да верувате во Него, туку и да страдате заради Него, "}, {30, "30 имајќи ја истата борба, каква што видовте во мене, а и сега слушате за мене. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view2() { struct mk2 poems[] = { {1, "1 И така, ако има некаква утеха во Христос, ако има некакво охрабрување од љубов, ако има некаква заедница на Духот, ако има некакво сочувство и сожалување, "}, {2, "2 направете ја мојата радост целосна, имајќи исти мисли и иста љубов, обединети во духот и со една цел. "}, {3, "3 Не правете ништо од ривалство или од суетно честољубие, туку во понизност сметајте се еден друг за поголем од себеси! "}, {4, "4 Не гледајте само на своите лични интереси, туку и на интересите на другите. "}, {5, "5 Имајте такви мисли во себе, какви што ги имаше и Исус Христос: "}, {6, "6 Кој, иако беше во ликот Божји, не го сметаше како нешто приграбено- тоа што е еднаков со Бог, "}, {7, "7 туку се лиши Самиот Себеси, земајќи лик на слуга, станувајќи сличен со луѓето. "}, {8, "8 И откако стана сличен на човек, Тој се понизи Самиот Себеси и стана послушен до смрт, дури до смрт на крст. "}, {9, "9 Затоа и Бог Го возвиши и Му подари име што е над секое име, "}, {10, "10 та во името Исус да се поклони секое колено на оние кои се на небото, на земјата и под земјата; "}, {11, "11 и секој јазик да признае дека Исус Христос е Господ, за слава на Бог Таткото. "}, {12, "12 Затоа, мили мои, како што секогаш бевте послушни, не само кога бев кај вас, туку уште повеќе сега, кога не сум кај вас, градете го своето спасение со страв и трепет. "}, {13, "13 Зашто Бог е Оној Кој ве поттикнува да сакате и да дејствувате според Неговата волја. "}, {14, "14 Правете сè без ропот и расправа, "}, {15, "15 за да бидете беспрекорни и незлобни Божји чеда, непорочни сред изопачено и расипано поколение, меѓу кое сте како светила во светот, "}, {16, "16 држејќи го цврсто словото на животот, за да имам со што да се фалам во Христовиот ден, дека не трчав залудно и дека залудно не се трудев. "}, {17, "17 Но, макар што сум излеан врз жртвата и службата на вашата вера, се радувам и ја споделувам својата радост со сите вас. "}, {18, "18 А исто така радувајте се и вие и споделете ја вашата радост со мене. "}, {19, "19 Но се надевам во Господ Исус наскоро да ви го испратам Тимотеј, та и јас да се охрабрам кога ќе дознаам како сте вие. "}, {20, "20 Зашто немам друг истомисленик, кој толку искрено ќе се грижи за вас, "}, {21, "21 бидејќи сите други го бараат своето, а не она што е на Христос Исус. "}, {22, "22 Bие го знаете неговиот докажан карактер, дека со мене служеше во ширењето на Евангелието како дете на таткото. "}, {23, "23 Затоа, се надевам дека ќе го испратам него веднаш штом ќе разберам што ќе стане со мене. "}, {24, "24 А се надевам во Господ дека и јас самиот наскоро ќе дојдам. "}, {25, "25 Сепак, сметав дека е за потребно да ви го испратам Епафродит, својот брат, соработник и соборец, а ваш пратеник и служител на моите потреби; "}, {26, "26 бидејќи копнееше по сите вас и беше нажален зашто сте чуле дека бил болен. "}, {27, "27 Навистина, беше смртно болен, но Бог му се смилува, и не само нему, туку и мене, за да не ми дојде тага врз тага. "}, {28, "28 Затоа го испратив поскоро, па повторно да се зарадувате кога ќе го видите, и јас да бидам помалку загрижен. "}, {29, "29 Затоа, примете го во Господ, со секаква радост и почитувајте ги таквите, "}, {30, "30 зашто заради Христовото дело се најде близу до смртта, излагајќи го својот живот на опасност, за да го надомести тоа што вие не можевте да го направите за мене. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view3() { struct mk3 poems[] = { {1, "1 На крај, браќа мои, радувајте се во Господ! Мене не ми е здодевно да ви го пишувам тоа па тоа, а вам ви служи како заштита. "}, {2, "2 Пазете се од кучињата, пазете се од злите работници, пазете се од лажното обрежување! "}, {3, "3 Зашто, вистинското обрежување сме ние кои служиме со Божјиот Дух и се фалиме во Христос Исус и не се надеваме на телото, "}, {4, "4 иако и јас можам да имам доверба во телото. Ако некој друг мисли дека може да има доверба во телото, јас уште повеќе: "}, {5, "5 обрежан сум во осмиот ден, од израелевиот род сум, од Бенјаминовото племе, Евреин од Евреите, по Закон - фарисеј, "}, {6, "6 по ревност - гонител на црквата, а според праведноста на Законот бев беспрекорен. "}, {7, "7 Но тоа што ми беше некогаш придобивка, го сметав за загуба поради Христос. "}, {8, "8 И уште повеќе, сметам дека сè е загуба во однос на превосходното познавање на Христос Исус, мојот Господ, заради Кого загубив сè и сè сметам за смет, за да Го придобијам Христос "}, {9, "9 и да се најдам во Него, без своја праведност, која доаѓа од Законот, туку по праведноста која доаѓа преку верата во Христос, праведноста која е од Бог врз основа на вера, "}, {10, "10 за да Го познавам Него и силата на Неговото воскресение, и учеството во Неговите страдања, станувајќи сличен на Него во Неговата смрт, "}, {11, "11 та некако да достигнам до воскресението од мртвите. "}, {12, "12 Не велам дека веќе го достигнав или дека веќе станав совршен, туку се стремам да го достигнам она за кое и самиот бев достигнат од Христос Исус. "}, {13, "13 Браќа, јас уште не мислам дека го достигнав тоа, но сепак правам едно: го заборавам она што е зад мене, а се стремам кон она што е пред мене; "}, {14, "14 трчам кон целта, за наградата на горното призвание од Бог во Христос Исус. "}, {15, "15 И така, ние кои сме совршени нека мислиме вака, а ако вие мислите и малку поинаку, Бог ќе ви го открие и тоа. "}, {16, "16 Сепак, да живееме според достигнатото! "}, {17, "17 Браќа, имајте ме за пример и гледајте на оние што живеат според примерот што го имате во нас! "}, {18, "18 Зашто мнозина, за кои ви зборував многупати, а сега зборувам и со солзи, живеат како непријатели на Христовиот крст. "}, {19, "19 Нивниот крај е погибел; нивниот бог им е стомакот; нивната слава е во нивниот срам; тие мислат само на земното. "}, {20, "20 А нашето граѓанство е на небесата, од каде и Го очекуваме Спасителот Господ Исус Христос, "}, {21, "21 Кој ќе го преобрази нашето понижено тело - да се сообрази со Неговото славно тело, според дејството на Неговата сила, со која може да покори сè под Себе. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view4() { struct mk4 poems[] = { {1, "1 Затоа, мили и многу сакани мои браќа за кои копнеам, моја радост и мој венец, стојте така цврсто во Господ, мили мои! "}, {2, "2 Ја преколнувам Еводија и ја преколнувам Синтихија да бидат едномислени во Господ. "}, {3, "3 Сепак, те молам и тебе, верен другару, помагај им, зашто со мене се трудеа за Евангелието, заедно со Климент и со другите мои соработници, чии имиња се во Книгата на животот. "}, {4, "4 Радувајте се секогаш во Господ и пак ќе кажам, радувајте се! "}, {5, "5 Bашата трпеливост нека им биде позната на сите луѓе! Господ е близу. "}, {6, "6 Не грижете се за ништо, туку во сè, преку молитва и благодарност, искажувајте ги своите барања пред Бог! "}, {7, "7 А Божјиот мир, што го надминува секое разбирање, ќе ги штити вашите срца и вашите мисли во Христос Исус. "}, {8, "8 Најпосле, браќа, сè што е вистинито, што е чесно, што е праведно, што е чисто, што е љубезно, што е на добар глас - ако е некаква доблест, ако е некаква пофалба - размислувајте за тоа! "}, {9, "9 Она што го научивте, примивте, чувте и видовте во мене - тоа правете го, и Бог на мирот ќе биде со вас! "}, {10, "10 Се зарадував многу во Господ, зашто сега најпосле ја оживеавте својата грижа за мене. Bие и инаку се грижевте, но немавте можност. "}, {11, "11 Не го зборувам тоа заради скудност, зашто научив да бидам задоволен во секакви околности. "}, {12, "12 Знам да живеам и во скудност, знам и во изобилство. Ја научив тајната да бидам сит и да гладувам во секакви околности; да сум во изобилство и во скудност. "}, {13, "13 Сè можам преку Христос, Кој ми дава сила. "}, {14, "14 Туку добро направивте што зедовте учество во моите неволи. "}, {15, "15 А знаете и вие, Вилипјани, дека во почетокот на проповедањето на Евангелието, кога заминав од Македонија, ниедна црква не беше со мене во давањето и примањето, освен единствено вие, "}, {16, "16 зашто ми испративте во Солун, еднаш и по вторпат, за моите потреби. "}, {17, "17 Јас не барам подарок, туку го барам плодот што се умножува во ваша полза. "}, {18, "18 Примив сè и имам изобилно. Целосно сум подмирен откако го примив од Епафродит она што ми испративте - благопријатен мирис, жртва прифатлива и по волјата на Бог. "}, {19, "19 А мојот Бог ќе ги исполни сите ваши потреби, според Своето богатство во славата - во Христос Исус. "}, {20, "20 А на нашиот Бог и Татко, слава во сите векови. Амин! "}, {21, "21 Поздравете го секој светија во Христос Исус! Bе поздравуваат браќата кои се со мене. "}, {22, "22 Bе поздравуваат сите светии, а особено оние од Цезаровиот дом. "}, {23, "23 Благодатта на Господ Исус Христос да биде со вашиот дух!"}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } };
[ "max@mkoldaev.ru" ]
max@mkoldaev.ru
18ca209264eabf13ba050e8cd495a39f067a793d
3de2cde7669ca200214415e28967e2bbdbeea5c8
/dev/test/so_5/execution_hint/basic_checks/main.cpp
3df47b4e96c643decfbe40d0d41c60b546f89fa7
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
crystax/android-vendor-sobjectizer
01ec752f19664c8d4563cdf077a674c06edcc81c
443f3b456f83e8ce8be972a28d150da7abb48fdd
refs/heads/master
2020-12-30T22:32:12.319910
2016-03-25T10:14:02
2016-03-25T10:14:02
58,122,012
0
1
null
null
null
null
UTF-8
C++
false
false
5,464
cpp
/* * Test for basic operations with execution hints. */ #define SO_5__EXECUTION_HINT__UNIT_TEST #include <utest_helper_1/h/helper.hpp> #include <so_5/all.hpp> class test_environment_t : public so_5::environment_t { public : test_environment_t() : so_5::environment_t( so_5::environment_params_t() ) {} virtual void init() {} }; struct msg_signal : public so_5::signal_t {}; struct msg_thread_safe_signal : public so_5::signal_t {}; struct msg_get_status : public so_5::signal_t {}; class a_test_t : public so_5::agent_t { public : a_test_t( so_5::environment_t & env ) : so_5::agent_t( env ) , m_signal_handled( false ) , m_thread_safe_signal_handled( false ) , m_get_status_handled( false ) {} void evt_signal() { m_signal_handled = true; } void evt_thread_safe_signal() { m_thread_safe_signal_handled = true; } std::string evt_get_status() { m_get_status_handled = true; return "OK"; } bool m_signal_handled; bool m_thread_safe_signal_handled; bool m_get_status_handled; }; UT_UNIT_TEST( no_handlers ) { using namespace so_5; test_environment_t env; a_test_t agent( env ); { execution_demand_t demand( &agent, message_limit::control_block_t::none(), 0, typeid(msg_signal), message_ref_t(), agent_t::get_demand_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( false, hint ); } { execution_demand_t demand( &agent, message_limit::control_block_t::none(), 0, typeid(msg_signal), message_ref_t(), agent_t::get_service_request_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); } { execution_demand_t demand( &agent, message_limit::control_block_t::none(), 0, typeid(msg_signal), message_ref_t(), agent_t::get_demand_handler_on_start_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); } { execution_demand_t demand( &agent, message_limit::control_block_t::none(), 0, typeid(msg_signal), message_ref_t(), agent_t::get_demand_handler_on_finish_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); } } UT_UNIT_TEST( event_handler ) { using namespace so_5; test_environment_t env; a_test_t agent( env ); agent.so_subscribe( agent.so_direct_mbox() ) .event( signal< msg_signal >, &a_test_t::evt_signal ); agent.so_subscribe( agent.so_direct_mbox() ) .event( signal< msg_thread_safe_signal >, &a_test_t::evt_thread_safe_signal, thread_safe ); { execution_demand_t demand( &agent, message_limit::control_block_t::none(), agent.so_direct_mbox()->id(), typeid(msg_signal), message_ref_t(), agent_t::get_demand_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); UT_CHECK_EQ( false, hint.is_thread_safe() ); UT_CHECK_EQ( false, agent.m_signal_handled ); hint.exec( query_current_thread_id() ); UT_CHECK_EQ( true, agent.m_signal_handled ); } { execution_demand_t demand( &agent, message_limit::control_block_t::none(), agent.so_direct_mbox()->id(), typeid(msg_thread_safe_signal), message_ref_t(), agent_t::get_demand_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); UT_CHECK_EQ( true, hint.is_thread_safe() ); UT_CHECK_EQ( false, agent.m_thread_safe_signal_handled ); hint.exec( query_current_thread_id() ); UT_CHECK_EQ( true, agent.m_thread_safe_signal_handled ); } } UT_UNIT_TEST( service_handler ) { using namespace so_5; test_environment_t env; a_test_t agent( env ); { std::promise< std::string > promise; auto f = promise.get_future(); message_ref_t msg( new msg_service_request_t< std::string, msg_get_status >( std::move(promise) ) ); execution_demand_t demand( &agent, message_limit::control_block_t::none(), agent.so_direct_mbox()->id(), typeid(msg_get_status), msg, agent_t::get_service_request_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); UT_CHECK_EQ( true, hint.is_thread_safe() ); hint.exec( query_current_thread_id() ); UT_CHECK_THROW( exception_t, f.get() ); UT_CHECK_EQ( false, agent.m_get_status_handled ); } agent.so_subscribe( agent.so_direct_mbox() ) .event( signal< msg_get_status >, &a_test_t::evt_get_status ); { std::promise< std::string > promise; auto f = promise.get_future(); message_ref_t msg( new msg_service_request_t< std::string, msg_get_status >( std::move(promise) ) ); execution_demand_t demand( &agent, message_limit::control_block_t::none(), agent.so_direct_mbox()->id(), typeid(msg_get_status), msg, agent_t::get_service_request_handler_on_message_ptr() ); auto hint = agent_t::so_create_execution_hint( demand ); UT_CHECK_EQ( true, hint ); UT_CHECK_EQ( false, hint.is_thread_safe() ); hint.exec( query_current_thread_id() ); UT_CHECK_EQ( "OK", f.get() ); UT_CHECK_EQ( true, agent.m_get_status_handled ); } } int main() { UT_RUN_UNIT_TEST( no_handlers ) UT_RUN_UNIT_TEST( event_handler ) UT_RUN_UNIT_TEST( service_handler ) return 0; }
[ "eao197@1d1731ae-3f85-447d-88f8-c72b288064d1" ]
eao197@1d1731ae-3f85-447d-88f8-c72b288064d1
f110bd3aacd78d21ad905a03ad04859c1ad4c4d4
6fc84b8d0a26d1d08cf9304dbb21f76c532ea082
/fmtgenrunnable.cpp
1958353cb8b56a1cea8f28a960e4121c04b2e232
[]
no_license
Smitt64/FmtHelper
e8b8cf37552d3a288b1d244d98ad5c019a5a1879
2f985ade1388e570b4ce660b1aafea28e69e49ee
refs/heads/master
2020-08-27T06:31:14.359573
2015-08-30T21:12:54
2015-08-30T21:12:54
41,204,165
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
#include "fmtgenrunnable.h" #include <QTextStream> #include "fmtobject.h" FmtGenRunnable::FmtGenRunnable(const QModelIndex &index, const QSqlDatabase &db) :QObject(NULL), QRunnable() { _index = index; _db = db; result = 0; setAutoDelete(true); } void FmtGenRunnable::run() { QString cpp, tablessql, updscript; QTextStream stream(&cpp); QTextStream stream2(&tablessql); QTextStream stream3(&updscript); try { FmtObject obj(_index, _db); obj.generateCppCode(&stream); emit stepFinish(cpp, FmtGenRunnable::GEN_CPP); obj.generateSqls(&stream2); emit stepFinish(tablessql, FmtGenRunnable::GEN_TABLE); obj.generateUpdateScript(&stream3); emit stepFinish(updscript, FmtGenRunnable::GEN_UPD_SCRIPT); } catch(int &e) { result = e; } emit finished(result); }
[ "smitt64@yandex.ru" ]
smitt64@yandex.ru
24a1b8c1fc0347bdd99c1407c742b3657905d80f
8b77fcdb9ca3e88f900994d753f522fecfdd956d
/4o Semestre/Análisis de Algoritmos/Ejercicio 05/SegmentTree.cpp
527b9460a39d1a432080603bdcf89ebf6f52b403
[]
no_license
akotadi/ESCOM
a345665639659880a60fe49c9d3288d83210e3ec
f0e19796dd70c0658af7115b84005631ccc2403f
refs/heads/master
2022-12-13T01:15:23.515074
2020-04-03T04:21:43
2020-04-03T04:21:43
125,299,374
6
1
null
2022-12-09T10:18:03
2018-03-15T02:07:16
HTML
UTF-8
C++
false
false
1,480
cpp
#include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; template<class T> struct SegTree { T dato; int i, d; SegTree* izq, *der; SegTree(int I, int D) : izq(NULL), der(NULL), i(I), d(D), dato() {} ~SegTree() { if (izq) delete izq; if (der) delete der; } T Construir() { if (i == d) return dato = T(); int m = (i + d) >> 1; izq = new SegTree(i, m); der = new SegTree(m + 1, d); return dato = izq->Construir() + der->Construir(); } T Actualizar(int a, T v) { if (a < i || d < a) return dato; if (a == i && d == a) return dato = v; if (!izq) { int m = (i + d) >> 1; izq = new SegTree(i, m); der = new SegTree(m + 1, d); } return dato = izq->Actualizar(a, v) + der->Actualizar(a, v); } T Query(int a, int b) { if (b < i || d < a) return T(); if (a <= i && d <= b) return dato; return izq? izq->Query(a, b) + der->Query(a, b): T(); } }; int main(int argc, char const *argv[]) { SegTree<int> seg(0,5); int m = seg.Construir(); cout<<m<<endl; int n[] = {-3,6,-1,7,-8,2}; for (int i = 0; i < 6; ++i) { m = seg.Actualizar(i,n[i]); cout<<m<<endl; } m = seg.Query(2,5); cout<<m<<endl; m = seg.Query(1,3); cout<<m<<endl; m = seg.Query(2,3); cout<<m<<endl; return 0; }
[ "manuel_7795@hotmail.com" ]
manuel_7795@hotmail.com
5a0a44814074bb2d6600b3e767b02981e48eec58
4f98aa76ef3ff2d7bd1f93733853577ed7d1de8c
/PC-kom-src/src/LogicUI_imp/utils_Terminal/Terminal_SendSection.hpp
ddc94df140da0a3170c29ddf13794bd0e5bee940
[]
no_license
Generall14/PC-kom
fc3b8a52fba9530753606d796f46ef80b4c11e40
8764858dcde8a5b9ed4cf8e4ee55846316654455
refs/heads/master
2022-07-04T20:51:24.662135
2022-06-28T11:06:57
2022-06-28T11:06:57
194,335,114
0
0
null
null
null
null
UTF-8
C++
false
false
833
hpp
#ifndef TERMINAL_SENDSECTION_HPP #define TERMINAL_SENDSECTION_HPP #include <QObject> #include <QLayout> #include <QString> #include <QTimer> #include <QLineEdit> #include <QCheckBox> #include <QSpinBox> #include <QBoxLayout> class Terminal_SendSection : public QObject { Q_OBJECT public: Terminal_SendSection(QBoxLayout *upperLayout); ~Terminal_SendSection(); QString Store() const; void Restore(QString desc); void Enable(); void Disable(); public slots: void Stop(); private slots: void timeoutChanged(int val); signals: void Send(QString str); private: QTimer* timer = nullptr; bool pause = false; QLineEdit* leSend = nullptr; QToolButton* tb = nullptr; QCheckBox* cb = nullptr; QSpinBox* sb = nullptr; }; #endif
[ "wojciech_kogut@o2.pl" ]
wojciech_kogut@o2.pl
2d4923a620569fcc7db7e2ed8d04b020458681f1
43441cde04695a2bf62a7a5f7db4072aa0a6d366
/vc60/src/StaticMem.cpp
999a5f97398d5ba31a74668e4af62ffd33c1fa68
[]
no_license
crespo2014/cpp-lib
a8aaf4b963d3bf41f91db3832dd51bcf601d54ee
de6b653bf4c689fc5ceb3e9fe0f4fe47d79acf95
refs/heads/master
2020-12-24T15:23:32.396924
2016-03-21T11:53:37
2016-03-21T11:53:37
26,559,932
0
0
null
null
null
null
UTF-8
C++
false
false
4,326
cpp
// StaticMem.cpp: implementation of the CStaticMem class. // ////////////////////////////////////////////////////////////////////// #include "StaticMem.h" #define _FILENAME_ "staticmem.c" #define _CHECK_BLOCK_ if ((!m_pblock)||(!m_block_max)) return _LOG_ERROR ERR_HANDLE,"Memory is undefined"); #define _CHECK_NO_LOCK_ if (m_locked) return _LOG_ERROR ERR_IS_LOCK,"Memory is locked"); #define _CHECK_IS_LOCK_ if (!m_locked) return _LOG_ERROR ERR_IS_LOCK,"Memory is not locked"); ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CStaticMem::CStaticMem() { } CStaticMem::~CStaticMem() { } CStaticMem::CStaticMem(void *pblock, DWORD blockSize) { m_pblock = (BYTE*)pblock; m_block_max = blockSize; m_block_free = 0; m_locked = 0; } void CStaticMem::SetBlock(void *pblock, DWORD blockSize) { m_pblock = (BYTE*)pblock; m_block_max = blockSize; m_block_free = 0; m_locked = 0; } DWORD CStaticMem::addS(char* str,DWORD size,char **pstr) { void* pvoid; if (size == 0) { char *cptr=str; while (*cptr++ != 0); size = (DWORD)(cptr-str+1); } if (_get(size,&pvoid,false) != ERR_OK) return _LOG_AT; memcpy(pvoid,str,size-1); ((BYTE*)pvoid)[size] = 0; *pstr = (char*)pvoid; return ERR_OK; } DWORD CStaticMem::lock() { _CHECK_BLOCK_; _CHECK_NO_LOCK_; m_locked = true; m_look_index = m_block_free; // anotamos la posicion libre // comenzamos con memoria alineada para pode devolver un compact if (m_block_free & (sizeof(void*)-1)) { m_block_free = (m_block_free + sizeof(void*)) & ~(sizeof(void*)-1); } return ERR_OK; } DWORD CStaticMem::lockAdd(void* dt,DWORD size) { _CHECK_IS_LOCK_; if (m_block_free + size > m_block_max) return _LOG_ERROR ERR_OVERFLOW,"No memory for %d bytes remain is %d ",size,m_block_max-m_block_free); memcpy(&m_pblock[m_block_free],dt,size); m_block_free += size; return ERR_OK; } DWORD CStaticMem::lockAvaliable(void** ppvoid,DWORD* ppsize) { _CHECK_IS_LOCK_; *ppsize = m_block_max - m_block_free; *ppvoid = &m_pblock[m_block_free]; return ERR_OK; } DWORD CStaticMem::lockCommit(DWORD size) { _CHECK_IS_LOCK_; if (m_block_free + size > m_block_max) return _LOG_ERROR ERR_OVERFLOW,"overflow"); m_block_free += size; return ERR_OK; } DWORD CStaticMem::lockCompact(void** ppvoid,DWORD* ppsize) { // vamos a comprobar la alineacion _CHECK_IS_LOCK_; DWORD pos; if (m_look_index & (sizeof(void*)-1)) { pos = (m_look_index + sizeof(void*)) & ~(sizeof(void*)-1); } else pos = m_look_index; *ppvoid = &m_pblock[pos]; if (ppsize) *ppsize = m_block_free - pos; return ERR_OK; } DWORD CStaticMem::lockClose() { _CHECK_IS_LOCK_; m_locked = false; return ERR_OK; } DWORD CStaticMem::lockFree() { _CHECK_IS_LOCK_; m_locked = false; m_block_free = m_look_index; return ERR_OK; } DWORD CStaticMem::lockSize() { if (!m_locked) return 0; DWORD pos; if (m_look_index & (sizeof(void*)-1)) { pos = (m_look_index + sizeof(void*)) & ~(sizeof(void*)-1); } else pos = m_look_index; return m_block_free - pos; } DWORD CStaticMem::_get(DWORD size, void **ppvoid, bool align) { DWORD offset; _CHECK_BLOCK_; _CHECK_NO_LOCK_; offset = m_block_free; if (align) { if (m_block_free & (sizeof(void*)-1)) offset = (m_block_free + sizeof(void*)) & ~(sizeof(void*)-1); } if (offset + size > m_block_max) return _LOG_ERROR ERR_OVERFLOW,"No memory for %d bytes remain is %d ",size,m_block_max-m_block_free); *ppvoid = &m_pblock[offset]; m_block_free = offset + size; return ERR_OK; } DWORD CStaticMem::_add(void *pdata, DWORD size, void **ppvoid, bool align) { void* pvoid; if (_get(size,&pvoid,align) != ERR_OK) return _LOG_AT; memcpy(pvoid,pdata,size); *ppvoid=pvoid; return ERR_OK; } // Implementar ITube DWORD CStaticMem::Start() { return lock(); } DWORD CStaticMem::End() { return ERR_OK; } DWORD CStaticMem::Push(BYTE b) { _CHECK_IS_LOCK_; if (m_block_free + 1 > m_block_max) return _LOG_ERROR ERR_NOMEMORY,"Memory is full"); m_pblock[m_block_free] = b; m_block_free ++; return ERR_OK; }
[ "lester.crespo.es@gmail.com" ]
lester.crespo.es@gmail.com
5dd99e85e42a940b698afa4a1a3ebaac2c232e0b
1c6371658cfe23d2d0c7d17731ef254b390439b8
/Source/NameServer/Ns_el.cpp
d719735659c878ae16631345e7e79fdce24faeb2
[]
no_license
mfkiwl/Orchestrator
6f5aa5c7f88d73220616fcadf9333d96565bd730
b9d8f563be7c99d131fda3d05381f01ab0e7a803
refs/heads/master
2022-12-10T00:53:04.887565
2018-11-05T15:54:08
2018-11-05T15:54:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,969
cpp
//------------------------------------------------------------------------------ #include "Ns_el.h" //============================================================================== Ns_el::Ns_el() { Put<Dindex_t>(); Put<Sindex_t>(); Put<Tindex_t>(); Put<Oindex_t>(); } //------------------------------------------------------------------------------ Ns_el::Ns_el(byte * s,int l):PMsg_p(s,l) { Put<Dindex_t>(); Put<Sindex_t>(); Put<Tindex_t>(); Put<Oindex_t>(); } //------------------------------------------------------------------------------ Ns_el::Ns_el(PMsg_p * p):PMsg_p(*p) { Put<Dindex_t>(); Put<Sindex_t>(); Put<Tindex_t>(); Put<Oindex_t>(); Dump(); } //------------------------------------------------------------------------------ Ns_el::~Ns_el() { } //------------------------------------------------------------------------------ vector<Ns_0 *> * Ns_el::Construct() // Receiver side (NameServer) function: // Routine to build and expose a vector of entities derived from the current // state of the object. // If there's a problem - and there shouldn't be - a entity type 'X' is written // to the output vector and the routine returns prematurely (i.e. the 'X' entity // is the last in the returned vector). Subsequent parts of the PMsg_p are // ignored. { Ns_X * pX = new Ns_X(); // Error entity static vector<Ns_0 *> vN; vN.clear(); // Output entity vector int cnt; // Stored key vector size unsigned * ploc = Get<unsigned>(0,cnt);// Get hold of the key vector try { if (ploc==0) throw((*pX)("KEY VECTOR")); // If it's not there.... for (int i=0;i<cnt;i++,*ploc++) { // Unpack, one key at a time int c2; // Item count (not used) unsigned char * pEtype = Get<unsigned char>(*ploc,c2); if (pEtype==0) throw((*pX)("ENTITY TYPE")); vector<string> vs; // Holder for the packed name vector Ns_0 * p; // Entity GetX(*ploc,vs); // Slurp it out switch (*pEtype) { case 'D' : { Ns_el::Dindex_t * pDindex = Get<Ns_el::Dindex_t>(*ploc,c2); if (pDindex==0) throw((*pX)("DEVICE INDEX")); p = new Ns_dev(pDindex,vs); // No idea why - vN.push_back(p); // Another BORLAND bug? } break; case 'S' : { Ns_el::Sindex_t * pSindex = Get<Ns_el::Sindex_t>(*ploc,c2); if (pSindex==0) throw((*pX)("SUPERVISOR INDEX")); p = new Ns_sup(pSindex,vs); // No idea why - vN.push_back(p); // Another BORLAND bug? } break; case 'T' : { Ns_el::Tindex_t * pTindex = Get<Ns_el::Tindex_t>(*ploc,c2); if (pTindex==0) throw((*pX)("TASK INDEX")); p = new Ns_tsk(pTindex,vs); // No idea why - vN.push_back(p); // Another BORLAND bug? } break; case 'O' : { Ns_el::Oindex_t * pOindex = Get<Ns_el::Oindex_t>(*ploc,c2); if (pOindex==0) throw((*pX)("OWNER INDEX")); p = new Ns_own(pOindex,vs); // No idea why - vN.push_back(p); // Another BORLAND bug? } break; default : throw((*pX)("UNRECOGNISED ENTITY TYPE")); } // switch p->type = *pEtype; p->key = *ploc; } // for } // try catch(Ns_0 * X) { // Cockup: Push the already allocated vN.push_back(X); // error entity onto the vector and bail return &vN; } delete pX; // Don't need the error entity return &vN; } //------------------------------------------------------------------------------ void Ns_el::Dump(FILE * fp) // The usual, but the logic is a bit fiddly here. We want to dump the *contents* // of the PMsg_p class that is the base class of Ns_el. Calling PMsg_p::Dump() // will not do the biz, because PMsg_p doesn't know anything about types, so the // Dump() will be largely impenetrable. The only state variable of Ns_el is // keyv, the vector of keys that have currently been used to load the class. // So we walk keyv, extracting the (integer) keys. We can use these to get the // entity types: Get<char>(keyv[?],...), and this gives us the complete // signature for the entity: {key,type}. // If keyv is empty, this is either because the object is genuinely empty, // or because the POETS entities have been streamed to the internal byte // buffer. { fprintf(fp,"Ns_el+++++++++++++++++++++++++++++++++++++\n"); fprintf(fp,"Current key vector (%u elements):\n",keyv.size()); WALKVECTOR(unsigned,keyv,i)fprintf(fp,"%3u\n",*i); fprintf(fp,"+ + + + + + + + + + + + + + + + + + + + + + + + + +\n"); fprintf(fp,"Walking the entities; dumping with unstreamed keys:\n"); // Dump with the unstreamed keys WALKVECTOR(unsigned,keyv,i) Dump0(fp,*i); fprintf(fp,"+ + + + + + + + + + + + + + + + + + + + + + + + + +\n"); fprintf(fp,"Walking the entities; dumping with stored key vector:\n"); int cnt; // Stored key vector size unsigned * ploc = Get<unsigned>(0,cnt);// Get hold of the key vector fprintf(fp,"Stored key vector has %u elements\n",cnt); // Dump with streamed keys if (ploc!=0) for(int i=0;i<cnt;i++) Dump0(fp,*ploc++); // If there are any duplicates, there shouldn't be fprintf(fp,"+ + + + + + + + + + + + + + + + + + + + + + + + + +\n"); fprintf(fp,"Down and dirty dump:\n"); PMsg_p::Dump(); fprintf(fp,"Ns_el-------------------------------------\n"); fflush(fp); } //------------------------------------------------------------------------------ void Ns_el::Dump0(FILE * fp,unsigned k) // Dump the entity with the POETS key k // There is an argument here for combining the four index types. They form a // nested subset sequence, and the top ones (owner and task) - these being the // ones with the potentialy wasted space - will be relatively rare. { int cnt; unsigned char * pEtype = Get<unsigned char>(k,cnt); unsigned char Etype = 'X'; if (pEtype==0) fprintf(fp,"*** TYPE UNLOAD FAIL ***\n"); else Etype = *pEtype; vector<string> vs; switch (Etype) { case 'D' : { fprintf(fp,"\nDevice key %3u:\n",k); Ns_el::Dindex_t Dindex; Ns_el::Dindex_t * pDindex = Get<Ns_el::Dindex_t>(k,cnt); if (pDindex==0) { fprintf(fp,"*** DEVICE INDEX UNLOAD FAIL ***\n"); break; } else Dindex = *pDindex; fprintf(fp,"key = %u\n",Dindex.key); if (Dindex.key!=k) fprintf(fp,"*** KEY MISMATCH ***\n"); Dindex.addr.Dump(fp); fprintf(fp,"attr = %u\n",Dindex.attr); fprintf(fp,"bin = %u\n",Dindex.bin); fprintf(fp,"inP(size) = %u\n",Dindex.inP/2); fprintf(fp,"ouP(size) = %u\n",Dindex.ouP/2); GetX(k,vs); fprintf(fp,"Name vector (%u elements)\n",vs.size()); WALKVECTOR(string,vs,i) fprintf(fp,"%s\n",(*i).c_str()); } break; case 'S' : { fprintf(fp,"\nSupervisor key %3u:\n",k); Ns_el::Sindex_t Sindex; Ns_el::Sindex_t * pSindex = Get<Ns_el::Sindex_t>(k,cnt); if (pSindex==0) { fprintf(fp,"*** SUPERVISOR INDEX UNLOAD FAIL ***\n"); break; } else Sindex = *pSindex; fprintf(fp,"key = %u\n",Sindex.key); if (Sindex.key!=k) fprintf(fp,"*** KEY MISMATCH ***\n"); Sindex.addr.Dump(fp); fprintf(fp,"attr = %u\n",Sindex.attr); fprintf(fp,"bin = %u\n",Sindex.bin); GetX(k,vs); fprintf(fp,"Name vector (%u elements)\n",vs.size()); WALKVECTOR(string,vs,i) fprintf(fp,"%s\n",(*i).c_str()); } break; case 'T' : { fprintf(fp,"\nTask key %3u:\n",k); Ns_el::Tindex_t Tindex; Ns_el::Tindex_t * pTindex = Get<Ns_el::Tindex_t>(k,cnt); if (pTindex==0) { fprintf(fp,"*** TASK INDEX UNLOAD FAIL ***\n"); break; } else Tindex = *pTindex; fprintf(fp,"key = %u\n",Tindex.key); if (Tindex.key!=k) fprintf(fp,"*** KEY MISMATCH ***\n"); GetX(k,vs); fprintf(fp,"Name vector (%u elements)\n",vs.size()); WALKVECTOR(string,vs,i) fprintf(fp,"%s\n",(*i).c_str()); } break; case 'O' : { fprintf(fp,"\nOwner key %3u:\n",k); Ns_el::Oindex_t Oindex; Ns_el::Oindex_t * pOindex = Get<Ns_el::Oindex_t>(k,cnt); if (pOindex==0) { fprintf(fp,"*** OWNER INDEX UNLOAD FAIL ***\n"); break; } else Oindex = *pOindex; fprintf(fp,"key = %u\n",Oindex.key); if (Oindex.key!=k) fprintf(fp,"*** KEY MISMATCH ***\n"); GetX(k,vs); fprintf(fp,"Name vector (%u elements)\n",vs.size()); WALKVECTOR(string,vs,i) fprintf(fp,"%s\n",(*i).c_str()); } break; default : fprintf(fp,"*** UNRECOGNISED ENTITY TYPE ***\n");; } } //------------------------------------------------------------------------------ int Ns_el::Length() // Retrieve length of streamed message { if (!keyv.empty()) { Put<unsigned>(0,&keyv[0],keyv.size()); // Load the key list keyv.clear(); // Everything is in the stream buffer } Msg_p::Stream(); return (int)Msg_p::vm.size(); } //------------------------------------------------------------------------------ void Ns_el::PutD(string Dname, // Device name string Dtype, // Device type string Sname, // Supervisor name string Tname, // Task name string Oname, // Owner name vector<string> inpin, // Device input pin names vector<string> inpintype, // Device input pin types vector<string> oupin, // Device output pin names vector<string> oupintype, // Device output pin types unsigned key, // PMsg_p key P_addr_t addr, // POETS hardware address unsigned attr, // Device attribute unsigned bin) // Binary file indentifier { struct Ns_el::Dindex_t Dindex; // This rather clunky initialisation section is the highest common factor of my // three C++ compilers..... Dindex.key = key; // PMsg_p key Dindex.addr = addr; // POETS composite address Dindex.attr = attr; // POETS device attribute Dindex.bin = bin; // ..and so on: see above Dindex.inP = inpin.size() + inpintype.size(); Dindex.ouP = oupin.size() + oupintype.size(); vector<string> vs; // Name container vs.push_back(Dname); // Device name vs.push_back(Dtype); // Device type vs.push_back(Sname); // Supervisor name vs.push_back(Tname); // Task name vs.push_back(Oname); // Owner name vs.insert(vs.end(),inpin.begin(),inpin.end()); vs.insert(vs.end(),inpintype.begin(),inpintype.end()); vs.insert(vs.end(),oupin.begin(),oupin.end()); vs.insert(vs.end(),oupintype.begin(),oupintype.end()); unsigned char Entity = 'D'; Put<unsigned char>(key,&Entity); // Entity type (device/supervisor...) Put<Dindex_t>(key,&Dindex); // Index structure PutX(key,&vs); // All the strings in one container keyv.push_back(key); // Add to the vector of used keys } //------------------------------------------------------------------------------ void Ns_el::PutO(string Oname, // Owner name unsigned key) // PMsg_p key { struct Ns_el::Oindex_t Oindex; // This rather clunky initialisation section is the highest common factor of my // three C++ compilers..... Oindex.key = key; // PMsg_p key vector<string> vs; // Name container vs.push_back(Oname); // Owner name unsigned char Entity = 'O'; Put<unsigned char>(key,&Entity); // Entity type (device/supervisor...) Put<Oindex_t>(key,&Oindex); // Index structure PutX(key,&vs); // All the strings in one container keyv.push_back(key); // Add to the vector of used keys } //------------------------------------------------------------------------------ void Ns_el::PutS(string Sname, // Supervisor name string Tname, // Task name string Oname, // Owner name unsigned key, // PMsg_p key P_addr_t addr, // POETS hardware address unsigned attr, // Device attribute unsigned bin) // Binary file indentifier { struct Ns_el::Sindex_t Sindex; // This rather clunky initialisation section is the highest common factor of my // three C++ compilers..... Sindex.key = key; // PMsg_p key Sindex.addr = addr; // POETS composite address Sindex.attr = attr; // POETS device attribute Sindex.bin = bin; // ..and so on: see above vector<string> vs; // Name container vs.push_back(Sname); // Supervisor name vs.push_back(Tname); // Task name vs.push_back(Oname); // Owner name unsigned char Entity = 'S'; Put<unsigned char>(key,&Entity); // Entity type (device/supervisor...) Put<Sindex_t>(key,&Sindex); // Index structure PutX(key,&vs); // All the strings in one container keyv.push_back(key); // Add to the vector of used keys } //------------------------------------------------------------------------------ void Ns_el::PutT(string Tname, // Task name string Oname, // Owner name unsigned key) // PMsg_p key { struct Ns_el::Tindex_t Tindex; // This rather clunky initialisation section is the highest common factor of my // three C++ compilers..... Tindex.key = key; // PMsg_p key vector<string> vs; // Name container vs.push_back(Tname); // Task name vs.push_back(Oname); // Owner name unsigned char Entity = 'T'; // Guess Put<unsigned char>(key,&Entity); // Entity type (device/supervisor...) Put<Tindex_t>(key,&Tindex); // Index structure PutX(key,&vs); // All the strings in one container keyv.push_back(key); // Add to the vector of used keys } //============================================================================== Ns_X * Ns_X::operator()(string s) { msg = s; return this; } //============================================================================== Ns_dev::Ns_dev(Ns_el::Dindex_t * pDindex,vector<string> & vs) { addr = pDindex->addr; attr = pDindex->attr; bin = pDindex->bin; Ename = vs[0]; Etype = vs[1]; Sname = vs[2]; Tname = vs[3]; Oname = vs[4]; vector<string>::iterator inbegin = vs.begin()+5; vector<string>::iterator inend = inbegin + pDindex->inP/2; vector<string>::iterator intypebegin = inend; vector<string>::iterator intypeend = intypebegin + pDindex->inP/2; vector<string>::iterator oubegin = intypeend; vector<string>::iterator ouend = oubegin + pDindex->ouP/2; vector<string>::iterator outypebegin = ouend; vector<string>::iterator outypeend = outypebegin + pDindex->ouP/2; inpin = vector<string>(inbegin,inend); inpintype = vector<string>(intypebegin,intypeend); oupin = vector<string>(oubegin,ouend); oupintype = vector<string>(outypebegin,outypeend); } //------------------------------------------------------------------------------ void Ns_dev::Dump(FILE * fp) { fprintf(fp,"Ns_dev++++++++++++++++++++++++++++++++++++\n"); addr.Dump(fp); fprintf(fp,"Device type = %s\n",Etype.c_str()); fprintf(fp,"Super name = %s\n",Sname.c_str()); fprintf(fp,"Task name = %s\n",Tname.c_str()); fprintf(fp,"Owner name = %s\n",Oname.c_str()); fprintf(fp,"attr = %u\n",attr); fprintf(fp,"bin = %u\n",bin); fprintf(fp,"\nInput pin name vector (%u elements)\n",inpin.size()); WALKVECTOR(string,inpin,i) fprintf(fp,"%s\n",(*i).c_str()); fprintf(fp,"\nInput pin type name vector (%u elements)\n",inpintype.size()); WALKVECTOR(string,inpintype,i) fprintf(fp,"%s\n",(*i).c_str()); fprintf(fp,"\nOutput pin name vector (%u elements)\n",oupin.size()); WALKVECTOR(string,oupin,i) fprintf(fp,"%s\n",(*i).c_str()); fprintf(fp,"\nOutput pin type name vector (%u elements)\n",oupintype.size()); WALKVECTOR(string,oupintype,i) fprintf(fp,"%s\n",(*i).c_str()); Ns_0::Dump(fp); fprintf(fp,"Ns_dev------------------------------------\n"); } //============================================================================== Ns_0::Ns_0() { } //------------------------------------------------------------------------------ void Ns_0::Dump(FILE * fp) { fprintf(fp,"Ns_0++++++++++++++++++++++++++++++++++++++\n"); fprintf(fp,"key = %u\n",key); fprintf(fp,"type = %c\n",type); fprintf(fp,"entity name = %s\n",Ename.c_str()); fprintf(fp,"Ns_0--------------------------------------\n"); } //============================================================================== Ns_sup::Ns_sup(Ns_el::Sindex_t * pSindex,vector<string> & vs) { Ename = vs[0]; Tname = vs[1]; Oname = vs[2]; addr = pSindex->addr; attr = pSindex->attr; bin = pSindex->bin; } //------------------------------------------------------------------------------ void Ns_sup::Dump(FILE * fp) { fprintf(fp,"Ns_sup++++++++++++++++++++++++++++++++++++\n"); addr.Dump(fp); fprintf(fp,"Task name = %s\n",Tname.c_str()); fprintf(fp,"Owner name = %s\n",Oname.c_str()); fprintf(fp,"attr = %u\n",attr); fprintf(fp,"bin = %u\n",bin); Ns_0::Dump(fp); fprintf(fp,"Ns_sup------------------------------------\n"); } //============================================================================== Ns_tsk::Ns_tsk(Ns_el::Tindex_t *,vector<string> & vs) { Ename = vs[0]; Oname = vs[1]; } //------------------------------------------------------------------------------ void Ns_tsk::Dump(FILE * fp) { fprintf(fp,"Ns_tsk++++++++++++++++++++++++++++++++++++\n"); fprintf(fp,"Owner name = %s\n",Oname.c_str()); Ns_0::Dump(fp); fprintf(fp,"Ns_tsk------------------------------------\n"); } //============================================================================== Ns_own::Ns_own(Ns_el::Oindex_t *,vector<string> & vs) { Ename = vs[0]; } //------------------------------------------------------------------------------ void Ns_own::Dump(FILE * fp) { fprintf(fp,"Ns_own++++++++++++++++++++++++++++++++++++\n"); Ns_0::Dump(fp); fprintf(fp,"Ns_own------------------------------------\n"); } //==============================================================================
[ "adr1r17@soton.ac.uk" ]
adr1r17@soton.ac.uk
ce12673eeaec9d4c404ace64c2a7896131bb7f43
43101a53873405918a35d6972afe8173289d3163
/leetcode/quick_sort.cpp
85c7ebdf109236fbe60c2b460b4042be46f11109
[]
no_license
dycforever/program
ba796c0b43d6a6353f93793a9c3c4d4d49e919bd
10259b95c5e92303e40117f97a5735c8306214a5
refs/heads/master
2021-06-29T17:52:52.768063
2021-01-31T10:37:29
2021-01-31T10:37:29
12,435,452
0
0
null
null
null
null
UTF-8
C++
false
false
1,678
cpp
#include <iostream> #include <vector> #include <random> #include <tuple> using namespace std; void qs(vector<float>& data, size_t start, size_t end) { float* dataPtr = data.data(); if (end <= 1 + start) { return; } if (end == 2 + start) { if (data[start] <= data[start + 1]) { return; } swap(data[start], data[start + 1]); return; } size_t lpos = start; size_t rpos = end - 1; size_t middle = start + (end - start) / 2; float pivot = data[middle]; while (lpos < rpos) { while (data[lpos] < pivot && lpos < rpos) { lpos++; } while (data[rpos] > pivot && lpos < rpos) { rpos--; } if (lpos != rpos) { swap(data[lpos], data[rpos]); lpos++; } } qs(data, start, lpos); qs(data, lpos, end); } void print(vector<float>& data) { for (auto n : data) { cout << n << ", "; } cout << endl; } bool checkOrder(vector<float>& data) { for (size_t i = 1; i < data.size(); i++) { if (data[i] < data[i-1]) { return false; } } return true; } int main() { std::mt19937_64 rng; std::uniform_real_distribution<double> unif(0, 1); double currentRandomNumber = unif(rng); size_t size = 1000; vector<float> data(size); for (size_t i = 0; i < size; i++) { data[i] = int(unif(rng) * 200); // data[i] = unif(rng); } // print(data); qs(data, 0, data.size()); // print(data); if (checkOrder(data)) { cout << "success\n"; } else { cout << "failed\n"; } }
[ "yichuan.dingyc@alibaba-inc.com" ]
yichuan.dingyc@alibaba-inc.com
5ab0a678172a211f516b94fad07fb3d707e642e4
9da899bf6541c6a0514219377fea97df9907f0ae
/Editor/BlueprintGraph/Classes/K2Node_Literal.h
c81fd22f5e628d188fcfc61acedbda7d194512dc
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,109
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "K2Node.h" #include "Textures/SlateIcon.h" #include "K2Node_Literal.generated.h" class AActor; class FBlueprintActionDatabaseRegistrar; class UEdGraphPin; UCLASS(MinimalAPI) class UK2Node_Literal : public UK2Node { GENERATED_UCLASS_BODY() private: /** If this is an object reference literal, keep a reference here so that it can be updated as objects move around */ UPROPERTY() TObjectPtr<class UObject> ObjectRef; public: //~ Begin UEdGraphNode Interface virtual void AllocateDefaultPins() override; virtual FText GetTooltipText() const override; virtual FLinearColor GetNodeTitleColor() const override; virtual FText GetNodeTitle(ENodeTitleType::Type TitleType) const override; virtual bool ShouldOverridePinNames() const override { return true; } virtual FSlateIcon GetIconAndTint(FLinearColor& OutColor) const override; //~ End UEdGraphNode Interface //~ Begin UK2Node Interface virtual bool IsNodePure() const override { return true; } virtual AActor* GetReferencedLevelActor() const override; virtual bool DrawNodeAsVariable() const override { return true; } virtual ERedirectType DoPinsMatchForReconstruction(const UEdGraphPin* NewPin, int32 NewPinIndex, const UEdGraphPin* OldPin, int32 OldPinIndex) const override; virtual bool NodeCausesStructuralBlueprintChange() const override { return true; } virtual void PostReconstructNode() override; virtual class FNodeHandlingFunctor* CreateNodeHandler(class FKismetCompilerContext& CompilerContext) const override; virtual void GetMenuActions(FBlueprintActionDatabaseRegistrar& ActionRegistrar) const override; //~ End UK2Node Interface /** Accessor for the value pin of the node */ BLUEPRINTGRAPH_API UEdGraphPin* GetValuePin() const; /** Sets the LiteralValue for the pin, and changes the pin type, if necessary */ BLUEPRINTGRAPH_API void SetObjectRef(UObject* NewValue); /** Gets the referenced object */ BLUEPRINTGRAPH_API UObject* GetObjectRef() const { return ObjectRef; } };
[ "ouczbs@qq.com" ]
ouczbs@qq.com
4b974df7ca755cafb9169622c0525e0d90878738
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/BRepBuilderAPI_MakeEdge.hxx
48c2f8ba198ca27a8dc2cc7b508144469d071600
[]
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
15,058
hxx
// 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. #ifndef _BRepBuilderAPI_MakeEdge_HeaderFile #define _BRepBuilderAPI_MakeEdge_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _BRepLib_MakeEdge_HeaderFile #include <BRepLib_MakeEdge.hxx> #endif #ifndef _BRepBuilderAPI_MakeShape_HeaderFile #include <BRepBuilderAPI_MakeShape.hxx> #endif #ifndef _Standard_Real_HeaderFile #include <Standard_Real.hxx> #endif #ifndef _Handle_Geom_Curve_HeaderFile #include <Handle_Geom_Curve.hxx> #endif #ifndef _Handle_Geom2d_Curve_HeaderFile #include <Handle_Geom2d_Curve.hxx> #endif #ifndef _Handle_Geom_Surface_HeaderFile #include <Handle_Geom_Surface.hxx> #endif #ifndef _Standard_Boolean_HeaderFile #include <Standard_Boolean.hxx> #endif #ifndef _BRepBuilderAPI_EdgeError_HeaderFile #include <BRepBuilderAPI_EdgeError.hxx> #endif class StdFail_NotDone; class TopoDS_Vertex; class gp_Pnt; class gp_Lin; class gp_Circ; class gp_Elips; class gp_Hypr; class gp_Parab; class Geom_Curve; class Geom2d_Curve; class Geom_Surface; class TopoDS_Edge; //! Provides methods to build edges. <br> //! <br> //! The methods have the following syntax, where <br> //! TheCurve is one of Lin, Circ, ... <br> //! <br> //! Create(C : TheCurve) <br> //! <br> //! Makes an edge on the whole curve. Add vertices <br> //! on finite curves. <br> //! <br> //! Create(C : TheCurve; p1,p2 : Real) <br> //! <br> //! Make an edge on the curve between parameters p1 <br> //! and p2. if p2 < p1 the edge will be REVERSED. If <br> //! p1 or p2 is infinite the curve will be open in <br> //! that direction. Vertices are created for finite <br> //! values of p1 and p2. <br> //! <br> //! Create(C : TheCurve; P1, P2 : Pnt from gp) <br> //! <br> //! Make an edge on the curve between the points P1 <br> //! and P2. The points are projected on the curve <br> //! and the previous method is used. An error is <br> //! raised if the points are not on the curve. <br> //! <br> //! Create(C : TheCurve; V1, V2 : Vertex from TopoDS) <br> //! <br> //! Make an edge on the curve between the vertices <br> //! V1 and V2. Same as the previous but no vertices <br> //! are created. If a vertex is Null the curve will <br> //! be open in this direction. <br> class BRepBuilderAPI_MakeEdge : public BRepBuilderAPI_MakeShape { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } Standard_EXPORT BRepBuilderAPI_MakeEdge(); Standard_EXPORT BRepBuilderAPI_MakeEdge(const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Lin& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Lin& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Lin& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Lin& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Circ& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Circ& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Circ& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Circ& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Elips& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Elips& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Elips& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Elips& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Hypr& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Hypr& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Hypr& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Hypr& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Parab& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Parab& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Parab& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const gp_Parab& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L,const gp_Pnt& P1,const gp_Pnt& P2,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom_Curve)& L,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S,const gp_Pnt& P1,const gp_Pnt& P2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2); Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S,const gp_Pnt& P1,const gp_Pnt& P2,const Standard_Real p1,const Standard_Real p2); //! The general method to directly create an edge is to give <br> //! - a 3D curve C as the support (geometric domain) of the edge, <br> //! - two vertices V1 and V2 to limit the curve (definition of the restriction of <br> //! the edge), and <br> //! - two real values p1 and p2 which are the parameters for the vertices V1 and V2 <br> //! on the curve. <br> //! The curve may be defined as a 2d curve in the parametric space of a surface: a <br> //! pcurve. The surface on which the edge is built is then kept at the level of the edge. <br> //! The default tolerance will be associated with this edge. <br> //! Rules applied to the arguments: <br> //! For the curve: <br> //! - The curve must not be a 'null handle'. <br> //! - If the curve is a trimmed curve the basis curve is used. <br> //! For the vertices: <br> //! - Vertices may be null shapes. When V1 or V2 is null the edge is open in the <br> //! corresponding direction and the parameter value p1 or p2 must be infinite <br> //! (remember that Precision::Infinite() defines an infinite value). <br> //! - The two vertices must be identical if they have the same 3D location. <br> //! Identical vertices are used in particular when the curve is closed. <br> //! For the parameters: <br> //! - The parameters must be in the parametric range of the curve (or the basis <br> //! curve if the curve is trimmed). If this condition is not satisfied the edge is not <br> //! built, and the Error function will return BRepAPI_ParameterOutOfRange. <br> //! - Parameter values must not be equal. If this condition is not satisfied (i.e. <br> //! if | p1 - p2 | ) the edge is not built, and the Error function will return <br> //! BRepAPI_LineThroughIdenticPoints. <br> //! Parameter values are expected to be given in increasing order: <br> //! C->FirstParameter() <br> //! - If the parameter values are given in decreasing order the vertices are switched, <br> //! i.e. the "first vertex" is on the point of parameter p2 and the "second vertex" is <br> //! on the point of parameter p1. In such a case, to keep the original intent of the <br> //! construction, the edge will be oriented "reversed". <br> //! - On a periodic curve the parameter values p1 and p2 are adjusted by adding or <br> //! subtracting the period to obtain p1 in the parametric range of the curve, and p2] <br> //! such that [ p1 , where Period is the period of the curve. <br> //! - A parameter value may be infinite. The edge is open in the corresponding <br> //! direction. However the corresponding vertex must be a null shape. If this condition <br> //! is not satisfied the edge is not built, and the Error function will return <br> //! BRepAPI_PointWithInfiniteParameter. <br> //! - The distance between the vertex and the point evaluated on the curve with the <br> //! parameter, must be lower than the precision of the vertex. If this condition is not <br> //! satisfied the edge is not built, and the Error function will return <br> //! BRepAPI_DifferentsPointAndParameter. <br> //! Other edge constructions <br> //! - The parameter values can be omitted, they will be computed by projecting the <br> //! vertices on the curve. Note that projection is the only way to evaluate the <br> //! parameter values of the vertices on the curve: vertices must be given on the curve, <br> //! i.e. the distance from a vertex to the curve must be less than or equal to the <br> //! precision of the vertex. If this condition is not satisfied the edge is not built, <br> //! and the Error function will return BRepAPI_PointProjectionFailed. <br> //! - 3D points can be given in place of vertices. Vertices will be created from the <br> //! points (with the default topological precision Precision::Confusion()). <br> //! Note: <br> //! - Giving vertices is useful when creating a connected edge. <br> //! - If the parameter values correspond to the extremities of a closed curve, <br> //! points must be identical, or at least coincident. If this condition is not <br> //! satisfied the edge is not built, and the Error function will return <br> //! BRepAPI_DifferentPointsOnClosedCurve. <br> //! - The vertices or points can be omitted if the parameter values are given. The <br> //! points will be computed from the parameters on the curve. <br> //! The vertices or points and the parameter values can be omitted. The first and last <br> //! parameters of the curve will then be used. <br> Standard_EXPORT BRepBuilderAPI_MakeEdge(const Handle(Geom2d_Curve)& L,const Handle(Geom_Surface)& S,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2,const Standard_Real p1,const Standard_Real p2); Standard_EXPORT void Init(const Handle(Geom_Curve)& C) ; Standard_EXPORT void Init(const Handle(Geom_Curve)& C,const Standard_Real p1,const Standard_Real p2) ; Standard_EXPORT void Init(const Handle(Geom_Curve)& C,const gp_Pnt& P1,const gp_Pnt& P2) ; Standard_EXPORT void Init(const Handle(Geom_Curve)& C,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2) ; Standard_EXPORT void Init(const Handle(Geom_Curve)& C,const gp_Pnt& P1,const gp_Pnt& P2,const Standard_Real p1,const Standard_Real p2) ; Standard_EXPORT void Init(const Handle(Geom_Curve)& C,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2,const Standard_Real p1,const Standard_Real p2) ; Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S) ; Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S,const Standard_Real p1,const Standard_Real p2) ; Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S,const gp_Pnt& P1,const gp_Pnt& P2) ; Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2) ; Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S,const gp_Pnt& P1,const gp_Pnt& P2,const Standard_Real p1,const Standard_Real p2) ; //! Defines or redefines the arguments for the construction of an edge. <br> //! This function is currently used after the empty constructor BRepAPI_MakeEdge(). <br> Standard_EXPORT void Init(const Handle(Geom2d_Curve)& C,const Handle(Geom_Surface)& S,const TopoDS_Vertex& V1,const TopoDS_Vertex& V2,const Standard_Real p1,const Standard_Real p2) ; //! Returns true if the edge is built. <br> Standard_EXPORT virtual Standard_Boolean IsDone() const; //! Returns the construction status <br> //! - BRepBuilderAPI_EdgeDone if the edge is built, or <br> //! - another value of the BRepBuilderAPI_EdgeError <br> //! enumeration indicating the reason of construction failure. <br> Standard_EXPORT BRepBuilderAPI_EdgeError Error() const; //! Returns the constructed edge. <br> //! Exceptions StdFail_NotDone if the edge is not built. <br> Standard_EXPORT const TopoDS_Edge& Edge() const; Standard_EXPORT operator TopoDS_Edge() const; //! Returns the first vertex of the edge. May be Null. <br> //! <br> Standard_EXPORT const TopoDS_Vertex& Vertex1() const; //! Returns the second vertex of the edge. May be Null. <br> //! <br> //! Warning <br> //! The returned vertex in each function corresponds respectively to <br> //! - the lowest, or <br> //! - the highest parameter on the curve along which the edge is built. <br> //! It does not correspond to the first or second vertex <br> //! given at the time of the construction, if the edge is oriented reversed. <br> //! Exceptions <br> //! StdFail_NotDone if the edge is not built. <br> Standard_EXPORT const TopoDS_Vertex& Vertex2() const; protected: private: BRepLib_MakeEdge myMakeEdge; }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
690b8c003294ca7e5527f5b748839ca093ed25b4
97ca456c57dd3e5e4e05c8ec23f61efb744431c7
/.bak/SbrYYY.h
2a2354b96354abc23616ee393a7b835a58642c4f
[]
no_license
kwokhung/testESP32
870b807749b7ff3b77dbb91d6e4bb61f675b9953
0005d5b8e131b86cda8d29c1be6325d58b86d3ab
refs/heads/master
2020-12-30T11:02:32.516155
2019-03-18T04:56:37
2019-03-18T04:56:37
98,839,362
0
0
null
null
null
null
UTF-8
C++
false
false
255
h
#ifndef SbrYYY_h #define SbrYYY_h #include "SbrBase.h" class SbrYYY : public SbrBase<SbrYYY> { public: friend class SbrBase; private: SbrYYY(std::string name) : SbrBase(name) { } void setup() override; void loop() override; }; #endif
[ "chu_kwokhung@yahoo.com.hk" ]
chu_kwokhung@yahoo.com.hk
7c9c1c9dc0884433165e54cae353d62f87e91301
dccb136394c3c7f4a636f17f444ebaf95e24ab66
/Baekjoon/baekjoon_14226.cpp
472fa9ad510946016a4e9f564a03f9a163528e3c
[]
no_license
Oh-kyung-tak/Algorithm
e2b88f6ae8e97130259dedfc30bb48591ae5b2fd
be63f972503170eb8ce06002a2eacd365ade7787
refs/heads/master
2020-04-25T22:37:41.799025
2020-01-19T08:55:42
2020-01-19T08:55:42
173,117,722
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
#include <iostream> #include <algorithm> #include <vector> #include <queue> using namespace std; queue<pair<int,int>> q; int visit[2001][2001] = { 0, }; int N; int copy = 0; int cnt = 0; void check_min() { q.push(make_pair(1,0)); while (1) { int size = q.size(); for (int i = 0; i < size; i++) { int num = q.front().first; int clip = q.front().second; q.pop(); visit[num][clip] = 1; if (num == N) { printf("%d", cnt); return; } q.push(make_pair(num, num)); if (visit[num + clip][clip] == 0 && num + clip <= 1000) { q.push(make_pair(num + clip, clip)); visit[num + clip][clip] = 1; } if (visit[num - 1][clip] == 0 && num - 1 > 0) { q.push(make_pair(num - 1, clip)); visit[num - 1][clip] = 1; } } cnt++; } } int main() { scanf("%d", &N); check_min(); }
[ "noreply@github.com" ]
noreply@github.com
d17fb531f30470b5b7cdd9483fa9965b67c14ef3
ac0b9c85542e6d1ef59c5e9df4618ddf22223ae0
/kratos/applications/PfemFluidDynamicsApplication/pfem_fluid_dynamics_application_variables.cpp
1ea770e7c4d08b2c60464043667041ea53724d94
[]
no_license
UPC-EnricBonet/trunk
30cb6fbd717c1e78d95ec66bc0f6df1a041b2b72
1cecfe201c8c9a1b87b2d87faf8e505b7b1f772d
refs/heads/master
2021-06-04T05:10:06.060945
2016-07-15T15:29:00
2016-07-15T15:29:00
33,677,051
3
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
// // Project Name: KratosPfemFluidDynamicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: February 2016 $ // Revision: $Revision: 0.0 $ // // #include "pfem_fluid_dynamics_application_variables.h" namespace Kratos { ///@name Type Definitions ///@{ ///@} ///@name Kratos Globals ///@{ //Create Variables KRATOS_CREATE_VARIABLE(double, M_MODULUS ) KRATOS_CREATE_VARIABLE(int, PATCH_INDEX ) KRATOS_CREATE_VARIABLE(bool, FREESURFACE ) ///@} }
[ "enriquebonetgil@hotmail.com" ]
enriquebonetgil@hotmail.com
09829d72f3ce4f235ba0add262dd777ea8da7e0d
543baf3f63e6a6b47534b524e54fa90c37613959
/codeforce/189/A.cpp
b68a35b32668a098c776bb7d43a9ee3f9576da9e
[]
no_license
funtion/algorithmProblems
ac9341f9fc5233cffe51d2140404983763b66265
dd27afc25670ea3ad2a681dc382a3e500e530c1a
refs/heads/master
2020-05-04T05:15:44.150235
2014-01-12T10:53:27
2014-01-12T10:53:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
587
cpp
#include <iostream> using namespace std; int n,a,b,c,dp[4001]; int g(int i,int d){ if(i-d<0)return 0; if(i-d==0)return 1; if(dp[i-d]==0)return 0; return dp[i-d]+1; } int main(){ cin>>n>>a>>b>>c; //dp[a]=dp[b]=dp[c] = 1; for(int i=1;i<=n;i++){ //if((i==a||i==b||i==c)&&i!=n)continue; //int aa = (i-a<0 || dp[i-a]==0)?0:dp[i-a]+1; //int bb = (i-b<0 || dp[i-b]==0)?0:dp[i-b]+1; //int cc = (i-c<0 || dp[i-c]==0)?0:dp[i-c]+1; int aa = g(i,a),bb=g(i,b),cc=g(i,c); dp[i] = max(aa,max(bb,cc)); } cout<<dp[n]; }
[ "acm@acm.com" ]
acm@acm.com
5e3763d9582f60ad65fd07b78f99e845d2e3e5c7
ab9324a08e91a44e14204240b57b3085366a1b6f
/Renderer/Renderer/include/Renderer/Buffer/VertexArrayTypes.h
7b2d47c94baab44e365c31ba3edf9f55548fa0a9
[ "MIT" ]
permissive
CitrusForks/unrimp
fe78fe19e5d9ad37135a1eaea652aadb679be7c9
94b68b773999d152667891bd4742910968aefbad
refs/heads/master
2021-01-02T22:46:12.212430
2017-07-30T06:41:50
2017-07-30T10:03:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,232
h
/*********************************************************\ * Copyright (c) 2012-2017 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Renderer/PlatformTypes.h" //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace Renderer { class IVertexBuffer; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Renderer { //[-------------------------------------------------------] //[ Definitions ] //[-------------------------------------------------------] /** * @brief * Vertex attribute format */ enum class VertexAttributeFormat : uint8_t { FLOAT_1 = 0, ///< Float 1 (one component per element, 32 bit floating point per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 FLOAT_2 = 1, ///< Float 2 (two components per element, 32 bit floating point per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 FLOAT_3 = 2, ///< Float 3 (three components per element, 32 bit floating point per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 FLOAT_4 = 3, ///< Float 4 (four components per element, 32 bit floating point per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 R8G8B8A8_UNORM = 4, ///< Unsigned byte 4 (four components per element, 8 bit integer per component), will be passed in a normalized form into shaders, supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 R8G8B8A8_UINT = 5, ///< Unsigned byte 4 (four components per element, 8 bit integer per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 SHORT_2 = 6, ///< Short 2 (two components per element, 16 bit integer per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 SHORT_4 = 7, ///< Short 4 (four components per element, 16 bit integer per component), supported by DirectX 9, DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 UINT_1 = 8 ///< Unsigned integer 1 (one components per element, 32 bit unsigned integer per component), supported by DirectX 10, DirectX 11, OpenGL and OpenGL ES 2 }; //[-------------------------------------------------------] //[ Types ] //[-------------------------------------------------------] /** * @brief * Vertex attribute ("Input element description" in Direct3D terminology) * * @note * - This piece of data is POD and can be serialized/deserialized as a whole (hence the byte alignment compiler setting) */ #pragma pack(push) #pragma pack(1) struct VertexAttribute { // Data destination VertexAttributeFormat vertexAttributeFormat; ///< Vertex attribute format char name[32]; ///< Vertex attribute name char semanticName[32]; ///< Vertex attribute semantic name uint32_t semanticIndex; ///< Vertex attribute semantic index // Data source uint32_t inputSlot; ///< Index of the vertex input slot to use (see "Renderer::VertexArrayVertexBuffer") uint32_t alignedByteOffset; ///< Offset (in bytes) from the start of the vertex to this certain attribute uint32_t strideInBytes; ///< Specifies the size in bytes of each vertex entry uint32_t instancesPerElement; /**< Number of instances to draw with the same data before advancing in the buffer by one element. 0 for no instancing meaning the data is per-vertex instead of per-instance, 1 for drawing one instance with the same data, 2 for drawing two instances with the same data and so on. Instanced arrays is a shader model 3 feature, only supported if "Renderer::Capabilities::instancedArrays" is true. In order to support Direct3D 9, do not use this within the first attribute. */ }; #pragma pack(pop) /** * @brief * Vertex attributes ("vertex declaration" in Direct3D 9 terminology, "input layout" in Direct3D 10 & 11 terminology) * * @see * - "Renderer::IVertexArray" class documentation */ #pragma pack(push) #pragma pack(1) struct VertexAttributes { uint32_t numberOfAttributes; ///< Number of attributes (position, color, texture coordinate, normal...), having zero attributes is valid const VertexAttribute* attributes; ///< At least "numberOfAttributes" instances of vertex array attributes, can be a null pointer in case there are zero attributes, the data is internally copied and you have to free your memory if you no longer need it VertexAttributes() : numberOfAttributes(0), attributes(nullptr) { // Nothing here } VertexAttributes(uint32_t _numberOfAttributes, const VertexAttribute* _attributes) : numberOfAttributes(_numberOfAttributes), attributes(_attributes) { // Nothing here } }; #pragma pack(pop) /** * @brief * Vertex array vertex buffer * * @see * - "Renderer::IVertexArray" class documentation */ struct VertexArrayVertexBuffer { IVertexBuffer* vertexBuffer; ///< Vertex buffer used at this vertex input slot (vertex array instances keep a reference to the vertex buffers used by the vertex array attributes, see "Renderer::IRenderer::createVertexArray()" for details) }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Renderer
[ "cofenberg@gmail.com" ]
cofenberg@gmail.com
f69e04f431df3ee145ef97bd574d6c42097ac3bb
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/VTK/Wrapping/Python/vtkPVEnvironmentInformationPython.cxx
5c27169eef8d0d6314d58eee8e5cf0f44f1182e9
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
8,981
cxx
// python wrapper for vtkPVEnvironmentInformation // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkPythonArgs.h" #include "vtkPythonOverload.h" #include "vtkConfigure.h" #include <vtksys/ios/sstream> #include "vtkIndent.h" #include "vtkPVEnvironmentInformation.h" #if defined(VTK_BUILD_SHARED_LIBS) # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_IMPORT #else # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_EXPORT #endif extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_vtkPVEnvironmentInformation(PyObject *, const char *); } extern "C" { VTK_PYTHON_EXPORT PyObject *PyVTKClass_vtkPVEnvironmentInformationNew(const char *); } #ifndef DECLARED_PyVTKClass_vtkPVInformationNew extern "C" { PyObject *PyVTKClass_vtkPVInformationNew(const char *); } #define DECLARED_PyVTKClass_vtkPVInformationNew #endif static const char **PyvtkPVEnvironmentInformation_Doc(); static PyObject * PyvtkPVEnvironmentInformation_GetClassName(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetClassName"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { const char *tempr = (ap.IsBound() ? op->GetClassName() : op->vtkPVEnvironmentInformation::GetClassName()); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_IsA(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "IsA"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); char *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetValue(temp0)) { int tempr = (ap.IsBound() ? op->IsA(temp0) : op->vtkPVEnvironmentInformation::IsA(temp0)); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_NewInstance(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "NewInstance"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { vtkPVEnvironmentInformation *tempr = (ap.IsBound() ? op->NewInstance() : op->vtkPVEnvironmentInformation::NewInstance()); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); if (result && PyVTKObject_Check(result)) { PyVTKObject_GetObject(result)->UnRegister(0); PyVTKObject_SetFlag(result, VTK_PYTHON_IGNORE_UNREGISTER, 1); } } } return result; } static PyObject * PyvtkPVEnvironmentInformation_SafeDownCast(PyObject *, PyObject *args) { vtkPythonArgs ap(args, "SafeDownCast"); vtkObject *temp0 = NULL; PyObject *result = NULL; if (ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkObject")) { vtkPVEnvironmentInformation *tempr = vtkPVEnvironmentInformation::SafeDownCast(temp0); if (!ap.ErrorOccurred()) { result = ap.BuildVTKObject(tempr); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_CopyFromObject(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "CopyFromObject"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); vtkObject *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkObject")) { if (ap.IsBound()) { op->CopyFromObject(temp0); } else { op->vtkPVEnvironmentInformation::CopyFromObject(temp0); } if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_CopyToStream(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "CopyToStream"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); vtkClientServerStream *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkClientServerStream")) { if (ap.IsBound()) { op->CopyToStream(temp0); } else { op->vtkPVEnvironmentInformation::CopyToStream(temp0); } if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_CopyFromStream(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "CopyFromStream"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); vtkClientServerStream *temp0 = NULL; PyObject *result = NULL; if (op && ap.CheckArgCount(1) && ap.GetVTKObject(temp0, "vtkClientServerStream")) { if (ap.IsBound()) { op->CopyFromStream(temp0); } else { op->vtkPVEnvironmentInformation::CopyFromStream(temp0); } if (!ap.ErrorOccurred()) { result = ap.BuildNone(); } } return result; } static PyObject * PyvtkPVEnvironmentInformation_GetVariable(PyObject *self, PyObject *args) { vtkPythonArgs ap(self, args, "GetVariable"); vtkObjectBase *vp = ap.GetSelfPointer(self, args); vtkPVEnvironmentInformation *op = static_cast<vtkPVEnvironmentInformation *>(vp); PyObject *result = NULL; if (op && ap.CheckArgCount(0)) { char *tempr = (ap.IsBound() ? op->GetVariable() : op->vtkPVEnvironmentInformation::GetVariable()); if (!ap.ErrorOccurred()) { result = ap.BuildValue(tempr); } } return result; } static PyMethodDef PyvtkPVEnvironmentInformation_Methods[] = { {(char*)"GetClassName", PyvtkPVEnvironmentInformation_GetClassName, METH_VARARGS, (char*)"V.GetClassName() -> string\nC++: const char *GetClassName()\n\n"}, {(char*)"IsA", PyvtkPVEnvironmentInformation_IsA, METH_VARARGS, (char*)"V.IsA(string) -> int\nC++: int IsA(const char *name)\n\n"}, {(char*)"NewInstance", PyvtkPVEnvironmentInformation_NewInstance, METH_VARARGS, (char*)"V.NewInstance() -> vtkPVEnvironmentInformation\nC++: vtkPVEnvironmentInformation *NewInstance()\n\n"}, {(char*)"SafeDownCast", PyvtkPVEnvironmentInformation_SafeDownCast, METH_VARARGS | METH_STATIC, (char*)"V.SafeDownCast(vtkObject) -> vtkPVEnvironmentInformation\nC++: vtkPVEnvironmentInformation *SafeDownCast(vtkObject* o)\n\n"}, {(char*)"CopyFromObject", PyvtkPVEnvironmentInformation_CopyFromObject, METH_VARARGS, (char*)"V.CopyFromObject(vtkObject)\nC++: virtual void CopyFromObject(vtkObject *object)\n\nTransfer information about a single object into this object. The\nobject must be a vtkPVEnvironmentInformationHelper.\n"}, {(char*)"CopyToStream", PyvtkPVEnvironmentInformation_CopyToStream, METH_VARARGS, (char*)"V.CopyToStream(vtkClientServerStream)\nC++: virtual void CopyToStream(vtkClientServerStream *)\n\nManage a serialized version of the information.\n"}, {(char*)"CopyFromStream", PyvtkPVEnvironmentInformation_CopyFromStream, METH_VARARGS, (char*)"V.CopyFromStream(vtkClientServerStream)\nC++: virtual void CopyFromStream(const vtkClientServerStream *)\n\nManage a serialized version of the information.\n"}, {(char*)"GetVariable", PyvtkPVEnvironmentInformation_GetVariable, METH_VARARGS, (char*)"V.GetVariable() -> string\nC++: char *GetVariable()\n\nGet the value of an environment variable\n"}, {NULL, NULL, 0, NULL} }; static vtkObjectBase *PyvtkPVEnvironmentInformation_StaticNew() { return vtkPVEnvironmentInformation::New(); } PyObject *PyVTKClass_vtkPVEnvironmentInformationNew(const char *modulename) { PyObject *cls = PyVTKClass_New(&PyvtkPVEnvironmentInformation_StaticNew, PyvtkPVEnvironmentInformation_Methods, "vtkPVEnvironmentInformation", modulename, NULL, NULL, PyvtkPVEnvironmentInformation_Doc(), PyVTKClass_vtkPVInformationNew(modulename)); return cls; } const char **PyvtkPVEnvironmentInformation_Doc() { static const char *docstring[] = { "vtkPVEnvironmentInformation - Information object that can\n\n", "Superclass: vtkPVInformation\n\n", "vtkPVEnvironmentInformation can be used to get values of environment\nvariables.\n\n", NULL }; return docstring; } void PyVTKAddFile_vtkPVEnvironmentInformation( PyObject *dict, const char *modulename) { PyObject *o; o = PyVTKClass_vtkPVEnvironmentInformationNew(modulename); if (o && PyDict_SetItemString(dict, (char *)"vtkPVEnvironmentInformation", o) != 0) { Py_DECREF(o); } }
[ "mpasVM@localhost.org" ]
mpasVM@localhost.org
923b4b7d080f2c0bc155b80d19b037117f55cbdd
ec2eccf877208e5d571f312808dca3b16adade32
/Algorithm/SearchInRotatedSortedArray.cpp
66121d28ca2a15875f0f34522876f4dbb6f59898
[]
no_license
Jerry990612/Cpp_Study
06e130150479d51418cda6dc784c95e58300d818
cd39823c9e2b91cff3af20efdad2aee31caba56d
refs/heads/master
2022-02-15T17:24:22.903058
2019-07-29T03:45:47
2019-07-29T03:45:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,728
cpp
/////////////////////////////////////////////////////////////////////////////////// // 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 // ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 // 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 // 你可以假设数组中不存在重复的元素。 // 你的算法时间复杂度必须是 O(log n) 级别。 ///////////////////////////////////////////////////////////////////////////////// // https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/ ///////////////////////////////////////////////////////////////////////////////// class Solution { public: int search(vector<int>& nums, int target) { if (nums.empty()) return -1; int left = 0, right = nums.size() - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < nums[right]) { if (nums[mid] < target && nums[right] >= target) { left = mid + 1; } else { right = mid - 1; } } else { if (nums[left] <= target && nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } } return -1; } };
[ "noreply@github.com" ]
noreply@github.com
570357f033eeadd658e36e85fdfc352dfacbe692
6ee6cc888f0a82e36fd1687fed4a109f0cb800a7
/leetcode/990.cpp
7993b07c304647a0b1400ba844543038ef30812e
[]
no_license
Rayleigh0328/OJ
1977e3dfc05f96437749b6259eda4d13133d2c87
3d7caaf356c69868a2f4359377ec75e15dafb4c3
refs/heads/master
2021-01-21T04:32:03.645841
2019-12-01T06:33:44
2019-12-01T06:33:44
49,385,474
1
0
null
null
null
null
UTF-8
C++
false
false
1,620
cpp
class DisjointSet{ private: int n; vector<int> leader; vector<int> weight; public: DisjointSet(int size): n(size) { leader = vector<int>(n); weight = vector<int>(n); for (int i=0;i<n;++i) { leader[i] = i; weight[i] = 1; } } int find_set(int k){ if (leader[k] == k) return k; leader[k] = find_set(leader[k]); weight[k] = weight[leader[k]]; return leader[k]; } void union_set(int x, int y){ if (find_set(x) == find_set(y)) return; // always attach smaller weight to larger weight // make sure the set of x have larger weight if (weight[find_set(x)] < weight[find_set(y)]){ union_set(y,x); } else{ weight[find_set(x)] = weight[find_set(x)] + weight[find_set(y)]; leader[find_set(y)] = find_set(x); } } int get_weight(int k){ return weight[find_set(k)]; } void print_leader(){ for (int i=0;i<n;++i){ printf("%d --> %d\n", i, find_set(i)); } } }; class Solution { int relabel(char ch){ return (int) ch - 'a'; } public: bool equationsPossible(vector<string>& equations) { DisjointSet ds(relabel('z') + 1); for (string eq : equations){ if (eq[1] == '=') ds.union_set(relabel(eq[0]), relabel(eq[3])); } for (string eq : equations){ if (eq[1] == '!' && ds.find_set(relabel(eq[0])) == ds.find_set(relabel(eq[3]))) return false; } return true; } };
[ "jingyun.bian@centro-T000325.centro.net" ]
jingyun.bian@centro-T000325.centro.net
ff875a8eaa5bc5c2e49f6081f96cefd3fb41ee69
48e064866defada66f187117ba4a074d2487d041
/src/filebuf.h
ba37b33f435556837bfa75520b315a29c2b7dc0e
[]
no_license
LaoZZZZZ/prefixMatching
efc71500e57cebe55b5863c3175c10038f313a51
e3daa0eded7f77696307e9836061b31694d789de
refs/heads/master
2016-09-11T14:32:17.477712
2015-05-06T15:15:28
2015-05-06T15:15:28
35,166,363
2
0
null
null
null
null
UTF-8
C++
false
false
17,673
h
/* * Copyright 2011, Ben Langmead <langmea@cs.jhu.edu> * * This file is part of Bowtie 2. * * Bowtie 2 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. * * Bowtie 2 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 Bowtie 2. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FILEBUF_H_ #define FILEBUF_H_ #include "suffix_commons.h" using namespace std; namespace prefixMatching{ /** * Simple, fast helper for determining if a character is a newline. */ static inline bool isnewline(int c) { return c == '\r' || c == '\n'; } /** * Simple, fast helper for determining if a character is a non-newline * whitespace character. */ static inline bool isspace_notnl(int c) { return isspace(c) && !isnewline(c); } /** * Simple wrapper for a FILE*, istream or ifstream that reads it in chunks * using fread and keeps those chunks in a buffer. It also services calls to * get(), peek() and gets() from the buffer, reading in additional chunks when * necessary. * * Helper functions do things like parse strings, numbers, and FASTA records. * * */ class FileBuf { public: FileBuf() { init(); } FileBuf(FILE *in) { init(); _in = in; assert(_in != NULL); } FileBuf(std::ifstream *inf) { init(); _inf = inf; assert(_inf != NULL); } FileBuf(std::istream *ins) { init(); _ins = ins; assert(_ins != NULL); } /** * Return true iff there is a stream ready to read. */ bool isOpen() { return _in != NULL || _inf != NULL || _ins != NULL; } /** * Close the input stream (if that's possible) */ void close() { if(_in != NULL && _in != stdin) { fclose(_in); } else if(_inf != NULL) { _inf->close(); } else { // can't close _ins } } /** * Get the next character of input and advance. */ int get() { assert(_in != NULL || _inf != NULL || _ins != NULL); int c = peek(); if(c != -1) { _cur++; if(_lastn_cur < LASTN_BUF_SZ) _lastn_buf[_lastn_cur++] = c; } return c; } /** * Return true iff all input is exhausted. */ bool eof() { return (_cur == _buf_sz) && _done; } /** * Initialize the buffer with a new C-style file. */ void newFile(FILE *in) { _in = in; _inf = NULL; _ins = NULL; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Initialize the buffer with a new ifstream. */ void newFile(std::ifstream *__inf) { _in = NULL; _inf = __inf; _ins = NULL; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Initialize the buffer with a new istream. */ void newFile(std::istream *__ins) { _in = NULL; _inf = NULL; _ins = __ins; _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Restore state as though we just started reading the input * stream. */ void reset() { if(_inf != NULL) { _inf->clear(); _inf->seekg(0, std::ios::beg); } else if(_ins != NULL) { _ins->clear(); _ins->seekg(0, std::ios::beg); } else { rewind(_in); } _cur = BUF_SZ; _buf_sz = BUF_SZ; _done = false; } /** * Peek at the next character of the input stream without * advancing. Typically we can simple read it from the buffer. * Occasionally we'll need to read in a new buffer's worth of data. */ int peek() { assert(_in != NULL || _inf != NULL || _ins != NULL); assert_leq(_cur, _buf_sz); if(_cur == _buf_sz) { if(_done) { // We already exhausted the input stream return -1; } // Read a new buffer's worth of data else { // Get the next chunk if(_inf != NULL) { _inf->read((char*)_buf, BUF_SZ); _buf_sz = _inf->gcount(); } else if(_ins != NULL) { _ins->read((char*)_buf, BUF_SZ); _buf_sz = _ins->gcount(); } else { assert(_in != NULL); _buf_sz = fread(_buf, 1, BUF_SZ, _in); } _cur = 0; if(_buf_sz == 0) { // Exhausted, and we have nothing to return to the // caller _done = true; return -1; } else if(_buf_sz < BUF_SZ) { // Exhausted _done = true; } } } return (int)_buf[_cur]; } /** * Store a string of characters from the input file into 'buf', * until we see a newline, EOF, or until 'len' characters have been * read. */ size_t gets(char *buf, size_t len) { size_t stored = 0; while(true) { int c = get(); if(c == -1) { // End-of-file buf[stored] = '\0'; return stored; } if(stored == len-1 || isnewline(c)) { // End of string buf[stored] = '\0'; // Skip over all end-of-line characters int pc = peek(); while(isnewline(pc)) { get(); // discard pc = peek(); } // Next get() will be after all newline characters return stored; } buf[stored++] = (char)c; } } /** * Store a string of characters from the input file into 'buf', * until we see a newline, EOF, or until 'len' characters have been * read. */ size_t get(char *buf, size_t len) { size_t stored = 0; for(size_t i = 0; i < len; i++) { int c = get(); if(c == -1) return i; buf[stored++] = (char)c; } return len; } static const size_t LASTN_BUF_SZ = 8 * 1024; /** * Keep get()ing characters until a non-whitespace character (or * -1) is reached, and return it. */ int getPastWhitespace() { int c; while(isspace(c = get()) && c != -1); return c; } /** * Keep get()ing characters until a we've passed over the next * string of newline characters (\r's and \n's) or -1 is reached, * and return it. */ int getPastNewline() { int c = get(); while(!isnewline(c) && c != -1) c = get(); while(isnewline(c)) c = get(); assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } /** * Keep get()ing characters until a we've passed over the next * string of newline characters (\r's and \n's) or -1 is reached, * and return it. */ int peekPastNewline() { int c = peek(); while(!isnewline(c) && c != -1) c = get(); while(isnewline(c)) c = get(); assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } /** * Keep peek()ing then get()ing characters until the next return * from peek() is just after the last newline of the line. */ int peekUptoNewline() { int c = peek(); while(!isnewline(c) && c != -1) { get(); c = peek(); } while(isnewline(c)) { get(); c = peek(); } assert_neq(c, '\r'); assert_neq(c, '\n'); return c; } /** * Parse a FASTA record. Append name characters to 'name' and and append * all sequence characters to 'seq'. If gotCaret is true, assuming the * file cursor has already moved just past the starting '>' character. */ template <typename TNameStr, typename TSeqStr> void parseFastaRecord( TNameStr& name, TSeqStr& seq, bool gotCaret = false) { int c; if(!gotCaret) { // Skip over caret and non-newline whitespace c = peek(); while(isspace_notnl(c) || c == '>') { get(); c = peek(); } } else { // Skip over non-newline whitespace c = peek(); while(isspace_notnl(c)) { get(); c = peek(); } } size_t namecur = 0, seqcur = 0; // c is the first character of the fasta name record, or is the first // newline character if the name record is empty while(!isnewline(c) && c != -1) { name[namecur++] = c; get(); c = peek(); } // sequence consists of all the non-whitespace characters between here // and the next caret while(true) { // skip over whitespace while(isspace(c)) { get(); c = peek(); } // if we see caret or EOF, break if(c == '>' || c == -1) break; // append and continue seq[seqcur++] = c; get(); c = peek(); } } /** * Parse a FASTA record and return its length. If gotCaret is true, * assuming the file cursor has already moved just past the starting '>' * character. */ void parseFastaRecordLength( size_t& nameLen, size_t& seqLen, bool gotCaret = false) { int c; nameLen = seqLen = 0; if(!gotCaret) { // Skip over caret and non-newline whitespace c = peek(); while(isspace_notnl(c) || c == '>') { get(); c = peek(); } } else { // Skip over non-newline whitespace c = peek(); while(isspace_notnl(c)) { get(); c = peek(); } } // c is the first character of the fasta name record, or is the first // newline character if the name record is empty while(!isnewline(c) && c != -1) { nameLen++; get(); c = peek(); } // sequence consists of all the non-whitespace characters between here // and the next caret while(true) { // skip over whitespace while(isspace(c)) { get(); c = peek(); } // if we see caret or EOF, break if(c == '>' || c == -1) break; // append and continue seqLen++; get(); c = peek(); } } /** * Reset to the beginning of the last-N-chars buffer. */ void resetLastN() { _lastn_cur = 0; } /** * Copy the last several characters in the last-N-chars buffer * (since the last reset) into the provided buffer. */ size_t copyLastN(char *buf) { memcpy(buf, _lastn_buf, _lastn_cur); return _lastn_cur; } /** * Get const pointer to the last-N-chars buffer. */ const char *lastN() const { return _lastn_buf; } /** * Get current size of the last-N-chars buffer. */ size_t lastNLen() const { return _lastn_cur; } private: void init() { _in = NULL; _inf = NULL; _ins = NULL; _cur = _buf_sz = BUF_SZ; _done = false; _lastn_cur = 0; // no need to clear _buf[] } static const size_t BUF_SZ = 256 * 1024; FILE *_in; std::ifstream *_inf; std::istream *_ins; size_t _cur; size_t _buf_sz; bool _done; UINT8 _buf[BUF_SZ]; // (large) input buffer size_t _lastn_cur; char _lastn_buf[LASTN_BUF_SZ]; // buffer of the last N chars dispensed }; /** * Wrapper for a buffered output stream that writes characters and * other data types. This class is *not* synchronized; the caller is * responsible for synchronization. */ class OutFileBuf { public: /** * Open a new output stream to a file with given name. */ OutFileBuf(const std::string& out, bool isInMem = false,bool binary = false) : name_(out.c_str()), cur_(0), closed_(false) { if(!isInMem) out_ = fopen(out.c_str(), binary ? "wb" : "w"); else{ size_t size = 2*BUF_SZ; char *p = (char *)out.c_str(); out_ = open_memstream(&p,&size); } if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out.c_str() << std::endl; throw 1; } } /** * Open a new output stream to a file with given name. */ OutFileBuf(const std::string& out, const char* option) : name_(out.c_str()), cur_(0), closed_(false) { assert(option); out_ = fopen(out.c_str(), option); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out.c_str() << std::endl; throw 1; } } /** * Open a new output stream to a file with given name. */ OutFileBuf(const char *out, bool binary = false) : name_(out), cur_(0), closed_(false) { assert(out != NULL); out_ = fopen(out, binary ? "wb" : "w"); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out << std::endl; throw 1; } } OutFileBuf(bool isInMem){ if(isInMem){ size_t size = 2*BUF_SZ; out_ = open_memstream(&dest_,&size); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << std::endl; throw 1; } closed_ = false; cur_ = 0; } else{ name_ = "cout"; cur_ = 0; closed_ = false; } } /** * Open a new output stream to standard out. */ OutFileBuf() : name_("cout"), cur_(0), closed_(false) { out_ = stdout; } /** * Close buffer when object is destroyed. */ virtual ~OutFileBuf() { close(); } /** * Open a new output stream to a file with given name. */ void setFile(const char *out, bool binary = false) { assert(out != NULL); out_ = fopen(out, binary ? "wb" : "w"); if(out_ == NULL) { std::cerr << "Error: Could not open alignment output file " << out << std::endl; throw 1; } reset(); } void setFile(FILE* out){ this->close(); assert(out != NULL); //this->close(); out_ = out; reset(); } /** * Write a single character into the write buffer and, if * necessary, flush. */ virtual void write(char c) { assert(!closed_); if(cur_ == BUF_SZ) flush(); buf_[cur_++] = c; } /** * Write a c++ string to the write buffer and, if necessary, flush. */ virtual void writeString(const std::string& s) { assert(!closed_); size_t slen = s.length(); if(cur_ + slen > BUF_SZ) { if(cur_ > 0) flush(); if(slen >= BUF_SZ) { fwrite(s.c_str(), slen, 1, out_); fflush(out_); } else { memcpy(&buf_[cur_], s.data(), slen); assert_eq(0, cur_); cur_ = slen; } } else { memcpy(&buf_[cur_], s.data(), slen); cur_ += slen; } assert_leq(cur_, BUF_SZ); } /** * Write a c++ string to the write buffer and, if necessary, flush. */ template<typename T> void writeString(const T& s) { assert(!closed_); size_t slen = s.length(); if(cur_ + slen > BUF_SZ) { if(cur_ > 0) flush(); if(slen >= BUF_SZ) { fwrite(s.toZBuf(), slen, 1, out_); fflush(out_); } else { memcpy(&buf_[cur_], s.toZBuf(), slen); assert_eq(0, cur_); cur_ = slen; } } else { memcpy(&buf_[cur_], s.toZBuf(), slen); cur_ += slen; } assert_leq(cur_, BUF_SZ); } /** * Write a c++ string to the write buffer and, if necessary, flush. */ virtual void writeChars(const char * s, size_t len) { assert(!closed_); if(cur_ + len > BUF_SZ) { if(cur_ > 0) flush(); if(len >= BUF_SZ) { fwrite(s, len, 1, out_); fflush(out_); } else { memcpy(&buf_[cur_], s, len); assert_eq(0, cur_); cur_ = len; } } else { memcpy(&buf_[cur_], s, len); cur_ += len; } assert_leq(cur_, BUF_SZ); } /** * Write a 0-terminated C string to the output stream. */ virtual void writeChars(const char * s) { writeChars(s, strlen(s)); } /** * Write any remaining bitpairs and then close the input */ virtual void close() { if(closed_) return; if(cur_ > 0) flush(); closed_ = true; if(out_ != stdout) { fclose(out_); } } char* getResult() { return dest_;} /** * Reset so that the next write is as though it's the first. */ virtual void reset() { cur_ = 0; closed_ = false; } virtual void flush() { if(!fwrite((const void *)buf_, cur_, 1, out_)) { std::cerr << "Error while flushing and closing output" << std::endl; std::cerr.flush(); throw 1; } // fflush(out_); cur_ = 0; } //by lu zhao size_t tellp(){ if(out_){ return ftell(out_) + cur_; } else return -1L; } /** * Return true iff this stream is closed. */ virtual bool closed() const { return closed_; } /** * Return the filename. */ virtual const char *name() { return name_; } protected: static const size_t BUF_SZ = 16 * 1024; const char *name_; //char *name_; //changed by luzhao FILE *out_; size_t cur_; char buf_[BUF_SZ]; // (large) input buffer bool closed_; char* dest_; //add by luzhao }; class OutMemBuf : public OutFileBuf{ public: OutMemBuf(char* dest,size_t size = 160*1024){ this->name_ = NULL; this->closed_ = false; this->out_ = NULL; out_ = open_memstream(&dest,&size); this->fileBuf_ = new OutFileBuf(); this->fileBuf_->setFile(out_); } //char* getResult() {return this->dest_;} ~OutMemBuf(){ //delete dest_; //dest_ = NULL; fileBuf_->flush(); this->close(); } /** * Write a single character into the write buffer and, if * necessary, flush. */ void write(char c) { this->fileBuf_->write(c); } /** * Write a c++ string to the write buffer and, if necessary, flush. */ void writeString(const std::string& s) { this->fileBuf_->writeString(s); } /** * Write a c++ string to the write buffer and, if necessary, flush. */ virtual void writeChars(const char * s, size_t len) { this->fileBuf_->writeChars(s,len); } /** * Write a 0-terminated C string to the output stream. */ virtual void writeChars(const char * s) { writeChars(s, strlen(s)); } /** * Write any remaining bitpairs and then close the input */ virtual void close() { //this->fileBuf_->close(); this->fileBuf_->flush(); fclose(out_); this->closed_ = true; } /** * Reset so that the next write is as though it's the first. */ virtual void reset() { this->fileBuf_->reset(); this->closed_ = false; } virtual void flush() { this->fileBuf_->flush(); } /** * Return true iff this stream is closed. */ virtual bool closed() const { return this->closed_; } /** * Return the filename. */ virtual const char *name() { return name_; } private: size_t mem_sz; OutFileBuf* fileBuf_; }; } //namespace #endif /*ndef FILEBUF_H_*/
[ "luzhao1986@gmail.com" ]
luzhao1986@gmail.com
1e7a72795b1bd256888a841d4e566bdba776d4f3
7f91c893175adb12e49c2646588213d38ae3a5fc
/src/ZNode.cpp
e1b3c3c51ad7565b254e24d9ebbce1bc17d2c770
[]
no_license
umbibio/libgbnet
340b32e5a7dddee7e5c7eed1d1289b644ae871db
293659eac29ffc6c19e1a5ba418c887513cc1d9c
refs/heads/master
2020-07-20T08:40:26.830363
2019-09-06T21:40:34
2019-09-06T21:41:34
206,610,438
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
#include "ZNode.h" namespace gbn { ZNode::~ZNode () { // std::cout << "Object at " << this << " destroyed, instance of ZNode \t" << this->id << "\t" << typeid(this).name() << std::endl; } ZNode::ZNode (std::string uid, double a, double b, gsl_rng * rng) : Beta ((std::string) "Z", uid, a, b, rng) {} ZNode::ZNode (std::string uid, double a, double b, double value) : Beta ((std::string) "Z", uid, a, b, value) {} double ZNode::get_children_loglikelihood () { double loglik = 0.; if (this->listen_children) for (auto child: this->children) loglik += child->get_own_loglikelihood(); return loglik; } }
[ "argearriojas@gmail.com" ]
argearriojas@gmail.com
2c07a062144a219a53d637c95493fffc9294ccbf
96bd1d19068e2958103562f578e7df4b92263227
/综合实验四/综合实验四/综合实验四/综合实验四Doc.h
0882ddfc3c5d8712a802f272bc2f96264f3d3e2a
[]
no_license
ChenQL6/chenql2
0c766df826105b0095fdff7676acb90cd4523a59
fcc0e162bf9f77aa38babc9263d81d06df2d40a3
refs/heads/master
2021-04-20T20:54:27.087545
2020-07-11T12:38:19
2020-07-11T12:38:19
249,716,812
1
0
null
null
null
null
GB18030
C++
false
false
974
h
// 综合实验四Doc.h : C综合实验四Doc 类的接口 // #pragma once #include "综合实验四Set.h" class C综合实验四Doc : public CDocument { protected: // 仅从序列化创建 C综合实验四Doc(); DECLARE_DYNCREATE(C综合实验四Doc) // 特性 public: C综合实验四Set m_综合实验四Set; // 操作 public: // 重写 public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // 实现 public: virtual ~C综合实验四Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // 用于为搜索处理程序设置搜索内容的 Helper 函数 void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
[ "1571590774@qq.com" ]
1571590774@qq.com
dcaa45a3697bdbbb927b66b504bf32c99fd8ec6e
6c865d8bdf70871f53f4a6e2caa9573afb0da584
/c_basics/src/octalToHexadecimal.cpp
f123cd079141cb1a1251287f8136e79299141832
[]
no_license
kittusairam/C_RnD
b685d0b542bf3d0f9ba3e43a9b1f8e488328d6af
5b533d72315cd2a2ae190654a42a265daff7d1d0
refs/heads/master
2021-04-27T00:27:18.731062
2018-03-11T16:48:13
2018-03-11T16:48:13
123,818,347
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
cpp
/* OVERVIEW: 1)Write a function which takes a octal number as input and returns the hexadecimal number for octalToHexadecimal(). E.g.: octalToHexadecimal(10) returns 8. 2)Write a function which takes a fractional octal number as input and returns the hexadecimal number for octalToHexadecimalFraction() until precision two E.g.: octalToHexadecimal(6.01) returns 6.04 INPUTS: Single octal number num; OUTPUT: hexadecimal value of the octal number num. Discalimer:Return 0 for invalid cases.[Negetive Numbers] There are no test cases for fraction method but it would be good if you complete that too. */ #include<stdlib.h> #include<math.h> int octalToHexadecimal(int num) { if (num <= 0){ return 0; } long int res = 0,result[32],top=-1; int i = 0; while (num){ res += (num % 10)*(long int)pow(8.0, i++); num /= 10; } while (res){ result[++top] = res % 16; res /= 16; } i = 0; while(i!=top+1){ res +=(result[i]*(int)pow(10.0, i)); i++; } return res; } float octalToHexadecimalFraction(float num) { return 0.0; }
[ "noreply@github.com" ]
noreply@github.com
a53e1ec8760948d09ff09c162f72f975980742d3
25d5843534ee02722f97591c26001db0751f4b3d
/DataStructure_Algorithm/2694_逆波兰表达式.cpp
a68cc83024b5debe50dfbfceb8871d0ec71ac41b
[]
no_license
131250208/DataStructure_Algorithm
50997289dd4040255a11fee6e5e6775f5cee232f
3c0c7f938fd32d7e1ec1ffdc5c61081985205ca3
refs/heads/master
2021-01-15T23:21:24.734988
2017-08-10T13:40:08
2017-08-10T13:40:08
99,925,913
0
0
null
null
null
null
GB18030
C++
false
false
1,597
cpp
/*考前练习*/ #include<iostream> #include<stdio.h> #include<string.h> static char input[100]; using namespace std; double recurse_2694() { scanf("%s", &input); if (strcmp(input, "+") == 0)return recurse_2694() + recurse_2694(); else if (strcmp(input, "-") == 0)return recurse_2694() - recurse_2694(); else if (strcmp(input, "*") == 0)return recurse_2694() * recurse_2694(); else if (strcmp(input, "/") == 0)return recurse_2694() / recurse_2694(); else { return atof(input); } } //int main() { // double res=recurse_2694(); // printf("%f\n", res); // system("pause"); // return 0; //} /*Accepted 错误次数:1 原因:输出没有保留小数点后的0 思路:递归 1、读取到符号,递归计算两个num,并根据读取到的符号计算结果返回 2、读取到数字,转换成浮点数直接返回 注意: cout<<输出不保留小数点后的0; printf("%f\n", v);能保留小数点后的0 */ //#include<iostream> //#include<stdlib.h> //#include<string.h> //using namespace std; //static char input[20]; //double calculate() { // cin >> input; // // if (strcmp(input, "+") == 0 || strcmp(input, "-") == 0 || // strcmp(input, "*") == 0 || strcmp(input, "/") == 0) { // char op = input[0]; // double num1 = calculate(); // double num2 = calculate(); // switch (op) // { // case '+':return num1 + num2; // case '-':return num1 - num2; // case '*':return num1 * num2; // case '/':return num1 / num2; // } // } // else // { // return atof(input); // } //} //int main() { // double v=calculate(); // printf("%f\n", v); // system("pause"); // return 0; //}
[ "wychengpublic@163.com" ]
wychengpublic@163.com
589abdd3e0d6f900a34e05bdc151c497385187e0
9dccda0fc2aa7ac7471b4f38f4eba8b316316fde
/it_kar.cpp
02c79e91e715b85c8316a22f3710a0a362cf0225
[]
no_license
troublefrom2001/pip
218e812eb4ad83520c9dc0bd8f6fcc3ea809db4b
62c377777a853b67d5166ecd3719264e474f9cd2
refs/heads/main
2023-04-29T12:34:11.428246
2021-04-29T06:48:28
2021-04-29T06:48:28
362,716,941
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
#include"h.h" void it_kar(SDL_Renderer *renderer, int x){ for(int i=800; i>730;i-=15){ it_gor(renderer,x, i, x+108,100,100,0); it_gor(renderer,x, i-1, x+108,130,130,0); it_gor(renderer,x, i-2, x+108,160,160,0); it_gor(renderer,x, i-3, x+108,200,200,0);} for(int i=x;i<=x+110;i+=15){ for(int j=0;j<4;j++){it_vert(renderer,i+j,740,800,130,130,0);} } it_vert(renderer,x,700,800,130,130,0); it_vert(renderer,x+108,700,800,130,130,0); it_gor(renderer,x, 700, x+108,100,100,0); it_gor(renderer,x, 699, x+108,130,130,0); it_gor(renderer,x, 698, x+108,160,160,0); it_gor(renderer,x, 697, x+108,200,200,0); } void it_karz(SDL_Renderer *renderer, int x){ for(int i=800; i>730;i-=15){ it_gor(renderer,x, i, x+108,0,0,0); it_gor(renderer,x, i-1, x+108,0,0,0); it_gor(renderer,x, i-2, x+108,0,0,0); it_gor(renderer,x, i-3, x+108,0,0,0);} for(int i=x;i<=x+110;i+=15){ for(int j=0;j<4;j++){it_vert(renderer,i+j,740,800,0,0,0);} } it_vert(renderer,x,700,800,0,0,0); it_vert(renderer,x+108,700,800,0,0,0); it_gor(renderer,x, 700, x+108,0,0,0); it_gor(renderer,x, 699, x+108,0,0,0); it_gor(renderer,x, 698, x+108,0,0,0); it_gor(renderer,x, 697, x+108,0,0,0); }
[ "83391698+troublefrom2001@users.noreply.github.com" ]
83391698+troublefrom2001@users.noreply.github.com
1a1c7837c39c988abd8f2267d31ba347fb038ee8
8531bbb748b168f7437bffae70e5c75b1f86f2af
/project/bench/main.cpp
ea6b1f8967574774bf12a34ba8cde78665ec5d6f
[ "MIT" ]
permissive
linpsong/cpplox
52164ce74310c3ae1bb79789be7baf833372d2a8
6b2b771c50fd3d0121283d1f2e54860e1d263bca
refs/heads/master
2022-05-12T11:49:46.897248
2020-04-09T01:49:53
2020-04-09T01:49:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,101
cpp
#include <iostream> #include <string> // (MSVC) Suppress warnings from dependencies; they're not ours to fix #pragma warning(push, 0) #include <benchmark/benchmark.h> #pragma warning(pop) #include <boost/process.hpp> #include <boost/program_options.hpp> using std::cout; using std::string; namespace process = boost::process; namespace program_options = boost::program_options; int main(int argc, /*const*/ char* argv[]) { program_options::options_description options_description { "Usage: bench [options]\n" "\n" "Options" }; options_description.add_options() ("help", "Print usage information and exit.") ("cpplox-file", program_options::value<string>(), "Required. File path to cpplox executable.") ("test-scripts-path", program_options::value<string>(), "Required. Path to test scripts.") ("jlox-file", program_options::value<string>(), "File path to jlox run cmake script.") ("node-file", program_options::value<string>(), "File path to node executable."); program_options::variables_map variables_map; program_options::store(program_options::parse_command_line(argc, argv, options_description), variables_map); program_options::notify(variables_map); // Check required options or respond to help if ( variables_map.count("help") || !variables_map.count("cpplox-file") || !variables_map.count("test-scripts-path") ) { cout << options_description << "\n"; return 0; } for (string script_name : {"binary_trees", "equality", "fib", "invocation", "properties", "string_equality"}) { benchmark::RegisterBenchmark(("cpplox_" + script_name).c_str(), [script_name, &variables_map] (benchmark::State& state) { const auto cpplox = variables_map.at("cpplox-file").as<string>(); const auto test_script = variables_map.at("test-scripts-path").as<string>() + "/" + script_name + ".lox"; const auto cmd = "\"" + cpplox + "\" \"" + test_script + "\""; for (auto _ : state) { process::ipstream cpplox_out; // Using boost system rather than std system due to errors on Windows. If the command was unquoted with // spaces in the path, then of course I'd get "not a command" errors. But if I wrapped the command in // quotes, then I'd get "syntax is incorrect errors". But boost system works just fine either way. process::system(cmd, process::std_out > cpplox_out); } }); if (variables_map.count("jlox-file") && variables_map.at("jlox-file").as<string>().size()) { benchmark::RegisterBenchmark(("jlox_" + script_name).c_str(), [script_name, &variables_map] (benchmark::State& state) { const auto jlox = variables_map.at("jlox-file").as<string>(); const auto test_script = variables_map.at("test-scripts-path").as<string>() + "/" + script_name + ".lox"; const auto cmd = "cmake -P \"" + jlox + "\" \"" + test_script + "\""; for (auto _ : state) { process::ipstream jlox_out; process::system(cmd, process::std_out > jlox_out); } }); } if (variables_map.count("node-file") && variables_map.at("node-file").as<string>().size()) { benchmark::RegisterBenchmark(("node_" + script_name).c_str(), [script_name, &variables_map] (benchmark::State& state) { const auto node = variables_map.at("node-file").as<string>(); const auto test_script = variables_map.at("test-scripts-path").as<string>() + "/" + script_name + ".js"; const auto cmd = "\"" + node + "\" \"" + test_script + "\""; for (auto _ : state) { process::ipstream node_out; process::system(cmd, process::std_out > node_out); } }); } } benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); }
[ "jeffrey.t.mott@intel.com" ]
jeffrey.t.mott@intel.com
4b32b3730bc8e9c1f543c9d458f1bd1c291bc9f4
ed1542846f8bb8d9f9f27b5ee446911387807a4f
/Final/NYUCodebase/Entity_untextured.cpp
3d8c9ae8c665c8d8a0d27e8a7a1957dfabdc88d8
[]
no_license
ChenZ0912/Game-Programming
3e873e9a300f4f6a97d4ca57bdc80df51e4eed00
a6a622980281426b693ac8c51775e343b7c29eef
refs/heads/master
2020-03-28T04:51:38.165322
2018-12-17T05:31:14
2018-12-17T05:31:14
147,741,271
0
0
null
null
null
null
UTF-8
C++
false
false
1,440
cpp
// // Entity_untextured.cpp // NYUCodebase // // Created by CHEN ZHOU on 12/15/18. // Copyright © 2018 Ivan Safrin. All rights reserved. // #include "Entity_untextured.h" Entity_Untextured::Entity_Untextured(float positionX, float positionY, float sizeX, float sizeY):position(positionX, positionY, 0.0f), size(sizeX, sizeY,0.0f){}; void Entity_Untextured::Draw(ShaderProgram* program){ glm::mat4 projectionMatrix = glm::mat4(1.0f); projectionMatrix = glm::ortho(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f); glm::mat4 viewMatrix = glm::mat4(1.0f); glm::mat4 modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, glm::vec3(position.x, position.y, position.z)); modelMatrix = glm::scale(modelMatrix, glm::vec3(size.x, size.y, size.z)); program->SetProjectionMatrix(projectionMatrix); program->SetModelMatrix(modelMatrix); program->SetViewMatrix(viewMatrix); program->SetColor(0.0f, 0.0f, 0.0f, 0.3f); glUseProgram(program->programID); float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program->positionAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program->positionAttribute); modelMatrix = glm::mat4(1.0f); } void Entity_Untextured::update(float elapsed){}
[ "cz1740@nyu.edu" ]
cz1740@nyu.edu
6f5cff6c45a652e317e0541ab8e2c833b3afda68
96c0a1bf68c18241bc5cd75565e390dddc16c8c0
/programs/CPP/13.cpp
b4e075cba38c5853d94022485dcf0178fe884f77
[]
no_license
abhishekannigeri/abhishekannigeriblog
3ba07b66d7e5eec14d237faa35191291528c09bf
d6a33783cef949706d51b9a0df05976ae6f58f85
refs/heads/master
2021-01-21T23:29:13.416792
2016-03-21T10:14:54
2016-03-21T10:14:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
988
cpp
#include<iostream> #include<cstdlib> using namespace std; int size; class stack1 { public : int a[20],n,top; stack1() { cout<<"Enter stack size\n"; cin>>size; top=0; } void push() { int ele; cout<<"Enter the element\n"; cin>>ele; a[top]=ele; top++; } void pop() { top--; cout<<"Deleted element is:"<<a[top]<<endl; } void display() { cout<<"Stack is :\n"; for(int i=top-1;i>=0;i--) cout<<a[i]<<"\t"; } }; class stack2: public stack1 { public : void push() { if(top==size) cout<<"Stack Overflow\n"; else stack1::push(); } void pop() { if(top==0) cout<<"Stack Underflow\n"; else stack1::pop(); } void display() { if(top==0) cout<<"Stack Empty\n"; else stack1::display(); } }; int main() { stack2 stk; while(1) { cout<<"\n1:PUSH\n2:POP\n3:Display\n4:Exit\n"; cout<<"ENter your choice\n"; int ch; cin>>ch; switch(ch) { case 1: stk.push(); break; case 2: stk.pop(); break; case 3: stk.display(); break; case 4: exit(0); default : cout<<"\nInvalid Choice\n"; break; } } return 0; }
[ "abhishek.anni001@gmail.com" ]
abhishek.anni001@gmail.com
e4a53b110d95297280594e1b6c41e3f80861a232
6d54a7b26d0eb82152a549a6a9dfde656687752c
/src/transport/GroupSession.h
bd3ab1931c2c7cbdc5302ae39dda8ad38f7d3459
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
project-chip/connectedhomeip
81a123d675cf527773f70047d1ed1c43be5ffe6d
ea3970a7f11cd227ac55917edaa835a2a9bc4fc8
refs/heads/master
2023-09-01T11:43:37.546040
2023-09-01T08:01:32
2023-09-01T08:01:32
244,694,174
6,409
1,789
Apache-2.0
2023-09-14T20:56:31
2020-03-03T17:05:10
C++
UTF-8
C++
false
false
4,852
h
/* * Copyright (c) 2021 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <app/util/basic-types.h> #include <lib/core/GroupId.h> #include <lib/core/ReferenceCounted.h> #include <lib/support/Pool.h> #include <transport/Session.h> namespace chip { namespace Transport { class IncomingGroupSession : public Session, public ReferenceCounted<IncomingGroupSession, NoopDeletor<IncomingGroupSession>, 0> { public: IncomingGroupSession(GroupId group, FabricIndex fabricIndex, NodeId peerNodeId) : mGroupId(group), mPeerNodeId(peerNodeId) { SetFabricIndex(fabricIndex); } ~IncomingGroupSession() override { NotifySessionReleased(); VerifyOrDie(GetReferenceCount() == 0); } void Retain() override { ReferenceCounted<IncomingGroupSession, NoopDeletor<IncomingGroupSession>, 0>::Retain(); } void Release() override { ReferenceCounted<IncomingGroupSession, NoopDeletor<IncomingGroupSession>, 0>::Release(); } bool IsActiveSession() const override { return true; } Session::SessionType GetSessionType() const override { return Session::SessionType::kGroupIncoming; } ScopedNodeId GetPeer() const override { return ScopedNodeId(mPeerNodeId, GetFabricIndex()); } ScopedNodeId GetLocalScopedNodeId() const override { return ScopedNodeId(kUndefinedNodeId, GetFabricIndex()); } Access::SubjectDescriptor GetSubjectDescriptor() const override { Access::SubjectDescriptor subjectDescriptor; subjectDescriptor.authMode = Access::AuthMode::kGroup; subjectDescriptor.subject = NodeIdFromGroupId(mGroupId); subjectDescriptor.fabricIndex = GetFabricIndex(); return subjectDescriptor; } bool RequireMRP() const override { return false; } const ReliableMessageProtocolConfig & GetRemoteMRPConfig() const override { static const ReliableMessageProtocolConfig cfg(GetDefaultMRPConfig()); VerifyOrDie(false); return cfg; } System::Clock::Timestamp GetMRPBaseTimeout() const override { return System::Clock::kZero; } System::Clock::Milliseconds32 GetAckTimeout() const override { VerifyOrDie(false); return System::Clock::Timeout(); } GroupId GetGroupId() const { return mGroupId; } private: const GroupId mGroupId; const NodeId mPeerNodeId; }; class OutgoingGroupSession : public Session, public ReferenceCounted<OutgoingGroupSession, NoopDeletor<OutgoingGroupSession>, 0> { public: OutgoingGroupSession(GroupId group, FabricIndex fabricIndex) : mGroupId(group) { SetFabricIndex(fabricIndex); } ~OutgoingGroupSession() override { NotifySessionReleased(); VerifyOrDie(GetReferenceCount() == 0); } void Retain() override { ReferenceCounted<OutgoingGroupSession, NoopDeletor<OutgoingGroupSession>, 0>::Retain(); } void Release() override { ReferenceCounted<OutgoingGroupSession, NoopDeletor<OutgoingGroupSession>, 0>::Release(); } bool IsActiveSession() const override { return true; } Session::SessionType GetSessionType() const override { return Session::SessionType::kGroupOutgoing; } // Peer node ID is unused: users care about the group, not the node ScopedNodeId GetPeer() const override { return ScopedNodeId(); } // Local node ID is unused: users care about the group, not the node ScopedNodeId GetLocalScopedNodeId() const override { return ScopedNodeId(); } Access::SubjectDescriptor GetSubjectDescriptor() const override { return Access::SubjectDescriptor(); // no subject exists for outgoing group session. } bool RequireMRP() const override { return false; } const ReliableMessageProtocolConfig & GetRemoteMRPConfig() const override { static const ReliableMessageProtocolConfig cfg(GetDefaultMRPConfig()); VerifyOrDie(false); return cfg; } System::Clock::Timestamp GetMRPBaseTimeout() const override { return System::Clock::kZero; } System::Clock::Milliseconds32 GetAckTimeout() const override { VerifyOrDie(false); return System::Clock::Timeout(); } GroupId GetGroupId() const { return mGroupId; } private: const GroupId mGroupId; }; } // namespace Transport } // namespace chip
[ "noreply@github.com" ]
noreply@github.com
9acec153863cafae9b8c9ecae75a3727ba973960
fa6b5a15bd5d7ed857c1705e26f58f7f6452c1cd
/BINARY TREE/10.RIght_view.cpp
53a827b76d5dff4ff2ba355eaf078166784eed92
[]
no_license
retro-2106/DSA_450_questions
d4cadc840f168a388db5258581712372be3e8629
7b23eba2661d6596870848ca3e3d1582236ca46f
refs/heads/main
2023-06-14T13:08:35.856589
2021-07-04T11:28:21
2021-07-04T11:28:21
308,229,380
1
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
ector<int> rightView(Node *root) { vector<int> ans; if(!root) return ans; queue<Node*> qu; qu.push(root); while(!qu.empty()) { int n = qu.size(); for(int i=1;i<=n;i++) { if(i == n) { ans.push_back(qu.front()->data); } Node *front = qu.front(); qu.pop(); if(front->left) { qu.push(front->left); } if(front->right) { qu.push(front->right); } } } return ans; }
[ "ashishcool2106@gmail.com" ]
ashishcool2106@gmail.com
36a120c57abc478dc2ce63986ec7e2d7b38e9f79
b01adb671949fcd94e1c4c29fd21bb5382785a85
/GeeksForGeeks/Left View of Binary Tree.cpp
5412139453f663aa21dbb21372fbe6de18b6fb2e
[ "MIT" ]
permissive
tanishq1g/cp_codes
c13f4841cbd3226c3600abc75eecb970aa416962
80b8ccc9e195a66d6d317076fdd54a02cd21275b
refs/heads/master
2021-06-20T00:37:48.926709
2021-02-05T17:59:10
2021-02-05T17:59:10
170,661,173
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include <iostream> #include <string> #include <vector> #include <locale> #include <algorithm> #include <cmath> #include <unordered_map> #include <bitset> #include <climits> #include <queue> using namespace std; // TREE struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; // A wrapper over leftViewUtil() void leftView(Node *root){ // Your code here if(root == NULL) return; queue<Node*> q; q.push(root); int s = q.size(); Node* temp = NULL; while(s != 0){ for(int i = 0; i < s; i++){ temp = q.front(); q.pop(); if(i == 0){ cout << temp->data << ' '; } if(temp->left != NULL){ q.push(temp->left); } if(temp->right != NULL){ q.push(temp->right); } } s = q.size(); } }
[ "tanishq.gupta@iiitb.org" ]
tanishq.gupta@iiitb.org
eb68be0f743ad07198bb97c7fabbbe65c777cd5c
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/tr1/4_metaprogramming/is_pod/value.cc
d7fdb4594adf003c6f5853e5ca4ae006084b4d68
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
1,963
cc
// 2004-12-26 Paolo Carlini <pcarlini@suse.de> // // Copyright (C) 2004-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, or (at your option) // any later version. // // 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 General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 4.5.3 Type properties #include <tr1/type_traits> #include <testsuite_hooks.h> #include <testsuite_tr1.h> void test01() { using std::tr1::is_pod; using namespace __gnu_test; VERIFY( (test_category<is_pod, void>(true)) ); VERIFY( (test_category<is_pod, int>(true)) ); VERIFY( (test_category<is_pod, float>(true)) ); VERIFY( (test_category<is_pod, EnumType>(true)) ); VERIFY( (test_category<is_pod, int*>(true)) ); VERIFY( (test_category<is_pod, int(*)(int)>(true)) ); VERIFY( (test_category<is_pod, int (ClassType::*)>(true)) ); VERIFY( (test_category<is_pod, int (ClassType::*) (int)>(true)) ); VERIFY( (test_category<is_pod, int[2]>(true)) ); VERIFY( (test_category<is_pod, float[][3]>(true)) ); VERIFY( (test_category<is_pod, EnumType[2][3][4]>(true)) ); VERIFY( (test_category<is_pod, int*[3]>(true)) ); VERIFY( (test_category<is_pod, int(*[][2])(int)>(true)) ); VERIFY( (test_category<is_pod, int (ClassType::*[2][3])>(true)) ); VERIFY( (test_category<is_pod, int (ClassType::*[][2][3]) (int)>(true)) ); VERIFY( (test_category<is_pod, ClassType>(true)) ); } int main() { test01(); return 0; }
[ "rink@rink.nu" ]
rink@rink.nu
ece3a25be1217260d7f69b044a687abe2a446463
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmbs12/pmsb13-data-20120615/sources/brbym28nz827lxic/404/sandbox/meyerclp/apps/dreme/dreme.cpp
95e6fd01f622de5ae68b7cd37cb2a046d7c9be8c
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
UTF-8
C++
false
false
5,353
cpp
#include "dreme.h" using namespace seqan; int main(int argc, char const ** argv){ Seq sequences; Seq background; IupacMaps IMaps; unsigned int kmer_len=4; unsigned int kmer_len_end=6; MapIupac(IMaps);//IupacMap for generalization if(argc !=3){ std::cerr<<"ERROR: Invalid argument count."<<std:: endl <<"Usage:" <<argv[0]<<"File"<<std::endl; return 1; } readFastA(sequences,argv[1]); //readFastA(background,argv[2]); //PrintFastA(sequences);//Debug background.seqs=sequences.seqs; sequences.SeqsNumber=length(sequences.seqs);//number of sequences background.SeqsNumber=length(background.seqs);//number of sequences for(unsigned int i=0;i<sequences.SeqsNumber-1;++i){ std::random_shuffle(begin(background.seqs[i]),end(background.seqs[i])); std::random_shuffle(begin(background.seqs[i]),end(background.seqs[i])); std::random_shuffle(begin(background.seqs[i]),end(background.seqs[i])); std::random_shuffle(begin(background.seqs[i]),end(background.seqs[i])); //std::random_shuffle(begin(background.seqs[i]),end(background.seqs[i])); } /*std::ofstream outfile; outfile.open("test2.fasta"); write2(outfile,sequences.ids,background.seqs,Fasta()); outfile.close(); std::ofstream output;*/ //PrintFastA(background);//Debug logFactorial(sequences.SeqsNumber+background.SeqsNumber);//save all relevant factorial numbers int c=0; // Anzahl der Motive, provisorisch do{ std::cout<<"new "<<std::endl; initST(sequences); initST(background); std::cout<<"init done"<<std::endl; sequences.generalizedSortedPValue.clear(); /***** - Bruteforce --> gets alls possible motifs form length 3 to 8 and counts them. - Only one occurence per sequence allowed *****/ initExactKmer(sequences,background,kmer_len,kmer_len_end); std::cout<<"Exact done"<<std::endl; /***** - Computes the pValue of each motif due to the counter and saves it in SortedPValue *****/ FisherExactTest(sequences,background); std::cout<<"Fisher done"<<std::endl; /***** - initiate by repeatedly picking the top motifs from SortedPValue - calls GeneralizeKmer and adds one wildcard to the Kmer and estimates the counter - after one generalization-round(top 100 motifs) the FisherExactTest is called, to compute the new SortedPValue-Map - if there is a pValue<treshold start again by picking the new top motifs *****/ //PrintMap(sequences.SortedPValue); InitGeneralization(IMaps,sequences,background); std::cout<<"Generalize done"<<std::endl; PrintMap(sequences.generalizedSortedPValue); sequences.seqCounter.clear(); background.seqCounter.clear(); sequences.SortedPValueReversed.clear(); /***** - if there is not a single pValue<treshold exit the programm *****/ if(sequences.generalizedSortedPValue.size()==0){ std::cout<<"Could not find a pValue<treshold"; std::exit(1); } //PrintMap(sequences.generalizedSortedPValue); std::map<String<Iupac>,unsigned int > seqCounter; std::map<String<Iupac>,unsigned int > backCounter; Finder<Index<StringSet<String<Dna5> > > > finder(sequences.SArray); Finder<Index<StringSet<String<Dna5> > > > finderB(background.SArray);//finder ins struct /***** - gets the top 100(generalized) motifs and computes the exact counter and pValue *****/ exactGeneralizeCount(seqCounter,backCounter, finder, finderB,sequences,background, IMaps); std::cout<<"exactGeneralize done"<<std::endl; //PrintFastA(sequences); PrintMap(sequences.generalizedSortedPValue); //std::cout<<sequences.generalizedSortedPValue.begin()->second; std::map<unsigned int,std::map<Iupac,double> > freqMatrix; std::map<unsigned int,std::map<Iupac,double> > freqMatrixB; /*output.open("output.fasta",std::ios::out|std::ios::app); write(output,(*sequences.generalizedSortedPValue.begin()).second); write(output," "); output.close();*/ /***** - Computes the probability of each nucleotide to appear at each position (from the top motif) - first output *****/ String<unsigned int> replaceString; String<unsigned int> replaceStringB; BuildFrequencyMatrix(freqMatrix,seqCounter, finder, (*sequences.generalizedSortedPValue.begin()).second,sequences,IMaps, replaceString); BuildFrequencyMatrix(freqMatrixB,backCounter, finderB, (*sequences.generalizedSortedPValue.begin()).second,background,IMaps,replaceStringB); std::cout<<(*sequences.generalizedSortedPValue.begin()).second<<std::endl; unsigned int KmerLength = length((*sequences.generalizedSortedPValue.begin()).second); bool foreground = true; PrintMap(freqMatrix,KmerLength,foreground); foreground=false; PrintMap(freqMatrixB,KmerLength,foreground); freqMatrix.clear(); freqMatrixB.clear(); sequences.generalizedKmer.clear(); sequences.seqCounter.clear(); sequences.SortedPValue.clear(); sequences.SortedPValueReversed.clear(); background.seqCounter.clear(); //std::cout<<replaceString[0]<<" "<<replaceString[1]<<" "<<replaceString[2]<<" "<<sequences.intervals[replaceString[0]]; //replaceKmer(sequences,replaceString); //replaceKmer(background,replaceStringB); clear(replaceString); clear(replaceStringB); //PrintFastA(sequences); clear(sequences.SArray); clear(background.SArray); //std::cout<<sequences.generalizedSortedPValue.begin()->first<<std::endl; ++c; } while(sequences.generalizedSortedPValue.begin()->first<0.05 && c<1); return 0; }
[ "mail@bkahlert.com" ]
mail@bkahlert.com
9222b3df4929e2dfbcd5d9588a281b9ab68509dd
9b11f561510070d40be43addeccc743f91025cfa
/codeforces/1279/A.cpp
c6794ae66614fd16c19606f7d9c07f103da3734a
[]
no_license
MasterMind90/cppractice
a5a1774fc87047c9c9f18ed6df2a58af4a027256
ce1b74d9e682e5d369df62f3ad9494798dceda85
refs/heads/master
2023-02-21T04:58:50.101142
2019-05-08T14:41:00
2021-01-14T21:11:38
328,998,830
0
0
null
null
null
null
UTF-8
C++
false
false
1,388
cpp
#ifndef LOCAL #pragma GCC optimize("O3") #endif #include "bits/stdc++.h" using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << '\n'; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " #define fastio ios_base::sync_with_stdio(false);cin.tie(0); typedef long long ll; const ll MOD = 1e9 + 7 ; const ll N = 2e5 + 10 ; const ll INF = 1e9 + 10 ; int main(){ fastio int t ; cin >> t ; while(t--){ vector<int> v(3) ; for(int i = 0; i < 3; i++) cin >> v[i] ; sort(v.begin(), v.end()) ; if ( v[0] + v[1] < v[2] - 1 ){ cout << "No" << endl; } else cout << "Yes" << endl; } return 0; }
[ "amjadm2008@gmail.com" ]
amjadm2008@gmail.com
7e1e41099347d05f78838602ff6e0ef76b80b416
159eed90e970c568c811bacbb37f2c9fc66233ef
/Detector/DetComponents/src/GeoSvc.h
1e3d74f5f4b15ee32bd7da98023348dafd97c438
[]
no_license
ocolegro/100TeVFWK
ca92cf530495094ca75995eb79e03d01a0ba244e
88dcbf47e7210ba9ac581324f95e7b094ada49dc
refs/heads/master
2020-12-10T03:13:29.360118
2017-06-26T09:07:54
2017-06-26T09:07:54
95,428,328
0
1
null
null
null
null
UTF-8
C++
false
false
1,936
h
// // GeoSvc.h // // // Created by Julia Hrdinka on 30/03/15. // // #ifndef GEOSVC_H #define GEOSVC_H // Interface #include "DetInterface/IGeoSvc.h" // Gaudi #include "GaudiKernel/IIncidentListener.h" #include "GaudiKernel/IIncidentSvc.h" #include "GaudiKernel/Incident.h" #include "GaudiKernel/MsgStream.h" #include "GaudiKernel/Service.h" #include "GaudiKernel/ServiceHandle.h" // DD4Hep #include "DD4hep/LCDD.h" // Geant4 #include "G4RunManager.hh" #include "G4VUserDetectorConstruction.hh" class GeoSvc : public extends2<Service, IGeoSvc, IIncidentListener> { public: /// Default constructor GeoSvc(const std::string& name, ISvcLocator* svc); /// Destructor virtual ~GeoSvc(); /// Initialize function virtual StatusCode initialize() final; /// Finalize function virtual StatusCode finalize() final; /// This function generates the DD4hep geometry StatusCode buildDD4HepGeo(); /// This function generates the Geant4 geometry StatusCode buildGeant4Geo(); // receive DD4hep Geometry virtual DD4hep::Geometry::DetElement getDD4HepGeo() override; virtual DD4hep::Geometry::LCDD* lcdd() override; // receive Geant4 Geometry virtual G4VUserDetectorConstruction* getGeant4Geo() override; /// Inform that a new incident has occurred virtual void handle(const Incident& inc) final; private: /// Pointer to the incident service ServiceHandle<IIncidentSvc> m_incidentSvc; /// Pointer to the interface to the DD4hep geometry DD4hep::Geometry::LCDD* m_dd4hepgeo; /// Pointer to the detector construction of DDG4 std::shared_ptr<G4VUserDetectorConstruction> m_geant4geo; /// XML-files with the detector description Gaudi::Property<std::vector<std::string>> m_xmlFileNames{this, "detectors", {}, "Detector descriptions XML-files"}; // output MsgStream m_log; // Flag set to true if any incident is fired from geometry constructors bool m_failureFlag; }; #endif // GEOSVC_H
[ "ocolegro@physics.ucsb.edu" ]
ocolegro@physics.ucsb.edu
b7233ecc3258053d8eb16e8869830111cadabd80
546d00dd96099d7ad669373f5771b9b200938f6e
/Sources/Sword3PaySys/Toolkits/mysql++-1.7.1-1-win32-vc++/include/field_names1.hh
5b56c68b7abe940b650981378f177628ecffdb59
[]
no_license
lubing521/mmo-resourse
74f6bcbd78aba61de0e8a681c4c6850f564e08d8
94fc594acba9bba9a9c3d0a5ecbca7a6363b42a5
refs/heads/master
2021-01-22T01:43:29.825927
2015-03-17T02:24:16
2015-03-17T02:24:16
36,480,084
2
1
null
2015-05-29T03:16:18
2015-05-29T03:16:18
null
UTF-8
C++
false
false
1,226
hh
#ifndef __field_names1_hh__ #define __field_names1_hh__ #include <vector> #include <algorithm> using namespace std ; #include "defs.h" #include "define_short.h" #include "coldata1.hh" #include "string_util.hh" //: A vector of the field names. class FieldNames : public vector<string> { private: void init (const ResUse *res); public: FieldNames () {} FieldNames (const ResUse *res) {init(res);} FieldNames (int i) : vector<string>(i) {} FieldNames& operator = (const ResUse *res) {init(res); return *this;} //: Creates a new list from the data in res. FieldNames& operator = (int i) {insert(begin(), i, ""); return *this;} //: Creates a new list with i field names. string& operator [] (int i) {return vector<string>::operator [] (i);} //: returns the field name of the field with that index number const string& operator [] (int i) const {return vector<string>::operator [] (i);} //: returns the field name of the field with that index number uint operator [] (string i) const { string temp(i); str_to_lwr(temp); return find(begin(),end(), temp) - begin(); } //: returns the index number of the field with that name }; #endif
[ "ichenq@gmail.com@6f215214-8c51-1d4b-a490-e1557286002c" ]
ichenq@gmail.com@6f215214-8c51-1d4b-a490-e1557286002c
97c22fa9e2899ae8c187b90cc02bb92ead60e13e
72806e672ae44be1ad5d1365224b9b430d1fa721
/pod/pinocchio/qap/GateBoolOR.cpp
42da52928ce22478ce3e51fd6edcd89762258f3d
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
imtypist/BlockSense
277814436a50c800625193d4c72982e326f9566a
00a0336205c1f1049d978b07bcf078b8c85374b0
refs/heads/master
2023-05-27T13:42:32.715625
2023-05-15T09:53:58
2023-05-15T09:53:58
145,524,879
14
4
null
2020-07-18T04:56:06
2018-08-21T07:33:59
C++
UTF-8
C++
false
false
477
cpp
#include <assert.h> #include "GateBoolOR.h" GateBoolOR::GateBoolOR(int N) { this->N = N; inputs = new BoolWire*[N]; maxInputs = N; assignedInputs = 0; output = NULL; } GateBoolOR::~GateBoolOR() { delete [] inputs; } inline void GateBoolOR::eval() { assert(inputs && output); bool result = false; for (int i = 0; i < N; i++) { result = result || inputs[i]->value; } output->value = result; } void GateBoolOR::generateSP(QSP* qsp) { this->genericSP(qsp); }
[ "junqin.huang@qq.com" ]
junqin.huang@qq.com
2373d66297b4a66b23780a34990895170896f1ab
e216c1df4b156d7a0d7b3f62d6b81b27d562211d
/Codeforces/Mail.Ru_Cup_2018_Round_3/B.cpp
68c85a2ae6e829c5d56c3c69243aaedc6b7d3214
[]
no_license
Bonayy/Competitive-Programming
0888b394c556c90559c66802e40d9ff6fd905780
03dc096da4978bc18d9e52704ebaf7bbc59ddca0
refs/heads/master
2022-12-19T20:58:40.693221
2020-09-30T04:22:19
2020-09-30T04:22:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,051
cpp
/* Author: Dung Tuan Le University of Rochester */ #include <bits/stdc++.h> #define fio ios_base::sync_with_stdio(false); cin.tie(NULL) #define FOR(i, l, r) for (int i=l; i<=r; i++) #define REP(i, r, l) for (int i=r; i>=l; i--) #define mp make_pair #define pb push_back #define fi first #define se second #define lb lower_bound #define ub upper_bound #define eps 1e-9 using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<long, long> pll; typedef pair<ll, ll> pllll; typedef pair<ld, ld> Point; typedef pair<Point, Point> line; struct strLine { ld a, b, c; }; typedef vector<int> vi; typedef vector<long> vl; typedef vector<ll> vll; const double pi = 3.141592653589793; #define maxm 1000 + 10 ll tcount[maxm]; int main() { fio; long n, m; cin >> n >> m; tcount[0] = n / m; FOR(i, 1, m - 1) { if (n >= i) tcount[(i * i) % m] += ((n - i) / m + 1); } ll res = 0; tcount[m] = tcount[0]; FOR(i, 0, m - 1) { res += 1LL * tcount[i] * tcount[m - i]; } cout << res; return 0; }
[ "dle8@u.rochester.edu" ]
dle8@u.rochester.edu
659acc3514cd9eb7f53abbec9715c5bf74c9c242
091afb7001e86146209397ea362da70ffd63a916
/inst/include/nt2/include/functions/scalar/rsqrt.hpp
ec8861d3125320d8bc6d7183ab71a2a6384b66c7
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
182
hpp
#ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_RSQRT_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_SCALAR_RSQRT_HPP_INCLUDED #include <nt2/arithmetic/include/functions/scalar/rsqrt.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
a78b2aba5d12a3656fcda60d6eb92d39e583764e
057a475216e9beed41983481aafcaf109bbf58da
/base/poco/Foundation/src/StreamChannel.cpp
817c047a65a7b1ec81ef3d9763fbc3f714546bff
[ "Apache-2.0", "BSL-1.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
567
cpp
// // StreamChannel.cpp // // Library: Foundation // Package: Logging // Module: StreamChannel // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/StreamChannel.h" #include "Poco/Message.h" namespace Poco { StreamChannel::StreamChannel(std::ostream& str): _str(str) { } StreamChannel::~StreamChannel() { } void StreamChannel::log(const Message& msg) { FastMutex::ScopedLock lock(_mutex); _str << msg.getText() << std::endl; } } // namespace Poco
[ "noreply@github.com" ]
noreply@github.com
d78eeb441a84a56f1368a94990dd670c6f7e01cd
7ebc12c326dd918bc96c08167f0457ed2f8f93de
/Trains/20112014/H/hax3.cpp
6601adc2d1895e13ee22962f1e2ff2aa7519ed89
[]
no_license
qwaker00/Olymp
635b61da0e80d1599edfe1bc9244b95f015b3007
c3ab2c559fa09f080a3f02c84739609e1e85075d
refs/heads/master
2021-01-18T16:35:58.452451
2015-08-06T16:45:58
2015-08-06T16:46:25
5,674,825
0
0
null
null
null
null
UTF-8
C++
false
false
2,498
cpp
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int pr[111], pn; int n; int take[111]; struct tlong { int data[111], len; tlong() : len(1) { memset(data, 0, sizeof(data)); }; void operator*=(int x) { int carry = 0; for (int i = 0; i < len; ++i) { carry += data[i] * x; data[i] = carry % 10; carry /= 10; } while (carry) { data[len++] = carry % 10; carry /= 10; } } void operator-=(const tlong& b) { int carry = 0; for (int i = 0; i < len; ++i) { carry += data[i] - b.data[i]; if (carry < 0) { data[i] = carry + 10; carry = -1; } else { data[i] = carry; carry = 0; } } while (len > 1 && data[len - 1] == 0) --len; } bool operator<(const tlong& b) const { if (len > b.len) return false; if (len < b.len) return true; for (int i = len - 1; i >= 0; --i) if (data[i] != b.data[i]) return data[i] < b.data[i]; return false; } void out() const { printf("%d", data[len - 1]); for (int i = len - 2; i >= 0; --i) printf("%d", data[i]); } }; bool any = false; tlong ans, ansa; inline void update() { tlong a, b; a.data[0] = 1; b.data[0] = 1; for (int i = 0; i < n; ++i) { if (take[i]) { a *= pr[i]; } else b *= pr[i]; } if (a < b) { swap(a, b); } a -= b; if (!any || a < ans) { ans = a; ansa = b; any = true; } } void gen(int c, int i) { if (c + c > n) return; update(); for (int j = i; j < n; ++j) { take[j] = 1; gen(c + 1, j + 1); take[j] = 0; } } int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); for (int i = 2; pn < 30; ++i) { bool prm = 1; for (int j = 0; j < pn; ++j) if (i % pr[j] == 0) { prm = 0; break; } if (prm) { pr[pn++] = i; } } cerr << pn << endl; cin >> n; gen(0, 0); cout << "\""; ansa.out(); cout << "\","; cout << endl; return 0; }
[ "grickevich@yandex-team.ru" ]
grickevich@yandex-team.ru
e89d25ff3517d6dc7df11e05bc5c54e9a4c2eee4
87fa3799bce046f93b518432f9221b647ea999e6
/2threads.cpp
cc41d2ce71b84f565a8e10e6a0496b5d3c35ad12
[ "MIT" ]
permissive
CMPT-431-SFU/Cpp11-Demos
ff2e5e522956e90f06f9cbb6a27d1c0c025324e9
56ed14c5eb9e355edf7a387943492f50c3d591ec
refs/heads/master
2020-12-10T00:23:23.715620
2020-02-25T18:39:27
2020-02-25T18:39:27
233,457,325
0
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
/* * * Simple thread example: one thread prints 0's the * other prints 1's * */ #include <thread> #include <iostream> #include <chrono> using namespace std; void print_zero() { while(1) cout << "0" << endl; } void print_one() { while(1) cout << "1" << endl; } int main(int argc, char* argv[]) { thread t1(print_zero); thread t2(print_one); t1.join(); t2.join(); return 0; }
[ "ashriram@cs.sfu.ca" ]
ashriram@cs.sfu.ca
42ccfced40d0bc4ec9dad8e56f2a02f2afb009b0
b1be8471950a7d7a834d67b11b24d70aa7ece501
/DemoApps/GLES2/Blur/source/ReferenceOnePassBlurredDraw.cpp
b11d21b01f4c5307738268d74dc685aec2b5aa18
[ "GPL-1.0-or-later", "JSON" ]
permissive
alexvonduar/gtec-demo-framework
1b212d9b43094abdfeae61e0d2e8a258e5a97771
6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749
refs/heads/master
2021-06-15T13:25:02.498022
2021-03-26T06:11:43
2021-03-26T06:11:43
168,854,730
0
0
BSD-3-Clause
2019-03-25T23:59:42
2019-02-02T16:59:46
C++
UTF-8
C++
false
false
6,441
cpp
/**************************************************************************************************************************************************** * Copyright (c) 2015 Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the Freescale Semiconductor, Inc. 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 <FslBase/Exceptions.hpp> #include <FslBase/Log/Log3Fmt.hpp> #include <FslDemoApp/Base/Service/Content/IContentManager.hpp> #include <FslDemoService/Graphics/IGraphicsService.hpp> #include <FslGraphics/Bitmap/Bitmap.hpp> #include <FslGraphics/Vertices/VertexPositionTexture.hpp> #include "GausianHelper.hpp" #include "VBHelper.hpp" #include "ReferenceOnePassBlurredDraw.hpp" #include <cassert> namespace Fsl { using namespace GLES2; namespace { const GLTextureImageParameters g_framebufferImageParams(GL_RGB565, GL_RGB, GL_UNSIGNED_BYTE); int UpdateKernelLength(const int32_t kernelLength) { int32_t moddedKernelLength = std::max(kernelLength, 3); int newKernelLength = ((moddedKernelLength / 2) * 2) + 1; moddedKernelLength = (newKernelLength < moddedKernelLength ? newKernelLength + 2 : newKernelLength); return moddedKernelLength; } } // FIX: the way the setup is done currently we cant change the framebuffer size (since the 'scene' thinks is using the fullscreen) ReferenceOnePassBlurredDraw::ReferenceOnePassBlurredDraw(const DemoAppConfig& config, const Config& blurConfig) : ABlurredDraw("Reference one pass") , m_batch2D(std::dynamic_pointer_cast<NativeBatch2D>(config.DemoServiceProvider.Get<IGraphicsService>()->GetNativeBatch2D())) , m_screenResolution(config.WindowMetrics.GetSizePx()) , m_framebufferOrg(config.WindowMetrics.GetSizePx(), GLTextureParameters(GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), g_framebufferImageParams, GL_DEPTH_COMPONENT16) { if (!m_batch2D) { throw std::runtime_error("NativeBatch2D unavailable"); } const int moddedKernelLength = UpdateKernelLength(blurConfig.KernelLength); FSLLOG3_WARNING_IF(moddedKernelLength != blurConfig.KernelLength, "The one pass shader is not compatible with the supplied kernel length of {} using {}", blurConfig.KernelLength, moddedKernelLength); const std::shared_ptr<IContentManager> contentManager = config.DemoServiceProvider.Get<IContentManager>(); float sigma = blurConfig.Sigma; if (blurConfig.UseOptimalSigma) { sigma = GausianHelper::FindOptimalSigma(moddedKernelLength); FSLLOG3_INFO("Using sigma of {}", sigma); } std::vector<double> kernel; GausianHelper::CalculateGausianKernel(kernel, moddedKernelLength, sigma); const std::string fragTemplate = contentManager->ReadAllText("GaussianTemplate.frag"); const std::string gaussianFrag = GausianHelper::GenerateGausianFragmentShader(fragTemplate, kernel, moddedKernelLength, m_framebufferOrg.GetSize()); const std::string basicShader = contentManager->ReadAllText("BasicShader.vert"); m_programBlur.Reset(basicShader, gaussianFrag); m_programNormal.Reset(basicShader, contentManager->ReadAllText("BasicShader.frag")); // m_programBlur.Reset(basicShader, contentManager->ReadAllText("BasicShader.frag")); VBHelper::BuildVB(m_vertexBufferLeft, BoxF(-1, -1, 0, 1), BoxF(0.0f, 0.0f, 0.5f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRight, BoxF(0, -1, 1, 1), BoxF(0.5f, 0.0f, 1.0f, 1.0f)); } void ReferenceOnePassBlurredDraw::Draw(AScene* const pScene) { assert(pScene != nullptr); // Render the 'source' image that we want to partially blur glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferOrg.Get()); { pScene->Draw(); } // Since we are only doing opaque non-overlapping 2d-composition type operations we can disable blend and depth testing glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // Composite the final image glBindFramebuffer(GL_FRAMEBUFFER, 0); { glViewport(0, 0, m_screenResolution.Width(), m_screenResolution.Height()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferOrg.GetTextureInfo().Handle); // Draw the left side using the normal shader glUseProgram(m_programNormal.Get()); glBindBuffer(m_vertexBufferLeft.GetTarget(), m_vertexBufferLeft.Get()); m_vertexBufferLeft.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw the right side using the blur shader glUseProgram(m_programBlur.Get()); glBindBuffer(m_vertexBufferRight.GetTarget(), m_vertexBufferRight.Get()); m_vertexBufferRight.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } } }
[ "Rene.Thrane@nxp.com" ]
Rene.Thrane@nxp.com
f9386e47ce7292f5925451ead9da28870c3299a4
239822875e18416f63b532f09d4ae703c261b028
/hareem/List.cpp
ac4fbc2f06b9621a9a9eec437020d0f8348962e9
[]
no_license
Lukaa98/operating-system-proj1
e2e6d17cb48c6d57f66e0d6287fdfcb87aced544
abc9c01781ff8c1d5998d2d90a9e6d4425f7c6e7
refs/heads/master
2020-11-24T07:56:26.570581
2019-10-16T07:16:32
2019-10-16T07:16:32
228,040,197
1
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
#include <unistd.h> #include <iostream> using namespace std; int main (int argc,char* argv[]) { const char* arg[] = {"ls",(char*)NULL}; execvp("ls",(char* const*)arg); }
[ "hbokhari98@gmail.com" ]
hbokhari98@gmail.com
7dbc3d53758ee0461fc6b4df788ebb3acb40ee28
ef4ce28d84d84c9403ae837d6447573361bf4c15
/rpcdump.cpp
40dc33bfc4795d2eb145fbfb05e23002fc9d2479
[]
no_license
failcoin/ttt
f8e99f18dff5723a15d45d88a5ec5f318ae652ec
0680f44c5c72d122f5057418897cc86b989dcaac
refs/heads/master
2016-09-06T11:42:35.728958
2014-03-17T12:47:57
2014-03-17T12:47:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
// Copyright (c) 2009-2012 Bitcoin Developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 AntiKeiserCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "importprivkey <antikeisercoinprivkey> [label]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(-5,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); CKeyID vchAddress = key.GetPubKey().GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKey(key)) throw JSONRPCError(-4,"Error adding key to wallet"); pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <antikeisercoinaddress>\n" "Reveals the private key corresponding to <antikeisercoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(-5, "Invalid AntiKeiserCoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(-3, "Address does not refer to a key"); CSecret vchSecret; bool fCompressed; if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret, fCompressed).ToString(); }
[ "root@failco.in" ]
root@failco.in
aca5c35f351a995056b629b2682d56611586e6b9
eb568794911a41f50ff666eed9648cc2025a4e44
/CertificationOAuth/CertificationOAuth/main.cpp
430cac3ba58031fa637187b63adc0a7e03526362
[]
no_license
ExistOrLive/DemoForLearning
fb9e888ba88932c0747b11978d2d51fc8eb5ae99
b0f3a5608d0a7b5d5c24ff13b9efc4eabd19851a
refs/heads/master
2022-10-27T04:27:45.688643
2021-04-19T02:47:20
2021-04-19T02:47:20
185,629,254
0
0
null
2022-10-06T19:23:55
2019-05-08T15:06:29
Python
UTF-8
C++
false
false
2,221
cpp
// // main.cpp // CertificationOAuth // // Created by 朱猛 on 2020/11/7. // #include <iostream> #include <string> #include "OpenXLSX.hpp" #include "httplib.h" using namespace std; using namespace OpenXLSX; int main(int argc, const char * argv[]) { cout << "检测程序开始: \n\n"; string sourceFilePath = "/Users/zhumeng/Downloads/淘宝200.xlsx"; XLDocument sourceDoc; XLDocument objDoc; try { sourceDoc.open(sourceFilePath); } catch (runtime_error error) { cout << "源excel 文件不存在" << endl; return 0; } auto wks = sourceDoc.workbook().worksheet("Sheet1"); auto rowCount = wks.rowCount(); cout << "检测数据共有" << rowCount << "条,请等待......\n\n" << endl; httplib::Client cli("http://zscx.osta.org.cn"); cli.set_connection_timeout(0,300000); for (int i = 1 ; i <= rowCount ; ++i){ string cardId = wks.cell(i, 1).value().asString(); string name = wks.cell(i, 2).value().asString(); cout << cardId; cout << " "; cout << name; cout << " "; httplib::Headers headers = { { "Referer","http://zscx.osta.org.cn/"},{"Origin","http://zscx.osta.org.cn"},{"Accept","*/*"} }; httplib::Params params = { {"tableName","CERT_T"},{"tableName1","000000"},{"CertificateID",""}, {"CID",cardId},{"Name",name},{"x","137"},{"y","24"},{"province","-1"} }; httplib::Result result = cli.Post("/jiandingApp/command/buzhongxin/ecCertSearchAll",headers,params); if(result) { string &body = result.value().body; if(body.find(cardId) != string::npos) { cout << "有证书" << endl; } else if (body.find("对不起,没有查到相关信息") != string::npos) { cout << "没有证书" << endl; } else { cout << "查询失败" << endl; } } else { cout << "查询失败" << endl; } } cout << "\n\n检测数据完毕" << endl; return 0; }
[ "2068531506@qq.com" ]
2068531506@qq.com
15feb28bd466d676cee7ed961125d49c16c64623
38b3240d55703809216b5a39a82f9aca9d18693c
/HW3/cs550_project_3/cs550_project_3/main.cpp
3c1b07b6d9f38f12131a68f1562c393133d0c067
[]
no_license
Jerrydepon/CS550_Computer-Graphics
1e5975027daa869b2929c28fbf6a2bc7b01818c8
8e0023d97f12df2154748da0e92dd1af5c5aaa25
refs/heads/master
2020-04-01T08:54:21.658348
2019-08-18T22:28:28
2019-08-18T22:28:28
153,051,518
0
0
null
null
null
null
UTF-8
C++
false
false
34,253
cpp
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define _USE_MATH_DEFINES #include <math.h> #ifdef WIN32 #include <windows.h> #pragma warning(disable:4996) #include "glew.h" #endif #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #define MS_IN_THE_ANIMATION_CYCLE 10000 // parameters of sphere #define SPHERE_RADIUS 1.5 #define SPHERE_SLICES 50 #define SPHERE_STACKS 50 // Author: Chih-Hsiang Wang // title of these windows: const char *WINDOWTITLE = { "Project_3 -- Chih-Hsiang Wang" }; const char *GLUITITLE = { "User Interface Window" }; // what the glui package defines as true and false: const int GLUITRUE = { true }; const int GLUIFALSE = { false }; // the escape key: #define ESCAPE 0x1b // initial window size: const int INIT_WINDOW_SIZE = { 600 }; // multiplication factors for input interaction: // (these are known from previous experience) const float ANGFACT = { 1. }; const float SCLFACT = { 0.005f }; // minimum allowable scale factor: const float MINSCALE = { 0.05f }; // active mouse buttons (or them together): const int LEFT = { 4 }; const int MIDDLE = { 2 }; const int RIGHT = { 1 }; bool prc = true; // which projection: enum Projections { ORTHO, PERSP }; // select texture mode enum SelectTexture { TEXTUREOFF, TEXTUREON, DISTORTIONON }; // which button: enum ButtonVals { RESET, QUIT }; // window background color (rgba): const GLfloat BACKCOLOR[ ] = { 0., 0., 0., 1. }; // line width for the axes: const GLfloat AXES_WIDTH = { 3. }; // the color numbers: // this order must match the radio button order enum Colors { RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA, WHITE, BLACK }; char * ColorNames[ ] = { "Red", "Yellow", "Green", "Cyan", "Blue", "Magenta", "White", "Black" }; // the color definitions: // this order must match the menu order const GLfloat Colors[ ][3] = { { 1., 0., 0. }, // red { 1., 1., 0. }, // yellow { 0., 1., 0. }, // green { 0., 1., 1. }, // cyan { 0., 0., 1. }, // blue { 1., 0., 1. }, // magenta { 1., 1., 1. }, // white { 0., 0., 0. }, // black }; // fog parameters: const GLfloat FOGCOLOR[4] = { .0, .0, .0, 1. }; const GLenum FOGMODE = { GL_LINEAR }; const GLfloat FOGDENSITY = { 0.30f }; const GLfloat FOGSTART = { 1.5 }; const GLfloat FOGEND = { 4. }; // non-constant global variables: int ActiveButton; // current button that is down GLuint AxesList; // list to hold the axes int AxesOn; // != 0 means to draw the axes int DebugOn; // != 0 means to print debugging info int DepthCueOn; // != 0 means to use intensity depth cueing int DepthBufferOn; int DepthFightingOn; int MainWindow; // window id for main graphics window float Scale; // scaling factor int WhichColor; // index into Colors[ ] int WhichProjection; // ORTHO or PERSP int WhichPerspective; int Xmouse, Ymouse; // mouse values float Xrot, Yrot; // rotation angles in degrees bool Frozen; float Time = 0; GLuint tex0; bool IfDistort; bool TextureOn; // function prototypes: void Animate( ); void Display( ); void DoAxesMenu( int ); void DoColorMenu( int ); void DoDepthMenu( int ); void DoDepthBufferMenu( int ); void DoDepthFightingMenu( int ); void DoDebugMenu( int ); void DoMainMenu( int ); void DoProjectMenu( int ); void DoPerspectiveMenu( int ); void DoRasterString( float, float, float, char * ); void DoStrokeString( float, float, float, float, char * ); float ElapsedSeconds( ); void InitGraphics( ); void InitLists( ); void InitMenus( ); void Keyboard( unsigned char, int, int ); void MouseButton( int, int, int, int ); void MouseMotion( int, int ); void Reset( ); void Resize( int, int ); void Visibility( int ); void Axes( float ); void HsvRgb( float[3], float [3] ); float Dot(float v1[3], float v2[3]); float Unit(float vin[3], float vout[3]); void Cross(float v1[3], float v2[3], float vout[3]); unsigned char* BmpToTexture(char *filename, int *width, int *height); void SphereTexture(float radius, int slices, int stacks); int width = 1024; int height = 512; // main program: int main( int argc, char *argv[ ] ) { // turn on the glut package: // (do this before checking argc and argv since it might // pull some command line arguments out) glutInit( &argc, argv ); // setup all the graphics stuff: InitGraphics( ); // create the display structures that will not change: InitLists( ); // init all the global variables used by Display( ): // this will also post a redisplay Reset( ); // setup all the user interface stuff: InitMenus( ); // draw the scene once and wait for some interaction: // (this will never return) glutSetWindow( MainWindow ); glutMainLoop( ); // this is here to make the compiler happy: return 0; } // this is where one would put code that is to be called // everytime the glut main loop has nothing to do // // this is typically where animation parameters are set // // do not call Display( ) from here -- let glutMainLoop( ) do it void Animate( ) { int ms = glutGet(GLUT_ELAPSED_TIME); //milliseconds ms %= MS_IN_THE_ANIMATION_CYCLE; Time = (float)ms*5000 / (float)MS_IN_THE_ANIMATION_CYCLE; // put animation stuff in here -- change some global variables // for Display( ) to find: // force a call to Display( ) next time it is convenient: glutSetWindow( MainWindow ); glutPostRedisplay( ); } // draw the complete scene: void Display( ) { if( DebugOn != 0 ) { fprintf( stderr, "Display\n" ); } // set which window we want to do the graphics into: glutSetWindow( MainWindow ); // erase the background: glDrawBuffer( GL_BACK ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // DepthBuffer if( DepthBufferOn) glEnable( GL_DEPTH_TEST ); else glDisable( GL_DEPTH_TEST ); // specify shading to be flat: glShadeModel( GL_FLAT ); // set the viewport to a square centered in the window: GLsizei vx = glutGet( GLUT_WINDOW_WIDTH ); GLsizei vy = glutGet( GLUT_WINDOW_HEIGHT ); GLsizei v = vx < vy ? vx : vy; // minimum dimension GLint xl = ( vx - v ) / 2; GLint yb = ( vy - v ) / 2; glViewport( xl, yb, v, v ); // set the viewing volume: // remember that the Z clipping values are actually // given as DISTANCES IN FRONT OF THE EYE // USE gluOrtho2D( ) IF YOU ARE DOING 2D ! glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); if( WhichProjection == ORTHO ) glOrtho( -3., 3., -3., 3., 0.1, 1000. ); else gluPerspective( 90., 1., 0.1, 1000. ); // place the objects into the scene: glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); // set the eye position, look-at position, and up-vector: gluLookAt(0., 0., 3., 0., 0., 0., 0., 1., 0.); // rotate the scene: glRotatef( (GLfloat)Yrot, 0., 1., 0. ); glRotatef( (GLfloat)Xrot, 1., 0., 0. ); // uniformly scale the scene: if( Scale < MINSCALE ) Scale = MINSCALE; glScalef( (GLfloat)Scale, (GLfloat)Scale, (GLfloat)Scale ); unsigned char* Texture; unsigned char* Texture2; if(prc == true) { Texture = BmpToTexture("worldtex.bmp", &width, &height); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &tex0); glBindTexture(GL_TEXTURE_2D, tex0); glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, Texture); glutPostRedisplay(); } else { Texture2 = BmpToTexture("icon.bmp", &width, &height); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &tex0); glBindTexture(GL_TEXTURE_2D, tex0); glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, Texture2); glutPostRedisplay(); } // set the fog parameters: if( DepthCueOn != 0 ) { glFogi( GL_FOG_MODE, FOGMODE ); glFogfv( GL_FOG_COLOR, FOGCOLOR ); glFogf( GL_FOG_DENSITY, FOGDENSITY ); glFogf( GL_FOG_START, FOGSTART ); glFogf( GL_FOG_END, FOGEND ); glEnable( GL_FOG ); } else { glDisable( GL_FOG ); } // possibly draw the axes: if( AxesOn != 0 ) { glColor3fv( &Colors[WhichColor][0] ); glCallList( AxesList ); } // since we are using glScalef( ), be sure normals get unitized: glEnable( GL_NORMALIZE ); // Set texture options if(TextureOn == 0) { glDisable(GL_TEXTURE_2D); glColor3f(0.5, 0.5, 0.5); SphereTexture(SPHERE_RADIUS, SPHERE_SLICES, SPHERE_STACKS); }else{ glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, tex0); SphereTexture(SPHERE_RADIUS, SPHERE_SLICES, SPHERE_STACKS); } // draw some gratuitous text that just rotates on top of the scene: glDisable( GL_DEPTH_TEST ); glColor3f( 0., 1., 1. ); // DoRasterString( 0., 1., 0., "Hi~I am here." ); // draw some gratuitous text that is fixed on the screen: // // the projection matrix is reset to define a scene whose // world coordinate system goes from 0-100 in each axis // // this is called "percent units", and is just a convenience // // the modelview matrix is reset to identity as we don't // want to transform these coordinates glDisable( GL_DEPTH_TEST ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); gluOrtho2D( 0., 100., 0., 100. ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); glColor3f( 1., 1., 1. ); DoRasterString( 5., 5., 0., "Project_3" ); // swap the double-buffered framebuffers: glutSwapBuffers( ); // be sure the graphics buffer has been sent: // note: be sure to use glFlush( ) here, not glFinish( ) ! glFlush( ); } void DoAxesMenu( int id ) { AxesOn = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoColorMenu( int id ) { WhichColor = id - RED; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoDebugMenu( int id ) { DebugOn = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoDepthMenu( int id ) { DepthCueOn = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoDepthBufferMenu( int id ) { DepthBufferOn = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoDepthFightingMenu( int id ) { DepthBufferOn = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoDistortMenu(int id) { IfDistort = (id == DISTORTIONON); TextureOn = (id != TEXTUREOFF); glutSetWindow(MainWindow); glutPostRedisplay(); } // main menu callback: void DoMainMenu( int id ) { switch( id ) { case RESET: Reset( ); break; case QUIT: // gracefully close out the graphics: // gracefully close the graphics window: // gracefully exit the program: glutSetWindow( MainWindow ); glFinish( ); glutDestroyWindow( MainWindow ); exit( 0 ); break; default: fprintf( stderr, "Don't know what to do with Main Menu ID %d\n", id ); } glutSetWindow( MainWindow ); glutPostRedisplay( ); } void DoProjectMenu( int id ) { WhichProjection = id; glutSetWindow( MainWindow ); glutPostRedisplay( ); } // use glut to display a string of characters using a raster font: void DoRasterString( float x, float y, float z, char *s ) { glRasterPos3f( (GLfloat)x, (GLfloat)y, (GLfloat)z ); char c; // one character to print for( ; ( c = *s ) != '\0'; s++ ) { glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, c ); } } // use glut to display a string of characters using a stroke font: void DoStrokeString( float x, float y, float z, float ht, char *s ) { glPushMatrix( ); glTranslatef( (GLfloat)x, (GLfloat)y, (GLfloat)z ); float sf = ht / ( 119.05f + 33.33f ); glScalef( (GLfloat)sf, (GLfloat)sf, (GLfloat)sf ); char c; // one character to print for( ; ( c = *s ) != '\0'; s++ ) { glutStrokeCharacter( GLUT_STROKE_ROMAN, c ); } glPopMatrix( ); } // return the number of seconds since the start of the program: float ElapsedSeconds( ) { // get # of milliseconds since the start of the program: int ms = glutGet( GLUT_ELAPSED_TIME ); // convert it to seconds: return (float)ms / 1000.f; } // initialize the glui window: void InitMenus( ) { glutSetWindow( MainWindow ); int numColors = sizeof( Colors ) / ( 3*sizeof(int) ); int colormenu = glutCreateMenu( DoColorMenu ); for( int i = 0; i < numColors; i++ ) { glutAddMenuEntry( ColorNames[i], i ); } int distortmenu = glutCreateMenu(DoDistortMenu); glutAddMenuEntry("No Texture", TEXTUREOFF); glutAddMenuEntry("Texture wo. Distortion", TEXTUREON); glutAddMenuEntry("Texture w. Distortion", DISTORTIONON); int axesmenu = glutCreateMenu( DoAxesMenu ); glutAddMenuEntry( "Off", 0 ); glutAddMenuEntry( "On", 1 ); int depthcuemenu = glutCreateMenu( DoDepthMenu ); glutAddMenuEntry( "Off", 0 ); glutAddMenuEntry( "On", 1 ); int depthbuffermenu = glutCreateMenu( DoDepthBufferMenu ); glutAddMenuEntry( "Off", 0 ); glutAddMenuEntry( "On", 1 ); int depthfightingmenu = glutCreateMenu( DoDepthFightingMenu ); glutAddMenuEntry( "Off", 0 ); glutAddMenuEntry( "On", 1 ); int debugmenu = glutCreateMenu( DoDebugMenu ); glutAddMenuEntry( "Off", 0 ); glutAddMenuEntry( "On", 1 ); int projmenu = glutCreateMenu( DoProjectMenu ); glutAddMenuEntry( "Orthographic", ORTHO ); glutAddMenuEntry( "Perspective", PERSP ); int mainmenu = glutCreateMenu( DoMainMenu ); glutAddSubMenu( "Texture", distortmenu); glutAddSubMenu( "Axes", axesmenu); glutAddSubMenu( "Colors", colormenu); glutAddSubMenu( "Depth Cue", depthcuemenu); glutAddSubMenu( "Depth Buffer", depthbuffermenu); glutAddSubMenu( "Depth Fighting",depthfightingmenu); glutAddSubMenu( "Projection", projmenu ); glutAddMenuEntry( "Reset", RESET ); glutAddSubMenu( "Debug", debugmenu); glutAddMenuEntry( "Quit", QUIT ); // attach the pop-up menu to the right mouse button: glutAttachMenu( GLUT_RIGHT_BUTTON ); } // initialize the glut and OpenGL libraries: // also setup display lists and callback functions void InitGraphics( ) { // request the display modes: // ask for red-green-blue-alpha color, double-buffering, and z-buffering: glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); // set the initial window configuration: glutInitWindowPosition( 0, 0 ); glutInitWindowSize( INIT_WINDOW_SIZE, INIT_WINDOW_SIZE ); // open the window and set its title: MainWindow = glutCreateWindow( WINDOWTITLE ); glutSetWindowTitle( WINDOWTITLE ); // set the framebuffer clear values: glClearColor( BACKCOLOR[0], BACKCOLOR[1], BACKCOLOR[2], BACKCOLOR[3] ); // setup the callback functions: // DisplayFunc -- redraw the window // ReshapeFunc -- handle the user resizing the window // KeyboardFunc -- handle a keyboard input // MouseFunc -- handle the mouse button going down or up // MotionFunc -- handle the mouse moving with a button down // PassiveMotionFunc -- handle the mouse moving with a button up // VisibilityFunc -- handle a change in window visibility // EntryFunc -- handle the cursor entering or leaving the window // SpecialFunc -- handle special keys on the keyboard // SpaceballMotionFunc -- handle spaceball translation // SpaceballRotateFunc -- handle spaceball rotation // SpaceballButtonFunc -- handle spaceball button hits // ButtonBoxFunc -- handle button box hits // DialsFunc -- handle dial rotations // TabletMotionFunc -- handle digitizing tablet motion // TabletButtonFunc -- handle digitizing tablet button hits // MenuStateFunc -- declare when a pop-up menu is in use // TimerFunc -- trigger something to happen a certain time from now // IdleFunc -- what to do when nothing else is going on glutSetWindow( MainWindow ); glutDisplayFunc( Display ); glutReshapeFunc( Resize ); glutKeyboardFunc( Keyboard ); glutMouseFunc( MouseButton ); glutMotionFunc( MouseMotion ); glutPassiveMotionFunc( NULL ); glutVisibilityFunc( Visibility ); glutEntryFunc( NULL ); glutSpecialFunc( NULL ); glutSpaceballMotionFunc( NULL ); glutSpaceballRotateFunc( NULL ); glutSpaceballButtonFunc( NULL ); glutButtonBoxFunc( NULL ); glutDialsFunc( NULL ); glutTabletMotionFunc( NULL ); glutTabletButtonFunc( NULL ); glutMenuStateFunc( NULL ); glutTimerFunc( -1, NULL, 0 ); glutIdleFunc( Animate ); // init glew (a window must be open to do this): #ifdef WIN32 GLenum err = glewInit( ); if( err != GLEW_OK ) { fprintf( stderr, "glewInit Error\n" ); } else fprintf( stderr, "GLEW initialized OK\n" ); fprintf( stderr, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); #endif } // initialize the display lists that will not change: // (a display list is a way to store opengl commands in // memory so that they can be played back efficiently at a later time // with a call to glCallList( ) void InitLists( ) { glutSetWindow(MainWindow); // create the axes: AxesList = glGenLists( 1 ); glNewList( AxesList, GL_COMPILE ); glLineWidth( AXES_WIDTH ); Axes( 1.5 ); glLineWidth( 1. ); glEndList( ); } // the keyboard callback: void Keyboard( unsigned char c, int x, int y ) { if( DebugOn != 0 ) fprintf( stderr, "Keyboard: '%c' (0x%0x)\n", c, c ); switch( c ) { case 'c': case 'C': prc = ! prc; break; case 'o': case 'O': WhichProjection = ORTHO; break; case 'p': case 'P': WhichProjection = PERSP; break; case 'q': case 'Q': case ESCAPE: DoMainMenu( QUIT ); // will not return here break; // happy compiler case 'f': case 'F': Frozen = ! Frozen; if( Frozen ) glutIdleFunc( NULL ); else glutIdleFunc( Animate ); break; default: fprintf( stderr, "Don't know what to do with keyboard hit: '%c' (0x%0x)\n", c, c ); } // force a call to Display( ): glutSetWindow( MainWindow ); glutPostRedisplay( ); } // called when the mouse button transitions down or up: void MouseButton( int button, int state, int x, int y ) { int b = 0; // LEFT, MIDDLE, or RIGHT if( DebugOn != 0 ) fprintf( stderr, "MouseButton: %d, %d, %d, %d\n", button, state, x, y ); // get the proper button bit mask: switch( button ) { case GLUT_LEFT_BUTTON: b = LEFT; break; case GLUT_MIDDLE_BUTTON: b = MIDDLE; break; case GLUT_RIGHT_BUTTON: b = RIGHT; break; default: b = 0; fprintf( stderr, "Unknown mouse button: %d\n", button ); } // button down sets the bit, up clears the bit: if( state == GLUT_DOWN ) { Xmouse = x; Ymouse = y; ActiveButton |= b; // set the proper bit } else { ActiveButton &= ~b; // clear the proper bit } } // called when the mouse moves while a button is down: void MouseMotion( int x, int y ) { if( DebugOn != 0 ) fprintf( stderr, "MouseMotion: %d, %d\n", x, y ); int dx = x - Xmouse; // change in mouse coords int dy = y - Ymouse; if( ( ActiveButton & LEFT ) != 0 ) { Xrot += ( ANGFACT*dy ); Yrot += ( ANGFACT*dx ); } if( ( ActiveButton & MIDDLE ) != 0 ) { Scale += SCLFACT * (float) ( dx - dy ); // keep object from turning inside-out or disappearing: if( Scale < MINSCALE ) Scale = MINSCALE; } Xmouse = x; // new current position Ymouse = y; glutSetWindow( MainWindow ); glutPostRedisplay( ); } // reset the transformations and the colors: // this only sets the global variables -- // the glut main loop is responsible for redrawing the scene void Reset( ) { ActiveButton = 0; AxesOn = 1; DebugOn = 0; DepthCueOn = 0; DepthBufferOn = 1; DepthFightingOn = 0; Scale = 1.0; WhichColor = WHITE; WhichProjection = ORTHO; Xrot = Yrot = 0.; Frozen = 0; } // called when user resizes the window: void Resize( int width, int height ) { if( DebugOn != 0 ) fprintf( stderr, "ReSize: %d, %d\n", width, height ); // don't really need to do anything since window size is // checked each time in Display( ): glutSetWindow( MainWindow ); glutPostRedisplay( ); } // handle a change to the window's visibility: void Visibility ( int state ) { if( DebugOn != 0 ) fprintf( stderr, "Visibility: %d\n", state ); if( state == GLUT_VISIBLE ) { glutSetWindow( MainWindow ); glutPostRedisplay( ); } else { // could optimize by keeping track of the fact // that the window is not visible and avoid // animating or redrawing it ... } } /////////////////////////////////////// HANDY UTILITIES: ////////////////////////// // the stroke characters 'X' 'Y' 'Z' : static float xx[ ] = { 0.f, 1.f, 0.f, 1.f }; static float xy[ ] = { -.5f, .5f, .5f, -.5f }; static int xorder[ ] = { 1, 2, -3, 4 }; static float yx[ ] = { 0.f, 0.f, -.5f, .5f }; static float yy[ ] = { 0.f, .6f, 1.f, 1.f }; static int yorder[ ] = { 1, 2, 3, -2, 4 }; static float zx[ ] = { 1.f, 0.f, 1.f, 0.f, .25f, .75f }; static float zy[ ] = { .5f, .5f, -.5f, -.5f, 0.f, 0.f }; static int zorder[ ] = { 1, 2, 3, 4, -5, 6 }; // fraction of the length to use as height of the characters: const float LENFRAC = 0.10f; // fraction of length to use as start location of the characters: const float BASEFRAC = 1.10f; // Draw a set of 3D axes: // (length is the axis length in world coordinates) void Axes( float length ) { glBegin( GL_LINE_STRIP ); glVertex3f( length, 0., 0. ); glVertex3f( 0., 0., 0. ); glVertex3f( 0., length, 0. ); glEnd( ); glBegin( GL_LINE_STRIP ); glVertex3f( 0., 0., 0. ); glVertex3f( 0., 0., length ); glEnd( ); float fact = LENFRAC * length; float base = BASEFRAC * length; glBegin( GL_LINE_STRIP ); for( int i = 0; i < 4; i++ ) { int j = xorder[i]; if( j < 0 ) { glEnd( ); glBegin( GL_LINE_STRIP ); j = -j; } j--; glVertex3f( base + fact*xx[j], fact*xy[j], 0.0 ); } glEnd( ); glBegin( GL_LINE_STRIP ); for( int i = 0; i < 5; i++ ) { int j = yorder[i]; if( j < 0 ) { glEnd( ); glBegin( GL_LINE_STRIP ); j = -j; } j--; glVertex3f( fact*yx[j], base + fact*yy[j], 0.0 ); } glEnd( ); glBegin( GL_LINE_STRIP ); for( int i = 0; i < 6; i++ ) { int j = zorder[i]; if( j < 0 ) { glEnd( ); glBegin( GL_LINE_STRIP ); j = -j; } j--; glVertex3f( 0.0, fact*zy[j], base + fact*zx[j] ); } glEnd( ); } // function to convert HSV to RGB // 0. <= s, v, r, g, b <= 1. // 0. <= h <= 360. // when this returns, call: // glColor3fv( rgb ); void HsvRgb( float hsv[3], float rgb[3] ) { // guarantee valid input: float h = hsv[0] / 60.f; while( h >= 6. ) h -= 6.; while( h < 0. ) h += 6.; float s = hsv[1]; if( s < 0. ) s = 0.; if( s > 1. ) s = 1.; float v = hsv[2]; if( v < 0. ) v = 0.; if( v > 1. ) v = 1.; // if sat==0, then is a gray: if( s == 0.0 ) { rgb[0] = rgb[1] = rgb[2] = v; return; } // get an rgb from the hue itself: float i = floor( h ); float f = h - i; float p = v * ( 1.f - s ); float q = v * ( 1.f - s*f ); float t = v * ( 1.f - ( s * (1.f-f) ) ); float r, g, b; // red, green, blue switch( (int) i ) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; break; default: r = 0; g = 0; b = 0; } rgb[0] = r; rgb[1] = g; rgb[2] = b; } // The lighting of the helicopter surfaces float Dot( float v1[3], float v2[3] ) { return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; } void Cross( float v1[3], float v2[3], float vout[3] ) { float tmp[3]; tmp[0] = v1[1]*v2[2] - v2[1]*v1[2]; tmp[1] = v2[0]*v1[2] - v1[0]*v2[2]; tmp[2] = v1[0]*v2[1] - v2[0]*v1[1]; vout[0] = tmp[0]; vout[1] = tmp[1]; vout[2] = tmp[2]; } float Unit( float vin[3], float vout[3] ) { float dist = vin[0]*vin[0] + vin[1]*vin[1] + vin[2]*vin[2]; if( dist > 0.0 ) { dist = sqrt( dist ); vout[0] = vin[0] / dist; vout[1] = vin[1] / dist; vout[2] = vin[2] / dist; } else { vout[0] = vin[0]; vout[1] = vin[1]; vout[2] = vin[2]; } return dist; } //open file int ReadInt(FILE *); short ReadShort(FILE *); struct bmfh { short bfType; int bfSize; short bfReserved1; short bfReserved2; int bfOffBits; } FileHeader; struct bmih { int biSize; int biWidth; int biHeight; short biPlanes; short biBitCount; int biCompression; int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; int biClrUsed; int biClrImportant; } InfoHeader; const int birgb = { 0 }; /** ** read a BMP file into a Texture: **/ unsigned char* BmpToTexture(char *filename, int *width, int *height) { int s, t, e; // counters int numextra; // # extra bytes each line in the file is padded with FILE *fp, *fp2; unsigned char *texture; int nums, numt; unsigned char *tp; fp = fopen("/Users/jerrywang/Documents/CS550_Computer_Graphics/HW/HW3/cs550_project_3/cs550_project_3/worldtex.bmp", "rb"); //path of the file fp2 = fopen("/Users/jerrywang/Documents/CS550_Computer_Graphics/HW/HW3/cs550_project_3/cs550_project_3/icon.bmp", "rb"); //path of the file if (fp == NULL) { fprintf(stderr, "Cannot open Bmp file '%s'\n", filename); return NULL; } if (fp2 == NULL) { fprintf(stderr, "Cannot open Bmp file '%s'\n", filename); return NULL; } FileHeader.bfType = ReadShort(fp); // if bfType is not 0x4d42, the file is not a bmp: if (FileHeader.bfType != 0x4d42){ fprintf(stderr, "Wrong type of file: 0x%0x\n", FileHeader.bfType); fclose(fp); return NULL; } FileHeader.bfSize = ReadInt(fp); FileHeader.bfReserved1 = ReadShort(fp); FileHeader.bfReserved2 = ReadShort(fp); FileHeader.bfOffBits = ReadInt(fp); InfoHeader.biSize = ReadInt(fp); InfoHeader.biWidth = ReadInt(fp); InfoHeader.biHeight = ReadInt(fp); nums = InfoHeader.biWidth; numt = InfoHeader.biHeight; InfoHeader.biPlanes = ReadShort(fp); InfoHeader.biBitCount = ReadShort(fp); InfoHeader.biCompression = ReadInt(fp); InfoHeader.biSizeImage = ReadInt(fp); InfoHeader.biXPelsPerMeter = ReadInt(fp); InfoHeader.biYPelsPerMeter = ReadInt(fp); InfoHeader.biClrUsed = ReadInt(fp); InfoHeader.biClrImportant = ReadInt(fp); // fprintf(stderr, "Image size found: %d x %d\n", ImageWidth, ImageHeight); texture = new unsigned char[ 3 * nums * numt ]; if (texture == NULL) { fprintf(stderr, "Cannot allocate the texture array!\b"); return NULL; } // extra padding bytes: numextra = 4*(((3*InfoHeader.biWidth)+3)/4) - 3*InfoHeader.biWidth; // we do not support compression: if (InfoHeader.biCompression != birgb) { fprintf(stderr, "Wrong type of image compression: %d\n", InfoHeader.biCompression); fclose(fp); return NULL; } rewind(fp); fseek(fp, 14+40, SEEK_SET); if (InfoHeader.biBitCount == 24) { for (t = 0, tp = texture; t < numt; t++) { for (s = 0; s < nums; s++, tp += 3) { *(tp+2) = fgetc(fp); // b *(tp+1) = fgetc(fp); // g *(tp+0) = fgetc(fp); // r } for (e = 0; e < numextra; e++) { fgetc(fp); } } } fclose(fp); *width = nums; *height = numt; return texture; } int ReadInt(FILE *fp) { unsigned char b3, b2, b1, b0; b0 = fgetc(fp); b1 = fgetc(fp); b2 = fgetc(fp); b3 = fgetc(fp); return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0; } short ReadShort(FILE *fp) { unsigned char b1, b0; b0 = fgetc(fp); b1 = fgetc(fp); return (b1 << 8) | b0; } // MARK: - Sphere struct point { float x, y, z; // coordinates float nx, ny, nz; // surface normal float s, t; // texture coords }; int NumLngs, NumLats; struct point* Pts; struct point* PtsPointer(int lat, int lng) { if (lat < 0) lat += (NumLats-1); if (lng < 0) lng += (NumLngs-1); if (lat > NumLats-1) lat -= (NumLats-1); if (lng > NumLngs-1) lng -= (NumLngs-1); return &Pts[NumLngs*lat + lng]; } void DrawPoint(struct point *p) { glNormal3f(p->nx, p->ny, p->nz); glTexCoord2f(p->s, p->t); glVertex3f(p->x, p->y, p->z); } void SphereTexture(float radius, int slices, int stacks) { struct point top, bot; // top, bottom points struct point *p; // set the globals: NumLngs = (slices > 3) ? slices : 3; NumLats = (stacks > 3) ? stacks : 3; // allocate the point data structure: Pts = new struct point[NumLngs * NumLats]; // fill the Pts structure: for (int ilat = 0; ilat < NumLats; ilat++) { float lat = -M_PI/2. + M_PI * (float)ilat / (float)(NumLats-1); float xz = cos(lat); float y = sin(lat); for (int ilng = 0; ilng < NumLngs; ilng++) { float lng = -M_PI + 2. * M_PI * (float)ilng / (float)(NumLngs-1); float x = xz * cos(lng); float z = -xz * sin(lng); p = PtsPointer(ilat, ilng); p->x = radius * x; p->y = radius * y; p->z = radius * z; p->nx = x; p->ny = y; p->nz = z; if (IfDistort) { p->s = (lng + M_PI) / (2.*M_PI) + Time/4/360; p->t = (lat + M_PI/2.) / M_PI + Time/4/360; } else { p->s = (lng + M_PI) / (2.*M_PI); p->t = (lat + M_PI/2.) / M_PI; } } } top.x = 0.; top.y = radius; top.z = 0.; top.nx = 0.; top.ny = 1.; top.nz = 0.; top.s = 0.; top.t = 1.; bot.x = 0.; bot.y = -radius; bot.z = 0.; bot.nx = 0.; bot.ny = -1.; bot.nz = 0.; bot.s = 0.; bot.t = 0.; // connect the north pole to the latitude NumLats-2: glBegin(GL_QUADS); for (int ilng = 0; ilng < NumLngs-1; ilng++) { p = PtsPointer(NumLats-1, ilng); DrawPoint(p); p = PtsPointer(NumLats-2, ilng); DrawPoint(p); p = PtsPointer(NumLats-2, ilng+1); DrawPoint(p); p = PtsPointer(NumLats-1, ilng+1); DrawPoint(p); } glEnd(); // connect the south pole to the latitude 1: glBegin(GL_QUADS); for (int ilng = 0; ilng < NumLngs-1; ilng++) { p = PtsPointer(0, ilng); DrawPoint(p); p = PtsPointer(0, ilng+1); DrawPoint(p); p = PtsPointer(1, ilng+1); DrawPoint(p); p = PtsPointer(1, ilng); DrawPoint(p); } glEnd(); // connect the other 4-sided polygons: glBegin(GL_QUADS); for (int ilat = 2; ilat < NumLats-1; ilat++) { for (int ilng = 0; ilng < NumLngs-1; ilng++) { p = PtsPointer(ilat-1, ilng); DrawPoint(p); p = PtsPointer(ilat-1, ilng+1); DrawPoint(p); p = PtsPointer(ilat, ilng+1); DrawPoint(p); p = PtsPointer(ilat, ilng); DrawPoint(p); } } glEnd(); delete [] Pts; Pts = NULL; }
[ "jerry2285@yahoo.com.tw" ]
jerry2285@yahoo.com.tw
bad11a9ce48681fb9ef3a61369d0590f84fd2717
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/tcr/src/v20190924/model/KeyValueString.cpp
ed7bf6dbe14f577cc540d5b79acfd09c7191f6e1
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
2,925
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tcr/v20190924/model/KeyValueString.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tcr::V20190924::Model; using namespace std; KeyValueString::KeyValueString() : m_keyHasBeenSet(false), m_valueHasBeenSet(false) { } CoreInternalOutcome KeyValueString::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Key") && !value["Key"].IsNull()) { if (!value["Key"].IsString()) { return CoreInternalOutcome(Core::Error("response `KeyValueString.Key` IsString=false incorrectly").SetRequestId(requestId)); } m_key = string(value["Key"].GetString()); m_keyHasBeenSet = true; } if (value.HasMember("Value") && !value["Value"].IsNull()) { if (!value["Value"].IsString()) { return CoreInternalOutcome(Core::Error("response `KeyValueString.Value` IsString=false incorrectly").SetRequestId(requestId)); } m_value = string(value["Value"].GetString()); m_valueHasBeenSet = true; } return CoreInternalOutcome(true); } void KeyValueString::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_keyHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Key"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_key.c_str(), allocator).Move(), allocator); } if (m_valueHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Value"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_value.c_str(), allocator).Move(), allocator); } } string KeyValueString::GetKey() const { return m_key; } void KeyValueString::SetKey(const string& _key) { m_key = _key; m_keyHasBeenSet = true; } bool KeyValueString::KeyHasBeenSet() const { return m_keyHasBeenSet; } string KeyValueString::GetValue() const { return m_value; } void KeyValueString::SetValue(const string& _value) { m_value = _value; m_valueHasBeenSet = true; } bool KeyValueString::ValueHasBeenSet() const { return m_valueHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
4df7393f21b4306113ceb83d2cfc9bf7c4621a22
e8478d7e80c73c8ee7f7d883743563668210c71a
/tests/host_vector_test.cpp
673339230eb92d16d9a2c714336f9c5eb811d173
[]
no_license
siavashadpey/linsolver
660b6a786c888baed4426ca20814e51a160aff60
f7910b5307650e7303fe369bc82e9094d0193c51
refs/heads/master
2022-11-30T18:08:42.826792
2020-08-12T23:10:35
2020-08-12T23:10:35
284,055,954
0
1
null
2020-08-12T23:10:36
2020-07-31T14:30:14
C++
UTF-8
C++
false
false
3,459
cpp
#include <stdio.h> #include <cmath> #include "gtest/gtest.h" #include "backends/host/host_vector.h" #define tol 1E-13 TEST(HostVector, test_1) { HostVector<double> v = HostVector<double>(); const int n = 5; v.allocate(n); double v_e[n]; double norm_e = 0.0; for (int i = 0; i < n; i++) { v[i] = (double)i; v_e[i] = (double)i; norm_e += v_e[i]*v_e[i]; } norm_e = sqrt(norm_e); EXPECT_EQ(n, v.n()); // size EXPECT_NEAR(v.norm(), norm_e, tol); // l2-norm computation for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], v_e[i], tol); // values } const double c = 2.4; v.scale(c); for (int i = 0; i < n; i++) { v_e[i] *= c; EXPECT_NEAR(v[i], v_e[i], tol); // scale } HostVector<double> w = HostVector<double>(); w.allocate(n); double w_e[n]; double v_dot_w = 0.; for (int i = 0; i < n; i++) { w[i] = (double) 3*(n - i); w_e[i] = (double) 3*(n - i); v_dot_w += w_e[i]*v_e[i]; } EXPECT_NEAR(v.dot(w), v_dot_w, tol); // dot product v.add(2, w, 3); for (int i = 0; i < n; i++) { v_e[i] = 2.*v_e[i] + 3.*w_e[i]; EXPECT_NEAR(v[i], v_e[i], tol); // v = a*v + b*w } w.add(1, v, 2); for (int i = 0; i < n; i++) { w_e[i] += 2.*v_e[i]; EXPECT_NEAR(w[i], w_e[i], tol); // v = v + b*w } w.add(2, v, 1); for (int i = 0; i < n; i++) { w_e[i] = 2.*w_e[i] + v_e[i]; EXPECT_NEAR(w[i], w_e[i], tol); // v = a*v + w } w.add(1, v, 0); for (int i = 0; i < n; i++) { EXPECT_NEAR(w[i], w_e[i], tol); // v = v } double v_data[] = {10., 8., 15.4, 17, 20.}; v.copy_from(v_data); for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], v_data[i], tol); // copy from raw data } v.scale(c); v.copy_to(v_data); for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], v_data[i], tol); // copy to raw data } const int n_new = 6; w.allocate(n_new); double w_new[n_new]; for (int i = 0; i < n_new; i++) { w[i] = (double) 4.*(n_new - i); w_new[i] = (double) 4.*(n_new - i); } v.copy_from(w); EXPECT_EQ(v.n(), n_new); // size for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], w_new[i], tol); // copy from another class instance } v.scale(c); v.copy_to(w); EXPECT_EQ(v.n(), n_new); // size for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], w[i], tol); // copy to another class instance } v.zeros(); for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], 0., tol); // zeroed } v.ones(); for (int i = 0; i < n; i++) { EXPECT_NEAR(v[i], 1., tol); // oneed } v.clear(); EXPECT_EQ(v.n(), 0); // cleared data } TEST(HostVector, test_2) { HostVector<double> v_h = HostVector<double>(); HostVector<double> w_h = HostVector<double>(); HostVector<double> vw_h = HostVector<double>(); const int n = 5; v_h.allocate(n); w_h.allocate(n); vw_h.allocate(n); for (int i = 0; i < n; i++) { v_h[i] = (double) 2.3 * i + 10.; w_h[i] = (double) -3. * i + 12.; vw_h[i] = v_h[i] * w_h[i]; } v_h.elementwise_multiply(w_h); for (int i = 0; i < n; i++) { EXPECT_NEAR(vw_h[i], v_h[i], tol); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "sia.shadpey@mail.utoronto.ca" ]
sia.shadpey@mail.utoronto.ca
ac867aab9bc4b9302f86e1f45df70e126123bab0
762e574fed6c42196aede4f1e00d1faac33dd8dc
/spatialmedia/parser.cpp
02a466c98b36c55d5b52b3ae39b329883b0001f7
[ "Apache-2.0" ]
permissive
spincle/Spatial-Media-For-iOS
e2ebe0216ea7e172619c9c13f3d9fcfffa0f6dba
9e5d4cad9e220f5a3806d08252bf80b12ea7d243
refs/heads/master
2021-06-17T01:46:26.787597
2017-05-15T12:30:19
2017-05-15T12:30:19
76,186,711
6
1
null
null
null
null
UTF-8
C++
false
false
4,727
cpp
/* ******************************************************************************* ** usage: spatialmedia [options] [files...] ** ** By default prints out spatial media metadata from specified files. ** ** positional arguments: ** file input/output files ** ** optional arguments: ** -h, --help show this help message and exit ** -i, --inject injects spatial media metadata into the first file ** specified (.mp4 or .mov) and saves the result to the ** second file specified ** ** Spherical Video: ** -s STEREO-MODE, --stereo STEREO-MODE ** stereo mode (none | top-bottom | left-right) ** -c CROP, --crop CROP crop region. Must specify 6 integers in the form of ** "w:h:f_w:f_h:x:y" where w=CroppedAreaImageWidthPixels ** h=CroppedAreaImageHeightPixels f_w=FullPanoWidthPixels ** f_h=FullPanoHeightPixels x=CroppedAreaLeftPixels ** y=CroppedAreaTopPixels ** ** Spatial Audio: ** -a, --spatial-audio spatial audio. First-order periphonic ambisonics with ** ACN channel ordering and SN3D normalization ** *********************************************************************************/ #include <algorithm> #include <iostream> #include <string> #include <getopt.h> #include "parser.h" using namespace std; namespace SpatialMedia { Parser::Parser ( ) { m_bInject = true; m_StereoMode = SM_NONE; for ( int t=0; t<6; t++ ) m_crop[t] = 0; m_bSpatialAudio = false; } Parser::~Parser ( ) { } void Parser::printHelp ( ) { cout << "usage: spatialmedia [options] [files...]" << endl; cout << endl; cout << "By default prints out spatial media metadata from specified files." << endl; cout << endl; cout << "positional arguments:" << endl; cout << " file input/output files" << endl; cout << endl; cout << "optional arguments:" << endl; cout << " -h, --help show this help message and exit" << endl; cout << " -i, --inject injects spatial media metadata into the first file" << endl; cout << " specified (.mp4 or .mov) and saves the result to the" << endl; cout << " second file specified" << endl; cout << endl; cout << "Spherical Video:" << endl; cout << " -s STEREO-MODE, --stereo STEREO-MODE" << endl; cout << " stereo mode (none | top-bottom | left-right)" << endl; cout << " \"none\": Mono frame layout." << endl; cout << " \"top-bottom\": Top half contains the left eye and bottom half contains the right eye." << endl; cout << " \"left-right\": Left half contains the left eye and right half contains the right eye." << endl; cout << " ( RFC: https://github.com/google/spatial-media/tree/master/docs/spherical-video-rfc.md )" << endl; cout << endl; cout << " -c CROP, --crop CROP crop region. Must specify 6 integers in the form of" << endl; cout << " \"w:h:f_w:f_h:x:y\" where w=CroppedAreaImageWidthPixels" << endl; cout << " h=CroppedAreaImageHeightPixels f_w=FullPanoWidthPixels" << endl; cout << " f_h=FullPanoHeightPixels x=CroppedAreaLeftPixels" << endl; cout << " y=CroppedAreaTopPixels" << endl; cout << endl; cout << "Spatial Audio:" << endl; cout << " -a, --spatial-audio spatial audio. First-order periphonic ambisonics with" << endl; cout << " ACN channel ordering and SN3D normalization" << endl; cout << " Enables injection of spatial audio metadata. If enabled, the file must contain a" << endl; cout << " 4-channel first-order ambisonics audio track with ACN channel ordering and SN3D" << endl; cout << " normalization; see the [Spatial Audio RFC](../docs/spatial-audio-rfc.md) for" << endl; cout << " more information." << endl; } std::string &Parser::getInFile ( ) { return m_strInFile; } std::string &Parser::getOutFile ( ) { return m_strOutFile; } bool Parser::getInject ( ) { return m_bInject; } Parser::enMode Parser::getStereoMode ( ) { return m_StereoMode; } int *Parser::getCrop ( ) { // return NULL if no croping was specified. for ( int t=0; t<6; t++ ) { if ( m_crop[t] != 0 ) return m_crop; } return NULL; } bool Parser::getSpatialAudio ( ) { return m_bSpatialAudio; } }; // nd of namespace SpatialMedia
[ "tomtomtongtong@gmail.com" ]
tomtomtongtong@gmail.com
27df39eefb2cadb6a0547c32a7a949680c050124
90e0a8dd428056f663257ae34328e83dc239551e
/thrift_async_test/ImagingHandler.h
8f000f80d10b875b2dd9e9f0359d59e6faa0ead5
[]
no_license
aubonbeurre/abbsandbox
f8bfbb1faec0e034ff6081176ac78554e02ad683
198fa843139960712fd53062708e01e4a9f94452
refs/heads/master
2020-04-06T03:33:05.823104
2011-09-06T19:39:13
2011-09-06T19:39:13
1,911,032
0
0
null
null
null
null
UTF-8
C++
false
false
344
h
#pragma once #include "gen-cpp/Imaging.h" namespace imaging { class ImagingHandler: public ImagingIf { public: ImagingHandler() { } virtual void mandelbrot(std::string& _return, const int32_t w, const int32_t h); virtual void transform(std::string& _return, const Transform::type t, const std::string& img); }; } // namespace imaging
[ "aubonbeurre@gmail.com" ]
aubonbeurre@gmail.com
2744feacf7904decae760b647e2144a8f2a9d77d
fb6010e5992307fd420309cbd99a01fef13200dc
/Algorithms/34. Find First and Last Position of Element in Sorted Array.cpp
7b556d6bc8057babd601d0e34fe92cce4a10adf6
[]
no_license
MegrezZhu/LeetCode
018e803701bbdb56827d98a3811fdb63cc787792
9105298f18a1284a5eeee7e2cc4745f5b45476c8
refs/heads/master
2023-02-10T08:55:08.884565
2021-01-11T05:44:39
2021-01-11T05:44:39
107,408,579
0
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
class Solution { vector<int> span(vector<int>& nums, int pos) { int l = pos, r = pos; while (l > 0 && nums[l - 1] == nums[l]) l--; while (r < nums.size() - 1 && nums[r + 1] == nums[r]) r++; return { l, r }; } public: vector<int> searchRange(vector<int>& nums, int target) { int n = nums.size(); int l = 0, r = n - 1; while (l <= r) { int mid = (l + r) / 2; if (nums[mid] == target) return span(nums, mid); if (nums[mid] < target) l = mid + 1; else r = mid - 1; } return {-1, -1}; } };
[ "mystery490815101@gmail.com" ]
mystery490815101@gmail.com
9fb96d850ed27a3e8574e9866e3548604b6160d6
eea7adb1221e39e949e9f13b92805f1f63c61696
/leetcode-04/solutions/cpp/0680.cpp
ef7e19bb38c004cb35867eb31702919e879b3007
[]
no_license
zhangchunbao515/leetcode
4fb7e5ac67a51679f5ba89eed56cd21f53cd736d
d191d3724f6f4b84a66d0917d16fbfc58205d948
refs/heads/master
2020-08-02T21:39:05.798311
2019-09-28T14:44:14
2019-09-28T14:44:14
211,514,370
1
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
class Solution { public: bool validPalindrome(string s) { const int n = s.length(); for (int i = 0; i < n / 2; i++) if (s[i] != s[n - 1 - i]) return validPalindrome(s, i + 1, n - 1 - i) || validPalindrome(s, i, n - 2 - i); return true; } private: bool validPalindrome(string& s, int l, int r) { for (int i = l; i <= l + (r - l) / 2; i++) if (s[i] != s[r - i + l]) return false; return true; } };
[ "zhangchunbao515@163.com" ]
zhangchunbao515@163.com
2c4726e351b8dbcafe8f069dd4822aa1118d90bc
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/random/detail/disable_warnings.hpp
6801bf56b2ed710536587ebe83711c56e600a402
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
128
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:eb1c675271f8f94d10623527120368274389b07f71bb14dd0f5185669f177773 size 823
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
89d41798bad1c404cc7b955d8bbc0fc01b8a904d
1c8a37527627e8bab2b0b9a07f4e8eeddbb68bfa
/Chess_org/ChessEngine/src/engine/ops/Movements.cpp
72f4c1efd2c9d1ebbdd87339e24c854fb02d0f5a
[ "MIT" ]
permissive
Jurymax99/Chess
b52975c2d70f4358ae7ab6cac214cabfa03ee729
6f8c2ab959907755af102b68eb5dec3b40793203
refs/heads/master
2022-05-31T14:30:39.497544
2020-05-03T16:33:42
2020-05-03T16:33:42
248,818,337
1
0
null
2020-03-24T18:36:01
2020-03-20T17:49:23
C++
UTF-8
C++
false
false
3,384
cpp
#include "Board.h" #include "Utilities.h" namespace Chess { namespace Engine { bool Board::makeMove(const char& type, const Position& source, const Position& dest, const int& player, const bool& enp) { Player* mover = player == RED ? &Red : &Green; main(dest) = main(source); main(source).removePiece(); ++halfMoves; target.possible = false; if (type == 'K') { mover->setKing(dest); if (player == RED) { Red.setCastleKing(false); Red.setCastleQueen(false); } else { Green.setCastleKing(false); Green.setCastleQueen(false); } } else if (type == 'R') { if (dest.checkH() == (player == RED ? 7 : 0)) { if (dest.checkW() == 0) { player == RED ? Red.setCastleQueen(false) : Green.setCastleQueen(false); } else if (dest.checkW() == 7) { player == RED ? Red.setCastleKing(false) : Green.setCastleKing(false); } } } else if (type == 'P'){ if (enp) { target = { dest.checkH(), dest.checkW(), true }; } halfMoves = 0; } ++turn; return true; } bool Board::makeFakeMove(const char& type, const Position& source, const Position& dest, const int& player) { Player* mover = player == RED ? &Red : &Green; main(dest) = main(source); main(source).removePiece(); if (type == 'K') { mover->setKing(dest); } int player_checked = player; bool totChecked = whoChecked(player_checked); //rollback if (type == 'K') { mover->setKing(source); } main(source) = main(dest); main(dest).removePiece(); if (not totChecked) { return true; } if (player_checked == player) { if (MODE == DEBUG) { if (player == RED) { std::cout << "FAKEMOVE::The red king is in check" << std::endl; } else { std::cout << "FAKEMOVE::The green king is in check" << std::endl; } } return false; } else { return true; } } bool Board::makeFakeMovePro(const Position& source, const Position& dest, const int& player) { Player* mover = player == RED ? &Red : &Green; bool first = main(source).isFirstMov(); std::vector<char> types = { 'Q', 'N', 'R', 'B' }; int i = 0; while (i < 4) { main(dest).addPiece(types[i], player); main(source).removePiece(); int player_checked = player; bool totChecked = whoChecked(player_checked); main(dest).removePiece(); main(source).addPiece('P', player); if (not first) { main(source).makeFirstMov(); } if (totChecked) { if (player_checked == player) { if (MODE == DEBUG) { if (player == RED) { std::cout << "FAKEMOVE::The red king is in check" << std::endl; } else { std::cout << "FAKEMOVE::The green king is in check" << std::endl; } } return false; } else { return true; } } ++i; } return true; } bool Board::pawnPromote(const Position& source, const Position& dest, const char& type, const int& player) { Player* mover = player == RED ? &Red : &Green; main(dest).addPiece(type, player); main(source).removePiece(); ++halfMoves; target.possible = false; halfMoves = 0; main(dest).makeFirstMov(); ++turn; return true; } } }
[ "noreply@github.com" ]
noreply@github.com
7dc9f2a7e5ddb7f8959fdd5ef782ccac25ebf065
3c43c85b33747c9dda3a258e21d71d65890748ce
/IOICAMP0094.cpp
f66e52f5c2fae2a53e1fdc89b988de72484915ae
[]
no_license
rareone0602/Competitive-Programming-Solutions
934fed13af0b4ba662dcdeacf14f64eb0559babf
2b42cfeba2d8e4ba5993bef6cf06481a3e85932f
refs/heads/master
2021-09-14T11:30:06.208446
2018-05-12T22:04:28
2018-05-12T22:04:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,614
cpp
#include <iostream> #include <cmath> #include <complex> #include <algorithm> #define X real() #define Y imag() #define F first #define S second #define eat(a) int a;scanf("%d",&a) #define FL(i,j,k) for(int i=j;i<k;++i) using namespace std; const int N=1010; const double eps=1e-8; typedef complex<double> pt; typedef pair<pt, pt> seg; int n,polyn;//半平面數,多邊形頂點 pt P[N],resultPoly[N],deqP[N]; seg HP[N],deqHP[N]; int sign(double d){return d<-eps?-1:(d>eps);} inline double XS(pt a,pt b){return a.X*b.Y-a.Y*b.X;}//叉積 inline pt Xection(seg a, seg b)//線段焦點 { double t=XS(a.S-a.F, b.S-b.F); return XS(a.S-a.F,b.S-a.F)/t*b.F-XS(a.S-a.F,b.F-a.F)/t*b.S; } double area(pt *poly,int n){ if(n<=2)return 0; double sum=0; FL(i, 2, n)sum+=XS(poly[i-1]-poly[0], poly[i]-poly[0]); return fabs(sum)/2; } void HPXection()//半平面交集 { sort(HP, HP+n, [=](seg a,seg b){return arg(a.S-a.F)>arg(b.S-b.F);}); int ne=0; FL(i, 0, n){ if(ne!=i && fabs(arg(HP[i].S-HP[i].F)-arg(HP[ne].S-HP[ne].F))<eps){ if(XS(HP[i].S-HP[i].F, HP[ne].S-HP[ne].F)>eps) HP[ne++]=HP[i]; }else{ HP[ne++]=HP[i]; } }n=ne; int l=0,r=0; deqHP[r++]=HP[0]; deqHP[r++]=HP[1]; deqP[r-2]=Xection(deqHP[r-1], deqHP[r-2]); FL(i,2,n){ while (r-l>=2 && sign(XS(HP[i].S-HP[i].F, deqP[r-2]-HP[i].F))<eps) --r; deqHP[r++]=HP[i]; deqP[r-2]=Xection(deqHP[r-1], deqHP[r-2]); } while(r-l>=2){ bool flag = 0; if(sign(XS(deqHP[r-1].S-deqHP[r-1].F, deqP[l]-deqHP[r-1].F)) < eps)flag = 1,l++; if(sign(XS(deqHP[l ].S-deqHP[l ].F, deqP[r-2]-deqHP[l].F)) < eps)flag = 1,r--; if(!flag) break; } deqP[r-1] = Xection(deqHP[l ], deqHP[r-1]); FL(i, l, r)resultPoly[i-l]=deqP[i]; polyn=r-l; } int main(){ eat(T); while (T--) { eat(N);eat(M); FL(i, 0, N){ eat(x);eat(y); P[i]=pt(x,y); }n=0; FL(i, 0, M){ eat(a);eat(b);eat(k); if(k==N+1)continue; sort(P, P+N, [=](pt p1,pt p2){return p1.X*a+p1.Y*b>p2.X*a+p2.Y*b;}); HP[n++]=seg(P[k-1],P[k-1]-pt(0,1)*pt(a,b)); } HP[n++]=seg(pt(0,0),pt(100,0)); HP[n++]=seg(pt(100,0),pt(100,100)); HP[n++]=seg(pt(100,100),pt(0,100)); HP[n++]=seg(pt(0,100),pt(0,0)); HPXection(); double a=area(resultPoly, polyn); printf("%.6lf\n",a/10000); } }
[ "rareone0602@me.com" ]
rareone0602@me.com
8140b59ced5eb34f4204bd5f43712291bb7cf6a0
65b9845d5b426d570d8fa31fe536bd04cdbeda98
/include/logging/StdOutput.h
e8b3f6568c04ddc4577d5b034cf8ee26043b3ff6
[ "BSL-1.0" ]
permissive
shenyanjun/eddic
72bb4fd51d36c370bf925200e075f751fd6f273d
4715ca46fae7d0d0eab45584a73b81b602b38004
refs/heads/master
2021-01-15T17:28:18.944839
2012-11-10T19:59:02
2012-11-10T19:59:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,417
h
/******************************************************************************* * * Copyright (c) 2008, 2009 Michael Schulze <mschulze@ivs.cs.uni-magdeburg.de> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holders nor the names of * 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 * OWNER 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. * * * $Id: StdOutput.h 1 2010-01-11 14:24:28Z perch $ * ******************************************************************************/ #ifndef __StdOutput_h__ #define __StdOutput_h__ #include <iostream> namespace logging { /*! \brief Provides an interface to the standard * output facilities of e.g. Linux or * Windows. */ template <std::ostream & stream = ::std::cout> class StdOutput { public: template<typename T> StdOutput & operator<<(T value) { stream << value; return *this; } }; } /* logging */ #endif
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
c436c40c95f78f9b0c796eb55cacc9f32191bd1c
eadd2c7a0b42191555c49af22217723f26efcf84
/canbustrans/src/canbustrans.cpp
78f0661ade6b8c0e683ab10696b76b56d701e03c
[]
no_license
nguyenanhlam691999/Projects
b88eaa5753a94ce66f1d37483a93ed728a62b0ff
8432e58fe820a530b61ffc5f56b6b53d2532f8f3
refs/heads/main
2023-04-15T02:41:36.195372
2021-04-27T05:42:49
2021-04-27T05:42:49
347,860,231
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
#include <Arduino.h> #include <mcp2515.h> #include <SPI.h> struct can_frame canMsg1; MCP2515 mcp2515(10); void setup() { Serial.begin(9600); while (!Serial) ; Serial.begin(9600); mcp2515.reset(); mcp2515.setBitrate(CAN_125KBPS); mcp2515.setNormalMode(); canMsg1.can_id = 0x0F6; canMsg1.can_dlc = 8; canMsg1.data[0] = 0; canMsg1.data[1] = 0; canMsg1.data[2] = 0; canMsg1.data[3] = 0; canMsg1.data[4] = 0; canMsg1.data[5] = 0; canMsg1.data[6] = 0; canMsg1.data[7] = 0; } void loop() { canMsg1.data[0] = 1; mcp2515.sendMessage(&canMsg1); delay(500); canMsg1.data[0] = 0; mcp2515.sendMessage(&canMsg1); delay(500); }
[ "thecrystal2014@gmail.com" ]
thecrystal2014@gmail.com
50ebe01a09e35a35c7c4112349e48760375bc001
f6cf14142621b8c4709c6f2073172f39577b1964
/api2/lib/rec/cv_lt/rgb2bgr.cpp
4503abeefb7bdd89f66fa785198d1d3d920a36d2
[]
no_license
BusHero/robotino_api2
f3eef6c1ace2ff5a8b93db691aa779db8a9ce3a1
9757814871aa90977c2548a8a558f4b2cb015e5d
refs/heads/master
2021-06-18T21:32:14.390621
2021-02-18T15:21:48
2021-02-18T15:21:48
165,231,765
1
0
null
null
null
null
UTF-8
C++
false
false
1,169
cpp
#include "rec/cv_lt/rgb2bgr.h" #include <algorithm> void rec::cv_lt::rgb2bgr( const char* src, const unsigned int srcWidth, const unsigned int srcHeight, const unsigned int srcStep, char* dst, const unsigned int dstWidth, const unsigned int dstHeight, const unsigned int dstStep ) { unsigned int width = std::min( srcWidth, dstWidth ); unsigned int height = std::min( srcHeight, dstHeight ); for( unsigned int line=0; line<height; ++line ) { const unsigned char* psrc = (const unsigned char*)src + srcStep * line; unsigned char* pdst = (unsigned char*)dst + dstStep * line; for( unsigned int x=0; x<width; ++x ) { unsigned char r = *(psrc++); unsigned char g = *(psrc++); unsigned char b = *(psrc++); *(pdst++) = b; *(pdst++) = g; *(pdst++) = r; } } } void rec::cv_lt::rgb2bgr( char* srcdst, const unsigned int width, const unsigned int height, const unsigned int step ) { for( unsigned int line=0; line<height; ++line ) { unsigned char* p = (unsigned char*)srcdst + step * line; for( unsigned int x=0; x<width; ++x ) { unsigned char r = *p; *p = *(p+2); *(p+2) = r; p += 3; } } }
[ "petru.cervac@gmail.com" ]
petru.cervac@gmail.com
19ec49791037c42683eb33407d0e219c48d1cb8c
faa5d1d27a89cba2657f6fe53d9106630ef2c104
/洛谷/P3879.cpp
44b7726dc946bc562286d09be98116a4e4e96ce0
[]
no_license
xiao-lin52/My-Codes
f4feef04a05b1904a1f31e0e5a04e0a48ee61cb9
d8fc530ade2bbac32c016a731c667c4189e3c6c7
refs/heads/main
2023-03-12T23:32:55.219341
2021-03-07T07:31:32
2021-03-07T07:31:32
304,806,222
1
0
null
null
null
null
UTF-8
C++
false
false
920
cpp
#include<bits/stdc++.h> #define SIZE 500010 using namespace std; struct Trie { int k,nxt[SIZE][26]; vector<int> isWord[SIZE]; void insert(char* str,int x) { int p=0,len=strlen(str); for(int i=0;i<len;i++) if(nxt[p][str[i]-'a']) p=nxt[p][str[i]-'a']; else p=nxt[p][str[i]-'a']=++k; if(isWord[p].empty()||isWord[p].back()!=x) isWord[p].push_back(x); } void find(char* str) { int p=0,len=strlen(str); for(int i=0;i<len;i++) if(nxt[p][str[i]-'a']) p=nxt[p][str[i]-'a']; else { printf("\n"); return; } for(int i=0;i<isWord[p].size();i++) printf("%d ",isWord[p][i]); printf("\n"); } }; Trie trie; int n,m,l; char a[30]; int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&l); for(int j=1;j<=l;j++) { scanf("%s",a); trie.insert(a,i); } } scanf("%d",&m); for(int i=1;i<=m;i++) { scanf("%s",a); trie.find(a); } return 0; }
[ "2492043904@qq.com" ]
2492043904@qq.com
7abe529bd761dd5eeeb3d4c2e51cd2fce06d6d3f
a600c54dfff84c93cc77aef9669aae1bc7f30f4c
/Source/Injector/InjectorMain.cpp
5d18062bb0b758c5f6b3d455fadf10ad16e3ac7d
[]
no_license
POETSII/Orchestrator
88003917b9fb107417bf1c1221f09c3b8a4fb70b
3369ec20cd1ad9b28293f044e2a960d7faf1dd7a
refs/heads/development
2022-10-13T06:47:40.505365
2022-07-28T12:44:06
2022-07-28T12:44:06
133,035,539
0
1
null
2022-07-12T15:17:57
2018-05-11T12:13:51
C++
UTF-8
C++
false
false
812
cpp
//------------------------------------------------------------------------------ #include "Debug.h" #include "Injector.h" #include "Unrec_t.h" #include "Pglobals.h" #include <stdio.h> //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { Injector * pInjector = 0; try { pInjector = new Injector(argc,argv,string(csINJECTORproc)); } catch(bad_alloc &) { printf("\n\n%s Main out of memory... \n\n",csINJECTORproc); fflush(stdout); } catch(Unrec_t & u) { u.Post(); } catch(...) { printf("\n\n%s Main unhandled exception...??? \n\n",csINJECTORproc); fflush(stdout); } DebugPrint("%s Main closing down.\n",csINJECTORproc); delete pInjector; return 0; } //------------------------------------------------------------------------------
[ "m.vousden@soton.ac.uk" ]
m.vousden@soton.ac.uk
bd4287424539cf4f2bf05c5737bd08b79fd98a8b
5008a2fc7d8a14711f430541d26bef4acef3e870
/Иван Борисов (81134)/BullsAndCows.cpp
08c1cea9e30de9cc41682fff4a64d4c0300fd69b
[]
no_license
ehadzhi/PeerCodeReview
d59ea13722b88ca88d34968613a0b78ca5e58531
31c38f592673a88cc4e805f3fc9140fab15d0c83
refs/heads/master
2021-06-01T08:47:45.753826
2015-05-14T11:27:35
2015-05-14T11:27:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,580
cpp
/* * BullsAndCows.cpp * * Created on: Apr 7, 2015 * Author: ivan */ //#include <cstdlib> #include <iostream> #include <stdlib.h> #include <ctime> #include <stdio.h> using namespace std; #include "BullsAndCows.h" int DEFAULT_SIZE = 4; BullsAndCows::BullsAndCows(int size) { srand(time(NULL)); this->setContainerSize(size); int* container = this->randomGameNumber(); this->setContainer(container); this->numberOfGuesses = 0; this->endGame = false; } BullsAndCows::BullsAndCows(int numbers[],int size) { this->sizeOfContainer = size; int* nums = numbers; this->setContainer(nums); this->numberOfGuesses = 0; this->endGame = false; } void BullsAndCows::setContainerSize(int size){ if(size <2 || size >4){ cout<<"Invalid size.Size was set to "<<DEFAULT_SIZE; this->sizeOfContainer = DEFAULT_SIZE; } else this->sizeOfContainer = size; } void BullsAndCows::setContainer(int* container){ numbersContainer = new int[sizeOfContainer]; for (int i = 0; i <this->sizeOfContainer; i++){ this->numbersContainer[i] = container[i]; } delete[] container; } int BullsAndCows::randomNumberWithZero() { return rand() % 10 ; } int BullsAndCows::randomNumberWithoutZero() { return (rand() % 9) + 1; } int* BullsAndCows::randomGameNumber(){ int* digits = new int[this->sizeOfContainer]; int count_nums = 1; digits[0] = this->randomNumberWithoutZero(); int curr_digit; bool checkDiffNum; while(count_nums < this->sizeOfContainer){ do { checkDiffNum = true; curr_digit = this->randomNumberWithZero(); for(int i= 0; i < count_nums; i++){ if(digits[i] == curr_digit){ checkDiffNum = false; } } } while(!checkDiffNum); digits[count_nums] = curr_digit; ++count_nums; } return digits; } bool BullsAndCows::IsInsideContainer(int num){ for (int i = 0; i < this->sizeOfContainer; i++) { if (this->numbersContainer[i] == num) return true; } return false; } //CowElement и BullElement съм ги направил без arr* ,понеже мисля че е излишно //ние можем да достъпим this->numbersContainer директно bool BullsAndCows::CowElement(int position, int value) { if(this->IsInsideContainer(value)){ if(this->numbersContainer[position] == value) return false; else return true; } else return false; } bool BullsAndCows::BullElement(int position, int value) { if(this->IsInsideContainer(value)){ if(this->numbersContainer[position] == value) return true; else return false; } else return false; } char* BullsAndCows::TryToGuess(int myGuess) { ++this->numberOfGuesses; int pos_digit,cows = 0,bulls = 0; bool win = true; for(int i = this->sizeOfContainer-1; i>=0;i--){ pos_digit = myGuess % 10; if(pos_digit != this->numbersContainer[i]) win = false; if(this->BullElement(i,pos_digit)) ++bulls; if(this->CowElement(i,pos_digit)) ++cows; myGuess /= 10; } char* message = new char[50]; if(win){ this->endGame = true; sprintf (message,"Congratualtions! You made a right guess!"); return message; } else { sprintf (message,"Cows: %d Bulls: %d" , cows, bulls); return message; } } void BullsAndCows::Start() { int number; do { cout<<"Your guess:"; cin>>number; cout<<" ["<<number<<"] => "; char* message; message = this->TryToGuess(number); cout<<message<<endl; } while(!this->endGame); cout<<"\n It took you "<<this->numberOfGuesses<<"guesses to finish the game"; } BullsAndCows::~BullsAndCows() { delete[] numbersContainer; }
[ "kazmanov@uni-sofia.bg" ]
kazmanov@uni-sofia.bg
31afe493839660a7ff5d07e42c1a21dca2596b77
cba830137eaa81165e398108c372bf8fde6db811
/test/32-markdownish.h
f7df80bf39edc9be74e1da4432475505aed7df45
[ "MIT" ]
permissive
Enuvesta/re2jit
b15aa1c3faf0fa3a564e61b85b25c949cbfa15be
6a2519b7adfc6211b22052822867af02db74dc5b
refs/heads/master
2021-01-14T08:40:21.793487
2015-12-02T17:24:07
2015-12-02T17:24:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,844
h
#include "00-definitions.h" /* A parser of a small (but most commonly used) subset of Markdown. * It uses regexps to tokenize the input text. Obviously. * * Initially, this thing was written as a bet that I could make a parser * of a subset of Markdown suitable for comments, etc. in less than 200 SLOC * in Python. (Full-fledged parsers were considered too extreme for that, * plus python-markdown2 generated malformed HTML on improperly nested * syntactic constructs at the time -- looks like they fixed that.) I won. * The project it was written for is long dead, but the parser still exists, * rewritten in dg, although it does not see much use. Here it is, in all its * magnificient regexp-y glory: https://github.com/pyos/dg/blob/gh-pages/dmark.dg */ #include <vector> #include <fstream> #include <sstream> #include <iostream> #include <iterator> // Damn, that looks bad without the verbose syntax (flag x). static const constexpr char stage1_re[] = "(?is)(?P<fenced>```)|(?P<code> {4}|\\t)|(?P<rule>\\s*(?:[*-]\\s*){3,}$)|(?P<ol>\\s*\\d+\\.\\s+)|(?P<ul>\\s*[*+-]\\s+)|(?P<h>\\s*(?P<h_size>#{1,6})\\s*)|(?P<quote>\\s*>)|(?P<break>\\s*$)|(?P<p>\\s*)"; static const constexpr int stage1_groups = 12; // Original regexp contains a backreference in order to properly match inline code: // // (?P<code> (`+) ... \2 ) // // re2 does not support them, so we'll change the syntax a bit to only accept single quotes. static const constexpr char stage2_re[] = "(?is)(?P<code>`(?P<code_>.+?)`)|(?P<bold>\\*\\*(?P<bold_>(?:\\\\?.)+?)\\*\\*)|(?P<italic>\\*(?P<italic_>(?:\\\\?.)+?)\\*)|(?P<strike>~~(?P<strike_>(?:\\\\?.)+?)~~)|(?P<invert>%%(?P<invert_>(?:\\\\?.)+?)%%)|(?P<hyperlink>[a-z][a-z0-9+.-]*:(?:[,.?]?[^\\s(<>)\"',.?%]|%[0-9a-f]{2}|\\([^\\s(<>)\"']+\\))+)|(?P<text>[\\w_]*\\w)|(?P<escape>\\\\?(?P<escaped>.))"; static const constexpr int stage2_groups = 15; static const RE2 stage1_re2(stage1_re); static const RE2 stage2_re2(stage2_re); static const re2jit::it stage1_jit(stage1_re); static const re2jit::it stage2_jit(stage2_re); template <typename T, int i> static const T& REGEXP(); template <> auto REGEXP<RE2, 1>() -> decltype((stage1_re2)) { return stage1_re2; } template <> auto REGEXP<RE2, 2>() -> decltype((stage2_re2)) { return stage2_re2; } template <> auto REGEXP<re2jit::it, 1>() -> decltype((stage1_jit)) { return stage1_jit; } template <> auto REGEXP<re2jit::it, 2>() -> decltype((stage2_jit)) { return stage2_jit; } template <typename M> auto join(const std::string& s, const M& parts) -> std::string { std::ostringstream u; auto i = std::begin(parts); auto e = std::end(parts); if (i != e) u << *i++; while (i != e) u << s << *i++; return u.str(); } template <typename T> auto stage2(std::string text) -> std::string { size_t off = 0; re2::StringPiece groups[stage2_groups]; while (match(REGEXP<T, 2>(), text.c_str() + off, RE2::UNANCHORED, groups, stage2_groups)) { auto lg = stage2_jit.lastgroup(groups, stage2_groups); auto rp = lg == "text" ? groups[ 0].as_string() : lg == "escape" ? groups[14].as_string() : lg == "hyperlink" ? "<a href=\"" + groups[0].as_string() + "\">" + groups[0].as_string() + "</a>" : lg == "code" ? "<code>" + stage2<T>(groups[ 2].as_string()) + "</code>" : lg == "bold" ? "<strong>" + stage2<T>(groups[ 4].as_string()) + "</strong>" : lg == "italic" ? "<em>" + stage2<T>(groups[ 6].as_string()) + "</em>" : lg == "strike" ? "<del>" + stage2<T>(groups[ 8].as_string()) + "</em>" : lg == "invert" ? "<span class='spoiler'>" + stage2<T>(groups[10].as_string()) + "</span>" : ""; text.replace(off = groups[0].data() - text.data(), groups[0].size(), rp); off += rp.size(); } return text; } template <typename T, typename M> auto stage1(const M& lines) -> std::string { std::string key, out; std::vector<std::string> grp; for (auto i = std::begin(lines), e = std::end(lines); i != e; ++i) { re2::StringPiece groups[stage1_groups]; // always matches at least an empty substring match(REGEXP<T, 1>(), re2::StringPiece{ i->data(), (int) i->size() }, RE2::ANCHOR_START, groups, stage1_groups); auto lg = stage1_jit.lastgroup(groups, stage1_groups); auto ln = i->substr(groups[0].size()); if (lg == "h") lg = "h" + std::to_string(groups[7].size()); if (grp.size() && key != lg) { out += key == "break" ? "" : key == "rule" ? "<br />" : key == "quote" ? "<blockquote>" + stage1<T>(grp) + "</blockquote>" : key == "p" ? "<p>" + stage2<T>(join("\n", grp)) + "</p>" : key == "code" ? "<pre>" + join("\n", grp) + "</pre>" : key == "fenced" ? "<pre>" + join("\n", grp) + "</pre>" : key == "ul" ? "<ul><li>" + join("</li><li>", grp) + "</li></ul>" : key == "ol" ? "<ol><li>" + join("</li><li>", grp) + "</li></ol>" : key[0] == 'h' ? "<" + key + ">" + join("\n", grp) + "</" + key + ">" : ""; grp.clear(); } key = lg; if (lg == "fenced") while (++i != e && *i != "```") grp.push_back(*i); else grp.push_back(ln); } return out; } template <typename T> auto markdownish(std::istream& in) -> std::string { std::string line; std::vector<std::string> lines; while (std::getline(in, line)) lines.push_back(line); lines.push_back(""); // induce a break return stage1<T>(lines); } template <typename T> auto markdownish(const std::string& input) -> std::string { std::istringstream ss(input); return markdownish<T>(ss); } auto readall(std::string name) -> std::string { std::ifstream in(name, std::ios::in); if (in) { std::string contents; in.seekg(0, std::ios::end); contents.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return contents; } throw errno; } #define MARKDOWNISH_TEST(name, kind, input, expect) \ test_case(name) { \ auto a = markdownish<kind>(input); \ return a == expect \ ? Result::Pass("ok") \ : Result::Fail("wrong: %s", a.c_str()); \ } #define MARKDOWNISH_RE2_TEST(name, input) \ test_case(name) { \ auto a = markdownish<RE2> (input); \ auto b = markdownish<re2jit::it> (input); \ return a == b; \ } #define MARKDOWNISH_FILE_RE2_TEST(name, fn) \ MARKDOWNISH_RE2_TEST(name, readall(fn)) #define MARKDOWNISH_PERF_TEST(n, name, input) \ MARKDOWNISH_RE2_TEST(name, input); \ \ GENERIC_PERF_TEST(name " [re2]", n \ , std::string r = input; \ , markdownish<RE2>(r); \ , {}); \ \ GENERIC_PERF_TEST(name " [jit]", n \ , std::string r = input; \ , markdownish<re2jit::it>(r); \ , {}); #define MARKDOWNISH_FILE_PERF_TEST(n, name, fn) \ MARKDOWNISH_PERF_TEST(n, name, readall(fn))
[ "pyos100500@gmail.com" ]
pyos100500@gmail.com
acd9923ccff647e5dd9015c2e48364bf64c37446
c24dfe35e7b412f4e70e3ae0f2f822251e71f889
/Combo.cpp
7016fa094bedccf9bfeb60c5776bc044e3c96a2e
[]
no_license
cjcoimbra/ChessterOSX
98dbbe269a23c6abf165309affd009048f61721a
89c6cbdfb295b3d929faa0bf036440b96a0007c6
refs/heads/master
2021-08-29T21:15:36.511182
2017-12-15T02:01:54
2017-12-15T02:01:54
114,315,298
0
0
null
null
null
null
UTF-8
C++
false
false
246
cpp
#include "StdAfx.h" #include "Combo.h" Combo::Combo(int id, int spt, int first_id) { this->combo_id = id; this->amount = 1; this->sprite_id = spt; ids.push_back(first_id); } Combo::Combo(void) { } Combo::~Combo(void) { }
[ "dm.black@gmail.com" ]
dm.black@gmail.com
e8c236347319389278301312cd2802f9aac102d3
c2cde38550b45893ea4c5b25bc4c379cabc29375
/cpp/hash.cpp
185743fbf85b9ea6588f82f977785ca84a3711f3
[]
no_license
nllanura/algorithms
2f7aa8434e720866b9f25183d3d190b3a09f5625
8da0e6b9e7e39c130aaa8f9439be2d59df8002de
refs/heads/master
2021-06-06T10:07:47.356386
2016-10-31T08:51:05
2016-10-31T08:51:05
72,343,509
1
0
null
null
null
null
UTF-8
C++
false
false
1,262
cpp
#include <iostream> #include <vector> using namespace std; class Hash_Entry { int key; int value; public: Hash_Entry(int key, int value) { this->key = key; this->value = value; } int get_key() { return this->key; } int get_value() { return this->value; } }; const int TABLE_SIZE = 128; class Hash_Table { vector<Hash_Entry*> table; public: Hash_Table() { vector<Hash_Entry*> new_table(TABLE_SIZE, NULL); table = new_table; } void put(int key, int value) { int hash = key % TABLE_SIZE; while(table[hash] != NULL && table[hash]->get_key() != key) { hash = (hash + 1) % TABLE_SIZE; } if(table[hash] != NULL) { delete table[hash]; } table[hash] = new Hash_Entry(key, value); } int get(int key) { int hash = key % TABLE_SIZE; while(table[hash] != NULL && table[hash]->get_key() != key) { hash = (hash + 1) % TABLE_SIZE; } if(table[hash] == NULL) { return -1; } return table[hash]->get_value(); } ~Hash_Table() { for(unsigned int i = 0; i < table.size(); i++) { if(table[i] != NULL) { delete table[i]; } } } }; int main() { Hash_Table table; table.put(3, 5); table.put(8, 20); table.put(136, 30); cout << table.get(8) << endl; cout << table.get(136) << endl; return 0; }
[ "nllan001@ucr.edu" ]
nllan001@ucr.edu
f9b5203668b33bb6dd7af6a208748354fa3a859e
f0cb8232579d2287c617bafc59d26bb17c6016c5
/src/future/cryptography/utils.h
ad36afe30a86e497f313b35fbcfa8c7d33f6ae06
[]
no_license
Delaunay/vanagandr
2c2dc3f9bb48b37baa22868fee269276f9fa9aca
157386c71225a338f719155a68c094c64879b5e6
refs/heads/master
2021-01-22T02:12:55.877454
2015-08-16T13:28:02
2015-08-16T13:28:02
28,604,330
0
0
null
null
null
null
UTF-8
C++
false
false
415
h
#ifndef VANAGANDR_CRYPTOGRAPHY_UTILS_HEADER #define VANAGANDR_CRYPTOGRAPHY_UTILS_HEADER #include "../enum.h" namespace vanagandr { namespace cryptography { /*! * Complexity * ---------- * - O(b) * * Possible Upgrade * ---------------- * - O(log(b)) * */ template<typename T> T modular_pow(a, b, mod) { T c = 1; for(T i = 1; i <= b; i++) c = c * a % mod; return c; } } } #endif
[ "pierre.delaunay@outlook.com" ]
pierre.delaunay@outlook.com
dd28a13f185581c5bf0d0f3f05423949314c07b6
1b5b708e0925265031790896fd2987178cfe7f78
/src/nubot/omni_vision/src/whites.cpp
b0519f1ce52ed5f844a4ad6a0f78bb5860d4a736
[ "Apache-2.0" ]
permissive
Gwynplainyg/nubot_ws
44998c39763e7e0595002a2045cb41298b7f74bd
627da6a93e104dfd47fd22042da0c1f69e908c65
refs/heads/master
2020-12-09T16:06:58.943363
2018-12-14T10:13:52
2018-12-14T10:13:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,755
cpp
#include "nubot/omni_vision/whites.h" using namespace nubot; Whites::Whites(ScanPoints & _scanpts,Transfer & _coor_transfer) { scanpts_ = &_scanpts; transfer_ =&_coor_transfer; img_white_.reserve(1000); h_low_=45; h_high_=120; nums_pts_line_=5; filter_width_=2; merge_wave_=3; int I_max=200; int I_min=20; int T_max=30; int T_min=10; memset(t_new,0,256*sizeof(float)); for (int i=0;i<I_min;i++) t_new[i]=float(T_min); for (int i=I_min;i<=I_max;i++) t_new[i]=float((cos(float(i-I_min)*SINGLEPI_CONSTANT/float(I_max-I_min)+SINGLEPI_CONSTANT)+1)*(T_max-T_min)/2+T_min); for (int i=I_max+1;i<256;i++) t_new[i]=float(T_max); } void Whites::showWhitePoints(cv::Mat & _img) { size_t numstrans=img_white_.size(); for(size_t i=0 ;i<numstrans; i++) cv::circle(_img,cv::Point(img_white_[i].x_,img_white_[i].y_),1,cv::Scalar(255,0,0),2,8,0); nubot::Circle Big_ROI = scanpts_->omni_img_->getBigROI(); nubot::Circle Small_ROI =scanpts_->omni_img_->getSmallROI(); cv::circle(_img,cv::Point(Big_ROI.center_.x_,Big_ROI.center_.y_),Big_ROI.radius_,cv::Scalar(0,0,255),1,8,0); cv::circle(_img,cv::Point(Small_ROI.center_.x_,Small_ROI.center_.y_),Small_ROI.radius_,cv::Scalar(0,0,255),1,8,0); imshow("image_info",_img); cv::waitKey(5.0); } void Whites::showWhitePoints(cv::Mat & _img, DPoint _robot_loc, Angle _angle,int filed_length,int filed_width) { float Xrate=(float)(_img.cols*1.0/filed_length); float Yrate=(float)(_img.rows*1.0/filed_width); std::vector<DPoint> world_pts; transfer_->calculateWorldCoordinates(robot_white_,_robot_loc,_angle,world_pts); int numstrans = robot_white_.size(); cv::circle(_img,cv::Point(int((_robot_loc.x_ + filed_length/2.0)*Xrate), int((filed_width -(_robot_loc.y_ +filed_width/2.0))*Yrate)), 5,cv::Scalar(255,0,255),10,8,0); for(size_t i=0 ;i<numstrans; i++) { if(std::abs(world_pts[i].x_)< filed_length/2.0 && std::abs(world_pts[i].y_) < filed_width/2.0) cv::circle(_img,cv::Point(int((world_pts[i].x_ + filed_length/2.0)*Xrate), int((filed_width -(world_pts[i].y_ +filed_width/2.0))*Yrate)), 1,cv::Scalar(255,0,0),2,8,0); } imshow("real_info",_img); cv::waitKey(5.0); } void Whites::detectWave(std::vector<uchar> & colors,std::vector<bool> & wave_hollow,std::vector<bool> & wave_peak) { int Line_Length=int(colors.size()); for(int i=1;i<Line_Length-1;i++) { if (colors[i]>colors[i+1] && colors[i]>=colors[i-1]) { wave_peak[i]=true; for (int j=1;j<=merge_wave_;j++) { if (i-j>=0) { if (wave_peak[i-j]&&std::abs(double(colors[i-j])-double(colors[i]))<10) { if(colors[i]<colors[i-j]) wave_peak[i]=false; else wave_peak[i-j]=false; for (int k=1; k<=j; k++) { wave_hollow[i-k]=false; } } } } } if (colors[i+1]>=colors[i] && colors[i]< colors[i-1]) { wave_hollow[i]=true; } } } void Whites::findNearHollow(vector<uchar> & colors,vector<bool> & wave_peak,vector<bool> & wave_hollow,vector<peak> & peak_count) { peak Peak; bool need_find_left=true; bool need_find_right=true; int Step; int Line_Length=int(wave_peak.size()); for(int i=0;i<Line_Length;i++) { if (wave_peak[i]) { Peak.peak_index = i; Peak.left_hollow = MIN_NUMBRT_CONST; Peak.right_hollow = MAX_NUMBRT_CONST; need_find_left=need_find_right=true; Step=1; while (need_find_left || need_find_right) { if (i-Step>=0 && need_find_left) { if (wave_hollow[i-Step]) { Peak.left_hollow=i-Step; need_find_left=false; } } if (i-Step<0) { Peak.left_hollow=MIN_NUMBRT_CONST; need_find_left=false; } if (i+Step<Line_Length && need_find_right) { if (wave_hollow[i+Step]) { Peak.right_hollow=i+Step; need_find_right=false; } } if (i+Step>=Line_Length) { need_find_right=false; Peak.right_hollow=MAX_NUMBRT_CONST; } Step++; } if(Peak.left_hollow!=MIN_NUMBRT_CONST||Peak.right_hollow!=MAX_NUMBRT_CONST) { Peak.near_hollow=std::abs(Peak.left_hollow-i)<std::abs(Peak.right_hollow-i) ? Peak.left_hollow : Peak.right_hollow; if (std::abs(Peak.left_hollow-i)==std::abs(Peak.right_hollow-i)) { if (colors[Peak.left_hollow]>=colors[Peak.right_hollow]) Peak.near_hollow=Peak.left_hollow; else Peak.near_hollow=Peak.right_hollow; } Peak.width=std::abs(Peak.peak_index-Peak.near_hollow); if(Peak.peak_index+Peak.width<Line_Length && Peak.peak_index-Peak.width>0) Peak.boundaries=true; else Peak.boundaries=false; peak_count.push_back(Peak); } } } } bool Whites::IsWhitePoint(std::vector<DPoint2i> & _pts,double _color_average,vector<uchar> & _colors,peak & _peaks) { double H_left=0; double H_right=0; int nwhites(0); double aver_colors=_color_average; cv::Mat & brg_image= scanpts_->omni_img_->bgr_image_; if ( _peaks.boundaries && _colors[_peaks.peak_index]>=aver_colors) //_peaks.width>5 && { if (std::abs(double(_colors[_peaks.peak_index])-double(_colors[_peaks.peak_index+_peaks.width]))>=t_new[int(aver_colors)] && std::abs(double(_colors[_peaks.peak_index])-double(_colors[_peaks.peak_index-_peaks.width]))>=t_new[int(aver_colors)]) { if (_peaks.left_hollow!=MIN_NUMBRT_CONST) { cv::Vec3b bgr =brg_image.at<cv::Vec3b>(cv::Point(_pts[_peaks.left_hollow].x_,_pts[_peaks.left_hollow].y_)); cv::Vec3b color_hsv=scanpts_->omni_img_->bgr2hsv(bgr); H_left=color_hsv[0]; } if (_peaks.right_hollow!=MAX_NUMBRT_CONST) { cv::Vec3b bgr = brg_image.at<cv::Vec3b>(cv::Point(_pts[_peaks.right_hollow].x_,_pts[_peaks.right_hollow].y_)); cv::Vec3b color_hsv=scanpts_->omni_img_->bgr2hsv(bgr); H_right=color_hsv[0]; } if (H_left>=h_low_ -20&& H_left<=h_high_ +40/*&& H_right>=h_low_&& H_right<=h_high_&&std::abs(H_left-H_right)<=80*/) { if ((_colors[_peaks.peak_index-_peaks.width]>=0.45*aver_colors && _colors[_peaks.peak_index+_peaks.width]>=0.45*aver_colors) || (_colors[_peaks.peak_index-_peaks.width]>=0.45*100 && _colors[_peaks.peak_index+_peaks.width]>=0.45*100)) { if (nwhites<nums_pts_line_&& _colors[_peaks.peak_index]>150) { nwhites++; return true; } } } } } return false; } void Whites::detectWhitePts(std::vector<DPoint2i> & pts,std::vector<uchar> & _ColorY_Aver,std::vector<DPoint2i> & whites) { whites.clear(); whites.reserve(10); CV_Assert(pts.size()==_ColorY_Aver.size()); int Line_Length=pts.size(); double ColorY_Aver_Sum(0); std::vector<bool> wave_peak(Line_Length,false); std::vector<bool> wave_hollow(Line_Length,false); std::vector<peak> peak_count; peak_count.reserve(Line_Length); for(int i=0; i<Line_Length; i++) ColorY_Aver_Sum=ColorY_Aver_Sum+_ColorY_Aver[i]; ColorY_Aver_Sum=ColorY_Aver_Sum/Line_Length; detectWave(_ColorY_Aver,wave_hollow,wave_peak); findNearHollow(_ColorY_Aver,wave_peak,wave_hollow, peak_count); size_t numstrans=peak_count.size(); for(size_t i=0;i<numstrans;i++) { if(IsWhitePoint(pts,ColorY_Aver_Sum,_ColorY_Aver,peak_count[i])) whites.push_back(pts[peak_count[i].peak_index]); } } void Whites::calculateWeights() { weights_.clear(); double ref2=150.0*150.0; double d2=250.0*250.0; double tmpweight(0); double distofeature(0); size_t numtrans=robot_white_.size(); weights_.resize(numtrans); #ifdef using_openmp #pragma omp parallel for private(tmpweight,distofeature) shared(ref2,d2) #endif for(size_t index=0; index < numtrans; index++) { distofeature=robot_white_[index].radius_*robot_white_[index].radius_; tmpweight=(ref2+d2)/(d2+distofeature); weights_[index]= tmpweight; } } void Whites::process() { weights_.clear(); img_white_.clear(); robot_white_.clear(); std::vector< std::vector<DPoint2i> > whites; size_t nums_polars=scanpts_->polar_pts_.size(); whites.resize(nums_polars); #ifdef using_openmp #pragma omp parallel for #endif for(size_t i = 0; i < nums_polars; i++) detectWhitePts(scanpts_->polar_pts_[i],scanpts_->filter_polar_pts_y_[i],whites[i]); for(size_t i = 0; i < nums_polars; i++) for(size_t j =0 ; j <whites[i].size(); j++) img_white_.push_back(whites[i][j]); size_t nums_horizs=scanpts_->horiz_pts_.size(); whites.clear(); whites.resize(2*nums_horizs); #ifdef using_openmp #pragma omp parallel for #endif for(size_t i = 0; i < nums_horizs ; i++) { detectWhitePts(scanpts_->horiz_pts_[i],scanpts_->filter_horiz_pts_y_[i],whites[i*2]); detectWhitePts(scanpts_->verti_pts_[i],scanpts_->filter_verti_pts_y_[i],whites[i*2+1]); } for(size_t i = 0; i < 2*nums_horizs; i++) for(size_t j =0 ; j <whites[i].size(); j++) img_white_.push_back(whites[i][j]); transfer_->calculateRealCoordinates(img_white_,robot_white_); calculateWeights(); }
[ "weijia.yao.nudt@gmail.com" ]
weijia.yao.nudt@gmail.com
7d7d29780c59673041f77a17d2ac93cc675337fe
e4014a72bd3e9c7316ce108852c8a411dcf6788c
/Code/Public/IFCommonLib/IFNodeObj.h
808845a50b0eec7fd594b6caf002b130b4f5a8b3
[]
no_license
oneofzero/Infinite
f6a3b90c73ef2d99fa34c077012c8d9fa37ebaf1
72c2d898d4c25b43a1eb90b38df4734e6919f420
refs/heads/master
2022-08-08T05:33:05.272088
2020-05-25T03:11:54
2020-05-25T03:11:54
261,687,231
1
0
null
null
null
null
GB18030
C++
false
false
2,143
h
#pragma once #include "IFAttributeSet.h" class IFNodeObj; typedef IFRefPtr<IFNodeObj> IFNodeObjPtr; typedef IFArray<IFNodeObjPtr> IFNodeObjList; class IFCOMMON_API IFNodeObj : public IFAttributeSet { IF_DECLARERTTI; IF_DECLARECREATEABLE; public: IFEventSlot<void(IFNodeObj* pObj, IFNodeObj* pSubObj)> event_SubObjAdd; IFEventSlot<void(IFNodeObj* pObj, IFNodeObj* pSubObj)> event_SubObjRemove; IFEventSlot<void(IFNodeObj* pObj)> event_AddToParent; IFEventSlot<void(IFNodeObj* pObj)> event_RemoveFromParent; public: IFNodeObj(); bool setName(const IFString& sName); const IFString& getName() { return m_sName; } bool addObj(IFNodeObj* spObj, bool bAutoReName = true); virtual bool addObjBefore(IFNodeObj* spObj, IFNodeObj* spBefore, bool bAutoReName = true); virtual bool removeObj(IFNodeObj* spObj); virtual bool removeFromParent(); virtual void removeAllObj(); IFNodeObj* getParent() { return m_pParent; } IFNodeObj* getNextSibling(); IFNodeObj* getPrevSibling(); //只支持从子对象中查找 IFNodeObj* getSubObj(const IFString& sName, bool bSearchChildNode = false); //支持通过路径查找. 比如 window1.button1 IFNodeObj* getObj(const IFString& sName); IFNodeObj* getSubObj(int nIndex); template< typename RT, typename FUN> RT for_each(const FUN& f) { for (m_nCurIterIndex = m_Children.size()-1; m_nCurIterIndex>=0; m_nCurIterIndex--) { if (auto p = f(m_Children[m_nCurIterIndex])) return p; } return NULL; } int getSubObjNum() { return m_Children.size(); } IFAttributeSetPtr clone(); virtual void assignTo(IFAttributeSet* pObj); virtual void copySubObjTo(IFNodeObj* pOther); protected: virtual ~IFNodeObj(); virtual void onRemoveFromParent(); virtual void setParent(IFNodeObj* pParent); protected: IFString m_sName; IFNodeObj* m_pParent; IFNodeObjList m_Children; int m_nCurIterIndex; IFMap<IFString, IFNodeObj*> m_sSubChildNameList; //IFNodeObjList::reverse_iterator m_CurIterateIt; IFNodeObjList::iterator m_InParentIterator; };
[ "huangcong@ztgame.com" ]
huangcong@ztgame.com
80247324cb8fcc1c3fb16277ada1bfbe798452d0
bd201e44af600c43abeac4679ea0cc489cd44e50
/Server/common/fxtimer.cpp
664850aa2cf0efa2617bd584da1cb75a87e17e73
[ "MIT" ]
permissive
MySun275312964/FxLib
87c98ac1cf32c90b8a99089bd054fa957764c5e6
e05b296a80741ec9db447f6de8379dfc66047521
refs/heads/master
2020-04-12T09:16:49.960853
2018-12-18T13:16:31
2018-12-18T13:16:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,695
cpp
#include <map> #include <set> #include <stdlib.h> #include "fxtimer.h" #include "fxmeta.h" #include "lock.h" #include "limiter_queue.h" #ifdef WIN32 #include <time.h> #else #include <sys/time.h> #endif // WIN32 double GetTimeOfDay() { static double s_qwTime = 0; #ifdef WIN32 s_qwTime = (double)time(NULL); SYSTEMTIME st; GetSystemTime(&st); s_qwTime = s_qwTime + st.wMilliseconds / 1000.0f; #else static struct timeval tv; gettimeofday(&tv, NULL); s_qwTime = tv.tv_sec / 1.0 + tv.tv_usec / 1000000.0; #endif return s_qwTime; } class FxTimerHandler: public IFxTimerHandler, TLimiterQueue<double>/*, IFxThread*/ { private: virtual bool CheckEvent(double c) { if (c <= m_qwSecond) { return true; } return false; } public: FxTimerHandler() : m_qwSecond(0) , m_qwDeltaTime(0) { m_qwSecond = GetTimeOfDay(); m_strTime[0] = 0; tm tmLocal, tmGM; time_t t = time(NULL); tmLocal = *localtime(&t); tmGM = *gmtime(&t); tmLocal.tm_isdst = 0; tmGM.tm_isdst = 0; m_dwTimeZone = (int)(mktime(&tmGM) - mktime(&tmLocal)) / 3600; m_dwDayTimeStart = (unsigned int)(t - (t - m_dwTimeZone * 3600) % 86400); //设置随机数种子 srand((unsigned int)m_qwSecond); //srand(0); // m_bStop = false; } virtual ~FxTimerHandler() { } virtual void Run() { __Refresh(); } virtual bool Init() { return true; } virtual void Uninit() { } virtual unsigned int GetSecond() { return (unsigned int)m_qwSecond; } virtual double GetMilliSecond() { return m_qwSecond; } virtual const char* GetTimeStr() { return m_strTime; } virtual const unsigned int GetTimeSeq() { return (unsigned int)((m_qwSecond - (unsigned int)m_qwSecond) * 1000); } virtual const int GetTimeZone() { return m_dwTimeZone; } virtual const int GetDayTimeStart() { return m_dwDayTimeStart; } virtual const double GetDeltaTime() { return m_qwDeltaTime; } // 添加事件 (多长事件后执行, 事件指针) virtual bool AddTimer(double dSecond, CEventBase* pEvent) { return PushEvent(GetMilliSecond() + dSecond, pEvent) != NULL; } // 添加事件 (每多少秒执行, 事件指针) 被60整除 virtual bool AddSecontTimer(unsigned int dwSecond, CEventBase* pEvent) { return PushEvent(GetSecond() - (GetSecond() % dwSecond) + dwSecond, pEvent) != NULL; } // 添加事件 (每多少分执行, 事件指针) 被60整除 virtual bool AddMinuteTimer(unsigned int dwMinute, CEventBase* pEvent) { return PushEvent(GetSecond() - GetSecond() % (dwMinute * 60) + dwMinute * 60, pEvent) != NULL; } // 添加事件 (每多少小时执行, 事件指针) 被24整除 virtual bool AddHourTimer(unsigned int dwHour, CEventBase* pEvent) { unsigned int dwH1 = (GetSecond() - m_dwDayTimeStart) / 3600; return PushEvent(m_dwDayTimeStart + (dwH1 - dwH1 % dwHour + dwHour) * 3600, pEvent) != NULL; } // 添加事件 (每天几点执行, 事件指针) virtual bool AddDayHourTimer(unsigned int dwHour, CEventBase* pEvent) { unsigned int dwTime = m_dwDayTimeStart + dwHour * 3600; if (dwTime <= GetSecond()) { dwTime += 86400; } return PushEvent(dwTime, pEvent) != NULL; } private: void __Refresh() { static double s_qwSecond = 0; static time_t s_dwTime = 0; s_qwSecond = GetTimeOfDay(); m_qwDeltaTime = s_qwSecond - m_qwSecond; if (m_qwDeltaTime >= 0.1f) { LogExe(LogLv_Critical, "FPS : %d", (int)(1 / m_qwDeltaTime)); } Proc((int)(1 / m_qwDeltaTime), s_qwSecond); if((unsigned int)s_qwSecond == (unsigned int)m_qwSecond) { m_qwSecond = s_qwSecond; return; } m_qwSecond = s_qwSecond; s_dwTime = (time_t)m_qwSecond; if (s_dwTime - m_dwDayTimeStart >= 86400) { m_dwDayTimeStart += 86400; } tm* tmLocal = localtime(&s_dwTime); //转化为本地时间 strftime(m_strTime, 64, "%Y-%m-%d %H:%M:%S", tmLocal); } private: double m_qwSecond; char m_strTime[64]; double m_qwDeltaTime; int m_dwTimeZone; unsigned int m_dwDayTimeStart; }; IFxTimerHandler* GetTimeHandler() { static FxTimerHandler oTimerHandler; return &oTimerHandler; } unsigned int IFxTimerHandler::GetTimeStampFromStr(const char* szTimeStr) { tm _tm; #ifdef WIN32 sscanf_s(szTimeStr, "%4d-%2d-%2d %2d:%2d:%2d", #else sscanf(szTimeStr, "%4d-%2d-%2d %2d:%2d:%2d", #endif //!WIN32 &_tm.tm_year, &_tm.tm_mon, &_tm.tm_mday, &_tm.tm_hour, &_tm.tm_min, &_tm.tm_sec); _tm.tm_year -= 1900; _tm.tm_mon -= 1; _tm.tm_isdst = 0; return (unsigned int)mktime(&_tm); }
[ "724789975@qq.com" ]
724789975@qq.com
b09f4237f13bdc7eb4c806ec2ba56e7c0a645160
dfe1f796a54143e5eb8661f3328ad29dbfa072d6
/psx/_dump_/40/_dump_c_src_/diabpsx/source/preport.cpp
ee67f5cfc5e01da965dc3cbb8b63a751cd8e0900
[ "Unlicense" ]
permissive
diasurgical/scalpel
0f73ad9be0750ce08eb747edc27aeff7931800cd
8c631dff3236a70e6952b1f564d0dca8d2f4730f
refs/heads/master
2021-06-10T18:07:03.533074
2020-04-16T04:08:35
2020-04-16T04:08:35
138,939,330
15
7
Unlicense
2019-08-27T08:45:36
2018-06-27T22:30:04
C
UTF-8
C++
false
false
184
cpp
// C:\diabpsx\SOURCE\PREPORT.CPP #include "types.h" // address: 0x8015A448 // line start: 74 // line end: 79 void InitPortals__Fv() { { // register: 16 register int i; } }
[ "anders@jenbo.dk" ]
anders@jenbo.dk
922a2fb2e11f693e2eefe14d4f304feeb6bb8447
8fd97c8310d59bf1ce9487e42dbf5395d4412345
/source/utils/logger/clog.cpp
63b893d8daa353ba11bd48a9a7618e2a494af342
[ "Zlib" ]
permissive
gummikana/poro
37c5dba0c11412e8ccdde5b4f5e949864c1e6e74
70162aca06ca5a1d4f92b8d01728e1764e4c6873
refs/heads/master
2023-06-22T17:48:43.103700
2019-09-17T15:32:31
2019-09-17T15:32:31
1,170,509
9
5
null
null
null
null
UTF-8
C++
false
false
6,780
cpp
/*************************************************************************** * * Copyright (c) 2003 - 2011 Petri Purho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ***************************************************************************/ #include "clog.h" #include "cloglistenerforfile.h" #include <fstream> #include <string> #include <iostream> #include <iomanip> #include <ostream> #include <sstream> #include <ctime> #include <cstdio> #include <cstdarg> #include <list> #include <algorithm> namespace ceng { /////////////////////////////////////////////////////////////////////////////// class CLog::CLogImpl { public: void AddListener( ILogListener* listener ) { if( listener != NULL ) myListeners.push_back( listener ); } void RemoveListener( ILogListener* listener ) { std::list< ILogListener* >::iterator i = std::find( myListeners.begin(), myListeners.end(), listener ); if( i != myListeners.end() ) myListeners.erase( i ); } void WriteLine( const std::string& line, CLog::LogType line_type ) { std::list< ILogListener* >::iterator i = myListeners.begin(); for( ; i != myListeners.end(); ++i ) { (*i)->WriteLine( line, line_type ); } } std::list< ILogListener* > myListeners; CLogListenerForFile* myFileLogger; }; /////////////////////////////////////////////////////////////////////////////// #define CENG_CFG_LOG_FILENAME_STR "log.txt" #ifdef NDEBUG # define CENG_CFG_HEADER_STR "Poro logger version 1.0.0" #else # define CENG_CFG_HEADER_STR "Poro logger version 1.0.0 DEBUG" #endif #ifndef NDEBUG # define CENG_CFG_LOG_COUNT_ERRORS true #else # define CENG_CFG_LOG_COUNT_ERRORS false #endif #define CENG_CFG_LOG_LEVEL 0 //----------------------------------------------------------------------------- CLog::CLog() : myCurrentType( LT_Normal ), impl( new CLogImpl ) { impl->myFileLogger = NULL; // # ifdef CENG_CFG_USE_LOG impl->myFileLogger = new CLogListenerForFile( CENG_CFG_LOG_FILENAME_STR, CENG_CFG_HEADER_STR, CENG_CFG_LOG_COUNT_ERRORS ); impl->myFileLogger->SetLogLevel( CENG_CFG_LOG_LEVEL ); impl->AddListener( impl->myFileLogger ); // # endif } CLog::CLog( const std::string& filename ) : myCurrentType( LT_Normal ), impl( new CLogImpl ) { impl->myFileLogger = NULL; impl->myFileLogger = new CLogListenerForFile( filename, CENG_CFG_HEADER_STR, CENG_CFG_LOG_COUNT_ERRORS ); impl->myFileLogger->SetLogLevel( CENG_CFG_LOG_LEVEL ); impl->AddListener( impl->myFileLogger ); } //============================================================================= CLog::~CLog() { if( impl->myFileLogger ) { impl->RemoveListener( impl->myFileLogger ); delete impl->myFileLogger; } delete impl; impl = NULL; } /////////////////////////////////////////////////////////////////////////////// CLog& CLog::Error() { myCurrentType = LT_Error; return *this; } CLog& CLog::Warning() { myCurrentType = LT_Warning; return *this; } CLog& CLog::Debug() { myCurrentType = LT_Debug; return *this; } CLog& CLog::Function() { WriteLine( "", LT_Function ); return *this; } CLog& CLog::Success() { WriteLine( "", LT_Success ); return *this; } /////////////////////////////////////////////////////////////////////////////// CLog& CLog::operator << (std::ostream &(*manipulator) (std::ostream &)) { std::stringstream ss; ss << manipulator; Write( ss.str() ); return *this; } //============================================================================= CLog& CLog::operator () ( char *str, ... ) { char string[1024]; // Temporary string va_list ap; // Pointer To List Of Arguments va_start(ap, str); // Parses The String For Variables vsprintf(string, str, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text Write( string ); return (*this); } //============================================================================= void CLog::Write( char *str, ... ) { char string[1024]; // Temporary string va_list ap; // Pointer To List Of Arguments va_start(ap, str); // Parses The String For Variables vsprintf(string, str, ap); // And Converts Symbols To Actual Numbers va_end(ap); // Results Are Stored In Text std::string tmp( string ); // tmp += "\n"; Write( tmp ); } //============================================================================= void CLog::Write( const std::string& str ) { static std::string buffer; // find the first line break in str int i = 0; for( i = 0; i < (int)str.size(); i++ ) { if( str.substr( i, 2 ) == "\n\r" || str[ i ] == '\n' || str[ i ] == '\r' || str[ i ] == '\0' ) { WriteLine( buffer + '\n', myCurrentType ); buffer = ""; myCurrentType = LT_Normal; } else { buffer += str[ i ]; } } } /////////////////////////////////////////////////////////////// void CLog::WriteLine( const std::string& line, CLog::LogType line_type ) { impl->WriteLine( line, line_type ); } /////////////////////////////////////////////////////////////////////////////// void CLog::AddListener( ILogListener* listener ) { impl->AddListener( listener ); } //============================================================================= void CLog::RemoveListener( ILogListener* listener ) { impl->RemoveListener( listener ); } /////////////////////////////////////////////////////////////////////////////// void CLog::SetFile( const std::string& name ) { if( impl && impl->myFileLogger ) impl->myFileLogger->Open( name ); } //============================================================================= void CLog::SetLogLevel( int loglevel ) { if( impl && impl->myFileLogger ) impl->myFileLogger->SetLogLevel( loglevel ); } /////////////////////////////////////////////////////////////////////////////// } // end of namespace ceng
[ "petri.purho@gmail.com" ]
petri.purho@gmail.com
acc8c36e1834048a493011f83d2ae6fbd059eb9f
1367d43ed9a5695fb14f2bacbd6380ef78cf0b54
/include/util.h
df2e0f5cc48d75f434e9980ab7dd5db7a6b53fbe
[]
no_license
xuechaofelix/BDD
1bbaf948c10f0630259c88769574c6fb22df41c4
302713f1f70e57e18741f6a57fc40273431ac7ee
refs/heads/master
2020-04-12T17:32:40.331518
2018-12-21T02:32:08
2018-12-21T02:32:08
162,648,780
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#ifndef UTIL_H_ #define UTIL_H_ #include <string> #include <fstream> #include <iomanip> #include <sstream> using namespace std; bool Write2File(string fileName,string content); template<typename T> string toString(const T& t){ ostringstream oss; oss<<t; return oss.str(); } #endif
[ "xuechaofelix@hotmail.com" ]
xuechaofelix@hotmail.com
1d1cd6c259390e873b426ebb7e1258eb513cea23
33d88cf70ad9f56d2833b150b932ab07d08e9b6e
/dp/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix.cpp
920ab310c19a5419f82f0e9073ac8d7f78b02c22
[]
no_license
sanyamdtu/interview_questions
386c33fd8a72ff22a73cfb4c3b1d4d730695cc63
157880e9d83009db455eec1a370010ea7b494ea0
refs/heads/main
2023-08-14T21:43:26.330843
2021-10-02T06:18:46
2021-10-02T06:18:46
315,205,280
0
0
null
null
null
null
UTF-8
C++
false
false
882
cpp
class Solution { public: int maxSquare(int n, int m, vector<vector<int>> arr) { int dp[n][m]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; i++) { dp[i][m - 1] = arr[i][m - 1]; } for (int i = 0; i < m; i++) { dp[n - 1][i] = arr[n - 1][i]; } for (int i = n - 2; i >= 0; i--) { for (int j = m - 2; j >= 0; j--) { if (arr[i][j] == 1) dp[i][j] = 1 + min(dp[i + 1][j + 1], min(dp[i + 1][j], dp[i][j + 1])); else dp[i][j] = 0; } } int ans = 0; for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { ans = max(ans, dp[i][j]); } } return ans; } };
[ "sanyamexam@gmail.com" ]
sanyamexam@gmail.com
588357c5e80d89dfe5a87fe81852454f919c023e
95f692202f127f964df763c5725950a35b18c922
/MusicPlay-master/src/ui/ContentWidget/MusiSongList/musicsongssummarizied.cpp
0c120a4398c14c5fdb65caf524f23a83821dd4b7
[]
no_license
renjiexiong/vlc
2ecabf2c4c5fc327956eaff40242fece50bfd217
ff0cf3a28b6a6e48b1e5a027a3c7b94ca00320a8
refs/heads/master
2023-07-02T09:01:03.086337
2021-08-02T02:41:06
2021-08-02T02:41:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,200
cpp
/************************************************* Copyright:kevin Author:Kevin LiQi Date:2016-03-12 Email:kevinlq0912@163.com QQ:936563422 Version:V1.0 Description:基于Qt的音乐播放器---歌曲汇总实现 Function: **************************************************/ #include "musicsongssummarizied.h" #include "musicsongslistwidget.h" #include "musicsongstoolitemrenamedwidget.h" #include "musicprogresswidget.h" #include <QLayout> #include <QDebug> #include <QContextMenuEvent> #include "songmenu.h" #include "myhelper.h" #include <QFileDialog> #include <QStringList> #include "controlvalues.h" MusicSongsSummarizied::MusicSongsSummarizied(QWidget *parent) :QToolBox(parent),m_renameLine(NULL) { initForm(); initWidget(); initConnect(); } MusicSongsSummarizied::~MusicSongsSummarizied() { clearAllLists(); } //导入歌曲:只有歌曲的名称 void MusicSongsSummarizied::importMusicSongsName(const QStringList &file_name_list) { //获取当前列表索引 int index = currentIndex(); QFileInfo finfo; QStringList fileNameList; QStringList filePath; if (file_name_list.isEmpty()) { return; } //提取出歌曲名称 foreach (QString str, file_name_list) { finfo = QFileInfo(str); fileNameList <<finfo.fileName(); filePath << finfo.filePath(); } //插入多条歌曲到列表中 for (int i = 0; i <fileNameList.count(); i++) { //将歌曲名称插入到列表中 m_mainSongLists.at(index)->addItemContent(fileNameList.at(i)); //保存歌曲信息,以便进行歌曲播放 m_mainSongLists.at(index)->saveMusicInfo(fileNameList.at(i),filePath.at(i)); } } void MusicSongsSummarizied::importMusicSongs(const QStringList &file_list) { MusicProgressWidget progress; progress.show(); progress.setTitle("导入歌曲"); progress.setRange(0, file_list.count()); for(int i = 0; i < file_list.count(); ++i) { // if(tag.readFile(file_list[i])) // { // m_musicFileNames[0] << MusicSong(file_list[i], 0, tag.getLengthString(), QString()); // } progress.setValue(i + 1); } // m_mainSongLists[0]->updateSongsFileName(m_musicFileNames[0]); } //导入歌曲:包含歌曲的路径和名称 void MusicSongsSummarizied::musicImportSongsSettingPath(const QStringList &path) { //获取当前列表索引 int index = currentIndex(); if (path.isEmpty()) { return; } //插入多条歌曲到列表中 for (int i = 0; i <path.count(); i++) { m_mainSongLists.at(index)->addItemContent(path.at(i)); } } void MusicSongsSummarizied::initForm() { setAttribute(Qt::WA_TranslucentBackground,true); //设置toolBox按钮样式 setStyleSheet("QToolBoxButton{min-height:40px;font-size:14px;color:white;}"); m_currentIndexs = 0; //默认为新建列表1,以后每次创建列表后,会依次增加(新建列表2,新建列表3……) m_newPlayListNum = 0; } void MusicSongsSummarizied::initWidget() { for (int i = 0; i < 3; i++) { MusicSongsListWidget *list = new MusicSongsListWidget(this); m_mainSongLists.append(list); } addItem(m_mainSongLists.at(0),QIcon(":/image/arrow-right"),"默认列表"); addItem(m_mainSongLists.at(1),QIcon(":/image/arrow-right"),"我的喜爱"); addItem(m_mainSongLists.at(2),QIcon(":/image/arrow-right"),"我的收藏"); //关联歌曲列表信息界面数据邮件菜单信号 this->initMusicActionConnect(); layout()->setSpacing(0); m_menu = new SongMenu(this); } void MusicSongsSummarizied::initMusicActionConnect() { for (int i = 0; i < m_mainSongLists.count();i++) { connect(m_mainSongLists.at(i),SIGNAL(signalPlayMusic(QString)), this,SLOT(slotPlayMusic(QString))); connect(m_mainSongLists.at(i),SIGNAL(signalPlayMusic()), this,SLOT(slotPlayMusic())); connect(m_mainSongLists.at(i),SIGNAL(signalAddMusic()), this,SLOT(slotAddMusic())); connect(m_mainSongLists.at(i),SIGNAL(signalDeleteMusic()), this,SLOT(slotDeleteMusic())); connect(m_mainSongLists.at(i),SIGNAL(signalDeleteAllMusic()), this,SLOT(slotDeleteAllMusic())); //请求上一首、下一首歌曲 connect(this,SIGNAL(signalRequestNextMusic()), m_mainSongLists.at(i),SLOT(slotGetNextMusic())); connect(this,SIGNAL(signalRequestPreviousMusic()), m_mainSongLists.at(i),SLOT(slotGetPreviouseMusic())); //接收上层发送过来的歌曲信息 connect(m_mainSongLists.at(i),SIGNAL(signalSendNextMusic(QString)), this,SIGNAL(signalSendNextMusic(QString))); connect(m_mainSongLists.at(i),SIGNAL(signalSendPreviousMusic(QString)), this,SIGNAL(signalSendPreviousMusic(QString))); /*****************根据播放模式请求歌曲******************/ connect(this,SIGNAL(signalRequestPlayCmd(int)), m_mainSongLists.at(i),SLOT(slotSendPlayCmd(int))); connect(m_mainSongLists.at(i),SIGNAL(signalSendPlayCmdMusicInfo(QString)), this,SIGNAL(signalSendPlayCmdMusic(QString))); } } void MusicSongsSummarizied::initConnect() { connect(this,SIGNAL(currentChanged(int)), this,SLOT(slotShowCurPlayList(int))); connect(m_menu,SIGNAL(signalAddNewList()), this,SLOT(slotAddNewPlayList())); connect(m_menu,SIGNAL(signalDeleteList()), this,SLOT(slotDeletePlayList())); connect(m_menu,SIGNAL(signalRename()), this,SLOT(slotRename())); //请求第一次播放时的歌曲信息 // connect(this,SIGNAL(signalRequestFirstPlayMusic()), // m_mainSongLists.at(m_currentIndexs),SLOT(slotGetFirstPlayMusic())); // connect(m_mainSongLists.at(m_currentIndexs),SIGNAL(signalSendFirstPlayMusic(QString)), // this,SIGNAL(signalSendFirstPlayMusic(QString))); //修改为以下一个函数调用 this->connectMusicList(m_currentIndexs); } /*当当前歌曲列表改变关联对应列表信号 * 本类调用 */ void MusicSongsSummarizied::connectMusicList(int index) { connect(this,SIGNAL(signalRequestFirstPlayMusic()), m_mainSongLists.at(index),SLOT(slotGetFirstPlayMusic())); connect(m_mainSongLists.at(index),SIGNAL(signalSendFirstPlayMusic(QString)), this,SIGNAL(signalSendFirstPlayMusic(QString))); } QString MusicSongsSummarizied::getCurPlayListName() const { return m_curPlayListName; } //改变item图标 void MusicSongsSummarizied::changeItemIcon() { for (int i = 0; i < count(); i++) { setItemIcon(i,QIcon(":/image/arrow-down.png")); } setItemIcon(currentIndex(), QIcon(":/image/arrow-right.png")); } void MusicSongsSummarizied::clearAllLists() { while (!m_mainSongLists.isEmpty()) { MusicSongsListWidget *w = m_mainSongLists.takeLast(); delete w; w = NULL; } } //显示鼠标右键菜单 void MusicSongsSummarizied::contextMenuEvent(QContextMenuEvent *event) { QToolBox::contextMenuEvent(event); m_menu->exec(event->globalPos()); } void MusicSongsSummarizied::slotShowCurPlayList(int index) { m_currentIndexs = index; if (index == -1) { return; } //当当前鼠标点击的item改变时,改变对应的item图标 changeItemIcon(); if(m_renameLine) { m_renameLine->slotRenameFinished(); } m_curPlayListName = itemText(index); this->connectMusicList(m_currentIndexs); } void MusicSongsSummarizied::slotPlayMusic() { //获取当前的音乐列表 int index = currentIndex(); qDebug()<<m_mainSongLists.at(index)->getSelectContent(); } void MusicSongsSummarizied::slotPlayMusic(const QString &name) { int index = currentIndex(); QString musicPath = ""; if (m_mainSongLists.at(index)->tableWidgetIsEmpty()) { return; }else{ musicPath = m_mainSongLists.at(index)->getMusicPath(name); } #if QDEBUG_OUT qDebug()<<"要播放的歌曲为:"; qDebug()<<"名称:"<<name; qDebug()<<"路径:"<<musicPath; #endif emit signalPlayMusic(musicPath); } //添加新的播放列表 void MusicSongsSummarizied::slotAddNewPlayList() { //对数新建列表个数进行限制 if (m_mainSongLists.count() > 10) { myHelper::ShowMessageBoxInfo("所添加列表数目已经达到最大值,请删除后在添加!"); return; } m_newPlayListNum++; MusicSongsListWidget *newList = new MusicSongsListWidget(this); m_mainSongLists.append(newList); addItem(newList,QString("新建列表%1").arg(m_newPlayListNum)); //对新建的列表右键菜单进行关联 for(int i = m_newPlayListNum + 2;i < m_mainSongLists.count();i++) { connect(m_mainSongLists.at(i),SIGNAL(signalPlayMusic(QString)), this,SLOT(slotPlayMusic(QString))); connect(m_mainSongLists.at(i),SIGNAL(signalPlayMusic()), this,SLOT(slotPlayMusic())); connect(m_mainSongLists.at(i),SIGNAL(signalAddMusic()), this,SLOT(slotAddMusic())); } } //打开添加音乐对话框,添加音乐 void MusicSongsSummarizied::slotAddMusic() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::ExistingFiles ); dialog.setViewMode(QFileDialog::Detail); dialog.setNameFilters(myHelper::supportFormatsFilterDialogString()); if(dialog.exec()) { //导入歌曲名称 importMusicSongsName(dialog.selectedFiles()); //导入歌曲名称和路径(程序需要保存歌曲信息时,需要将歌曲的路径存入数据库中,这里暂时没有用到数据库) //musicImportSongsSettingPath(dialog.selectedFiles()); } } void MusicSongsSummarizied::slotAddMusicFolder() { } /*删除列表 * 在删除列表时:1.默认列表不允许删除; * 2.若列表中有歌曲存在,给出提示,是否删除,否则直接删除,没有提示 */ void MusicSongsSummarizied::slotDeletePlayList() { int index = currentIndex(); if (index == 0 || index == 1 || index == 2 ) { myHelper::ShowMessageBoxError("默认列表不能删除!"); return; }else if (!m_mainSongLists.at(index)->tableWidgetIsEmpty()) { if (myHelper::ShowMessageBoxQuesion("列表不为空,是否要删除?")) { removeItem(index); m_mainSongLists.removeAt(index); }else return; }else { removeItem(index); m_mainSongLists.removeAt(index); } } void MusicSongsSummarizied::slotRename() { int index = currentIndex(); if (index == 0 || index == 1 || index == 2) { myHelper::ShowMessageBoxError("默认播放列表不能修改!"); return; } if (!m_renameLine) { m_renameIndex = currentIndex(); m_renameLine = new MusicSongsToolItemRenamedWidget(m_renameIndex*26, QToolBox::itemText(m_renameIndex),this); connect(m_renameLine,SIGNAL(signalRenameFinished(QString)), this,SLOT(slotSetChangItemName(QString))); m_renameLine->show(); } } //这里真正改变了列表名称 void MusicSongsSummarizied::slotSetChangItemName(const QString &name) { setItemText(m_renameIndex,name); delete m_renameLine; m_renameLine = NULL; } //删除当前鼠标所点击的音乐 void MusicSongsSummarizied::slotDeleteMusic() { int index = currentIndex(); if (m_mainSongLists.at(index)->tableWidgetIsEmpty()) { return; }else { m_mainSongLists.at(index)->removeItem(); } } //删除本列表中的所有音乐 void MusicSongsSummarizied::slotDeleteAllMusic() { //获取当前列表 int index = currentIndex(); if (!m_mainSongLists.at(index)->tableWidgetIsEmpty()) { m_mainSongLists.at(index)->removeAllItem(); } } void MusicSongsSummarizied::slotChangeListStatus() { }
[ "zhengrui@hudunsoft.com" ]
zhengrui@hudunsoft.com
f1675549b06cfaf122f1e62c2b69c2496145c6dc
1777d9a09471e3e3523193dc0d808a5328815a13
/Matriz.cpp
27fc151d83687f21d99aad2649423d59a104892b
[]
no_license
thiagomcoutinho/TP1-POO
fe73a6b0f00ac4ec3f637569d5d6adb1ef4201ed
9a297112e9d644ebe6b4468937eec55fe754c732
refs/heads/master
2020-06-28T19:08:21.518870
2019-08-03T01:23:31
2019-08-03T01:23:31
200,315,970
0
0
null
null
null
null
UTF-8
C++
false
false
8,286
cpp
#include"Matriz.h" #include<iostream> #include<stdexcept> #include<bits/stdc++.h> // PUBLIC METHODS Matriz::Matriz(const int n_rows_, const int n_cols_){ n_rows = n_rows_; n_cols = n_cols_; if(n_rows != 0 && n_cols != 0){ m = new double*[n_rows]; for(int i=0; i<n_rows; i++){ m[i] = new double[n_cols]; } } } Matriz::Matriz(const Matriz &A){ n_rows = A.getRows(); n_cols = A.getCols(); if(n_rows != 0 && n_cols != 0){ m = new double*[n_rows]; for(int i=0; i<n_rows; i++){ m[i] = new double[n_cols]; for(int j=0; j<n_cols; j++){ m[i][j] = A.m[i][j]; } } } } Matriz::Matriz(const int n_rows_, const int n_cols_, const double &fill){ n_rows = n_rows_; n_cols = n_cols_; if(n_rows != 0 && n_cols != 0){ m = new double*[n_rows]; for(int i=0; i<n_rows; i++){ m[i] = new double[n_cols]; for(int j=0; j<n_cols; j++){ m[i][j] = fill; } } } } Matriz::~Matriz(){ if(n_rows > 0){ for (int i=0; i < n_rows; i++){ delete [] m[i]; } delete [] m; } n_rows = 0; n_cols = 0; } inline int Matriz::getRows() const{ return(n_rows); } inline int Matriz::getCols() const{ return(n_cols); } void Matriz::zeros(){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] = 0; } } } void Matriz::ones(){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] = 1; } } } void Matriz::unit(){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ if(i==j){ m[i][j] = 1; }else{ m[i][j] = 0; } } } } Matriz Matriz::operator + (const double &const_value){ Matriz C(n_rows, n_cols); for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] + const_value; } } return(C); } Matriz Matriz::operator - (const double &const_value){ Matriz C(n_rows, n_cols); for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] - const_value; } } return(C); } Matriz Matriz::operator * (const double &scalar){ Matriz C(n_rows, n_cols); for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] * scalar; } } return(C); } Matriz Matriz::operator / (const double &scalar){ if(scalar == 0){ throw invalid_argument( "Division by zero!" ); } Matriz C(n_rows, n_cols); for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] / scalar; } } return(C); } Matriz & Matriz::operator += (const double &scalar){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] += scalar; } } return(*this); } Matriz & Matriz::operator -= (const double &scalar){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] -= scalar; } } return(*this); } Matriz & Matriz::operator *= (const double &scalar){ for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] *= scalar; } } return(*this); } Matriz & Matriz::operator /= (const double &scalar){ if(scalar == 0){ throw invalid_argument( "Division by zero!" ); return(*this); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] /= scalar; } } return(*this); } Matriz & Matriz::operator = (const Matriz &B){ int nrows_b = B.getRows(); int ncols_b = B.getCols(); double **resize; resize = new double*[nrows_b]; for(int i=0; i<nrows_b; i++){ resize[i] = new double[ncols_b]; for(int j=0; j<ncols_b; j++){ resize[i][j] = B.m[i][j]; } } for (int i=0; i < n_rows; i++){ delete [] m[i]; } delete [] m; n_rows = nrows_b; n_cols = ncols_b; m = resize; return(*this); } Matriz Matriz::operator + (const Matriz &B){ int nrows_b = B.getRows(); int ncols_b = B.getCols(); Matriz C(n_rows, n_cols); if(nrows_b != n_rows || ncols_b != n_cols){ Matriz Erro(0, 0); return(Erro); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] + B.m[i][j]; } } return(C); } Matriz Matriz::operator - (const Matriz &B){ int nrows_b = B.getRows(); int ncols_b = B.getCols(); Matriz C(n_rows, n_cols); if(nrows_b != n_rows || ncols_b != n_cols){ Matriz Erro(0, 0); return(Erro); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ C.m[i][j] = m[i][j] - B.m[i][j]; } } return(C); } Matriz Matriz::operator * (const Matriz &B){ const int n_rows_b = B.getRows(); if(n_cols != n_rows_b){ Matriz Erro(0, 0); return(Erro); } double sum; const int n_cols_b = B.getCols(); Matriz C(n_rows, n_cols_b); for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols_b; j++){ sum = 0; for(int k=0; k<n_cols; k++){ sum += m[i][k]*B.m[k][j]; } C.m[i][j] = sum; } } return(C); } Matriz & Matriz::operator += (const Matriz &B){ int nrows_b = B.getRows(); int ncols_b = B.getCols(); if(nrows_b != n_rows || ncols_b != n_cols){ n_rows = 0; n_cols = 0; return(*this); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] += B.m[i][j]; } } return(*this); } Matriz & Matriz::operator *= (const Matriz &B){ const int n_rows_b = B.getRows(); const int n_cols_b = B.getCols(); if(n_cols != n_rows_b){ n_cols = 0; n_rows = 0; return(*this); } Matriz C = *this; double **resize; resize = new double*[n_rows_b]; for(int i=0; i<n_rows_b; i++){ resize[i] = new double[n_cols_b]; for(int j=0; j<n_cols_b; j++){ resize[i][j] = B.m[i][j]; } } for (int i=0; i < n_rows; i++){ delete [] m[i]; } delete [] m; n_cols = n_cols_b; m = resize; double sum; for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ sum = 0; for(int k=0; k<n_cols; k++){ sum += C.m[i][k]*B.m[k][j]; } m[i][j] = sum; } } return(*this); } Matriz & Matriz::operator -= (const Matriz &B){ int nrows_b = B.getRows(); int ncols_b = B.getCols(); Matriz C(nrows_b, ncols_b); if(nrows_b != n_rows || ncols_b != n_cols){ n_cols = 0; n_rows = 0; return(*this); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ m[i][j] -= B.m[i][j]; } } return(*this); } bool Matriz::operator == (const Matriz &B) const{ bool equals = true; const int nrows_b = B.getRows(); const int ncols_b = B.getCols(); if(nrows_b != n_rows || ncols_b != n_cols){ return(false); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ if(m[i][j] != B.m[i][j]){ equals=false; break; } } if(!equals){ return(false); } } return(equals); } bool Matriz::operator != (const Matriz &B) const{ bool equals = true; const int nrows_b = B.getRows(); const int ncols_b = B.getCols(); if(nrows_b != n_rows || ncols_b != n_cols){ return(true); } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ if(m[i][j] != B.m[i][j]){ equals=false; break; } } if(!equals){ return(true); } } return(!equals); } Matriz & Matriz::operator ~ (){ double **resize; resize = new double*[n_rows]; for(int i=0; i<n_rows; i++){ resize[i] = new double[n_cols]; } for(int i=0; i<n_rows; i++){ for(int j=0; j<n_cols; j++){ resize[j][i] = m[i][j]; } } for (int i=0; i < n_rows; i++){ delete [] m[i]; } delete [] m; swap(n_rows, n_cols); m = resize; return(*this); } double& Matriz::operator () (const int &row, const int &col) const{ return(m[row-1][col-1]); } ostream& operator << (ostream& os, const Matriz &B){ const int nrows_b = B.getRows(); const int ncols_b = B.getCols(); for(int i=0; i<nrows_b; i++){ for(int j=0; j<ncols_b; j++){ os << B.m[i][j]; os << "\t"; } os << endl; } return(os); } istream& operator >> (istream &in, Matriz &B){ const int nrows_b = B.getRows(); const int ncols_b = B.getCols(); for(int i=0; i<nrows_b; i++){ for(int j=0; j<ncols_b; j++){ in >> B.m[i][j]; } } return(in); }
[ "thiagomaltac@gmail.com" ]
thiagomaltac@gmail.com
c562d33e12932e5aae0fc991e2eb21b29b13d4e1
de13bba043b6d9cf3e78a8481ee16142ee84f127
/Plugins/Bugly/Source/Bugly/Public/GenericBugly.h
35f006c393dd110aed76c9324d55f166c82a8e5c
[ "MIT" ]
permissive
crazytuzi/UE4Bugly
92610dd507ab32ed6e36703f6a29a03884723fec
4f91379b11481aa32f58018aac35b2a394b45ae5
refs/heads/master
2023-03-18T00:23:17.496948
2022-11-21T03:46:18
2022-11-21T03:46:18
223,711,970
3
1
MIT
2022-04-29T16:33:41
2019-11-24T08:08:30
C++
UTF-8
C++
false
false
1,340
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Templates/SharedPointer.h" #include "GenericBuglyDelegate.h" class BUGLY_API FGenericBugly { public: FGenericBugly(); virtual ~FGenericBugly(); virtual void OnStartup(const FString& InAppId, const FString& InAppVersion, const FString& InAppChanenl, bool bDebug); virtual void OnShutdown(); virtual void SetCrashDelegate(TSharedPtr<FGenericBuglyDelegate> InCrashDelegate); virtual TSharedPtr<FGenericBuglyDelegate> GetCrashDelegate(); virtual void TestNativeCrash(); virtual void SetUserId(const FString& InUserId); virtual void SetUserSceneTag(int32 InSceneTag); virtual void PutUserData(const FString& InKey, const FString& InValue); virtual void LogVerbose(const FString& InLog, const FString& InTag = TEXT("")); virtual void LogDebug(const FString& InLog, const FString& InTag = TEXT("")); virtual void LogInfo(const FString& InLog, const FString& InTag = TEXT("")); virtual void LogWarning(const FString& InLog, const FString& InTag = TEXT("")); virtual void LogError(const FString& InLog, const FString& InTag = TEXT("")); virtual void SetLogCache(int32 ByteSize); virtual void UpdateVersion(const FString& InAppVersion); protected: TSharedPtr<FGenericBuglyDelegate> CrashDelegate; };
[ "newzeadev@gmail.com" ]
newzeadev@gmail.com
49de05b21a60367fefbba239cd151b6270ccc03e
376883e26add80c6e3dc75fd3571b994d37eda51
/src/signACommonUI/Chart2D/SAFigureWindowOverlay.cpp
5388562ed230b2f3fe64933fda5ba3ef8e40ea4e
[]
no_license
rpzhu/sa
4375142a565e9ed058acd2d0f2729f6cfa499c73
1a01b4ab065d2b596496126b43140e8bda922a53
refs/heads/master
2022-11-28T12:36:27.491989
2020-07-30T01:22:08
2020-07-30T01:22:08
275,979,744
1
0
null
null
null
null
UTF-8
C++
false
false
267
cpp
#include "SAFigureWindowOverlay.h" #include <QDebug> SAFigureWindowOverlay::SAFigureWindowOverlay(SAFigureWindow* fig) :QwtWidgetOverlay(fig) ,m_fig(nullptr) { m_fig = fig; } SAFigureWindow *SAFigureWindowOverlay::figure() const { return m_fig; }
[ "872207648@qq.com" ]
872207648@qq.com
5698ac16ef78f6b097c9b4df29fb920ca5041106
959f9c455401745d071114cf569ec458a3657f3e
/src/AddTest.cpp
c9180cf544258cd602473b94904d455d0692b32a
[]
no_license
swallville/trab2
56b72594aa12a9e584c42fb40b7c0d0cd73b4cb5
ca67a71dc4c0e276d79208cc27cc85e0ace8acfa
refs/heads/master
2021-01-18T00:18:35.391288
2016-09-21T22:48:13
2016-09-21T22:48:13
68,666,337
0
0
null
null
null
null
UTF-8
C++
false
false
4,762
cpp
/* * AddTest.cpp * Lab2 * * Created by Lukas Ferreira on 14/09/16. * Copyright © 2016 Lukas Ferreira. All rights reserved. */ #include "funcs.hpp" using namespace Add; using namespace testing; class AddTest : public::Test { void SetUp(){} virtual void TearDown(){} }; /* Teste da funcao from_roman(): Descrição: Converte um numero romano para decimal Parâmetros: input - referencia para a string do numero romano Retorno: int - numero romano em sua forma decimal */ TEST_F(AddTest, from_roman){ string num = "MDCC"; /* 1700 */ string num1 = "LXXIX"; /* 79 */ string numex = "LXXiX"; /* 79 */ string num2 = "DCCCXCIX"; /* 899 */ //string momo = "MDXLIX"; string num3 = "MCMXLIX"; /* 1949 */ string num4 = "MCMLXXXIV"; /* 1984 */ string num5 = "MCMXCIX"; /* 1999 */ string num6 = "MMDCCCLXXXVIII"; /* 2888 */ string num7 = "MMCMXCIX"; /* 2999 */ string num8 = "mmcmxcix"; /* 2999 minusculo*/ string emp = ""; /* string vazia */ /* Strings com numeros ou conteudo invalido */ string wrng = "VV"; string wrng2 = "VVV"; string wrng3 = "CCCC"; string wrng4 = "DD"; string wrng5 = "iiiii"; string wrng6 = "ll"; string wrng7 = "IXL"; string wrng8 = "IIV"; string wrng9 = "XXL"; string wrng10 = "XXC"; string wrng11 = "CCD"; string wrng12 = "CCM"; string wrng13 = "ixl"; string err = "MCMXDXCIX"; string err2 = "MCMXDXCIX"; string err3 = "21421"; string err4 = "HOMEMPASSARO"; string err5 = "MMMX"; /* 3010 */ string err6 = "MMC MXCIX"; /* 2999, mas com caracter invalido */ string err7 = "!MMCMXCIX"; /* 2999, mas com caracter invalido */ Addition addition; /* Testes */ EXPECT_EQ(1700, addition.from_roman(num)); EXPECT_EQ(79, addition.from_roman(num1)); EXPECT_EQ(79, addition.from_roman(numex)); EXPECT_EQ(899, addition.from_roman(num2)); EXPECT_EQ(1949, addition.from_roman(num3)); EXPECT_EQ(1984, addition.from_roman(num4)); EXPECT_EQ(1999, addition.from_roman(num5)); EXPECT_EQ(2888, addition.from_roman(num6)); EXPECT_EQ(2999, addition.from_roman(num7)); EXPECT_EQ(2999, addition.from_roman(num8)); EXPECT_EQ(-1, addition.from_roman(emp)); EXPECT_EQ(-1, addition.from_roman(wrng)); EXPECT_EQ(-1, addition.from_roman(wrng2)); EXPECT_EQ(-1, addition.from_roman(wrng3)); EXPECT_EQ(-1, addition.from_roman(wrng4)); EXPECT_EQ(-1, addition.from_roman(wrng5)); EXPECT_EQ(-1, addition.from_roman(wrng6)); EXPECT_EQ(-1, addition.from_roman(wrng7)); EXPECT_EQ(-1, addition.from_roman(wrng8)); EXPECT_EQ(-1, addition.from_roman(wrng9)); EXPECT_EQ(-1, addition.from_roman(wrng10)); EXPECT_EQ(-1, addition.from_roman(wrng11)); EXPECT_EQ(-1, addition.from_roman(wrng12)); EXPECT_EQ(-1, addition.from_roman(wrng13)); EXPECT_EQ(-1, addition.from_roman(err)); EXPECT_EQ(-1, addition.from_roman(err2)); EXPECT_EQ(-1, addition.from_roman(err3)); EXPECT_EQ(-1, addition.from_roman(err4)); EXPECT_EQ(-1, addition.from_roman(err5)); EXPECT_EQ(-1, addition.from_roman(err6)); EXPECT_EQ(-1, addition.from_roman(err7)); } /* Teste da funcao to_roman(): Descrição: Converte um numero decimal para romano Parâmetros: value - inteiro a ser convertido para romano Retorno: string - numero decimal em sua forma romana */ TEST_F(AddTest, to_roman){ int momo = 1786; int momo2 = 400; int momo3 = 2547; Addition addition; EXPECT_EQ("MDCCLXXXVI", addition.to_roman(momo)); EXPECT_EQ("CD", addition.to_roman(momo2)); EXPECT_EQ("MMDXLVII", addition.to_roman(momo3)); EXPECT_NE("CCCC", addition.to_roman(400)); } /* Teste da funcao it_contains(): Descrição: Verifica se o numero romano e 900 ou 400 ou 90 ou 9 ou 4 Parâmetros: input - numero romano a ser verificado Retorno: True se o numero romano existir, False do contrario */ TEST_F(AddTest, it_contains){ string caseA = "CM"; string caseB = "CD"; string caseC = "XC"; string caseD = "XL"; string caseE = "IX"; string caseF = "IV"; string err1 = "MCMXDXCIX"; string emp = ""; /* string vazia */ string num = "MDCC"; /* 1700 */ Addition addition; EXPECT_EQ(true, addition.it_contains(caseA)); EXPECT_EQ(true, addition.it_contains(caseB)); EXPECT_EQ(true, addition.it_contains(caseC)); EXPECT_EQ(true, addition.it_contains(caseD)); EXPECT_EQ(true, addition.it_contains(caseF)); EXPECT_EQ(true, addition.it_contains(caseE)); EXPECT_EQ(true, addition.it_contains(caseF)); EXPECT_NE(true, addition.it_contains(err1)); EXPECT_NE(true, addition.it_contains(emp)); EXPECT_NE(true, addition.it_contains(num)); }
[ "unlisislukasferreira@hotmail.com" ]
unlisislukasferreira@hotmail.com
537e192204b9b852721a50f6ddb84634c04fce90
acd9c9594202027796af3dd48e4a6ca6680e08d5
/contest7/J.cpp
a59a646f31b27d841d2422482b20125b21937deb
[]
no_license
ZhekLu/Yandex-Algorithms-Training
3f9a7727169fbf31f1a996ed4aa1102292e87249
625e5a54e9e370a7bfa5417a70f75c55f3338d2a
refs/heads/main
2023-08-25T11:54:36.214847
2021-10-04T17:45:30
2021-10-04T17:45:30
382,930,954
3
0
null
null
null
null
UTF-8
C++
false
false
1,586
cpp
#include <iostream> #include <set> #include <tuple> #include <unordered_set> using namespace std; enum Events { BLOCK_END = -1, BLOCK_START = 1 }; int main() { int blockNum, W, L; cin >> blockNum >> W >> L; set<tuple<int, Events, int, int>> events; //z, type, area, index for(int i = 1, x1, y1, z1, x2, y2, z2, area; i <= blockNum; i++) { cin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2; area = (x2 - x1) * (y2 - y1); events.insert(make_tuple(z1, BLOCK_START, area, i)); events.insert(make_tuple(z2, BLOCK_END, area, i)); } int complexArea = W * L; int minBlocksNum = INT32_MAX, currBlocksNum = 0, currArea = 0; for(auto&[z, type, area, index] : events) { currBlocksNum += type; currArea += type * area; if(currArea == complexArea && currBlocksNum < minBlocksNum) minBlocksNum = currBlocksNum; } if(minBlocksNum > blockNum) { cout << "NO"; } else { cout << "YES" << endl << minBlocksNum << endl; unordered_set<int> nowUsed; for(auto&[z, type, area, index] : events) { currBlocksNum += type; currArea += type * area; if(type == BLOCK_START) { nowUsed.insert(index); if(currArea == complexArea && currBlocksNum == minBlocksNum) break; } else { nowUsed.erase(index); } } for(auto& ind : nowUsed) cout << ind << endl; } }
[ "justletmego@list.ru" ]
justletmego@list.ru
6bb646681f88217ef956b505cee91bb795a330f3
960858e0bec3398d75dc07e6705506ec83c9df3d
/src/hostviewcli/stdafx.h
9832c1dfd6c485fc1db2b5dd55f0715a8cb41eba
[ "MIT" ]
permissive
radtek/hostview-win
85db65547f2c5f049b4877650eb3ba0a7932a7f5
db890b83956081d98e64005873eb2e7e4c6891e6
refs/heads/master
2021-09-14T17:11:48.218173
2018-05-16T12:54:02
2018-05-16T12:54:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
h
/** * The MIT License (MIT) * * Copyright (c) 2015 Muse / INRIA * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <stdio.h> #include <tchar.h> #include <winsock2.h> #include <Windows.h> #include <map> #include <string> #include <time.h> #include "Shlwapi.h" #define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS // VS2015 compat #ifdef _UNICODE #define tstring wstring #else #define tstring string #endif
[ "annakaisa.pietilainen@gmail.com" ]
annakaisa.pietilainen@gmail.com
2dbcd03ccff990ffd3de72d828ad730d9abc183e
0f39b426b8f9e8b4c096070b85a0852580c2f904
/DeepLearningToolKit/Toolkit/Core/Container/SanRange.h
ce3acf1cc409b313a4afa1774f0ed5fc5ab7cff7
[ "MIT" ]
permissive
zxyinz/DeepLearningForBlueShark
838db4fbc4caf65907ac76555ed29a5734130a9e
025206aa7450b7ec86ebab9ca2bbcabe4421af91
refs/heads/master
2021-01-21T11:54:31.328844
2017-05-03T22:37:11
2017-05-03T22:37:11
85,154,420
0
0
null
null
null
null
UTF-8
C++
false
false
2,231
h
#include"SanContainerDef.h" #pragma once using namespace std; namespace San { #ifndef __STDSANRANGE_H__ #define __STDSANRANGE_H__ template<class _type, class _Allocator = cSanSystemAllocator> struct _srange { private: _type Min; _type Max; _type Step; public: _srange(const _type &Min, const _type &Max, const _type &Step = 1) :Min(Min), Max(Max), Step(Step) { }; _srange(const _srange<_type, _Allocator> &Range) :Min(Range.Min), Max(Range.Max), Step(Range.Step) { }; ~_srange() { }; bool operator==(const _srange<_type, _Allocator> &Range) const { return (this->Min == Range.Min) && (this->Max == Range.Max) && (this->Step == Range.Step); }; bool operator!=(const _srange<_type, _Allocator> &Range) const { return (this->Min != Range.Min) || (this->Max != Range.Max) || (this->Step != Range.Step); }; bool operator==(const _type &Val) const { return this->iInRange(Val); }; bool operator!=(const _type &Val) const { return !this->iInRange(Val); }; bool operator<(const _type &Val) const { return Val < this->Min; }; bool operator>(const _type &Val) const { return Val > this->Max; }; bool iInRange(const _type &Val) const { return (Val >= Min) && (Val < Max); // [Min, Max), Min <= Max }; int32 iCompare(const _type &Val) const { return this->iInRange(Val) ? 0 : (Val < Min ? -1 : 1); }; void iSetMin(const _type &Min) { this->Min = Min; }; void iSetMax(const _type &Max) { this->Max = Max; }; void iSetStep(const _type &Step) { this->Step = Step; }; //Step == 0 void iSetRange(const _type &Min, const _type &Max) //Opt call set ? { this->Min = Min; this->Max = Max; }; void iSetRange(const _type &Min, const _type &Max, const _type &Step) //Opt call set ? { this->Min = Min; this->Max = Max; this->Step = Step; }; const _type& iMin() const { return this->Min; } const _type& iMax() const { return this->Max; } const _type& iStep() const { return this->Step; } //STL //begin(), end(), cbegin(), cend(), size() ? ++ uint32 size() const { return (this->Max - this->Min) / this->Step; /* Step == 0 */ } bool empty() const { return this->Min == this->Max; } }; #endif }
[ "zxyinz@gmail.com" ]
zxyinz@gmail.com
66ee5653e5cb1911cc9e08ba225ce27641585109
488b49075ae89dcb84dc22ca27a961671049e89a
/baekjoon/9461-파도반수열.cpp
f68e125f9dbc8242ce5797cf07944920ecc1ab78
[]
no_license
blytheej/alg
4cb2f24d30e7e35b6282ad08c823e23f756bfc3c
332f12ddc643a91501fccaf5dfaaafd1fe8a38a4
refs/heads/master
2020-03-27T03:33:39.719217
2019-10-17T04:48:51
2019-10-17T04:48:51
145,871,728
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include <stdio.h> int main() { int tc; scanf("%d", &tc); long long int wave[102]; wave[0] = 1; wave[1] = 1; wave[2] = 1; wave[3] = 2; wave[4] = 2; for (int i = 5; i <= 100; i++) { wave[i] = wave[i - 1] + wave[i - 5]; } for (int i = 0; i < tc; i++) { int n; scanf("%d", &n); printf("%lld\n", wave[n-1]); } }
[ "blytheej@naver.com" ]
blytheej@naver.com
0ddb34827841deda89f2fb63caade89efcf71fb0
672ba9aba77ead521356284c8fc47165bcd8adf1
/tags/0.2/api/include/api/init.hpp
ecfe8c2fb83031e9aeb6d099f875da369ef11e1b
[]
no_license
BGCX261/zia-tamer-svn-to-git
fdca85aeb6c2290c6b89dc574aa202192c521d04
852ed903f0adefcdd0869ec2d954cc8a25bb5c5a
refs/heads/master
2021-01-10T21:53:38.993041
2015-08-25T15:27:48
2015-08-25T15:27:48
41,600,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,532
hpp
#ifndef _INITDLL_H_ #define _INITDLL_H_ #include <list> #include "IModule.hpp" #include "IConf.hpp" #include "HttpStep.hpp" #include "IStream.hpp" extern "C" { /*! * \brief Global log * * This will be given by the Core. * Use it only inside external functions of the dll. */ zia::api::ILog* gLog; /*! * \brief First called function of the DLL. * * Can be used to initialize global datas. * * \param conf The IConf of the Zia server. */ void dll_load(zia::api::IConf& conf); /*! * \brief Function called when new request. * * Typicaly used to allocated an IModule and set HttpStep callbacks. * * \param stepsCallbacks The list to fill with HttpStep::Pair. * \param conf The IConf of the Zia server. * \return a IModule pointer that will be used by the server, * 0 if you dont want to use your module for this request. */ zia::api::IModule* module_new(std::list<zia::api::HttpStep::Pair>& stepsCallbacks, zia::api::IConf& conf); /*! * \brief Function called for delete an IModule instance. * * Can be called at any time. * * \param moduleToDelete The IModule pointer returned by `ziaApi_newModule`. */ void module_delete(zia::api::IModule* moduleToDelete); /*! * \brief Function called when unloading the dll. */ void dll_unload(); } #endif /* _INITDLL_H_ */
[ "you@example.com" ]
you@example.com
fa7c945b97b75adad16f168891c38ef9bc8f4021
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+addr-rfi-data-rfi.c.cbmc.cpp
9283a8da1ea545fd682df0655b942b13fcc39dbf
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
44,334
cpp
// 0:vars:3 // 6:thr0:1 // 7:thr1:1 // 3:atom_1_X0_1:1 // 4:atom_1_X5_1:1 // 5:atom_1_X8_1:1 #define ADDRSIZE 8 #define NPROC 3 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !37, metadata !DIExpression()), !dbg !46 // br label %label_1, !dbg !47 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !45), !dbg !48 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !38, metadata !DIExpression()), !dbg !49 // call void @llvm.dbg.value(metadata i64 2, metadata !41, metadata !DIExpression()), !dbg !49 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !50 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !51 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !42, metadata !DIExpression()), !dbg !52 // call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !52 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !53 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !54 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !57, metadata !DIExpression()), !dbg !93 // br label %label_2, !dbg !75 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !92), !dbg !95 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !60, metadata !DIExpression()), !dbg !96 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !62, metadata !DIExpression()), !dbg !96 // %conv = trunc i64 %0 to i32, !dbg !79 // call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !93 // %xor = xor i32 %conv, %conv, !dbg !80 creg_r1 = max(creg_r0,creg_r0); ASSUME(active[creg_r1] == 2); r1 = r0 ^ r0; // call void @llvm.dbg.value(metadata i32 %xor, metadata !63, metadata !DIExpression()), !dbg !93 // %add = add nsw i32 2, %xor, !dbg !81 creg_r2 = max(0,creg_r1); ASSUME(active[creg_r2] == 2); r2 = 2 + r1; // %idxprom = sext i32 %add to i64, !dbg !81 // %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !81 r3 = 0+r2*1; ASSUME(creg_r3 >= 0); ASSUME(creg_r3 >= creg_r2); ASSUME(active[creg_r3] == 2); // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !64, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64 1, metadata !66, metadata !DIExpression()), !dbg !101 // store atomic i64 1, i64* %arrayidx monotonic, align 8, !dbg !81 // ST: Guess iw(2,r3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,r3); cw(2,r3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,r3)] == 2); ASSUME(active[cw(2,r3)] == 2); ASSUME(sforbid(r3,cw(2,r3))== 0); ASSUME(iw(2,r3) >= 0); ASSUME(iw(2,r3) >= creg_r3); ASSUME(cw(2,r3) >= iw(2,r3)); ASSUME(cw(2,r3) >= old_cw); ASSUME(cw(2,r3) >= cr(2,r3)); ASSUME(cw(2,r3) >= cl[2]); ASSUME(cw(2,r3) >= cisb[2]); ASSUME(cw(2,r3) >= cdy[2]); ASSUME(cw(2,r3) >= cdl[2]); ASSUME(cw(2,r3) >= cds[2]); ASSUME(cw(2,r3) >= cctrl[2]); ASSUME(cw(2,r3) >= caddr[2]); // Update caddr[2] = max(caddr[2],creg_r3); buff(2,r3) = 1; mem(r3,cw(2,r3)) = 1; co(r3,cw(2,r3))+=1; delta(r3,cw(2,r3)) = -1; ASSUME(creturn[2] >= cw(2,r3)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !68, metadata !DIExpression()), !dbg !102 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !84 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r4 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r4 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r4 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !70, metadata !DIExpression()), !dbg !102 // %conv4 = trunc i64 %1 to i32, !dbg !85 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !67, metadata !DIExpression()), !dbg !93 // %xor5 = xor i32 %conv4, %conv4, !dbg !86 creg_r5 = max(creg_r4,creg_r4); ASSUME(active[creg_r5] == 2); r5 = r4 ^ r4; // call void @llvm.dbg.value(metadata i32 %xor5, metadata !71, metadata !DIExpression()), !dbg !93 // %add6 = add nsw i32 %xor5, 1, !dbg !87 creg_r6 = max(creg_r5,0); ASSUME(active[creg_r6] == 2); r6 = r5 + 1; // call void @llvm.dbg.value(metadata i32 %add6, metadata !72, metadata !DIExpression()), !dbg !93 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !73, metadata !DIExpression()), !dbg !107 // %conv9 = sext i32 %add6 to i64, !dbg !89 // call void @llvm.dbg.value(metadata i64 %conv9, metadata !75, metadata !DIExpression()), !dbg !107 // store atomic i64 %conv9, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !89 // ST: Guess iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0); cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0)] == 2); ASSUME(active[cw(2,0)] == 2); ASSUME(sforbid(0,cw(2,0))== 0); ASSUME(iw(2,0) >= creg_r6); ASSUME(iw(2,0) >= 0); ASSUME(cw(2,0) >= iw(2,0)); ASSUME(cw(2,0) >= old_cw); ASSUME(cw(2,0) >= cr(2,0)); ASSUME(cw(2,0) >= cl[2]); ASSUME(cw(2,0) >= cisb[2]); ASSUME(cw(2,0) >= cdy[2]); ASSUME(cw(2,0) >= cdl[2]); ASSUME(cw(2,0) >= cds[2]); ASSUME(cw(2,0) >= cctrl[2]); ASSUME(cw(2,0) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0) = r6; mem(0,cw(2,0)) = r6; co(0,cw(2,0))+=1; delta(0,cw(2,0)) = -1; ASSUME(creturn[2] >= cw(2,0)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !77, metadata !DIExpression()), !dbg !109 // %2 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !91 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r7 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r7 = buff(2,0); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r7 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %2, metadata !79, metadata !DIExpression()), !dbg !109 // %conv13 = trunc i64 %2 to i32, !dbg !92 // call void @llvm.dbg.value(metadata i32 %conv13, metadata !76, metadata !DIExpression()), !dbg !93 // %cmp = icmp eq i32 %conv, 1, !dbg !93 // %conv14 = zext i1 %cmp to i32, !dbg !93 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !80, metadata !DIExpression()), !dbg !93 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !81, metadata !DIExpression()), !dbg !113 // %3 = zext i32 %conv14 to i64 // call void @llvm.dbg.value(metadata i64 %3, metadata !83, metadata !DIExpression()), !dbg !113 // store atomic i64 %3, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !95 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // %cmp18 = icmp eq i32 %conv4, 1, !dbg !96 // %conv19 = zext i1 %cmp18 to i32, !dbg !96 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !84, metadata !DIExpression()), !dbg !93 // call void @llvm.dbg.value(metadata i64* @atom_1_X5_1, metadata !85, metadata !DIExpression()), !dbg !116 // %4 = zext i32 %conv19 to i64 // call void @llvm.dbg.value(metadata i64 %4, metadata !87, metadata !DIExpression()), !dbg !116 // store atomic i64 %4, i64* @atom_1_X5_1 seq_cst, align 8, !dbg !98 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= max(creg_r4,0)); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r4==1); mem(4,cw(2,4)) = (r4==1); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // %cmp23 = icmp eq i32 %conv13, 1, !dbg !99 // %conv24 = zext i1 %cmp23 to i32, !dbg !99 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !88, metadata !DIExpression()), !dbg !93 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !89, metadata !DIExpression()), !dbg !119 // %5 = zext i32 %conv24 to i64 // call void @llvm.dbg.value(metadata i64 %5, metadata !91, metadata !DIExpression()), !dbg !119 // store atomic i64 %5, i64* @atom_1_X8_1 seq_cst, align 8, !dbg !101 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= max(creg_r7,0)); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r7==1); mem(5,cw(2,5)) = (r7==1); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // ret i8* null, !dbg !102 ret_thread_2 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !129, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i8** %argv, metadata !130, metadata !DIExpression()), !dbg !186 // %0 = bitcast i64* %thr0 to i8*, !dbg !100 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !100 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !131, metadata !DIExpression()), !dbg !188 // %1 = bitcast i64* %thr1 to i8*, !dbg !102 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !102 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !135, metadata !DIExpression()), !dbg !190 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !136, metadata !DIExpression()), !dbg !191 // call void @llvm.dbg.value(metadata i64 0, metadata !138, metadata !DIExpression()), !dbg !191 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !105 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !139, metadata !DIExpression()), !dbg !193 // call void @llvm.dbg.value(metadata i64 0, metadata !141, metadata !DIExpression()), !dbg !193 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !107 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !142, metadata !DIExpression()), !dbg !195 // call void @llvm.dbg.value(metadata i64 0, metadata !144, metadata !DIExpression()), !dbg !195 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !109 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !145, metadata !DIExpression()), !dbg !197 // call void @llvm.dbg.value(metadata i64 0, metadata !147, metadata !DIExpression()), !dbg !197 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !111 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_1_X5_1, metadata !148, metadata !DIExpression()), !dbg !199 // call void @llvm.dbg.value(metadata i64 0, metadata !150, metadata !DIExpression()), !dbg !199 // store atomic i64 0, i64* @atom_1_X5_1 monotonic, align 8, !dbg !113 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !151, metadata !DIExpression()), !dbg !201 // call void @llvm.dbg.value(metadata i64 0, metadata !153, metadata !DIExpression()), !dbg !201 // store atomic i64 0, i64* @atom_1_X8_1 monotonic, align 8, !dbg !115 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !116 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call11 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !117 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %2 = load i64, i64* %thr0, align 8, !dbg !118, !tbaa !119 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r9 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r9 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r9 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // %call12 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !123 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %3 = load i64, i64* %thr1, align 8, !dbg !124, !tbaa !119 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r10 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r10 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r10 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call13 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !125 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !155, metadata !DIExpression()), !dbg !213 // %4 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !127 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r11 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r11 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r11 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %4, metadata !157, metadata !DIExpression()), !dbg !213 // %conv = trunc i64 %4 to i32, !dbg !128 // call void @llvm.dbg.value(metadata i32 %conv, metadata !154, metadata !DIExpression()), !dbg !186 // %cmp = icmp eq i32 %conv, 2, !dbg !129 // %conv14 = zext i1 %cmp to i32, !dbg !129 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !158, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !160, metadata !DIExpression()), !dbg !217 // %5 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !131 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r12 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r12 = buff(0,0+1*1); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r12 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %5, metadata !162, metadata !DIExpression()), !dbg !217 // %conv18 = trunc i64 %5 to i32, !dbg !132 // call void @llvm.dbg.value(metadata i32 %conv18, metadata !159, metadata !DIExpression()), !dbg !186 // %cmp19 = icmp eq i32 %conv18, 1, !dbg !133 // %conv20 = zext i1 %cmp19 to i32, !dbg !133 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !163, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !165, metadata !DIExpression()), !dbg !221 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !135 // LD: Guess old_cr = cr(0,0+2*1); cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+2*1)] == 0); ASSUME(cr(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cr(0,0+2*1) >= 0); ASSUME(cr(0,0+2*1) >= cdy[0]); ASSUME(cr(0,0+2*1) >= cisb[0]); ASSUME(cr(0,0+2*1) >= cdl[0]); ASSUME(cr(0,0+2*1) >= cl[0]); // Update creg_r13 = cr(0,0+2*1); crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+2*1) < cw(0,0+2*1)) { r13 = buff(0,0+2*1); } else { if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) { ASSUME(cr(0,0+2*1) >= old_cr); } pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1)); r13 = mem(0+2*1,cr(0,0+2*1)); } ASSUME(creturn[0] >= cr(0,0+2*1)); // call void @llvm.dbg.value(metadata i64 %6, metadata !167, metadata !DIExpression()), !dbg !221 // %conv24 = trunc i64 %6 to i32, !dbg !136 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !164, metadata !DIExpression()), !dbg !186 // %cmp25 = icmp eq i32 %conv24, 1, !dbg !137 // %conv26 = zext i1 %cmp25 to i32, !dbg !137 // call void @llvm.dbg.value(metadata i32 %conv26, metadata !168, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !170, metadata !DIExpression()), !dbg !225 // %7 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !139 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r14 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r14 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r14 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %7, metadata !172, metadata !DIExpression()), !dbg !225 // %conv30 = trunc i64 %7 to i32, !dbg !140 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !169, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* @atom_1_X5_1, metadata !174, metadata !DIExpression()), !dbg !228 // %8 = load atomic i64, i64* @atom_1_X5_1 seq_cst, align 8, !dbg !142 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r15 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r15 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r15 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %8, metadata !176, metadata !DIExpression()), !dbg !228 // %conv34 = trunc i64 %8 to i32, !dbg !143 // call void @llvm.dbg.value(metadata i32 %conv34, metadata !173, metadata !DIExpression()), !dbg !186 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_1, metadata !178, metadata !DIExpression()), !dbg !231 // %9 = load atomic i64, i64* @atom_1_X8_1 seq_cst, align 8, !dbg !145 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r16 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r16 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r16 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %9, metadata !180, metadata !DIExpression()), !dbg !231 // %conv38 = trunc i64 %9 to i32, !dbg !146 // call void @llvm.dbg.value(metadata i32 %conv38, metadata !177, metadata !DIExpression()), !dbg !186 // %and = and i32 %conv34, %conv38, !dbg !147 creg_r17 = max(creg_r15,creg_r16); ASSUME(active[creg_r17] == 0); r17 = r15 & r16; // call void @llvm.dbg.value(metadata i32 %and, metadata !181, metadata !DIExpression()), !dbg !186 // %and39 = and i32 %conv30, %and, !dbg !148 creg_r18 = max(creg_r14,creg_r17); ASSUME(active[creg_r18] == 0); r18 = r14 & r17; // call void @llvm.dbg.value(metadata i32 %and39, metadata !182, metadata !DIExpression()), !dbg !186 // %and40 = and i32 %conv26, %and39, !dbg !149 creg_r19 = max(max(creg_r13,0),creg_r18); ASSUME(active[creg_r19] == 0); r19 = (r13==1) & r18; // call void @llvm.dbg.value(metadata i32 %and40, metadata !183, metadata !DIExpression()), !dbg !186 // %and41 = and i32 %conv20, %and40, !dbg !150 creg_r20 = max(max(creg_r12,0),creg_r19); ASSUME(active[creg_r20] == 0); r20 = (r12==1) & r19; // call void @llvm.dbg.value(metadata i32 %and41, metadata !184, metadata !DIExpression()), !dbg !186 // %and42 = and i32 %conv14, %and41, !dbg !151 creg_r21 = max(max(creg_r11,0),creg_r20); ASSUME(active[creg_r21] == 0); r21 = (r11==2) & r20; // call void @llvm.dbg.value(metadata i32 %and42, metadata !185, metadata !DIExpression()), !dbg !186 // %cmp43 = icmp eq i32 %and42, 1, !dbg !152 // br i1 %cmp43, label %if.then, label %if.end, !dbg !154 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r21); ASSUME(cctrl[0] >= 0); if((r21==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([112 x i8], [112 x i8]* @.str.1, i64 0, i64 0), i32 noundef 77, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !155 // unreachable, !dbg !155 r22 = 1; T0BLOCK2: // %10 = bitcast i64* %thr1 to i8*, !dbg !158 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !158 // %11 = bitcast i64* %thr0 to i8*, !dbg !158 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !158 // ret i32 0, !dbg !159 ret_thread_0 = 0; ASSERT(r22== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
546290d7103708f970ff4164ea00558a0f1cb077
22d4ec8baf3258edf318a7832a169a11e9fd12d1
/Flocking/SeekAndFace.h
a65fe44e3dd1546ab652d2e6c967565aa39539cf
[]
no_license
Laurareilly/EventSystem
fee7f902266f8d9c6766ee8b3eb56517a4e322ef
e219f4499b88373c0d45d48f8f317d36449bfb4f
refs/heads/master
2021-07-22T20:48:47.566374
2017-10-31T00:25:11
2017-10-31T00:25:11
108,455,791
0
0
null
null
null
null
UTF-8
C++
false
false
639
h
/* Author: Laura Reilly Class: EGP 410-02 Assignment: Assignment 2- Steering behaviors Certification of Authenticity: I certify that this assignment is entirely my own work. */ #pragma once #include "FaceSteering.h" #include "SeekSteering.h" class SeekAndFace: public Steering { //so that wander steering can use our seek and face steering friend class WanderSteering; friend class WanderAndChaseSteering; public: SeekAndFace(const UnitID& ownerID, const Vector2D& targetLoc, const UnitID& targetID = INVALID_UNIT_ID); ~SeekAndFace(); protected: Steering* getSteering() override; FaceSteering* mpFace; SeekSteering* mpSeek; };
[ "laura.reilly@mymail.champlain.edu" ]
laura.reilly@mymail.champlain.edu
d1af248192ca1afa65ba9bf73f554d3bdd16aff4
c4617bb18dee000848aee5593e8668c3d1516b97
/Experiment_Controller_V6/Pixelfly/pixelfly_cam.cpp
aed359c205996cb0bd96c50179155cd98a12b42b
[]
no_license
liangqibox/Lithium6_ATI
469f688dbea6a128b53e159cc4b9e9562f0a9640
b81cea8895ed15db941019a8c00101499317b731
refs/heads/master
2020-12-26T10:32:39.611130
2020-01-31T18:26:17
2020-01-31T18:26:17
237,481,429
1
0
null
null
null
null
UTF-8
C++
false
false
6,607
cpp
#include "pixelfly_cam.h" #include <QDebug> Pixelfly_Cam::Pixelfly_Cam(QObject *parent) : QObject(parent){ wCamNum = 0; hBWConv = 0; wTriggerMode = 0x0000; dwDelay = 0; dwExposure = 100; wTimeBaseDelay = 0; wTimeBaseExposure = 0x0001; XRes = 1392; YRes = 1040; wBitPerPixel = 14; dwSize = XRes*YRes*2; wBinH = 1; wBinV = 1; ROIx = XRes; ROIy = YRes; strGeneral.wSize = sizeof(strGeneral); strGeneral.strCamType.wSize = sizeof(strGeneral.strCamType); strCamType.wSize = sizeof(strCamType); strSensor.wSize = sizeof(strSensor); strSensor.strDescription.wSize = sizeof(strSensor.strDescription); strSensor.strDescription2.wSize = sizeof(strSensor.strDescription2); strDescription.wSize = sizeof(strDescription); strTiming.wSize = sizeof(strTiming); strStorage.wSize = sizeof(strStorage); strRecording.wSize = sizeof(strRecording); BUFFER_MAXIMUM = 2; bufferCounter = 0; } Pixelfly_Cam::~Pixelfly_Cam() { Close_Camera(); } int Pixelfly_Cam::Open_Camera(){ int err = PCO_OpenCamera(&hCam, wCamNum); PCO_GetGeneral(hCam, &strGeneral); PCO_GetCameraType(hCam, &strCamType); PCO_GetSensorStruct(hCam, &strSensor); PCO_GetCameraDescription(hCam, &strDescription); PCO_GetTimingStruct(hCam, &strTiming); PCO_GetRecordingStruct(hCam, &strRecording); PCO_ResetSettingsToDefault(hCam); PCO_SetBitAlignment(hCam,0x0001); Set_Trigger(0x0000); Set_Exposure(100); //Start_Recording(); PCO_SensorInfo strSensorInfo; strSensorInfo.wSize = sizeof(PCO_SensorInfo); strSensorInfo.hCamera = hCam; strSensorInfo.iCamNum = 0; strSensorInfo.iConversionFactor = strSensor.strDescription.wConvFactDESC[0]; strSensorInfo.iDarkOffset = 30; strSensorInfo.iDataBits = strSensor.strDescription.wDynResDESC; strSensorInfo.iSensorInfoBits = CONVERT_SENSOR_UPPERALIGNED;// Input data is upper aligned strSensorInfo.strColorCoeff.da11 = 1.0; strSensorInfo.strColorCoeff.da12 = 0.0; strSensorInfo.strColorCoeff.da13 = 0.0; strSensorInfo.strColorCoeff.da21 = 0.0; strSensorInfo.strColorCoeff.da22 = 1.0; strSensorInfo.strColorCoeff.da23 = 0.0; strSensorInfo.strColorCoeff.da31 = 0.0; strSensorInfo.strColorCoeff.da32 = 0.0; strSensorInfo.strColorCoeff.da33 = 1.0; PCO_ConvertCreate(&hBWConv,&strSensorInfo,PCO_BW_CONVERT); return err; } int Pixelfly_Cam::Close_Camera(){ PCO_SetRecordingState(hCam,0x0000); PCO_CancelImages(hCam); PCO_ConvertDelete(hBWConv); Free_Buffer(); return PCO_CloseCamera(hCam); } int Pixelfly_Cam::Free_Buffer(){ for(int i=0 ;i<16; i++){ SHORT free = i; PCO_FreeBuffer(hCam,free); } //PCO_CancelImages(hCam); for(int i=0; i<wBuf.size(); i++){ delete wBuf.at(i); } images.clear(); bufferCounter=0; BufEvent.clear(); wBuf.clear(); sBufNr.clear(); return 0; } int Pixelfly_Cam::Set_Exposure(int usec){ dwExposure = usec; int err = PCO_SetDelayExposureTime(hCam,dwDelay,dwExposure,wTimeBaseDelay,wTimeBaseExposure); return err; } int Pixelfly_Cam::Set_Trigger(int mode){ wTriggerMode = mode; int err = PCO_SetTriggerMode(hCam,wTriggerMode); return err; } int Pixelfly_Cam::Allocate_Buffer(){ HANDLE BE = 0; SHORT Number = -1; WORD *Buffer = new WORD[uint(XRes)*uint(YRes)]; DWORD Size = uint(XRes)*uint(YRes)*sizeof(WORD); PCO_AllocateBuffer(hCam,&Number,Size,&Buffer,&BE); BufEvent.append(BE); sBufNr.append(Number); wBuf.append(Buffer); //PCO_AddBufferEx(hCam,DWORD(Number),DWORD(Number),Number,XRes,YRes,wBitPerPixel); //qDebug() << "Buffer add" << Number; return int(Number); } int Pixelfly_Cam::Start_Recording(int trigger){ //Free_Buffer(); //if(Open_Camera()==0){ Set_Trigger(trigger); PCO_GetCameraHealthStatus(hCam,&dwWarn,&dwError,&dwStatus); for(int i=0; i<BUFFER_MAXIMUM; i++)Allocate_Buffer(); bufferCounter = 0; PCO_ArmCamera(hCam); PCO_SetRecordingState(hCam,0x0001); return 0; //} //else return -1; } int Pixelfly_Cam::Stop_Recording(){ PCO_GetCameraHealthStatus(hCam,&dwWarn,&dwError,&dwStatus); //int err = Close_Camera(); int err = PCO_SetRecordingState(hCam,0x0000); Free_Buffer(); return err; } int Pixelfly_Cam::Wait_for_Image(int msec){ PCO_AddBufferEx(hCam,DWORD(0),DWORD(0),sBufNr.at(bufferCounter),XRes,YRes,wBitPerPixel); uint error = WaitForSingleObject(BufEvent.at(bufferCounter),msec); if(error == WAIT_TIMEOUT){ ResetEvent(BufEvent.at(bufferCounter)); bufferCounter++; if(bufferCounter>=BUFFER_MAXIMUM)bufferCounter = 0; emit Wait_time_out(); qDebug() << "Image" << bufferCounter << "Wait Timeout"; } else if(error == WAIT_FAILED){ ResetEvent(BufEvent.at(bufferCounter)); bufferCounter++; if(bufferCounter>=BUFFER_MAXIMUM)bufferCounter = 0; emit Wait_time_out(); qDebug() << "Image" << bufferCounter << "Wait Failed"; } else{ BYTE image_data_8[uint(XRes)*uint(YRes)]; QList<int> image_data; image_data.append(int(XRes)); image_data.append(int(YRes)); for(int y=1; y<int(YRes)+1; y++){ for(int x=0; x<int(XRes); x++){ image_data_8[x+XRes*(y-1)]= wBuf.at(bufferCounter)[x+XRes*(y-1)]/64; //image_data_8[x+XRes*(y-1)]= wBuf.at(bufferCounter)[x+XRes*(y-1)] & 0xFF; image_data.append(int(wBuf.at(bufferCounter)[x+XRes*(y-1)])); } } QImage image = QImage((uchar*)image_data_8,int(XRes),int(YRes),QImage::Format_Indexed8); ResetEvent(BufEvent.at(bufferCounter)); bufferCounter++; if(bufferCounter>=BUFFER_MAXIMUM)bufferCounter = 0; emit Image_receive(image); emit Image_data_receive(image_data); //images_data.append(image_data); } //images.append(image); if(images.size()>=BUFFER_MAXIMUM)images.removeFirst(); if(images_data.size()>=BUFFER_MAXIMUM)images_data.removeFirst(); return 0; } int Pixelfly_Cam::Force_Trigger(){ WORD triggered; PCO_ForceTrigger(hCam,&triggered); return triggered; } QImage Pixelfly_Cam::Read_Image(){ QImage image = QImage(XRes,YRes,QImage::Format_Indexed8); image.fill(Qt::blue); if(!images.isEmpty())return images.last(); return image; } int Pixelfly_Cam::Set_Buffer_Number(int n){ BUFFER_MAXIMUM = n; return BUFFER_MAXIMUM; }
[ "60519181+liangqibox@users.noreply.github.com" ]
60519181+liangqibox@users.noreply.github.com
f06d882f98682f035e95192bb6c6bf447a584183
2f874d5907ad0e95a2285ffc3592b8f75ecca7cd
/src/websocketpp/websocketpp/transport/base/connection.hpp
fb93a6ea2d2fae6f168ae3b21c9a1ddcb41b5855
[ "BSD-3-Clause", "Zlib", "MIT", "MIT-Wu", "ISC", "BSL-1.0" ]
permissive
dzcoin/DzCoinService
fb93809a37fad0a26bf26189266b44cf4c797865
b0056717d6bcc1741f4fb3f3f166cd8ce78393f9
refs/heads/master
2021-01-20T20:28:41.639585
2016-08-15T06:21:51
2016-08-15T06:21:51
65,678,478
0
0
null
null
null
null
UTF-8
C++
false
false
8,813
hpp
/* * copyright (c) 2014, peter thorson. all rights reserved. * * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * neither the name of the websocket++ project 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 peter thorson 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. * */ #ifndef websocketpp_transport_base_con_hpp #define websocketpp_transport_base_con_hpp #include <websocketpp/common/cpp11.hpp> #include <websocketpp/common/connection_hdl.hpp> #include <websocketpp/common/functional.hpp> #include <websocketpp/common/memory.hpp> #include <websocketpp/common/system_error.hpp> namespace websocketpp { /// transport policies provide network connectivity and timers /** * ### connection interface * * transport connection components needs to provide: * * **init**\n * `void init(init_handler handler)`\n * called once shortly after construction to give the policy the chance to * perform one time initialization. when complete, the policy must call the * supplied `init_handler` to continue setup. the handler takes one argument * with the error code if any. if an error is returned here setup will fail and * the connection will be aborted or terminated. * * websocket++ will call init only once. the transport must call `handler` * exactly once. * * **async_read_at_least**\n * `void async_read_at_least(size_t num_bytes, char *buf, size_t len, * read_handler handler)`\n * start an async read for at least num_bytes and at most len * bytes into buf. call handler when done with number of bytes read. * * websocket++ promises to have only one async_read_at_least in flight at a * time. the transport must promise to only call read_handler once per async * read. * * **async_write**\n * `void async_write(const char* buf, size_t len, write_handler handler)`\n * `void async_write(std::vector<buffer> & bufs, write_handler handler)`\n * start a write of all of the data in buf or bufs. in second case data is * written sequentially and in place without copying anything to a temporary * location. * * websocket++ promises to have only one async_write in flight at a time. * the transport must promise to only call the write_handler once per async * write * * **set_handle**\n * `void set_handle(connection_hdl hdl)`\n * called by websocket++ to let this policy know the hdl to the connection. it * may be stored for later use or ignored/discarded. this handle should be used * if the policy adds any connection handlers. connection handlers must be * called with the handle as the first argument so that the handler code knows * which connection generated the callback. * * **set_timer**\n * `timer_ptr set_timer(long duration, timer_handler handler)`\n * websocket++ uses the timers provided by the transport policy as the * implementation of timers is often highly coupled with the implementation of * the networking event loops. * * transport timer support is an optional feature. a transport method may elect * to implement a dummy timer object and have this method return an empty * pointer. if so, all timer related features of websocket++ core will be * disabled. this includes many security features designed to prevent denial of * service attacks. use timer-free transport policies with caution. * * **get_remote_endpoint**\n * `std::string get_remote_endpoint()`\n * retrieve address of remote endpoint * * **is_secure**\n * `void is_secure()`\n * whether or not the connection to the remote endpoint is secure * * **dispatch**\n * `lib::error_code dispatch(dispatch_handler handler)`: invoke handler within * the transport's event system if it uses one. otherwise, this method should * simply call `handler` immediately. * * **async_shutdown**\n * `void async_shutdown(shutdown_handler handler)`\n * perform any cleanup necessary (if any). call `handler` when complete. */ namespace transport { /// the type and signature of the callback passed to the init hook typedef lib::function<void(lib::error_code const &)> init_handler; /// the type and signature of the callback passed to the read method typedef lib::function<void(lib::error_code const &,size_t)> read_handler; /// the type and signature of the callback passed to the write method typedef lib::function<void(lib::error_code const &)> write_handler; /// the type and signature of the callback passed to the read method typedef lib::function<void(lib::error_code const &)> timer_handler; /// the type and signature of the callback passed to the shutdown method typedef lib::function<void(lib::error_code const &)> shutdown_handler; /// the type and signature of the callback passed to the interrupt method typedef lib::function<void()> interrupt_handler; /// the type and signature of the callback passed to the dispatch method typedef lib::function<void()> dispatch_handler; /// a simple utility buffer class struct buffer { buffer(char const * b, size_t l) : buf(b),len(l) {} char const * buf; size_t len; }; /// generic transport related errors namespace error { enum value { /// catch-all error for transport policy errors that don't fit in other /// categories general = 1, /// underlying transport pass through pass_through, /// async_read_at_least call requested more bytes than buffer can store invalid_num_bytes, /// async_read called while another async_read was in progress double_read, /// operation aborted operation_aborted, /// operation not supported operation_not_supported, /// end of file eof, /// tls short read tls_short_read, /// timer expired timeout, /// read or write after shutdown action_after_shutdown, /// other tls error tls_error, }; class category : public lib::error_category { public: category() {} char const * name() const _websocketpp_noexcept_token_ { return "websocketpp.transport"; } std::string message(int value) const { switch(value) { case general: return "generic transport policy error"; case pass_through: return "underlying transport error"; case invalid_num_bytes: return "async_read_at_least call requested more bytes than buffer can store"; case operation_aborted: return "the operation was aborted"; case operation_not_supported: return "the operation is not supported by this transport"; case eof: return "end of file"; case tls_short_read: return "tls short read"; case timeout: return "timer expired"; case action_after_shutdown: return "a transport action was requested after shutdown"; case tls_error: return "generic tls related error"; default: return "unknown"; } } }; inline lib::error_category const & get_category() { static category instance; return instance; } inline lib::error_code make_error_code(error::value e) { return lib::error_code(static_cast<int>(e), get_category()); } } // namespace error } // namespace transport } // namespace websocketpp _websocketpp_error_code_enum_ns_start_ template<> struct is_error_code_enum<websocketpp::transport::error::value> { static bool const value = true; }; _websocketpp_error_code_enum_ns_end_ #endif // websocketpp_transport_base_con_hpp
[ "dzgrouphelp@foxmail.com" ]
dzgrouphelp@foxmail.com
6b280af83ac36df1fe3f3deec17a627e7ef7f4db
6ba38fe94e7ea5146c633f56f59c0c3278d695a7
/plugins/core/FakeMonkey/FakeMonkeyEyeMovementChannel.h
d65d147c86611347430584625e00dfe161c71273
[ "MIT" ]
permissive
mworks/mworks
b49b721c2c5c0471180516892649fe3bd753a326
abf78fc91a44b99a97cf0eafb29e68ca3b7a08c7
refs/heads/master
2023-09-05T20:04:58.434227
2023-08-30T01:08:09
2023-08-30T01:08:09
2,356,013
14
11
null
2012-10-03T17:48:45
2011-09-09T14:55:57
C++
UTF-8
C++
false
false
1,702
h
/* * FakeMonkeyMovementChannel.h * FakeMonkey * * Created by bkennedy on 10/24/08. * Copyright 2008 mit. All rights reserved. * */ #ifndef FAKE_MONKEY_EYE_MOVEMENT_CHANNEL_H #define FAKE_MONKEY_EYE_MOVEMENT_CHANNEL_H #include "FakeMonkeyStatus.h" #include "MWorksCore/Clock.h" #include "MWorksCore/GenericVariable.h" using namespace mw; class mFakeMonkeyEyeMovementChannel : public mw::Component { protected: boost::shared_ptr <Variable> eye_h; boost::shared_ptr <Variable> eye_v; MWorksTime update_period; int samples_per_update; shared_ptr <Clock> clock; shared_ptr <boost::mutex> monkey_lock; shared_ptr <mFakeMonkeyStatus> status; shared_ptr <MWorksTime> saccade_duration; shared_ptr <MWorksTime> saccade_start_time; shared_ptr <float> saccade_start_h; shared_ptr <float> saccade_target_h; shared_ptr <float> saccade_start_v; shared_ptr <float> saccade_target_v; public: mFakeMonkeyEyeMovementChannel(const shared_ptr<Variable> &eye_h_variable, const shared_ptr<Variable> &eye_v_variable, const MWorksTime update_period_, const int samples_per_update_); MWorksTime getUpdatePeriod() const; virtual void setChannelParams(const shared_ptr <Clock> &a_clock, const shared_ptr <boost::mutex> monkey_lock_, const shared_ptr <mFakeMonkeyStatus> &status, const shared_ptr <MWorksTime> &saccade_start_time, const shared_ptr <MWorksTime> &saccade_duration, const shared_ptr <float> &saccade_start_h, const shared_ptr <float> &saccade_start_v, const shared_ptr <float> &saccade_target_h, const shared_ptr <float> &saccade_target_v); void update(); }; #endif
[ "cstawarz@mit.edu" ]
cstawarz@mit.edu
b774b820a90b7f3f51808c74bf4cdb47719d6e87
9173f55583dcade2474ffe3f0ba4f9e2692572d7
/src/syntax/ast/ast_range.hpp
e1f3e3d4515b0090df93e25830d0235f49a5e79c
[]
no_license
nyanzebra/cat
234888ecd6f6029358fe165e7ecd492a28b9217c
118ee41c98bd73173f9243c8997688346ccec5dc
refs/heads/master
2021-03-24T12:02:07.875373
2018-06-26T07:47:23
2018-06-26T07:47:23
118,212,345
0
0
null
null
null
null
UTF-8
C++
false
false
343
hpp
#pragma once #include "ast_expression.hpp" namespace syntax { class ast_range final : public ast_expression { private: protected: public: private: protected: public: std::ostream& print(std::ostream& stream, size_t tabs = 0) override { return stream; } void* accept(code_generator_visitor* visitor) override; }; } // namespace syntax
[ "robbaldwin95@gmail.com" ]
robbaldwin95@gmail.com
94f91e9ded6e7f10ce25e92be2059a9b4aa2974b
bdb2c303701fc74d2c2291bb9ee45e6ce0d0b80e
/scripts/src/aux.hpp
ddb273c8ab52deb3c59ef95c64bf9efc90509ec9
[]
no_license
simaomenesesjoao/kestrel
bde9c711fb9dc673dfdeb175882c9594e65a6009
ffdb305f7677971fcb27cab2e31ba17592195c4f
refs/heads/master
2021-06-14T20:33:12.567853
2021-05-26T22:54:29
2021-05-26T22:54:29
198,523,213
0
0
null
null
null
null
UTF-8
C++
false
false
2,994
hpp
double jackson(unsigned n, unsigned N); Eigen::Array<TR, -1, -1> calc_dos(Eigen::Array<TR, -1, -1> mu, Eigen::Array<TR, -1, -1> energies, std::string mode); void extended_euclidean(int a, int b, int *x, int *y, int *gcd); class variables{ public: double avg_time; unsigned iter; unsigned max_iter; bool has_initialized; bool has_finished; unsigned Lx, Ly; unsigned nx, ny; unsigned nrandom, ndisorder, nmoments; int mult, seed; double anderson_W; std::string status; variables(){ has_initialized = false; has_finished = false; status=""; } void update_status(){ std::string init = "0"; std::string fin = "0"; if(has_initialized) init = "1"; if(has_finished) fin = "1"; //std::cout << "before string\n" << std::flush; status = init + " " + fin + " running " + "Lx=" + std::to_string(Lx) + " " + "Ly=" + std::to_string(Ly) + " " + "nx=" + std::to_string(nx) + " " + "ny=" + std::to_string(ny) + " " + "NR=" + std::to_string(nrandom) + " " + "ND=" + std::to_string(ndisorder) + " " + "N=" + std::to_string(nmoments) + " " + "B=" + std::to_string(mult) + " " + "S=" + std::to_string(seed) + " " + "W=" + std::to_string(anderson_W) + " " + "i=" + std::to_string(iter) + " " + "M=" + std::to_string(max_iter) + " " + "T=" + std::to_string(avg_time); }; void update_status(std::string custom){ status = custom; } }; struct parameters{ unsigned Lx, Ly; unsigned nx, ny; unsigned nrandom, ndisorder, nmoments; int mult, seed; double anderson_W; Eigen::Array<TR, -1, -1> energies; unsigned NEnergies; bool found_NEnergies; bool found_energies; bool output_energies; bool need_write; std::string saveto, readfrom; bool need_moremoments; unsigned moremoments; bool need_read; std::string filename_read; std::string filename_write; bool need_print_to_file, need_print_to_cout, need_print; bool need_log_status; std::string filename_status; }; void parse_input(int argc, char **argv, parameters*); void load(std::string, KPM_vector *, KPM_vector *, Eigen::Array<TR, -1, -1> *); void print_ham_info(parameters P); void print_cheb_info(parameters P); void print_compilation_info(); void print_magnetic_info(parameters, int, int, int); void print_output_info(parameters); void print_restart_info(parameters); void print_log_info(parameters); void print_dos(parameters P, unsigned N_lists, unsigned *nmoments_list, Eigen::Array<TR, -1, -1> *dos);
[ "simao_meneses_joao@hotmail.com" ]
simao_meneses_joao@hotmail.com
4810d62f56d1fb38eaf957308dbeba427f6ef4d8
bc1a36a31673a24228f52bc48069b1b86c07e6b4
/picturepushbutton.h
0ed63c1cfb38b7e40557db9c079b7a5ce28d1e98
[]
no_license
lgbo-ustc/videoplayer
9418ebf7dbea1c55044c1cb72507815d1f74758d
e2c1b709b6cfca689f39eaf6c9ac468fb286be21
refs/heads/master
2021-01-10T21:59:13.077778
2013-08-10T08:46:17
2013-08-10T08:46:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
390
h
#ifndef PICTUREPUSHBUTTON_H #define PICTUREPUSHBUTTON_H #include <QPushButton> class PicturePushButton : public QPushButton { Q_OBJECT QPixmap pixmap; QIcon icon; public: explicit PicturePushButton(QWidget *parent = 0); void setPixmapPath(const QString &path); void setSizeExt(const QSize &size); signals: public slots: }; #endif // PICTUREPUSHBUTTON_H
[ "lgbo.ustc@gmail.com" ]
lgbo.ustc@gmail.com