blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
0e07a078f5854955f9bfdf76586395648c1e2725
347308b1938d3ec47ebf97bbfca4c8bc40bc8980
/20200731_I/I5_신희주_20200804.cpp
fedbec9a8c06fc7f110afcde1111298bf1c8914f
[]
no_license
heejuShin/2020PPS
8fbd407be218ccbfce323b1a1239bd80c14d03de
4be47d369e45f042267f134d74b9ad75db980ccd
refs/heads/master
2022-11-29T00:02:36.595770
2020-08-11T03:00:27
2020-08-11T03:00:27
281,132,022
0
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
I5_신희주_20200804.cpp
#include <iostream> #include <string> using namespace std; int main() { int N; cin >> N; string data[14]={"baby", "sukhwan", "tururu", "turu", "very", "cute", "tururu", "turu", "in", "bed", "tururu", "turu", "baby", "sukhwan"}; N--; int a, b; a=N%14; if(a==2 || a==3 || a==6 || a==7 || a==10 || a==11){ b=N/14; if((a%2==0&&b<3)||(a%2==1&&b<4)) for(int i=0; i<b; i++){ data[a].append("ru"); } else{ data[a]="tu+ru*"; if(a%2==0) data[a].append(to_string(b+2)); else data[a].append(to_string(b+1)); } } cout << data[a]; }
b36d90ca349c4c0da0c295cdcd0693cdba12b2fe
facd1a0521ba65677176adbbd3ceda766ce191a8
/OGLWin32/OGLRectangle3D.cpp
6daf331b3c0e9cccd5905c122eb81d10fe4ce91c
[]
no_license
Podginator/OGLVisualizer
2f951ad27232e2f7fbc9266c662a54c400985140
0db1be1beb615d31e8bb10d80aa56c19aa04a1b6
refs/heads/master
2021-01-23T13:22:46.119709
2015-01-13T12:42:40
2015-01-13T12:42:40
25,320,356
0
0
null
null
null
null
UTF-8
C++
false
false
1,688
cpp
OGLRectangle3D.cpp
#include "OGLRectangle3D.h" OGLRectangle3D::OGLRectangle3D(const Vec3f& position, const Color& color, float height, float width) : _height(height), _width(width), OGLShape3D(position, color, 4, GL_QUADS) { //init the OGLRectangle to a fixed size vertexs[0] = Vec3f(position); vertexs[1] = Vec3f(position.X() + width, position.Y(), position.Z()); vertexs[2] = Vec3f(position.X() + width, position.Y() + height, position.Z()); vertexs[3] = Vec3f(position.X(), position.Y() + height, position.Z()); } OGLRectangle3D::~OGLRectangle3D(){} void OGLRectangle3D::CenterRotate(float deg) { //Move them towards the center. for (size_t i = 0; i < _size; i++) { vertexs[i] -= Vec3f((_width*0.5f), (_height*0.5f), 0); } Matrix<float> rotMat = MathHelper::Matrix2Dtransform(deg); for (size_t i = 0; i < _size; i++) { //Move it to the center. vertexs[i] -= _position; //Then rotate. Vec2f Temp = rotMat * Vec2f(vertexs[i].X(), vertexs[i].Y()); vertexs[i] = Vec3f(Temp.X(), Temp.Y(), _position.Z()); //Then move back. vertexs[i] += _position; vertexs[i].Z(_position.Z()); } for (size_t i = 0; i < _size; i++) { vertexs[i] += Vec3f((_width*0.5f), (_height*0.5f), 0); } //We've changed the shape, so we have to reget the binding box. } void OGLRectangle3D::Scale(float scale) { for (size_t i = 0; i < _size; i++) { vertexs[i] -= Vec3f((_width*0.5f), (_height*0.5f), 0); } OGLShape3D::Scale(scale); for (size_t i = 0; i < _size; i++) { vertexs[i] += Vec3f((_width*0.5f), (_height*0.5f), 0) * scale; } }
801f96282cf66c0f886a8cb47e819e202e4c0241
e615577da886371cdafc5359e70b5d311ca297e8
/chp10-vector/chp10-vector/Character.cpp
e6f741e178e9b7313881f4bbc46bb6770f564d94
[ "MIT" ]
permissive
cmacdougald/2020SPRING-ITSE1307
d9163eeb05a566de900e7bb3a720912fadb826c3
c7d941deace980fd99dfadcd55518f75b3d20684
refs/heads/master
2020-12-20T01:48:33.922482
2020-05-07T22:14:50
2020-05-07T22:14:50
235,920,889
0
0
null
null
null
null
UTF-8
C++
false
false
1,445
cpp
Character.cpp
#include "stdafx.h" #include "Character.h" Character::Character() { setName("Blank"); setMana(50); setHealth(100); } Character::~Character() { } void Character::setMana(int intpMana) { this->intMana = (intpMana > 100 ? 100 : (intpMana < 0 ? 0 : intpMana)); } int Character::getMana() { return this->intMana; } void Character::setHealth(int intpHealth) { this->intHealth = (intpHealth > 200 ? 200 : (intpHealth < 0 ? 0 : intpHealth)); } int Character::getHealth() { return this->intHealth; } std::string Character::toString() { return this->getName() + ": M(" + std::to_string(getMana()) + ") H(" + std::to_string(getHealth()) + ")"; } void Character::setName(std::string strpName) { this->strName = strpName; } std::string Character::getName() { return this->strName; } void Character::inputName() { std::string strTemp = ""; std::cout << "Please enter a name: "; std::cin >> strTemp; setName(strTemp); } void Character::inputMana() { int intTempMana = 0; std::cout << "Please enter " + getName() + "'s mana: "; std::cin >> intTempMana; setMana(intTempMana); } void Character::inputHealth() { int intTempHealth = 0; std::cout << "Please enter " + getName() + "'s health: "; std::cin >> intTempHealth; setHealth(intTempHealth); } void Character::input() { inputName(); inputHealth(); inputMana(); }
d86239bce3305d71e9d75eb47b959976208ae1e1
e98bfb9a0bbd0fe76a9987e1b6abddaaf9af5ed8
/Tutorial18/lightmapShaderClass.h
931da129daa11a7e8426142670b867d7d5a3aab6
[]
no_license
dhcdht/dx11tutorial
247a37c62b9188dc014783451306bad9a49b0126
a14b2757cd03b0df7f62781a212b0e37f33d8bbc
refs/heads/master
2016-09-06T16:16:51.453109
2012-05-16T02:21:59
2012-05-16T02:21:59
4,133,094
1
2
null
null
null
null
UTF-8
C++
false
false
1,233
h
lightmapShaderClass.h
/******************************************************************** created: 2012/05/14 created: 14:5:2012 21:08 filename: D:\Documents\C\DX11Tutorial\Tutorial18\lightmapShaderClass.h file path: D:\Documents\C\DX11Tutorial\Tutorial18 file base: lightmapShaderClass file ext: h author: dhc purpose: *********************************************************************/ #ifndef lightmapShaderClass_h__ #define lightmapShaderClass_h__ #include <D3D11.h> #include <D3DX10math.h> #include <D3DX11async.h> #include <fstream> using namespace std; class LightmapShaderClass { private: struct MatrixBufferType { D3DXMATRIX world; D3DXMATRIX view; D3DXMATRIX projection; }; public: LightmapShaderClass(); LightmapShaderClass(const LightmapShaderClass &other); ~LightmapShaderClass(); bool initialize(ID3D11Device *aD3DDevice, HWND aHwnd); void shutdown(); bool render(ID3D11DeviceContext *aD3DDeviceContext, int aIndexCount, D3DXMATRIX aWorldMatrix, D3DXMATRIX aViewMatrix, D3DXMATRIX aProjectionMatrix, ID3D11ShaderResourceView **aTextures); private: bool initializeShader(ID3D11Device *aD3DDevice, HWND aHwnd) }; #endif // lightmapShaderClass_h__
8f83596ccca3330978f8d040e638a3b35d2c0594
65025edce8120ec0c601bd5e6485553697c5c132
/Engine/foundation/memory/win360/win360memoryconfig.cc
3e6e5731d4277cda408b5ccfc70215d67511806e
[ "MIT" ]
permissive
stonejiang/genesis-3d
babfc99cfc9085527dff35c7c8662d931fbb1780
df5741e7003ba8e21d21557d42f637cfe0f6133c
refs/heads/master
2020-12-25T18:22:32.752912
2013-12-13T07:45:17
2013-12-13T07:45:17
15,157,071
4
4
null
null
null
null
UTF-8
C++
false
false
6,310
cc
win360memoryconfig.cc
/**************************************************************************** Copyright (c) 2008, Radon Labs GmbH Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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. ****************************************************************************/ #if WIN32 #include "stdneb.h" #include "memory/win360/win360memoryconfig.h" #include "core/sysfunc.h" #if NEBULA3_OBJECTS_USE_MEMORYPOOL #include "memory/poolarrayallocator.h" #endif namespace Memory { HANDLE volatile Heaps[NumHeapTypes] = { NULL }; #if NEBULA3_OBJECTS_USE_MEMORYPOOL PoolArrayAllocator* ObjectPoolAllocator = 0; #endif //------------------------------------------------------------------------------ /** This method is called once at application startup from Core::SysFunc::Setup() to setup the various Nebula3 heaps. */ void SetupHeaps() { // setup global heaps const SIZE_T megaByte = 1024 * 1024; const SIZE_T kiloByte = 1024; unsigned int i; for (i = 0; i < NumHeapTypes; i++) { n_assert(0 == Heaps[i]); SIZE_T initialSize = 0; SIZE_T maxSize = 0; bool useLowFragHeap = false; switch (i) { case DefaultHeap: case ObjectHeap: case ObjectArrayHeap: case ScaleformHeap: initialSize = 4 * megaByte; useLowFragHeap = true; break; case ResourceHeap: case PhysicsHeap: case AppHeap: case NetworkHeap: initialSize = 8 * megaByte; break; case ScratchHeap: initialSize = 8 * megaByte; break; case StringDataHeap: initialSize = 2 * megaByte; useLowFragHeap = true; break; case StreamDataHeap: initialSize = 16 * megaByte; break; case Xbox360GraphicsHeap: case Xbox360AudioHeap: // the special Xbox360 write combined heap, this is handled as a // special case in Memory::Alloc() initialSize = 0; break; default: Core::SysFunc::Error("Invalid heap type in Memory::SetupHeaps() (win360memoryconfig.cc)!"); break; } if (0 != initialSize) { Heaps[i] = HeapCreate(0, initialSize, maxSize); if (useLowFragHeap) { #if __WIN32__ // enable the Win32 LowFragmentationHeap ULONG heapFragValue = 2; HeapSetInformation(Heaps[i], HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue)); #endif } } else { Heaps[i] = 0; } } #if NEBULA3_OBJECTS_USE_MEMORYPOOL // setup the RefCounted pool allocator // HMM THESE NUMBERS ARE SO HIGH BECAUSE OF GODSEND... #if NEBULA3_DEBUG uint objectPoolSizes[PoolArrayAllocator::NumPools] = { 128 * kiloByte, // 28 byte blocks 4196 * kiloByte, // 60 byte blocks 512 * kiloByte, // 92 byte blocks 1024 * kiloByte, // 124 byte blocks 128 * kiloByte, // 156 byte blocks 128 * kiloByte, // 188 byte blocks 128 * kiloByte, // 220 byte blocks 2048 * kiloByte // 252 byte blocks }; #else uint objectPoolSizes[PoolArrayAllocator::NumPools] = { 2048 * kiloByte, // 28 byte blocks 2048 * kiloByte, // 60 byte blocks 1024 * kiloByte, // 92 byte blocks 1024 * kiloByte, // 124 byte blocks 128 * kiloByte, // 156 byte blocks 128 * kiloByte, // 188 byte blocks 2048 * kiloByte, // 220 byte blocks 2048 * kiloByte // 252 byte blocks }; #endif ObjectPoolAllocator = n_new(PoolArrayAllocator); ObjectPoolAllocator->Setup("ObjectPoolAllocator", ObjectHeap, objectPoolSizes); #endif } //------------------------------------------------------------------------------ /** */ const char* GetHeapTypeName(HeapType heapType) { switch (heapType) { case DefaultHeap: return "Default Heap"; case ObjectHeap: return "Object Heap"; case ObjectArrayHeap: return "Object Array Heap"; case ResourceHeap: return "Resource Heap"; case ScratchHeap: return "Scratch Heap"; case StringDataHeap: return "String Data Heap"; case StreamDataHeap: return "Stream Data Heap"; case PhysicsHeap: return "Physics Heap"; case AppHeap: return "App Heap"; case NetworkHeap: return "Network Heap"; case Xbox360GraphicsHeap: return "Xbox360 Graphics Heap"; case Xbox360AudioHeap: return "Xbox360 Audio Heap"; case ScaleformHeap: return "Scaleform Heap"; default: Core::SysFunc::Error("Invalid HeapType arg in Memory::GetHeapTypeName()! (win360memoryconfig.cc)"); return 0; } } } // namespace Win360 #endif
ea796541d12c320af2f7b5e9c42e1566da8375e3
c5cb7c000bda758872b8f66b8b8b8f3c448d350c
/BinarySearch/BinarySearch/BinarySearch.cpp
61d94437b5de6e69e4be58dafda5fa72a76d3c7b
[]
no_license
moldypeach/Generic-Binary-Search
a796487832ed7294affd41a9660dee08e5c21fd4
9d60b5a9248004ef46d4c919a14dae639fa6ab0e
refs/heads/master
2020-05-20T02:34:14.493524
2014-04-24T13:47:23
2014-04-24T13:47:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,626
cpp
BinarySearch.cpp
/* * FILE: BinarySearch.cpp * LAST REVISED: 28 Jan 2014 * AUTHOR: Todd Parker * EMAIL: todd.i.parker@maine.edu * COURSE: CIS354 - Algorithms and Data Structures * * BinarySearch.cpp creates three static arrays with 10 items of data types int, double, and string. It then calls * static methods from the BinarySearch header file to print the unsorted array, sort it, and then print the sorted * array. It then prompts the user to search for a key within the sorted array, and returns either the index where it * was found or a key not found message. */ #include "BinarySearch.h" #include "SignatureBlock.h" int main() { // Declare three arrays of data types int, double, and string for testing binarySearch generic template int list[] = {9, 10, 15, 5, 0, 100, 250, 76, 1212, 1}; double list1[] = {0.125, 99.99, .314, 5.93, 25, 25.01, 1111.11, 12.95, 30.5, 66.6}; string list2[] = {"out", "best", "programming", "agony", "i", "describes", "live", "school", "work", "experiences"}; int key = 0; // store the user-specified integer key double key1 = 0; // store the user-specified double key string key2 = ""; // store the user-specified string key int keyLocation = 0; // store the location result of user-seached key int menuChoice = 0; // store the user-entered menu choice char exitLoop = 'N'; // control exit of menu loop do { SignatureBlock::printHeader(); // Print signature block cout << "Which array would you like to test generic Binary Search on?" << endl; cout << "\tInteger -- 1" << endl; cout << "\tDouble -- 2" << endl; cout << "\tString -- 3" << endl; cout << "Choice: "; cin >> menuChoice; // get menu option switch (menuChoice) { case 1: { cout << "\n10 element Integer array" << endl; BinarySearch<int>::copyArray(list,10); // make a copy of integer array and sort it cout << "Please enter a key to search for: "; cin >> key; cout << endl; keyLocation = BinarySearch<int>::binarySearch(key); // search int array for entered key if (keyLocation != -1) cout << "The index of " << key << " was found at index " << keyLocation << endl; else cout << "The key " << key << " was NOT found." << endl; break; } case 2: { cout << "\n10 element Double array" << endl; BinarySearch<double>::copyArray(list1,10); // make a copy of double array and sort it cout << "Please enter a key to search for: "; cin >> key1; cout << endl; keyLocation = BinarySearch<double>::binarySearch(key1); // search double array for entered key if (keyLocation != -1) cout << "The index of " << key1 << " was found at index " << keyLocation << endl; else cout << "The key " << key1 << " was NOT found." << endl; break; } case 3: { cout << "\n10 element String array" << endl; BinarySearch<string>::copyArray(list2,10); // make copy of string array and sort it cout << "Please enter a key to search for: "; cin >> key2; cout << endl; keyLocation = BinarySearch<string>::binarySearch(key2); // search string array for entered key if (keyLocation != -1) cout << "The index of " << key2 << " was found at " << keyLocation << endl; else cout << "The key " << key2 << " was NOT found." << endl; break; } default: { cout << "I thought we were friends... Why are you trying to break me?" << endl; } } // end switch cout << "Exit Program? (Y | N): "; cin >> exitLoop; cout << endl; } while ( exitLoop == 'N' ); // end do...while loop getchar(); // pause window before exiting return 0; } // end main
a4056ec946d79db46cab44763882b0acca0e4b4b
99a9d3e7e8e4e4fa2cbed59bda81d258e7f0572c
/implement/rmWiener/WienerFilter.h
34153aedac3d140adef9e77adca84358df4a6716
[]
no_license
duscha/RM
06c0011865849d04aaf569ef53e9d0d3f850e6ee
c7452e66b25721cb21407e2ac628ce80e67be65a
refs/heads/master
2021-01-13T09:09:28.001687
2010-06-25T16:59:19
2010-06-25T16:59:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,422
h
WienerFilter.h
// Standard header files #include <iostream> #include <string> #include <vector> #define _ITPP_ // set for the moment compilation to _ITPP_ #ifdef _ITPP_ // IT++ header files #include <itpp/itbase.h> #include <itpp/itcomm.h> #elif _ARMADILLO_ #include <armadillo> #endif // RM header files #include "rmNoise.h" using namespace std; using namespace itpp; #define DEBUG 1 //! statistical limit for number of line of sights before attempting a S(i,j) iteration #define LOSLIMIT 100 namespace RM { // namespace RM /*! \class wienerfilter \ingroup RM \brief Wiener Filter class \author Sven Duscha (sduscha@mpa-garching.mpg.de) \date 15-06-2009 (Last change: 09-11-2009) */ class wienerfilter : public rmNoise { public: #ifdef _ITPP_ //! Signal matrix (complex double) cmat S; //! System response matrix (complex double) cmat R; //! (rms) noise matrix (real double) mat N; // cmat N; // (rms) noise matrix (complex double) cvec j; // information source vector complex double vector ITTP type //! Data vector cvec d; //! Signal vector cvec s; // Intermediate products cmat W; // W = R.H()*N cmat M; // M = W*R //! Final Wiener filter matrix: WF=(inv(S) + M)*W cmat WF; //! Propagator = error of final map, intermediate result (complex double) cmat D; //! Map error (each Faraday Depth) cvec maperror; //! Instrumental fidelity (complex double) cmat Q; //! Reconstructed map vector m cvec m; #elif _ARMADILLO_ cx_mat S; cx_mat R; mat N; vector<complex<double>> j; vector<complex<double>> d; vector<complex<double>> s; cx_mat W cx_mat M; cx_mat WF; cx_mat D; vector<complex<double>> maperror; cx_mat Q; vector<complex<double>> m; #endif // Observational parameters //! Epsilon zero emissivity at frequency nu zero double epsilon_0; //! Frequency nu for which emissivity epsilon zero applies double nu_0; //! Spectral dependence power law factor alpha double alpha; double variance_s; // standard deviation of s, complex (since both for Q and U) double lambda_phi; // lambda nu for spectral dependence coherence length vector<double> lambdas; // lambdas in data vector<double> lambdasquareds; // lambda squareds in data vector<double> delta_lambdasquareds; // delta lambda squareds distance between lambda squareds vector<double> frequencies; // frequencies present in observation vector<double> delta_frequencies; // delta frequencies distances between frequencies vector<double> bandwidths; // if we have bandwidths given, different from delta frequencies vector<double> faradaydepths; // Faraday depths to probe for vector<double> delta_faradaydepths; // delta faradays distance between Faraday depths // Instrumental parameters vector<complex<double> > bandpass; // bandpass factor for each frequency unsigned long maxiterations; // maximum number of iterations to perform unsigned long number_of_iterations; // number of iterations in this Wiener filtering double rmsthreshold; // rms threshold till iterations stop // String constants for memmber attributes (mainly file access names, initialized with default names) string Sfilename; // filename for S matrix file string Rfilename; // filename for R matrix file string Nfilename; // filename for N matrix file string Dfilename; // filename for D matrix file string Qfilename; // filename for Q matrix file string Sformula; // formula for initial S guess string Stype; // type of spectral dependency //***************************************************** // // Wiener filtering algorithm functions // //***************************************************** void createNoiseMatrix(double noise); // create an instrument/simulated noise matrix, complex due to P=Q+iU and noise might differ in Q and U void createNoiseMatrix(vector<double> &noiseperchan); // create a noise matrix with rms noise for each frequency channel void createResponseMatrix(); // create the Response matrix frequencies as No. of columns, Faraday depths as No. of rows void createResponseMatrixIntegral(); // integral form of Response matrix void createSMatrix(const string &); // initial guess for the S matrix, Types: "whitesignal", "gaussian", "powerlaw", "deconvolution" void iterateSMatrix(); // adjust S matrix from result of Wiener filtering // Algorithm functions void computeVariance_s(); // compute dispersion_s (taken from data vector d) void computej(); // R^(dagger)N^(inverse)*d void computeD(); // D=R^(dagger)N^(inverse)R void computeQ(); // compute Q=RSR^(dagger) // Compute intermediate product matrices void computeW(); // W = R^{dagger}*N^{inverse} void computeM(); // M = W*R void reconstructm(); // function to reconstruct the map m // Functions to free memory of matrices that are not needed anymore void deleteN(); void deleteR(); void doWienerFiltering(); // do internal Wiener filtering (D, j etc.) #ifdef _ITPP_ void applyWF(const cvec &data, cvec &map); // apply WF-Matrix to data vector #elif _ARMADILLO_ void applyWF(const std::vector<std::complex<double> > &data, std::vector<std::complex<double> > &map); #endif public: wienerfilter(); // default constructor wienerfilter(int nfreqs, int nfaradays); wienerfilter(int nfreqs, vector<double> &faradays); wienerfilter(int nfreqs, int nfaradays, std::string &formula); ~wienerfilter(); // destructor // perform Wiener Filtering on the wienerfilter object void wienerFiltering(double noise, const std::string &type="white"); void wienerFiltering(double noise, double lambda_phi, double alpha=0.7); void wienerFiltering(double noise, double lambda_phi, double alpha, const std::string &type="white"); void wienerFiltering(double noise, double lambda_phi, double epsilon_zero, double alpha=0.7); void wienerFiltering(double noise, double lambda_phi, double epsilon_zero, double alpha, const std::string &type="white"); void wienerFiltering(const vector<double> &noise, const std::string &type="white"); void wienerFiltering(const vector<double> &noise, double lambda_phi, double alpha=0.7); void wienerFiltering(const vector<double> &noise, double lambda_phi, double alpha, const std::string &type="white"); void wienerFiltering(const vector<double> &noise, double epsilon_zero, double lambda_phi, double alpha=0.7); void wienerFiltering(const vector<double> &noise, double epsilon_zero, double lambda_phi, double alpha, const std::string &type); void computeWF(); //! compute Wiener Filter operator // Member access functions (D and Q are results and handeled below) // double getVariance_s(void); // for debugging get variance_s void setVariance_s(double s); // debug: set variance_s double getLambdaPhi(); // get lambda_phi void setLambdaPhi(double lambdaphi); // set lambda_phi vector<double> getLambdas(); // get lambdas vector void setLambdas(const vector<double> &lambdas); // set lambdas vector vector<double> getLambdaSquareds(); // get lambda squareds used in data void setLambdaSquareds(vector<double> &lambdasquareds); // set lambda squareds used in data vector<double> getDeltaLambdaSquareds(); // get the delta Lambda Squareds associated with the data void setDeltaLambdaSquareds(const vector<double> &delta_lambdasqs); // set the delta Lambda Squareds associated with the data vector<double> getFrequencies(); // get frequencies vector wth observed frequencies void setFrequencies(const vector<double> &freqs); // set frequencies vector with to observed frequencies vector<double> getDeltaFrequencies(); // get delta frequencies distances between observed frequencies void setDeltaFrequencies(const vector<double> &deltafreqs); // set delta frequencies distances between observed frequencies vector<double> getFaradayDepths(); // get the Faraday depths to be probed for void setFaradayDepths(const vector<double> &faraday_depths); // set the Faraday depths to be probed for vector<complex<double> > getBandpass(); // get bandpass for each frequency void setBandpass(const vector<complex<double> > &); // set bandpass for each frequency double getVariance_s(); // get dispersion_s (no set function only compute above) double getEpsilonZero(); // get epsilon zero value of spectral dependence void setEpsilonZero(double); // set epsilon zero value of spectral dependence double getNuZero(); // get nu zero value of spectral dependence void setNuZero(double); // set nu zero value of spectral dependence double getAlpha(); // get alpha power law exponent of spectral dependence void setAlpha(double); // set alpha power law exponent of spectral dependence #ifdef _ITPP_ cmat getSignalMatrix(); // get S signal covariance matrix cmat getResponseMatrix(); // get R response matrix mat getNoiseMatrix(); // get N noise matrix cvec getInformationSourceVector(); // get j information source vector cmat getD(); // D cvec computeMapError(); // Diagonal elements of D matrix // cvec getMapError(); // return maperror from class attributes vector<complex<double> > getMapError(); cmat getInstrumentFidelity(); // Q cmat getWienerFilter(); // WF final Wiener Filter matrix operator cvec getDataVector(); // get data in data vector d void setDataVector(cvec &); // set data vector to content of cvec &data void setDataVector(vector<complex<double> > &); // allows to input external data into data vector cvec getSignalVector(); // get the signal vector void setSignalVector(cvec &); // DEBUG: this function is only for debugging! #elif _ARMADILLO_ cx_mat getSignalMatrix(); // get S signal covariance matrix cx_mat getResponseMatrix(); // get R response matrix mat getNoiseMatrix(); // get N noise matrix vector<complex<double> > getInformationSourceVector(); // get j information source vector cx_mat getD(); // D vector<complex<double> > computeMapError(); // Diagonal elements of D matrix vector<complex<double> > getMapError(); cx_mat getInstrumentFidelity(); // Q cx_mat getWienerFilter(); // WF final Wiener Filter matrix operator vector<complex<double> > getDataVector(); // get data in data vector d void setDataVector(vector<complex<double> > &); // set data vector to content of cvec &data void setDataVector(vector<complex<double> > &); // allows to input external data into data vector vector<complex<double> > getSignalVector(); // get the signal vector void setSignalVector(vector<complex<double> > &); #endif unsigned long getMaxIterations(); // get the limit of maximum iterations void setMaxIterations(unsigned long maxiterations); // set the limit of maximum iterations unsigned long getNumberOfIterations(); // get current number of iterations string getSformula(); // get S matrix formula used for spectral dependence string getStype(); // get type of spectral dependence double getRMSthreshold(); // get RMS limit threshold void setRMSthreshold(double rms); // set RMS limit threshold // File access functions for configuration and algorithm parameters etc. void readConfigFile(const string &filename); // read configuration from file void writeConfigFile(const string &filename); // write configuration to file void readSignalMatrix(const string &filename); // read Signal matrix from .it file void writeSignalMatrix(const string &filename); // write Signal matrix to .it file void readNoiseMatrix(const string &filename); // read Noise matrix from .it file void writeNoiseMatrix(const string &filename); // write Noise matrix to .it file void readResponseMatrix(const string &filename); // read Response matrix from .it file void writeResponseMatrix(const string &filename); // write Response matrix to .it file void readPropagatorMatrix(const string &filename); // read Propagator matrix from .it file void writePropagatorMatrix(const string &filename); // write Propagator matrix to .it file void readInstrumentFidelityMatrix(const string &filename); // read Instrument fidelity matrix from .it file void writeInstrumentFidelityMatrix(const string &filename); // write Instrument fidelity matrix to .it file void saveAllMatrices(); // save all matrices to .it files //************************************************************************************ // // Data I/O functions to convert to STL vector<double> and vector<complex<double> > // //************************************************************************************ void getData(vector<complex<double> > &cmplx); // get data from STL complex vector void getData(vector<double> &re, vector<double> &im); // get data from real and imaginary STL vectors void exportSignal(vector<complex<double> > &cmplx); // export signal to STL complex vector void exportSignal(vector<double> &re, vector<double> &im); // export signal to real and imaginary STL vectors //************************************************************************************ // // Functions to read in simulated data from files // //************************************************************************************ void readLambdaSqFromFile(const std::string &filename); // read lambda squareds from a file void readLambdaSqAndDeltaLambdaSqFromFile(const std::string &filename); void readSimDataFromFile(const std::string &filename); // read lambda squareds and complex intensity from file void read4SimDataFromFile(const std::string &filename); // read complete set of simulated data: lambdasq, delta lambda sq and complex intensity from file void read4SimFreqDataFromFile(const std::string &filename); // read complete frequency (!) set of simulated data: frequencies, delta frequencies and complex intensity void readSignalFromFile(const std::string &filename); // read a real signal from file void readFaradayDepthsFromFile(const std::string &filename); void readRealDataFromFile(const std::string &filename); // read real data from a file void readDataFromFile(const std::string &filename); // read a data from a file and write it into the data vector //************************************************************************************ // // ASCII (GNUplot) format writing functions // //************************************************************************************ #ifdef _ITPP_ void writeASCII(const vector<double>, const cvec &v, const std::string &filename); // STL vector and a complex ITPP vector void writeASCII(const vec &v, const std::string &filename); // output a vector to an ASCII file void writeASCII(const cvec &v, const std::string &filename); // output a complex vector to an ASCII file // ASCII (GNUplot) with coordinates void writeASCII(const vec &coord, const vec &v, const std::string &filename); // output a coordinate vector and a vector to an ASCII file void writeASCII(const vec &coord, const cvec &v, const std::string &filename); // output a coordinate vector and a vector to an ASCII file void writeASCII(const cmat M, const std::string &filename); // output a complex matrix M to GNUplot ASCII format void writeASCII(const cmat M, const std::string &part, const std::string &filename); // output the real or imaginary part of a complex matrix to GNUplot ASCII format // === Mathematica text format output routines ================================ void writeMathematica (cmat M, const std::string &part, const std::string &filename); #elif _ARMADILLO_ void writeASCII(vector<double> &v, vector<complex<double> > &cv, const std::string &filename); // output a STL vector // ASCII (GNUplot) with coordinates void writeASCII(cx_mat M, const std::string &filename); // output a complex matrix M to GNUplot ASCII format // === Mathematica text format output routines ================================ void writeMathematica (cx_mat M, const std::string &part, const std::string &filename); #endif void writeASCII(vector<double> &v, vector<complex<double> > &cv, const std::string &filename); // output a STL vector void writeASCII(vector<double> &v, const std::string &filename); // output a STL vector void writeASCII(vector<double> &v1, vector<double> &v2, const std::string &filename); // output a STL void writeASCII(mat M, const std::string &filename); // output a real matrix M to GNUplot ASCII format void writeMathematica (mat M, const string &filename); void writeASCII(vector<double> &v, const std::string &filename); // output a STL vector void writeASCII(vector<double> &v1, vector<double> &v2, const std::string &filename); // output a STL // High-level output functions working directly on class attributes: data map etc. // In the implementation these distinguish internally between _ITPP_ and _ARMADILLO_ // but the function prototype stays the same of course // //! Write data vector d to an ASCII file void writeDataToFile(const std::string &filename); //! Write signal vector s to an ASCII file void writeSignalToFile(const std::string &filename); //! Write map vector m to an ASCII file void writeMapToFile(const std::string &filename); //! Create simple data void createData (double max, double stretch, double shift=0); //! Create a simple signal void createSignal (double max, double stretch, double shift=0); //! Simple Response Matrix for testing void createSimpleResponseMatrix (int shift, double scale); // === Helper functions ======================================================= //! Compute P=sqrt(Q+iU) void complexPower(const vector<complex<double> > &signal, vector<double> &power); #ifdef _ITPP_ //! Compute P=sqrt(Q+iU) void complexPower(const cvec &signal, vector<double> &power); #endif }; } // end namespace RM
7a170a23551ce678f1247381820818bf7db2b16f
007759b14d17cecf8332d0653d31a2adb51dde4f
/project/0.4/include/myslam/mappoint.h
d52e022f10bc9edd6d83f45b4524043008d450b6
[ "MIT" ]
permissive
MrCocoaCat/slambook_cc
8e2270267720091cd572b81d12d27a1fe5f28314
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
refs/heads/master
2021-09-10T13:00:24.621364
2018-03-26T14:03:12
2018-03-26T14:03:12
90,761,569
4
1
null
null
null
null
UTF-8
C++
false
false
2,456
h
mappoint.h
/* * <one line to give the program's name and a brief idea of what it does.> * Copyright (C) 2016 <copyright holder> <email> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef MAPPOINT_H #define MAPPOINT_H #include "myslam/common_include.h" namespace myslam { class Frame; //地图特征点 class MapPoint { public: typedef shared_ptr<MapPoint> Ptr; unsigned long id_; // 通过factory_id_ 进行赋值ID //静态成员变量,属于该类,而不是成员,用于记录ID号 static unsigned long factory_id_; // factory id bool good_; // wheter a good point Vector3d pos_; // 世界坐标 Position in world Vector3d norm_; // Normal of viewing direction Mat descriptor_; // Descriptor for matching list<Frame*> observed_frames_; // key-frames that can observe this point int matched_times_; // being an inliner in pose estimation int visible_times_; // being visible in current frame MapPoint(); //带参数构造 MapPoint( unsigned long id, const Vector3d& position, const Vector3d& norm, Frame* frame=nullptr, const Mat& descriptor=Mat() ); //内联函数,在编译时进行展开, //const 修饰this 指针,不可以对该类的成员函数进行修改 inline cv::Point3f getPositionCV() const { return cv::Point3f( pos_(0,0), pos_(1,0), pos_(2,0) ); } //通过该函数进行构造 static MapPoint::Ptr createMapPoint(); //重载函数,相同函数名不同参数列表 static MapPoint::Ptr createMapPoint( const Vector3d& pos_world, const Vector3d& norm_, const Mat& descriptor, Frame* frame ); }; } #endif // MAPPOINT_H
c30267a5b91db728c17e33306a8c5c2a91316f6d
dcacb4ec90828f396e18d91636d613e53e7b8890
/plugins/cordova-open-zwave/lib/windows/open-zwave/build/winRT/vs2015/options.h
8f164caf5b24b2c997ea381a4b24c0744820913e
[]
no_license
sgrebnov/cordova-open-zwave-sample
cce150ee48c65c9260251487c3c77fd5c5a72aa4
561851f3c6cda09dc2b2366a0adbfe220b0e9349
refs/heads/master
2021-01-10T04:17:27.058711
2016-03-23T17:23:37
2016-03-23T17:23:43
54,558,584
0
0
null
null
null
null
UTF-8
C++
false
false
67,330
h
options.h
#pragma once #using <mscorlib.dll> #using <System.dll> #using <System.Data.dll> #using <System.Xml.dll> using namespace System::Security::Permissions; [assembly:SecurityPermissionAttribute(SecurityAction::RequestMinimum, SkipVerification=false)]; // // This source code was auto-generated by xsd, Version=4.6.81.0. // namespace OpenZWave_WinMD { using namespace System; ref class NewDataSet; /// <summary> ///Represents a strongly typed in-memory cache of data. ///</summary> [System::Serializable, System::ComponentModel::DesignerCategoryAttribute(L"code"), System::ComponentModel::ToolboxItem(true), System::Xml::Serialization::XmlSchemaProviderAttribute(L"GetTypedDataSetSchema"), System::Xml::Serialization::XmlRootAttribute(L"NewDataSet"), System::ComponentModel::Design::HelpKeywordAttribute(L"vs.data.DataSet")] public ref class NewDataSet : public ::System::Data::DataSet { public : ref class OptionsDataTable; public : ref class OptionDataTable; public : ref class OptionsRow; public : ref class OptionRow; public : ref class OptionsRowChangeEvent; public : ref class OptionRowChangeEvent; private: OpenZWave_WinMD::NewDataSet::OptionsDataTable^ tableOptions; private: OpenZWave_WinMD::NewDataSet::OptionDataTable^ tableOption; private: ::System::Data::DataRelation^ relationOptions_Option; private: ::System::Data::SchemaSerializationMode _schemaSerializationMode; public : [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] delegate System::Void OptionsRowChangeEventHandler(::System::Object^ sender, OpenZWave_WinMD::NewDataSet::OptionsRowChangeEvent^ e); public : [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] delegate System::Void OptionRowChangeEventHandler(::System::Object^ sender, OpenZWave_WinMD::NewDataSet::OptionRowChangeEvent^ e); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] NewDataSet(); protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] NewDataSet(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::Browsable(false), System::ComponentModel::DesignerSerializationVisibility(::System::ComponentModel::DesignerSerializationVisibility::Content)] property OpenZWave_WinMD::NewDataSet::OptionsDataTable^ Options { OpenZWave_WinMD::NewDataSet::OptionsDataTable^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::Browsable(false), System::ComponentModel::DesignerSerializationVisibility(::System::ComponentModel::DesignerSerializationVisibility::Content)] property OpenZWave_WinMD::NewDataSet::OptionDataTable^ Option { OpenZWave_WinMD::NewDataSet::OptionDataTable^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::BrowsableAttribute(true), System::ComponentModel::DesignerSerializationVisibilityAttribute(::System::ComponentModel::DesignerSerializationVisibility::Visible)] virtual property ::System::Data::SchemaSerializationMode SchemaSerializationMode { ::System::Data::SchemaSerializationMode get() override; System::Void set(::System::Data::SchemaSerializationMode value) override; } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::DesignerSerializationVisibilityAttribute(::System::ComponentModel::DesignerSerializationVisibility::Hidden)] property ::System::Data::DataTableCollection^ Tables { ::System::Data::DataTableCollection^ get() new; } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::DesignerSerializationVisibilityAttribute(::System::ComponentModel::DesignerSerializationVisibility::Hidden)] property ::System::Data::DataRelationCollection^ Relations { ::System::Data::DataRelationCollection^ get() new; } protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void InitializeDerivedDataSet() override; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataSet^ Clone() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Boolean ShouldSerializeTables() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Boolean ShouldSerializeRelations() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void ReadXmlSerializable(::System::Xml::XmlReader^ reader) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Xml::Schema::XmlSchema^ GetSchemaSerializable() override; internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitVars(); internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitVars(::System::Boolean initTable); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitClass(); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Boolean ShouldSerializeOptions(); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Boolean ShouldSerializeOption(); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void SchemaChanged(::System::Object^ sender, ::System::ComponentModel::CollectionChangeEventArgs^ e); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] static ::System::Xml::Schema::XmlSchemaComplexType^ GetTypedDataSetSchema(::System::Xml::Schema::XmlSchemaSet^ xs); public : /// <summary> ///Represents the strongly named DataTable class. ///</summary> [System::Serializable, System::Xml::Serialization::XmlSchemaProviderAttribute(L"GetTypedTableSchema")] ref class OptionsDataTable : public ::System::Data::DataTable, public ::System::Collections::IEnumerable { private: ::System::Data::DataColumn^ columnOptions_Id; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionsRowChangeEventHandler^ OptionsRowChanging; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionsRowChangeEventHandler^ OptionsRowChanged; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionsRowChangeEventHandler^ OptionsRowDeleting; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionsRowChangeEventHandler^ OptionsRowDeleted; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionsDataTable(); internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionsDataTable(::System::Data::DataTable^ table); protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionsDataTable(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataColumn^ Options_IdColumn { ::System::Data::DataColumn^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::Browsable(false)] property ::System::Int32 Count { ::System::Int32 get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property OpenZWave_WinMD::NewDataSet::OptionsRow^ default [::System::Int32 ] { OpenZWave_WinMD::NewDataSet::OptionsRow^ get(::System::Int32 index); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void AddOptionsRow(OpenZWave_WinMD::NewDataSet::OptionsRow^ row); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OpenZWave_WinMD::NewDataSet::OptionsRow^ AddOptionsRow(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Collections::IEnumerator^ GetEnumerator(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataTable^ Clone() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataTable^ CreateInstance() override; internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitVars(); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitClass(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OpenZWave_WinMD::NewDataSet::OptionsRow^ NewOptionsRow(); protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataRow^ NewRowFromBuilder(::System::Data::DataRowBuilder^ builder) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Type^ GetRowType() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowChanged(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowChanging(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowDeleted(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowDeleting(::System::Data::DataRowChangeEventArgs^ e) override; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void RemoveOptionsRow(OpenZWave_WinMD::NewDataSet::OptionsRow^ row); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] static ::System::Xml::Schema::XmlSchemaComplexType^ GetTypedTableSchema(::System::Xml::Schema::XmlSchemaSet^ xs); }; public : /// <summary> ///Represents the strongly named DataTable class. ///</summary> [System::Serializable, System::Xml::Serialization::XmlSchemaProviderAttribute(L"GetTypedTableSchema")] ref class OptionDataTable : public ::System::Data::DataTable, public ::System::Collections::IEnumerable { private: ::System::Data::DataColumn^ columnname; private: ::System::Data::DataColumn^ column_value; private: ::System::Data::DataColumn^ columnOptions_Id; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionRowChangeEventHandler^ OptionRowChanging; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionRowChangeEventHandler^ OptionRowChanged; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionRowChangeEventHandler^ OptionRowDeleting; public: [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] event OpenZWave_WinMD::NewDataSet::OptionRowChangeEventHandler^ OptionRowDeleted; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionDataTable(); internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionDataTable(::System::Data::DataTable^ table); protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionDataTable(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataColumn^ nameColumn { ::System::Data::DataColumn^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataColumn^ _valueColumn { ::System::Data::DataColumn^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataColumn^ Options_IdColumn { ::System::Data::DataColumn^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0"), System::ComponentModel::Browsable(false)] property ::System::Int32 Count { ::System::Int32 get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property OpenZWave_WinMD::NewDataSet::OptionRow^ default [::System::Int32 ] { OpenZWave_WinMD::NewDataSet::OptionRow^ get(::System::Int32 index); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void AddOptionRow(OpenZWave_WinMD::NewDataSet::OptionRow^ row); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OpenZWave_WinMD::NewDataSet::OptionRow^ AddOptionRow(System::String^ name, System::String^ _value, OpenZWave_WinMD::NewDataSet::OptionsRow^ parentOptionsRowByOptions_Option); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Collections::IEnumerator^ GetEnumerator(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataTable^ Clone() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataTable^ CreateInstance() override; internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitVars(); private: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void InitClass(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OpenZWave_WinMD::NewDataSet::OptionRow^ NewOptionRow(); protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Data::DataRow^ NewRowFromBuilder(::System::Data::DataRowBuilder^ builder) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Type^ GetRowType() override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowChanged(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowChanging(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowDeleted(::System::Data::DataRowChangeEventArgs^ e) override; protected: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] virtual ::System::Void OnRowDeleting(::System::Data::DataRowChangeEventArgs^ e) override; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void RemoveOptionRow(OpenZWave_WinMD::NewDataSet::OptionRow^ row); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] static ::System::Xml::Schema::XmlSchemaComplexType^ GetTypedTableSchema(::System::Xml::Schema::XmlSchemaSet^ xs); }; public : /// <summary> ///Represents strongly named DataRow class. ///</summary> ref class OptionsRow : public ::System::Data::DataRow { private: OpenZWave_WinMD::NewDataSet::OptionsDataTable^ tableOptions; internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionsRow(::System::Data::DataRowBuilder^ rb); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property System::Int32 Options_Id { System::Int32 get(); System::Void set(System::Int32 value); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] cli::array< OpenZWave_WinMD::NewDataSet::OptionRow^ >^ GetOptionRows(); }; public : /// <summary> ///Represents strongly named DataRow class. ///</summary> ref class OptionRow : public ::System::Data::DataRow { private: OpenZWave_WinMD::NewDataSet::OptionDataTable^ tableOption; internal: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionRow(::System::Data::DataRowBuilder^ rb); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property System::String^ name { System::String^ get(); System::Void set(System::String^ value); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property System::String^ _value { System::String^ get(); System::Void set(System::String^ value); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property System::Int32 Options_Id { System::Int32 get(); System::Void set(System::Int32 value); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property OpenZWave_WinMD::NewDataSet::OptionsRow^ OptionsRow { OpenZWave_WinMD::NewDataSet::OptionsRow^ get(); System::Void set(OpenZWave_WinMD::NewDataSet::OptionsRow^ value); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Boolean IsOptions_IdNull(); public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ::System::Void SetOptions_IdNull(); }; public : /// <summary> ///Row event argument class ///</summary> [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ref class OptionsRowChangeEvent : public ::System::EventArgs { private: OpenZWave_WinMD::NewDataSet::OptionsRow^ eventRow; private: ::System::Data::DataRowAction eventAction; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionsRowChangeEvent(OpenZWave_WinMD::NewDataSet::OptionsRow^ row, ::System::Data::DataRowAction action); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property OpenZWave_WinMD::NewDataSet::OptionsRow^ Row { OpenZWave_WinMD::NewDataSet::OptionsRow^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataRowAction Action { ::System::Data::DataRowAction get(); } }; public : /// <summary> ///Row event argument class ///</summary> [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] ref class OptionRowChangeEvent : public ::System::EventArgs { private: OpenZWave_WinMD::NewDataSet::OptionRow^ eventRow; private: ::System::Data::DataRowAction eventAction; public: [System::Diagnostics::DebuggerNonUserCodeAttribute] [System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] OptionRowChangeEvent(OpenZWave_WinMD::NewDataSet::OptionRow^ row, ::System::Data::DataRowAction action); public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property OpenZWave_WinMD::NewDataSet::OptionRow^ Row { OpenZWave_WinMD::NewDataSet::OptionRow^ get(); } public: [System::Diagnostics::DebuggerNonUserCodeAttribute, System::CodeDom::Compiler::GeneratedCodeAttribute(L"System.Data.Design.TypedDataSetGenerator", L"4.0.0.0")] property ::System::Data::DataRowAction Action { ::System::Data::DataRowAction get(); } }; }; } namespace OpenZWave_WinMD { inline NewDataSet::NewDataSet() { this->BeginInit(); this->InitClass(); ::System::ComponentModel::CollectionChangeEventHandler^ schemaChangedHandler = gcnew ::System::ComponentModel::CollectionChangeEventHandler(this, &OpenZWave_WinMD::NewDataSet::SchemaChanged); __super::Tables->CollectionChanged += schemaChangedHandler; __super::Relations->CollectionChanged += schemaChangedHandler; this->EndInit(); } inline NewDataSet::NewDataSet(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context) : ::System::Data::DataSet(info, context, false) { if (this->IsBinarySerialized(info, context) == true) { this->InitVars(false); ::System::ComponentModel::CollectionChangeEventHandler^ schemaChangedHandler1 = gcnew ::System::ComponentModel::CollectionChangeEventHandler(this, &OpenZWave_WinMD::NewDataSet::SchemaChanged); this->Tables->CollectionChanged += schemaChangedHandler1; this->Relations->CollectionChanged += schemaChangedHandler1; return; } ::System::String^ strSchema = (cli::safe_cast<::System::String^ >(info->GetValue(L"XmlSchema", ::System::String::typeid))); if (this->DetermineSchemaSerializationMode(info, context) == ::System::Data::SchemaSerializationMode::IncludeSchema) { ::System::Data::DataSet^ ds = (gcnew ::System::Data::DataSet()); ds->ReadXmlSchema((gcnew ::System::Xml::XmlTextReader((gcnew ::System::IO::StringReader(strSchema))))); if (ds->Tables[L"Options"] != nullptr) { __super::Tables->Add((gcnew OpenZWave_WinMD::NewDataSet::OptionsDataTable(ds->Tables[L"Options"]))); } if (ds->Tables[L"Option"] != nullptr) { __super::Tables->Add((gcnew OpenZWave_WinMD::NewDataSet::OptionDataTable(ds->Tables[L"Option"]))); } this->DataSetName = ds->DataSetName; this->Prefix = ds->Prefix; this->Namespace = ds->Namespace; this->Locale = ds->Locale; this->CaseSensitive = ds->CaseSensitive; this->EnforceConstraints = ds->EnforceConstraints; this->Merge(ds, false, ::System::Data::MissingSchemaAction::Add); this->InitVars(); } else { this->ReadXmlSchema((gcnew ::System::Xml::XmlTextReader((gcnew ::System::IO::StringReader(strSchema))))); } this->GetSerializationData(info, context); ::System::ComponentModel::CollectionChangeEventHandler^ schemaChangedHandler = gcnew ::System::ComponentModel::CollectionChangeEventHandler(this, &OpenZWave_WinMD::NewDataSet::SchemaChanged); __super::Tables->CollectionChanged += schemaChangedHandler; this->Relations->CollectionChanged += schemaChangedHandler; } inline OpenZWave_WinMD::NewDataSet::OptionsDataTable^ NewDataSet::Options::get() { return this->tableOptions; } inline OpenZWave_WinMD::NewDataSet::OptionDataTable^ NewDataSet::Option::get() { return this->tableOption; } inline ::System::Data::SchemaSerializationMode NewDataSet::SchemaSerializationMode::get() { return this->_schemaSerializationMode; } inline System::Void NewDataSet::SchemaSerializationMode::set(::System::Data::SchemaSerializationMode value) { this->_schemaSerializationMode = __identifier(value); } inline ::System::Data::DataTableCollection^ NewDataSet::Tables::get() { return __super::Tables; } inline ::System::Data::DataRelationCollection^ NewDataSet::Relations::get() { return __super::Relations; } inline ::System::Void NewDataSet::InitializeDerivedDataSet() { this->BeginInit(); this->InitClass(); this->EndInit(); } inline ::System::Data::DataSet^ NewDataSet::Clone() { OpenZWave_WinMD::NewDataSet^ cln = (cli::safe_cast<OpenZWave_WinMD::NewDataSet^ >(__super::Clone())); cln->InitVars(); cln->SchemaSerializationMode = this->SchemaSerializationMode; return cln; } inline ::System::Boolean NewDataSet::ShouldSerializeTables() { return false; } inline ::System::Boolean NewDataSet::ShouldSerializeRelations() { return false; } inline ::System::Void NewDataSet::ReadXmlSerializable(::System::Xml::XmlReader^ reader) { if (this->DetermineSchemaSerializationMode(reader) == ::System::Data::SchemaSerializationMode::IncludeSchema) { this->Reset(); ::System::Data::DataSet^ ds = (gcnew ::System::Data::DataSet()); ds->ReadXml(reader); if (ds->Tables[L"Options"] != nullptr) { __super::Tables->Add((gcnew OpenZWave_WinMD::NewDataSet::OptionsDataTable(ds->Tables[L"Options"]))); } if (ds->Tables[L"Option"] != nullptr) { __super::Tables->Add((gcnew OpenZWave_WinMD::NewDataSet::OptionDataTable(ds->Tables[L"Option"]))); } this->DataSetName = ds->DataSetName; this->Prefix = ds->Prefix; this->Namespace = ds->Namespace; this->Locale = ds->Locale; this->CaseSensitive = ds->CaseSensitive; this->EnforceConstraints = ds->EnforceConstraints; this->Merge(ds, false, ::System::Data::MissingSchemaAction::Add); this->InitVars(); } else { this->ReadXml(reader); this->InitVars(); } } inline ::System::Xml::Schema::XmlSchema^ NewDataSet::GetSchemaSerializable() { ::System::IO::MemoryStream^ stream = (gcnew ::System::IO::MemoryStream()); this->WriteXmlSchema((gcnew ::System::Xml::XmlTextWriter(stream, nullptr))); stream->Position = 0; return ::System::Xml::Schema::XmlSchema::Read((gcnew ::System::Xml::XmlTextReader(stream)), nullptr); } inline ::System::Void NewDataSet::InitVars() { this->InitVars(true); } inline ::System::Void NewDataSet::InitVars(::System::Boolean initTable) { this->tableOptions = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsDataTable^ >(__super::Tables[L"Options"])); if (initTable == true) { if (this->tableOptions != nullptr) { this->tableOptions->InitVars(); } } this->tableOption = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionDataTable^ >(__super::Tables[L"Option"])); if (initTable == true) { if (this->tableOption != nullptr) { this->tableOption->InitVars(); } } this->relationOptions_Option = this->Relations[L"Options_Option"]; } inline ::System::Void NewDataSet::InitClass() { this->DataSetName = L"NewDataSet"; this->Prefix = L""; this->Namespace = L"http://code.google.com/p/open-zwave/"; this->Locale = (gcnew ::System::Globalization::CultureInfo(L"")); this->EnforceConstraints = true; this->SchemaSerializationMode = ::System::Data::SchemaSerializationMode::IncludeSchema; this->tableOptions = (gcnew OpenZWave_WinMD::NewDataSet::OptionsDataTable()); __super::Tables->Add(this->tableOptions); this->tableOption = (gcnew OpenZWave_WinMD::NewDataSet::OptionDataTable()); __super::Tables->Add(this->tableOption); ::System::Data::ForeignKeyConstraint^ fkc; fkc = (gcnew ::System::Data::ForeignKeyConstraint(L"Options_Option", gcnew cli::array< ::System::Data::DataColumn^ >(1) {this->tableOptions->Options_IdColumn}, gcnew cli::array< ::System::Data::DataColumn^ >(1) {this->tableOption->Options_IdColumn})); this->tableOption->Constraints->Add(fkc); fkc->AcceptRejectRule = ::System::Data::AcceptRejectRule::None; fkc->DeleteRule = ::System::Data::Rule::Cascade; fkc->UpdateRule = ::System::Data::Rule::Cascade; this->relationOptions_Option = (gcnew ::System::Data::DataRelation(L"Options_Option", gcnew cli::array< ::System::Data::DataColumn^ >(1) {this->tableOptions->Options_IdColumn}, gcnew cli::array< ::System::Data::DataColumn^ >(1) {this->tableOption->Options_IdColumn}, false)); this->relationOptions_Option->Nested = true; this->Relations->Add(this->relationOptions_Option); } inline ::System::Boolean NewDataSet::ShouldSerializeOptions() { return false; } inline ::System::Boolean NewDataSet::ShouldSerializeOption() { return false; } inline ::System::Void NewDataSet::SchemaChanged(::System::Object^ sender, ::System::ComponentModel::CollectionChangeEventArgs^ e) { if (e->Action == ::System::ComponentModel::CollectionChangeAction::Remove) { this->InitVars(); } } inline ::System::Xml::Schema::XmlSchemaComplexType^ NewDataSet::GetTypedDataSetSchema(::System::Xml::Schema::XmlSchemaSet^ xs) { OpenZWave_WinMD::NewDataSet^ ds = (gcnew OpenZWave_WinMD::NewDataSet()); ::System::Xml::Schema::XmlSchemaComplexType^ type = (gcnew ::System::Xml::Schema::XmlSchemaComplexType()); ::System::Xml::Schema::XmlSchemaSequence^ sequence = (gcnew ::System::Xml::Schema::XmlSchemaSequence()); ::System::Xml::Schema::XmlSchemaAny^ any = (gcnew ::System::Xml::Schema::XmlSchemaAny()); any->Namespace = ds->Namespace; sequence->Items->Add(any); type->Particle = sequence; ::System::Xml::Schema::XmlSchema^ dsSchema = ds->GetSchemaSerializable(); if (xs->Contains(dsSchema->TargetNamespace)) { ::System::IO::MemoryStream^ s1 = (gcnew ::System::IO::MemoryStream()); ::System::IO::MemoryStream^ s2 = (gcnew ::System::IO::MemoryStream()); try { ::System::Xml::Schema::XmlSchema^ schema = nullptr; dsSchema->Write(s1); for ( ::System::Collections::IEnumerator^ schemas = xs->Schemas(dsSchema->TargetNamespace)->GetEnumerator(); schemas->MoveNext(); ) { schema = (cli::safe_cast<::System::Xml::Schema::XmlSchema^ >(schemas->Current)); s2->SetLength(0); schema->Write(s2); if (s1->Length == s2->Length) { s1->Position = 0; s2->Position = 0; for ( ; ((s1->Position != s1->Length) && (s1->ReadByte() == s2->ReadByte())); ) { ; } if (s1->Position == s1->Length) { return type; } } } } finally { if (s1 != nullptr) { s1->Close(); } if (s2 != nullptr) { s2->Close(); } } } xs->Add(dsSchema); return type; } inline NewDataSet::OptionsDataTable::OptionsDataTable() { this->TableName = L"Options"; this->BeginInit(); this->InitClass(); this->EndInit(); } inline NewDataSet::OptionsDataTable::OptionsDataTable(::System::Data::DataTable^ table) { this->TableName = table->TableName; if (table->CaseSensitive != table->DataSet->CaseSensitive) { this->CaseSensitive = table->CaseSensitive; } if (table->Locale->ToString() != table->DataSet->Locale->ToString()) { this->Locale = table->Locale; } if (table->Namespace != table->DataSet->Namespace) { this->Namespace = table->Namespace; } this->Prefix = table->Prefix; this->MinimumCapacity = table->MinimumCapacity; } inline NewDataSet::OptionsDataTable::OptionsDataTable(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context) : ::System::Data::DataTable(info, context) { this->InitVars(); } inline ::System::Data::DataColumn^ NewDataSet::OptionsDataTable::Options_IdColumn::get() { return this->columnOptions_Id; } inline ::System::Int32 NewDataSet::OptionsDataTable::Count::get() { return this->Rows->Count; } inline OpenZWave_WinMD::NewDataSet::OptionsRow^ NewDataSet::OptionsDataTable::default::get(::System::Int32 index) { return (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(this->Rows[index])); } inline ::System::Void NewDataSet::OptionsDataTable::AddOptionsRow(OpenZWave_WinMD::NewDataSet::OptionsRow^ row) { this->Rows->Add(row); } inline OpenZWave_WinMD::NewDataSet::OptionsRow^ NewDataSet::OptionsDataTable::AddOptionsRow() { OpenZWave_WinMD::NewDataSet::OptionsRow^ rowOptionsRow = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(this->NewRow())); cli::array< ::System::Object^ >^ columnValuesArray = gcnew cli::array< ::System::Object^ >(1) {nullptr}; rowOptionsRow->ItemArray = columnValuesArray; this->Rows->Add(rowOptionsRow); return rowOptionsRow; } inline ::System::Collections::IEnumerator^ NewDataSet::OptionsDataTable::GetEnumerator() { return this->Rows->GetEnumerator(); } inline ::System::Data::DataTable^ NewDataSet::OptionsDataTable::Clone() { OpenZWave_WinMD::NewDataSet::OptionsDataTable^ cln = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsDataTable^ >(__super::Clone())); cln->InitVars(); return cln; } inline ::System::Data::DataTable^ NewDataSet::OptionsDataTable::CreateInstance() { return (gcnew OpenZWave_WinMD::NewDataSet::OptionsDataTable()); } inline ::System::Void NewDataSet::OptionsDataTable::InitVars() { this->columnOptions_Id = __super::Columns[L"Options_Id"]; } inline ::System::Void NewDataSet::OptionsDataTable::InitClass() { this->columnOptions_Id = (gcnew ::System::Data::DataColumn(L"Options_Id", ::System::Int32::typeid, nullptr, ::System::Data::MappingType::Hidden)); __super::Columns->Add(this->columnOptions_Id); this->Constraints->Add((gcnew ::System::Data::UniqueConstraint(L"Constraint1", gcnew cli::array< ::System::Data::DataColumn^ >(1) {this->columnOptions_Id}, true))); this->columnOptions_Id->AutoIncrement = true; this->columnOptions_Id->AllowDBNull = false; this->columnOptions_Id->Unique = true; } inline OpenZWave_WinMD::NewDataSet::OptionsRow^ NewDataSet::OptionsDataTable::NewOptionsRow() { return (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(this->NewRow())); } inline ::System::Data::DataRow^ NewDataSet::OptionsDataTable::NewRowFromBuilder(::System::Data::DataRowBuilder^ builder) { return (gcnew OpenZWave_WinMD::NewDataSet::OptionsRow(builder)); } inline ::System::Type^ NewDataSet::OptionsDataTable::GetRowType() { return OpenZWave_WinMD::NewDataSet::OptionsRow::typeid; } inline ::System::Void NewDataSet::OptionsDataTable::OnRowChanged(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowChanged(e); { this->OptionsRowChanged(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionsRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionsDataTable::OnRowChanging(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowChanging(e); { this->OptionsRowChanging(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionsRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionsDataTable::OnRowDeleted(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowDeleted(e); { this->OptionsRowDeleted(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionsRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionsDataTable::OnRowDeleting(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowDeleting(e); { this->OptionsRowDeleting(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionsRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionsDataTable::RemoveOptionsRow(OpenZWave_WinMD::NewDataSet::OptionsRow^ row) { this->Rows->Remove(row); } inline ::System::Xml::Schema::XmlSchemaComplexType^ NewDataSet::OptionsDataTable::GetTypedTableSchema(::System::Xml::Schema::XmlSchemaSet^ xs) { ::System::Xml::Schema::XmlSchemaComplexType^ type = (gcnew ::System::Xml::Schema::XmlSchemaComplexType()); ::System::Xml::Schema::XmlSchemaSequence^ sequence = (gcnew ::System::Xml::Schema::XmlSchemaSequence()); OpenZWave_WinMD::NewDataSet^ ds = (gcnew OpenZWave_WinMD::NewDataSet()); ::System::Xml::Schema::XmlSchemaAny^ any1 = (gcnew ::System::Xml::Schema::XmlSchemaAny()); any1->Namespace = L"http://www.w3.org/2001/XMLSchema"; any1->MinOccurs = ::System::Decimal(0); any1->MaxOccurs = ::System::Decimal::MaxValue; any1->ProcessContents = ::System::Xml::Schema::XmlSchemaContentProcessing::Lax; sequence->Items->Add(any1); ::System::Xml::Schema::XmlSchemaAny^ any2 = (gcnew ::System::Xml::Schema::XmlSchemaAny()); any2->Namespace = L"urn:schemas-microsoft-com:xml-diffgram-v1"; any2->MinOccurs = ::System::Decimal(1); any2->ProcessContents = ::System::Xml::Schema::XmlSchemaContentProcessing::Lax; sequence->Items->Add(any2); ::System::Xml::Schema::XmlSchemaAttribute^ attribute1 = (gcnew ::System::Xml::Schema::XmlSchemaAttribute()); attribute1->Name = L"namespace"; attribute1->FixedValue = ds->Namespace; type->Attributes->Add(attribute1); ::System::Xml::Schema::XmlSchemaAttribute^ attribute2 = (gcnew ::System::Xml::Schema::XmlSchemaAttribute()); attribute2->Name = L"tableTypeName"; attribute2->FixedValue = L"OptionsDataTable"; type->Attributes->Add(attribute2); type->Particle = sequence; ::System::Xml::Schema::XmlSchema^ dsSchema = ds->GetSchemaSerializable(); if (xs->Contains(dsSchema->TargetNamespace)) { ::System::IO::MemoryStream^ s1 = (gcnew ::System::IO::MemoryStream()); ::System::IO::MemoryStream^ s2 = (gcnew ::System::IO::MemoryStream()); try { ::System::Xml::Schema::XmlSchema^ schema = nullptr; dsSchema->Write(s1); for ( ::System::Collections::IEnumerator^ schemas = xs->Schemas(dsSchema->TargetNamespace)->GetEnumerator(); schemas->MoveNext(); ) { schema = (cli::safe_cast<::System::Xml::Schema::XmlSchema^ >(schemas->Current)); s2->SetLength(0); schema->Write(s2); if (s1->Length == s2->Length) { s1->Position = 0; s2->Position = 0; for ( ; ((s1->Position != s1->Length) && (s1->ReadByte() == s2->ReadByte())); ) { ; } if (s1->Position == s1->Length) { return type; } } } } finally { if (s1 != nullptr) { s1->Close(); } if (s2 != nullptr) { s2->Close(); } } } xs->Add(dsSchema); return type; } inline NewDataSet::OptionDataTable::OptionDataTable() { this->TableName = L"Option"; this->BeginInit(); this->InitClass(); this->EndInit(); } inline NewDataSet::OptionDataTable::OptionDataTable(::System::Data::DataTable^ table) { this->TableName = table->TableName; if (table->CaseSensitive != table->DataSet->CaseSensitive) { this->CaseSensitive = table->CaseSensitive; } if (table->Locale->ToString() != table->DataSet->Locale->ToString()) { this->Locale = table->Locale; } if (table->Namespace != table->DataSet->Namespace) { this->Namespace = table->Namespace; } this->Prefix = table->Prefix; this->MinimumCapacity = table->MinimumCapacity; } inline NewDataSet::OptionDataTable::OptionDataTable(::System::Runtime::Serialization::SerializationInfo^ info, ::System::Runtime::Serialization::StreamingContext context) : ::System::Data::DataTable(info, context) { this->InitVars(); } inline ::System::Data::DataColumn^ NewDataSet::OptionDataTable::nameColumn::get() { return this->columnname; } inline ::System::Data::DataColumn^ NewDataSet::OptionDataTable::_valueColumn::get() { return this->column_value; } inline ::System::Data::DataColumn^ NewDataSet::OptionDataTable::Options_IdColumn::get() { return this->columnOptions_Id; } inline ::System::Int32 NewDataSet::OptionDataTable::Count::get() { return this->Rows->Count; } inline OpenZWave_WinMD::NewDataSet::OptionRow^ NewDataSet::OptionDataTable::default::get(::System::Int32 index) { return (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(this->Rows[index])); } inline ::System::Void NewDataSet::OptionDataTable::AddOptionRow(OpenZWave_WinMD::NewDataSet::OptionRow^ row) { this->Rows->Add(row); } inline OpenZWave_WinMD::NewDataSet::OptionRow^ NewDataSet::OptionDataTable::AddOptionRow(System::String^ name, System::String^ _value, OpenZWave_WinMD::NewDataSet::OptionsRow^ parentOptionsRowByOptions_Option) { OpenZWave_WinMD::NewDataSet::OptionRow^ rowOptionRow = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(this->NewRow())); cli::array< ::System::Object^ >^ columnValuesArray = gcnew cli::array< ::System::Object^ >(3) {name, _value, nullptr}; if (parentOptionsRowByOptions_Option != nullptr) { columnValuesArray[2] = parentOptionsRowByOptions_Option[0]; } rowOptionRow->ItemArray = columnValuesArray; this->Rows->Add(rowOptionRow); return rowOptionRow; } inline ::System::Collections::IEnumerator^ NewDataSet::OptionDataTable::GetEnumerator() { return this->Rows->GetEnumerator(); } inline ::System::Data::DataTable^ NewDataSet::OptionDataTable::Clone() { OpenZWave_WinMD::NewDataSet::OptionDataTable^ cln = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionDataTable^ >(__super::Clone())); cln->InitVars(); return cln; } inline ::System::Data::DataTable^ NewDataSet::OptionDataTable::CreateInstance() { return (gcnew OpenZWave_WinMD::NewDataSet::OptionDataTable()); } inline ::System::Void NewDataSet::OptionDataTable::InitVars() { this->columnname = __super::Columns[L"name"]; this->column_value = __super::Columns[L"value"]; this->columnOptions_Id = __super::Columns[L"Options_Id"]; } inline ::System::Void NewDataSet::OptionDataTable::InitClass() { this->columnname = (gcnew ::System::Data::DataColumn(L"name", ::System::String::typeid, nullptr, ::System::Data::MappingType::Attribute)); __super::Columns->Add(this->columnname); this->column_value = (gcnew ::System::Data::DataColumn(L"value", ::System::String::typeid, nullptr, ::System::Data::MappingType::Attribute)); __super::Columns->Add(this->column_value); this->columnOptions_Id = (gcnew ::System::Data::DataColumn(L"Options_Id", ::System::Int32::typeid, nullptr, ::System::Data::MappingType::Hidden)); __super::Columns->Add(this->columnOptions_Id); this->columnname->AllowDBNull = false; this->columnname->Namespace = L""; this->column_value->AllowDBNull = false; this->column_value->Namespace = L""; } inline OpenZWave_WinMD::NewDataSet::OptionRow^ NewDataSet::OptionDataTable::NewOptionRow() { return (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(this->NewRow())); } inline ::System::Data::DataRow^ NewDataSet::OptionDataTable::NewRowFromBuilder(::System::Data::DataRowBuilder^ builder) { return (gcnew OpenZWave_WinMD::NewDataSet::OptionRow(builder)); } inline ::System::Type^ NewDataSet::OptionDataTable::GetRowType() { return OpenZWave_WinMD::NewDataSet::OptionRow::typeid; } inline ::System::Void NewDataSet::OptionDataTable::OnRowChanged(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowChanged(e); { this->OptionRowChanged(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionDataTable::OnRowChanging(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowChanging(e); { this->OptionRowChanging(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionDataTable::OnRowDeleted(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowDeleted(e); { this->OptionRowDeleted(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionDataTable::OnRowDeleting(::System::Data::DataRowChangeEventArgs^ e) { __super::OnRowDeleting(e); { this->OptionRowDeleting(this, (gcnew OpenZWave_WinMD::NewDataSet::OptionRowChangeEvent((cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionRow^ >(e->Row)), e->Action))); } } inline ::System::Void NewDataSet::OptionDataTable::RemoveOptionRow(OpenZWave_WinMD::NewDataSet::OptionRow^ row) { this->Rows->Remove(row); } inline ::System::Xml::Schema::XmlSchemaComplexType^ NewDataSet::OptionDataTable::GetTypedTableSchema(::System::Xml::Schema::XmlSchemaSet^ xs) { ::System::Xml::Schema::XmlSchemaComplexType^ type = (gcnew ::System::Xml::Schema::XmlSchemaComplexType()); ::System::Xml::Schema::XmlSchemaSequence^ sequence = (gcnew ::System::Xml::Schema::XmlSchemaSequence()); OpenZWave_WinMD::NewDataSet^ ds = (gcnew OpenZWave_WinMD::NewDataSet()); ::System::Xml::Schema::XmlSchemaAny^ any1 = (gcnew ::System::Xml::Schema::XmlSchemaAny()); any1->Namespace = L"http://www.w3.org/2001/XMLSchema"; any1->MinOccurs = ::System::Decimal(0); any1->MaxOccurs = ::System::Decimal::MaxValue; any1->ProcessContents = ::System::Xml::Schema::XmlSchemaContentProcessing::Lax; sequence->Items->Add(any1); ::System::Xml::Schema::XmlSchemaAny^ any2 = (gcnew ::System::Xml::Schema::XmlSchemaAny()); any2->Namespace = L"urn:schemas-microsoft-com:xml-diffgram-v1"; any2->MinOccurs = ::System::Decimal(1); any2->ProcessContents = ::System::Xml::Schema::XmlSchemaContentProcessing::Lax; sequence->Items->Add(any2); ::System::Xml::Schema::XmlSchemaAttribute^ attribute1 = (gcnew ::System::Xml::Schema::XmlSchemaAttribute()); attribute1->Name = L"namespace"; attribute1->FixedValue = ds->Namespace; type->Attributes->Add(attribute1); ::System::Xml::Schema::XmlSchemaAttribute^ attribute2 = (gcnew ::System::Xml::Schema::XmlSchemaAttribute()); attribute2->Name = L"tableTypeName"; attribute2->FixedValue = L"OptionDataTable"; type->Attributes->Add(attribute2); type->Particle = sequence; ::System::Xml::Schema::XmlSchema^ dsSchema = ds->GetSchemaSerializable(); if (xs->Contains(dsSchema->TargetNamespace)) { ::System::IO::MemoryStream^ s1 = (gcnew ::System::IO::MemoryStream()); ::System::IO::MemoryStream^ s2 = (gcnew ::System::IO::MemoryStream()); try { ::System::Xml::Schema::XmlSchema^ schema = nullptr; dsSchema->Write(s1); for ( ::System::Collections::IEnumerator^ schemas = xs->Schemas(dsSchema->TargetNamespace)->GetEnumerator(); schemas->MoveNext(); ) { schema = (cli::safe_cast<::System::Xml::Schema::XmlSchema^ >(schemas->Current)); s2->SetLength(0); schema->Write(s2); if (s1->Length == s2->Length) { s1->Position = 0; s2->Position = 0; for ( ; ((s1->Position != s1->Length) && (s1->ReadByte() == s2->ReadByte())); ) { ; } if (s1->Position == s1->Length) { return type; } } } } finally { if (s1 != nullptr) { s1->Close(); } if (s2 != nullptr) { s2->Close(); } } } xs->Add(dsSchema); return type; } inline NewDataSet::OptionsRow::OptionsRow(::System::Data::DataRowBuilder^ rb) : ::System::Data::DataRow(rb) { this->tableOptions = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsDataTable^ >(this->Table)); } inline System::Int32 NewDataSet::OptionsRow::Options_Id::get() { return (cli::safe_cast<::System::Int32 >(this[this->tableOptions->Options_IdColumn])); } inline System::Void NewDataSet::OptionsRow::Options_Id::set(System::Int32 value) { this[this->tableOptions->Options_IdColumn] = value; } inline cli::array< OpenZWave_WinMD::NewDataSet::OptionRow^ >^ NewDataSet::OptionsRow::GetOptionRows() { if (this->Table->ChildRelations[L"Options_Option"] == nullptr) { return gcnew cli::array< OpenZWave_WinMD::NewDataSet::OptionRow^ >(0); } else { return (cli::safe_cast<cli::array< OpenZWave_WinMD::NewDataSet::OptionRow^ >^ >(__super::GetChildRows(this->Table->ChildRelations[L"Options_Option"]))); } } inline NewDataSet::OptionRow::OptionRow(::System::Data::DataRowBuilder^ rb) : ::System::Data::DataRow(rb) { this->tableOption = (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionDataTable^ >(this->Table)); } inline System::String^ NewDataSet::OptionRow::name::get() { return (cli::safe_cast<::System::String^ >(this[this->tableOption->nameColumn])); } inline System::Void NewDataSet::OptionRow::name::set(System::String^ value) { this[this->tableOption->nameColumn] = value; } inline System::String^ NewDataSet::OptionRow::_value::get() { return (cli::safe_cast<::System::String^ >(this[this->tableOption->_valueColumn])); } inline System::Void NewDataSet::OptionRow::_value::set(System::String^ value) { this[this->tableOption->_valueColumn] = value; } inline System::Int32 NewDataSet::OptionRow::Options_Id::get() { try { return (cli::safe_cast<::System::Int32 >(this[this->tableOption->Options_IdColumn])); } catch (::System::InvalidCastException^ e) { throw (gcnew ::System::Data::StrongTypingException(L"The value for column \'Options_Id\' in table \'Option\' is DBNull.", e)); } } inline System::Void NewDataSet::OptionRow::Options_Id::set(System::Int32 value) { this[this->tableOption->Options_IdColumn] = value; } inline OpenZWave_WinMD::NewDataSet::OptionsRow^ NewDataSet::OptionRow::OptionsRow::get() { return (cli::safe_cast<OpenZWave_WinMD::NewDataSet::OptionsRow^ >(this->GetParentRow(this->Table->ParentRelations[L"Options_Option"]))); } inline System::Void NewDataSet::OptionRow::OptionsRow::set(OpenZWave_WinMD::NewDataSet::OptionsRow^ value) { this->SetParentRow(value, this->Table->ParentRelations[L"Options_Option"]); } inline ::System::Boolean NewDataSet::OptionRow::IsOptions_IdNull() { return this->IsNull(this->tableOption->Options_IdColumn); } inline ::System::Void NewDataSet::OptionRow::SetOptions_IdNull() { this[this->tableOption->Options_IdColumn] = ::System::Convert::DBNull; } inline NewDataSet::OptionsRowChangeEvent::OptionsRowChangeEvent(OpenZWave_WinMD::NewDataSet::OptionsRow^ row, ::System::Data::DataRowAction action) { this->eventRow = row; this->eventAction = action; } inline OpenZWave_WinMD::NewDataSet::OptionsRow^ NewDataSet::OptionsRowChangeEvent::Row::get() { return this->eventRow; } inline ::System::Data::DataRowAction NewDataSet::OptionsRowChangeEvent::Action::get() { return this->eventAction; } inline NewDataSet::OptionRowChangeEvent::OptionRowChangeEvent(OpenZWave_WinMD::NewDataSet::OptionRow^ row, ::System::Data::DataRowAction action) { this->eventRow = row; this->eventAction = action; } inline OpenZWave_WinMD::NewDataSet::OptionRow^ NewDataSet::OptionRowChangeEvent::Row::get() { return this->eventRow; } inline ::System::Data::DataRowAction NewDataSet::OptionRowChangeEvent::Action::get() { return this->eventAction; } }
47d959b9b816465f96ae4a6982383cd011062b8a
2f570b0c97db4f8936297fd9adee89e667d150ae
/BFSandPrimStandAlone.cpp
39cd2085dd86ed89384627f8901eaff054ccc2a5
[]
no_license
haffent1/project8Graphs
9209836cd9e88ab03259d1b692ff200d104ad05c
6819d05980f9b74a41bdc5703b43d17fa30d199f
refs/heads/main
2023-04-23T00:32:53.986508
2021-05-12T16:09:23
2021-05-12T16:09:23
362,127,408
0
0
null
null
null
null
UTF-8
C++
false
false
2,943
cpp
BFSandPrimStandAlone.cpp
/*this is a throw-away file so that i can work on these while mitch is working in graphs.cpp */ Prim(int root){ //make a min priority queue //check syntax MinPriorityQueue<int> primQueue = new MinPriorityQueue<int>(size); //size is an atrib of graph Vertex* U = new Vertex; int child; for(int i = 0 ; i < size ; i++){ //size is the number of verties vertiecesArray[i]->predecessor = NULL; vertiecesArray[i]->key = 2147483647; // this is the largest value that an int in c++ can hold primQueue.insert(vertiecesArray[i]); }//end of for loop vertiecesArray[root]->key = 0; while(primQueue.empty() != true){ U = vertiecesArray[primQueue.extractMin()]; // this syntex is kinda ugly if (U->predecessor != NULL){ //this is the section that should handle the printing and just skip the first interation cout << GraphWeights(U->value, U->parent->value)<<endl; } for(int j = 0 ; j < Alist[U->value].length ; j++){ //this is assuming that the linked pointed to in Alist have a length value child = Alist[U->value].pop()->value(); //get the numaric value of the child if(GraphWeights(U->value, child) < v.key{ vertiecesArray[child].key = GraphWeights(U->value, child); vertiecesArray[child].predecessor = U; }// end of if weight is less than key } // end of for loop for adjacency list of U }// end of while loop for primQueue not empty }//end of prims //============================================================================== //DFS //============================================================================== void dfs(){ //for colors 0==white, 1==grey, 2==black int time = 0; int *timep = &time; for(int i = 0 ; i < size ; i++){ vertiecesArray[i]->predecessor = NULL; vertiecesArray[i]->color = 0; }//end of for(int i = 0 ; i < size ; i++){ if(vertiecesArray[i]->color == 0){ dfsVisit(i); } } }//end of dfs void dfsVisit(int i, int *timep){ int child; vertex *U = vertiecesArray[i]; vertex *v; U->color = 1; //1 == grey *(timep)++; U->discovery = *(timep); for(int j = 0 ; j < Alist[U->value].length ; j++){ //this is the most ugly syntex ive ever written, im sorry v = Alist[U->value].pop(); //get the numaric value of the child if(v->color == 0){ //0 == white v->predecessor = U; //the U and v might be swapped in this dfsVisit(U->value,timep); }//end of if white U->color = 2; //set color to black *(timep)++; U->finish = *(timep); cout<<U<<endl;// print the verties in the order that they are visited }// end of for loop covering all children of }//end of dfsVisit bool cycle(){ //there is a way to use the dfs to figure this out }
802605565a58afa84bcdbb916892b298b0ce6a25
5f6a0ee7014def8429ccde0d15dfd29c198f69e4
/src/instinctmodel.h
c4710d5ba08dd3c34ab2057484cf28f35d0b9825
[]
no_license
pdJeeves/BrainInVatKit
d939c2b7a33b973c64cb70397b4e912f52b9e40a
c15c446b276cf2f82596954f1d77e04c26d70341
refs/heads/master
2021-01-20T14:39:17.653202
2017-05-10T19:06:12
2017-05-10T19:06:12
66,598,131
0
0
null
null
null
null
UTF-8
C++
false
false
416
h
instinctmodel.h
#ifndef INSTINCTMODEL_H #define INSTINCTMODEL_H /* class InstinctModel { int _length; InstinctData * instincts; class Instinct { const InstinctData & data; public: Instinct(InstinctData & data) : data(data) { } }; public: InstinctModel(); Instinct operator[](int i) { return Instinct(instincts[i]); } int length() const { return _length; } }; */ #endif // INSTINCTMODEL_H
5bc953a4966d364da5f5932be5e48617f4ccafbe
539e2cd845843f3bc53424cbb9ed5b7105fd8017
/HashTablesHomework_1/Header.h
5d501482d6c08f950135c79119137496a51c0ecc
[]
no_license
TryMorita/CPlusPlus-Hashtables
66aa0ea16da4530f0e1336d4901ccf5941c8e768
270a747dbea6b090bebc0b1662b3c52986fc8312
refs/heads/master
2023-03-19T18:16:01.485570
2021-03-09T01:56:14
2021-03-09T01:56:14
345,851,620
0
0
null
null
null
null
UTF-8
C++
false
false
674
h
Header.h
#ifndef Header_h #define Header_h //Basic Header that includes all of the libries we'll be using //Declan Morita 11373005. I got help from Elias, Brian, Edwardo and Dara. And Adam your string splitter from last year and a csv writer from last year. using namespace std; #include <vector> #include <string> #include <cstring> #include <string.h> #include <iomanip> #include <iostream> #include <ostream> #include <fstream> #include <sstream> #include <math.h> #include <iterator> #include <stdlib.h> #include <utility> // utility includes the move and swap functions #include<unordered_map> #include<algorithm> #include <cstdio> #include "AdamsStringSplitter.h" #endif
af36c691e4ec09ce91831cfe320df71f8ab85efa
69bef33c890952976b9cb863c87d2d7381504997
/CodeC2/C2_Bai10_LeUyen.cpp
b1061263e7ced4700baedb407012ca66b794282d
[]
no_license
hieu-ln/IT81-15
0c5f60b31525507f5e48f9c722364564af530447
26eb9c37b6a608b8990b05eb12fe2ab8604b1f2f
refs/heads/master
2020-06-11T06:42:58.752934
2019-08-21T13:31:41
2019-08-21T13:32:43
193,879,804
0
0
null
2019-08-11T08:44:00
2019-06-26T10:07:23
C++
UTF-8
C++
false
false
2,404
cpp
C2_Bai10_LeUyen.cpp
//#include <iostream> //using namespace std; //struct Node //{ // int info; // Node *link; //}; //Node * sp; //void init() //{ // sp = NULL; //} //int isEmpty() //{ // if (sp == NULL) // return 1; // return 0; //} //void Push(int x) //{ // Node *p; // p = new Node; // p->info = x; // p->link = sp; // sp = p; //} //int Pop(int &x) //{ // if (sp!= NULL) // { // Node *p = sp; // x = p -> info; // sp = p ->link; // delete p; // return 1; // } // return 0; //} //void Process_stack () //{ // if (sp != NULL) // { // Node *p = sp; // do{ // cout << p->info << " "; // p = p->link; // } while (p != NULL); // cout << endl; // } //} //int Convert (int tp) //{ // init(); // while (tp != 0) // { // int d = tp % 2; // Push(d); // tp /= 2; // } // int np = 0; // while (!isEmpty()) // { // int x; // if (Pop(x)) // np = np * 10 + x; // } // return np; //} //int main() //{ // int chon; // char tt; // do{ // cout << "1. Khai bao" // << "\n2. Khoi tao stack rong" // << "\n3. Kiem tra stack rong" // << "\n4. Them 1 phan tu" // << "\n5. Xoa 1 phan tu" // << "\n6. Xuat queue" // << "\n7. Doi tu thap phan sang nhi phan" // << "\nNhap chon: "; // cin >> chon; // switch(chon) // { // case 1: // cout << "Khai bao cau truc danh sach thanh cong! "; // break; // case 2: // init(); // cout << "Khoi tao stack rong thanh cong\n"; // break; // case 3: // if (isEmpty() == 1) // cout << "Queue rong\n"; // else // cout << "Queue khong rong\n"; // break; // case 4: // int x; // cout << "Nhap gia tri muon them "; // cin >> x; // Push(x); // cout << "Hang doi sau khi them vao\n"; // Process_stack(); // break; // case 5: // if (Pop(x) != 0) // { // cout << "Phan tu lay ra co gia tri " << x << "\n"; // cout << "Stack sau khi lay ra\n"; // Process_stack(); // } // else // cout << "Stack rong\n"; // break; // case 6: // cout << "Stack:\n"; // Process_stack(); // case 7: // cout << "Nhap so muon doi tu thap phan sang nhi phan:"; // int so; // cin >> so; // cout << "Ket qua: " << Convert(so) << endl; // default: // break; // } // cout << "Ban co muon tiep tuc khong? (Y/N)"; // cin >> tt; // } while (tt == 'Y' || tt == 'y'); // system ("pause"); // return 0; //}
44ed7a8b853196c80539740cea4a3429ca65b80e
23ef5e365496b0b82d566dbb80ea9f0c1140546e
/src/main/cpp/option_processor.cc
3e2f6622122d9d08ca5b3c136e1d5f55eb676a9e
[ "Apache-2.0" ]
permissive
ibmsoe/bazel
dbce1c0b71f58b4590fa84bc86d7b99808a81c80
102841908e9753d128c0341eb2292f3df1e8cd04
refs/heads/master
2021-01-24T00:19:04.109853
2016-07-14T00:09:52
2016-07-14T11:13:00
63,352,564
8
10
null
2016-07-14T16:30:41
2016-07-14T16:30:40
null
UTF-8
C++
false
false
16,878
cc
option_processor.cc
// Copyright 2014 The Bazel Authors. 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 "src/main/cpp/option_processor.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <algorithm> #include <cassert> #include <set> #include <utility> #include "src/main/cpp/blaze_util.h" #include "src/main/cpp/blaze_util_platform.h" #include "src/main/cpp/util/file.h" #include "src/main/cpp/util/strings.h" using std::list; using std::map; using std::set; using std::vector; // On OSX, there apparently is no header that defines this. extern char **environ; namespace blaze { constexpr char BlazeStartupOptions::WorkspacePrefix[]; OptionProcessor::RcOption::RcOption(int rcfile_index, const string& option) : rcfile_index_(rcfile_index), option_(option) { } OptionProcessor::RcFile::RcFile(const string& filename, int index) : filename_(filename), index_(index) { } blaze_exit_code::ExitCode OptionProcessor::RcFile::Parse( const string& workspace, vector<RcFile*>* rcfiles, map<string, vector<RcOption> >* rcoptions, string* error) { list<string> initial_import_stack; initial_import_stack.push_back(filename_); return Parse( workspace, filename_, index_, rcfiles, rcoptions, &initial_import_stack, error); } blaze_exit_code::ExitCode OptionProcessor::RcFile::Parse( const string& workspace, const string& filename_ref, const int index, vector<RcFile*>* rcfiles, map<string, vector<RcOption> >* rcoptions, list<string>* import_stack, string* error) { string filename(filename_ref); // file string contents; if (!ReadFile(filename, &contents)) { // We checked for file readability before, so this is unexpected. blaze_util::StringPrintf(error, "Unexpected error reading .blazerc file '%s'", filename.c_str()); return blaze_exit_code::INTERNAL_ERROR; } // A '\' at the end of a line continues the line. blaze_util::Replace("\\\r\n", "", &contents); blaze_util::Replace("\\\n", "", &contents); vector<string> startup_options; vector<string> lines = blaze_util::Split(contents, '\n'); for (int line = 0; line < lines.size(); ++line) { blaze_util::StripWhitespace(&lines[line]); // Check for an empty line. if (lines[line].empty()) { continue; } vector<string> words; // This will treat "#" as a comment, and properly // quote single and double quotes, and treat '\' // as an escape character. // TODO(bazel-team): This function silently ignores // dangling backslash escapes and missing end-quotes. blaze_util::Tokenize(lines[line], '#', &words); if (words.empty()) { // Could happen if line starts with "#" continue; } string command = words[0]; if (command == "import") { if (words.size() != 2 || (words[1].compare(0, BlazeStartupOptions::WorkspacePrefixLength, BlazeStartupOptions::WorkspacePrefix) == 0 && !BlazeStartupOptions::WorkspaceRelativizeRcFilePath( workspace, &words[1]))) { blaze_util::StringPrintf(error, "Invalid import declaration in .blazerc file '%s': '%s'", filename.c_str(), lines[line].c_str()); return blaze_exit_code::BAD_ARGV; } if (std::find(import_stack->begin(), import_stack->end(), words[1]) != import_stack->end()) { string loop; for (list<string>::const_iterator imported_rc = import_stack->begin(); imported_rc != import_stack->end(); ++imported_rc) { loop += " " + *imported_rc + "\n"; } blaze_util::StringPrintf(error, "Import loop detected:\n%s", loop.c_str()); return blaze_exit_code::BAD_ARGV; } rcfiles->push_back(new RcFile(words[1], rcfiles->size())); import_stack->push_back(words[1]); blaze_exit_code::ExitCode parse_exit_code = RcFile::Parse(workspace, rcfiles->back()->Filename(), rcfiles->back()->Index(), rcfiles, rcoptions, import_stack, error); if (parse_exit_code != blaze_exit_code::SUCCESS) { return parse_exit_code; } import_stack->pop_back(); } else { for (int word = 1; word < words.size(); ++word) { (*rcoptions)[command].push_back(RcOption(index, words[word])); if (command == "startup") { startup_options.push_back(words[word]); } } } } if (!startup_options.empty()) { string startup_args; blaze_util::JoinStrings(startup_options, ' ', &startup_args); fprintf(stderr, "INFO: Reading 'startup' options from %s: %s\n", filename.c_str(), startup_args.c_str()); } return blaze_exit_code::SUCCESS; } OptionProcessor::OptionProcessor() : initialized_(false), parsed_startup_options_(new BlazeStartupOptions()) { } // Return the path of the depot .blazerc file. string OptionProcessor::FindDepotBlazerc(const string& workspace) { // Package semantics are ignored here, but that's acceptable because // blaze.blazerc is a configuration file. vector<string> candidates; BlazeStartupOptions::WorkspaceRcFileSearchPath(&candidates); for (const auto& candidate : candidates) { string blazerc = blaze_util::JoinPath(workspace, candidate); if (!access(blazerc.c_str(), R_OK)) { return blazerc; } } return ""; } // Return the path of the .blazerc file that sits alongside the binary. // This allows for canary or cross-platform Blazes operating on the same depot // to have customized behavior. string OptionProcessor::FindAlongsideBinaryBlazerc(const string& cwd, const string& arg0) { string path = arg0[0] == '/' ? arg0 : blaze_util::JoinPath(cwd, arg0); string base = blaze_util::Basename(arg0); string binary_blazerc_path = path + "." + base + "rc"; if (!access(binary_blazerc_path.c_str(), R_OK)) { return binary_blazerc_path; } return ""; } // Return the path of the bazelrc file that sits in /etc. // This allows for installing Bazel on system-wide directory. string OptionProcessor::FindSystemWideBlazerc() { string path = BlazeStartupOptions::SystemWideRcPath(); if (!path.empty() && !access(path.c_str(), R_OK)) { return path; } return ""; } // Return the path to the user's rc file. If cmdLineRcFile != NULL, // use it, dying if it is not readable. Otherwise, return the first // readable file called rc_basename from [workspace, $HOME] // // If no readable .blazerc file is found, return the empty string. blaze_exit_code::ExitCode OptionProcessor::FindUserBlazerc( const char* cmdLineRcFile, const string& rc_basename, const string& workspace, string* blaze_rc_file, string* error) { if (cmdLineRcFile != NULL) { string rcFile = MakeAbsolute(cmdLineRcFile); if (access(rcFile.c_str(), R_OK)) { blaze_util::StringPrintf(error, "Error: Unable to read .blazerc file '%s'.", rcFile.c_str()); return blaze_exit_code::BAD_ARGV; } *blaze_rc_file = rcFile; return blaze_exit_code::SUCCESS; } string workspaceRcFile = blaze_util::JoinPath(workspace, rc_basename); if (!access(workspaceRcFile.c_str(), R_OK)) { *blaze_rc_file = workspaceRcFile; return blaze_exit_code::SUCCESS; } const char* home = getenv("HOME"); if (home == NULL) { *blaze_rc_file = ""; return blaze_exit_code::SUCCESS; } string userRcFile = blaze_util::JoinPath(home, rc_basename); if (!access(userRcFile.c_str(), R_OK)) { *blaze_rc_file = userRcFile; return blaze_exit_code::SUCCESS; } *blaze_rc_file = ""; return blaze_exit_code::SUCCESS; } blaze_exit_code::ExitCode OptionProcessor::ParseOptions( const vector<string>& args, const string& workspace, const string& cwd, string* error) { assert(!initialized_); initialized_ = true; const char* blazerc = NULL; bool use_master_blazerc = true; // Check if there is a blazerc related option given args_ = args; for (int i= 1; i < args.size(); i++) { const char* arg_chr = args[i].c_str(); const char* next_arg_chr = (i + 1) < args.size() ? args[i + 1].c_str() : NULL; if (blazerc == NULL) { blazerc = GetUnaryOption(arg_chr, next_arg_chr, "--blazerc"); } if (blazerc == NULL) { blazerc = GetUnaryOption(arg_chr, next_arg_chr, "--bazelrc"); } if (use_master_blazerc && (GetNullaryOption(arg_chr, "--nomaster_blazerc") || GetNullaryOption(arg_chr, "--nomaster_bazelrc"))) { use_master_blazerc = false; } } // Parse depot and user blazerc files. // This is a little inefficient (copying a multimap around), but it is a // small one and this way I don't have to care about memory management. vector<string> candidate_blazerc_paths; if (use_master_blazerc) { candidate_blazerc_paths.push_back(FindDepotBlazerc(workspace)); candidate_blazerc_paths.push_back(FindAlongsideBinaryBlazerc(cwd, args[0])); candidate_blazerc_paths.push_back(FindSystemWideBlazerc()); } string user_blazerc_path; blaze_exit_code::ExitCode find_blazerc_exit_code = FindUserBlazerc( blazerc, BlazeStartupOptions::RcBasename(), workspace, &user_blazerc_path, error); if (find_blazerc_exit_code != blaze_exit_code::SUCCESS) { return find_blazerc_exit_code; } candidate_blazerc_paths.push_back(user_blazerc_path); // Throw away missing files, dedupe candidate blazerc paths, and parse the // blazercs, all while preserving order. Duplicates can arise if e.g. the // binary's path *is* the depot path. set<string> blazerc_paths; for (const auto& candidate_blazerc_path : candidate_blazerc_paths) { if (!candidate_blazerc_path.empty() && (blazerc_paths.insert(candidate_blazerc_path).second)) { blazercs_.push_back( new RcFile(candidate_blazerc_path, blazercs_.size())); blaze_exit_code::ExitCode parse_exit_code = blazercs_.back()->Parse(workspace, &blazercs_, &rcoptions_, error); if (parse_exit_code != blaze_exit_code::SUCCESS) { return parse_exit_code; } } } blaze_exit_code::ExitCode parse_startup_options_exit_code = ParseStartupOptions(error); if (parse_startup_options_exit_code != blaze_exit_code::SUCCESS) { return parse_startup_options_exit_code; } // Determine command if (startup_args_ + 1 >= args.size()) { command_ = ""; return blaze_exit_code::SUCCESS; } command_ = args[startup_args_ + 1]; AddRcfileArgsAndOptions(parsed_startup_options_->batch, cwd); for (unsigned int cmd_arg = startup_args_ + 2; cmd_arg < args.size(); cmd_arg++) { command_arguments_.push_back(args[cmd_arg]); } return blaze_exit_code::SUCCESS; } blaze_exit_code::ExitCode OptionProcessor::ParseOptions( int argc, const char* argv[], const string& workspace, const string& cwd, string* error) { vector<string> args(argc); for (int arg = 0; arg < argc; arg++) { args[arg] = argv[arg]; } return ParseOptions(args, workspace, cwd, error); } static bool IsArg(const string& arg) { return blaze_util::starts_with(arg, "-") && (arg != "--help") && (arg != "-help") && (arg != "-h"); } blaze_exit_code::ExitCode OptionProcessor::ParseStartupOptions(string *error) { // Process rcfile startup options map< string, vector<RcOption> >::const_iterator it = rcoptions_.find("startup"); blaze_exit_code::ExitCode process_arg_exit_code; bool is_space_separated; if (it != rcoptions_.end()) { const vector<RcOption>& startup_options = it->second; int i = 0; // Process all elements except the last one. for (; i < startup_options.size() - 1; i++) { const RcOption& option = startup_options[i]; const string& blazerc = blazercs_[option.rcfile_index()]->Filename(); process_arg_exit_code = parsed_startup_options_->ProcessArg( option.option(), startup_options[i + 1].option(), blazerc, &is_space_separated, error); if (process_arg_exit_code != blaze_exit_code::SUCCESS) { return process_arg_exit_code; } if (is_space_separated) { i++; } } // Process last element, if any. if (i < startup_options.size()) { const RcOption& option = startup_options[i]; if (IsArg(option.option())) { const string& blazerc = blazercs_[option.rcfile_index()]->Filename(); process_arg_exit_code = parsed_startup_options_->ProcessArg( option.option(), "", blazerc, &is_space_separated, error); if (process_arg_exit_code != blaze_exit_code::SUCCESS) { return process_arg_exit_code; } } } } // Process command-line args next, so they override any of the same options // from .blazerc. Stop on first non-arg, this includes --help unsigned int i = 1; if (!args_.empty()) { for (; (i < args_.size() - 1) && IsArg(args_[i]); i++) { process_arg_exit_code = parsed_startup_options_->ProcessArg( args_[i], args_[i + 1], "", &is_space_separated, error); if (process_arg_exit_code != blaze_exit_code::SUCCESS) { return process_arg_exit_code; } if (is_space_separated) { i++; } } if (i < args_.size() && IsArg(args_[i])) { process_arg_exit_code = parsed_startup_options_->ProcessArg( args_[i], "", "", &is_space_separated, error); if (process_arg_exit_code != blaze_exit_code::SUCCESS) { return process_arg_exit_code; } i++; } } startup_args_ = i -1; return blaze_exit_code::SUCCESS; } // Appends the command and arguments from argc/argv to the end of arg_vector, // and also splices in some additional terminal and environment options between // the command and the arguments. NB: Keep the options added here in sync with // BlazeCommandDispatcher.INTERNAL_COMMAND_OPTIONS! void OptionProcessor::AddRcfileArgsAndOptions(bool batch, const string& cwd) { // Provide terminal options as coming from the least important rc file. command_arguments_.push_back("--rc_source=client"); command_arguments_.push_back("--default_override=0:common=--isatty=" + ToString(IsStandardTerminal())); command_arguments_.push_back( "--default_override=0:common=--terminal_columns=" + ToString(GetTerminalColumns())); // Push the options mapping .blazerc numbers to filenames. for (int i_blazerc = 0; i_blazerc < blazercs_.size(); i_blazerc++) { const RcFile* blazerc = blazercs_[i_blazerc]; command_arguments_.push_back("--rc_source=" + blaze::ConvertPath(blazerc->Filename())); } // Push the option defaults for (map<string, vector<RcOption> >::const_iterator it = rcoptions_.begin(); it != rcoptions_.end(); ++it) { if (it->first == "startup") { // Skip startup options, they are parsed in the C++ wrapper continue; } for (int ii = 0; ii < it->second.size(); ii++) { const RcOption& rcoption = it->second[ii]; command_arguments_.push_back( "--default_override=" + ToString(rcoption.rcfile_index() + 1) + ":" + it->first + "=" + rcoption.option()); } } // Pass the client environment to the server in server mode. if (batch) { command_arguments_.push_back("--ignore_client_env"); } else { for (char** env = environ; *env != NULL; env++) { command_arguments_.push_back("--client_env=" + string(*env)); } } command_arguments_.push_back("--client_cwd=" + blaze::ConvertPath(cwd)); const char *emacs = getenv("EMACS"); if (emacs != NULL && strcmp(emacs, "t") == 0) { command_arguments_.push_back("--emacs"); } } void OptionProcessor::GetCommandArguments(vector<string>* result) const { result->insert(result->end(), command_arguments_.begin(), command_arguments_.end()); } const string& OptionProcessor::GetCommand() const { return command_; } const BlazeStartupOptions& OptionProcessor::GetParsedStartupOptions() const { return *parsed_startup_options_.get(); } OptionProcessor::~OptionProcessor() { for (auto it : blazercs_) { delete it; } } } // namespace blaze
b06a780e89504ad931978bd3f3c330cf55659157
ad7bd0a23b3ba39fbc8bae47f3ee421c984f9ef0
/include/main.h
be0e3458409508431831951c0ff372a819a1f041
[]
no_license
xiandongz/RutherfordScatter
1c4bb4a7c674788ca075150cb0c3ca9d42373fab
9e39c3e7a2edce3d8a27f71b1e90bb32bcf73777
refs/heads/master
2020-03-28T09:46:45.969169
2018-09-09T19:34:25
2018-09-09T19:34:25
148,059,161
0
1
null
null
null
null
UTF-8
C++
false
false
235
h
main.h
#ifndef Main_h #define Main_h #include<iostream> #include<iomanip> #include<string> #include<fstream> #include<stdio.h> #include <TH1.h> #include <TLorentzVector.h> #include <TFile.h> #include <TTree.h> using namespace std; #endif
d10ed505283d6096386fc72c578e4aa005162996
0e9db6e1f2f4ffea6b21deb61d5acee54e28e8fd
/src/tf2odom.cpp
bb3d5532731288e9c288e4dcffe33a38d39e65e6
[ "Apache-2.0" ]
permissive
arpg/carplanner_msgs
f914fe9d176c29e2a828de9af810a82f64578059
3efe558262c358a15077280c8e23438d0eb4463d
refs/heads/master
2022-07-30T17:54:57.280888
2022-06-22T20:31:03
2022-06-22T20:31:03
188,785,730
0
0
null
null
null
null
UTF-8
C++
false
false
2,061
cpp
tf2odom.cpp
#include <ros/ros.h> #include <tf/transform_listener.h> #include <tf/transform_datatypes.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/Point.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/TransformStamped.h> int main(int argc, char** argv){ ros::init(argc, argv, "robot_odom_publisher"); ros::NodeHandle node; ros::NodeHandle pnode("~"); std::string parent_frame, child_frame, odom_topic; pnode.param("parent_frame", parent_frame, std::string("world")); pnode.param("child_frame", child_frame, std::string("base_link")); pnode.param("odom_topic", odom_topic, std::string("odometry")); double rate_; pnode.param("rate", rate_, (double)50); ros::Publisher robot_odom_pub = node.advertise<nav_msgs::Odometry>(odom_topic, 10); tf::TransformListener listener; nav_msgs::Odometry odom_msg; geometry_msgs::TransformStamped tf_msg; geometry_msgs::Quaternion quat_msg; geometry_msgs::PointStamped point_msg; odom_msg.header.frame_id = parent_frame; ros::Rate rate(rate_); while (node.ok()){ rate.sleep(); ros::spinOnce(); tf::StampedTransform transform; try{ listener.lookupTransform(parent_frame.c_str(), child_frame.c_str(), ros::Time(0), transform); odom_msg.header.stamp = ros::Time::now(); odom_msg.pose.pose.position.x = transform.getOrigin().x(); odom_msg.pose.pose.position.y = transform.getOrigin().y(); odom_msg.pose.pose.position.z = transform.getOrigin().z(); tf::quaternionTFToMsg(transform.getRotation().normalize(), odom_msg.pose.pose.orientation); robot_odom_pub.publish(odom_msg); } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); // ros::Duration(0.1).sleep(); } /* point_msg.header.stamp = ros::Time::now(); point_msg.point.x = odom_msg.pose.pose.position.x; point_msg.point.y = odom_msg.pose.pose.position.y; point_msg.point.z = odom_msg.pose.pose.position.z; robot_point_pub.publish(point_msg); */ } return 0; };
44b105393877b2f5b916d147ae08657e8f1814cb
0aead7d30688caec4ee3ca4b0293888aff69c5a3
/examProblems/P81453.cc
a8e578d72456c2325479e903b6a31591c52f5fce
[]
no_license
GarJor/EDA
63fbe6be79df16d1afe91a96a1470f50b54c3d6a
ccf1b98f3410434b63e230a9848df7797bb028be
refs/heads/master
2020-04-09T14:13:01.564283
2018-12-13T17:44:06
2018-12-13T17:44:06
160,390,466
0
0
null
null
null
null
UTF-8
C++
false
false
800
cc
P81453.cc
#include <iostream> #include <vector> #include <queue> #include <stack> #include <set> using namespace std; typedef vector<int> VI; typedef vector<set<int> > VVI; VI bfs(int v, VVI& g){ VI p(v, -1); VI s(v, -1); queue<int> Q; Q.push(0); p[0] = -2; s[0] = 0; while(!Q.empty()){ int o = Q.front(); Q.pop(); if(o == v-1) return p; for(int a : g[o]){ if(s[a] == -1 ){ p[a] = o; s[a] = s[o]+1; Q.push(a); } } } return VI(); } int main(){ int v, a; while(cin >> v >>a){ VVI g(v); while(--a >= 0){ int x, y; cin >> x >> y; g[x].insert(y); } VI res = bfs(v, g); int cursor = v-1; stack<int> S; while(res[cursor] > -1) { S.push(cursor); cursor = res[cursor]; } cout << 0; while(!S.empty()){ cout << ' ' << S.top(); S.pop(); } cout << endl; } }
e76d12591c2058ba82bdcf991d5c65247743d984
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5686313294495744_0/C++/Yao/c.cc
94ee3f47e325a56aad29dbfb610cdb4f8357f780
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
634
cc
c.cc
#include<stdio.h> #include<string.h> char s[16][2][1024]; int a[2][16]; int dp[1<<16]; char str[1024]; int main() { int N,cs=0,i,j,k,n; for(scanf("%d",&N);N--;) { scanf("%d",&n); for(i=0;i<n;i++) scanf("%s %s",s[i][0],s[i][1]); memset(a,0,sizeof(a)); for(i=0;i<2;i++) for(j=0;j<n;j++) { for(k=0;k<n;k++) if (!strcmp(s[j][i],s[k][i])) a[i][j]|=1<<k; } memset(dp,0,sizeof(dp)); for(i=0;i<(1<<n);i++) { for(j=0;j<n;j++) if (!(i&(1<<j))) { if ((i&a[0][j])!=0 && (i&a[1][j])!=0) { if (dp[i]+1>dp[i|(1<<j)]) dp[i|(1<<j)]=dp[i]+1; } } } printf("Case #%d: %d\n",++cs,dp[(1<<n)-1]); } return 0; }
8dce16b9554296bc2e57f3a6c3001741822277c3
c3af582a76e5d7c7ea2885a9df73b5e0ba06853e
/libs/image_toolbox/Convert.cpp
c24752de73110b6d52652414b889270f582e001d
[ "LicenseRef-scancode-public-domain-disclaimer" ]
permissive
paprikamario/colorchecker
73b0fed1fd39570240824bd35029b30de4e51732
433acb8688b6926534f4162956ccc79a66a4f2f5
refs/heads/master
2022-02-14T19:26:26.802376
2017-12-31T16:41:39
2017-12-31T16:41:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,171
cpp
Convert.cpp
#include "Convert.hpp" #include <algorithm> #include <vector> #include <opencv2/opencv.hpp> #include <common/Logging.hpp> namespace komb { std::vector<cv::Mat1b> rgb2Cmyk(const cv::Mat3b& img) { // Adapted from https://gist.github.com/wyudong/9c392578c6247e7d1d28 std::vector<cv::Mat1b> ret; // Allocate CMYK to store 4 components for (int i = 0; i < 4; ++i) { ret.push_back(cv::Mat(img.size(), CV_8UC1)); } std::vector<cv::Mat> rgb; cv::split(img, rgb); for (int i = 0; i < img.rows; ++i) { for (int j = 0; j < img.cols; ++j) { float r = rgb[2].at<uchar>(i, j) / 255.0f; float g = rgb[1].at<uchar>(i, j) / 255.0f; float b = rgb[0].at<uchar>(i, j) / 255.0f; float k = std::min(std::min(1 - r, 1 - g), 1 - b); ret[0].at<uchar>(i, j) = (1 - r - k) / (1 - k) * 255.0f; ret[1].at<uchar>(i, j) = (1 - g - k) / (1 - k) * 255.0f; ret[2].at<uchar>(i, j) = (1 - b - k) / (1 - k) * 255.0f; ret[3].at<uchar>(i, j) = k * 255.0f; } } return ret; } cv::Mat convertAndRescale(const cv::Mat& src) { cv::Mat out; convertAndRescale(src, out); return out; } // Only to 8 bit. void convertAndRescale(const cv::Mat& src, cv::Mat& out_image) { double minVal, maxVal; minMaxLoc(src, &minVal, &maxVal); src.convertTo(out_image, CV_8U, 255.0 / (maxVal - minVal), -minVal * 255.0 / (maxVal - minVal)); } cv::Mat rescale(const cv::Mat& src) { cv::Mat dst; double dst_max = src.depth() == CV_8U ? 255.0 : 1.0; cv::normalize(src, dst, 0, dst_max, cv::NORM_MINMAX); return dst; } cv::Mat toFloatMat(const cv::Mat& mat) { if (mat.depth() == CV_32F) { return mat; } cv::Mat image; if (mat.depth() == CV_8U) { mat.convertTo(image, CV_32F, 1.0 / 255.0); } else { mat.convertTo(image, CV_32F); } return image; } cv::Mat3b ignoreAlpha(const cv::Mat4b& img) { cv::Mat1b channels[4]; cv::split(img, channels); cv::Mat3b out; cv::merge(channels, 3, out); return out; } } // namespace komb
db2e9b886b313a5b9ee21b1167b53fa782107ebb
48d6a1e371647852275033ead360e37f97199be7
/DHDCC.h
15871211292e7514a9a6f42a08d4bef1a198d755
[]
no_license
OneginForte/DCC_decoder
7445ef5dd55bb09bb8454c0305173bd6a9920feb
34dea52fd56d2ef8c5fd071a3c793d4160f3aff9
refs/heads/master
2022-07-04T16:36:52.125699
2020-05-19T20:00:25
2020-05-19T20:00:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,081
h
DHDCC.h
#ifndef H_DHDCC_03032016 #define H_DHDCC_03032016 // --------------------------------------------------------------------------------------------------------------------------------------------------------------- // Simple DCC decoder // Vasily Vasilchikov // doublehead@mail.ru // http://scaletrainsclub.com/board // --------------------------------------------------------------------------------------------------------------------------------------------------------------- #include <Arduino.h> #include <EEPROM.h> #define DHDCC_EEPROM_LENGTH 1024 #define DHDCC_MaxPacketLength 5 // Maximum DCC Packet Length // Multi Function Digital Decoder // #define DHDCC_MFDD // Accessory Digital Decoder #define DHDCC_ADD // Number of adresses served by accessory decoder (base adress + slave adresses) e.g. for adresses 10,11,12 - DHDCC_ADD_ADRESSES=3 #define DHDCC_ADD_ADRESSES 2 // --------------------------------------------------------------------------------------------------------------------------------------------------------------- // class for holding DCC packet // --------------------------------------------------------------------------------------------------------------------------------------------------------------- class DCCPacket{ public: DCCPacket(void); void SetDHDCC_ADDress(volatile byte * InDHDCC_ADDress); bool PushData(volatile byte * InData); byte GetDHDCC_ADDress(void); byte GetDataLength(void); byte GetData(byte Position); void Clear(); private: byte DataPositionCounter; byte DHDCC_ADDress; byte Data[DHDCC_MaxPacketLength-1]; }; // --------------------------------------------------------------------------------------------------------------------------------------------------------------- // class for holding DCC packets stack // --------------------------------------------------------------------------------------------------------------------------------------------------------------- /*class DCCPacketStack{ public: DCCPacketStack(void); bool PushPacket(DCCPacket * InPacket); bool PopPacket(DCCPacket * OutPacket); void Clear(void); private: byte StoredPackets; byte LastStoredPacketPosition; DCCPacket Packets[10]; };*/ // --------------------------------------------------------------------------------------------------------------------------------------------------------------- // Main library class // --------------------------------------------------------------------------------------------------------------------------------------------------------------- class DHDCC{ public: void DecoderSetup(byte InPin); bool GetFnState(byte InFN); bool GetOutputState(byte InOutput); byte GetSpeed(); byte GetDirection(); }; bool DHDCC_GlobalFN(byte InFN); bool DHDCC_GlobalFNSet(byte InFN, byte InState); bool DHDCC_GlobalOutput(byte InOutput); bool DHDCC_GlobalOutputSet(byte InOutput, byte InState); void DHDCC_ProcessPackets(void); void DCC_ISR(); #endif //H_DHDCC_03032016
9cd3d8005274012b9d8ade7453543c954467f75f
cdd1901812799e5542ac6c2ecd5af06eb30aeacd
/Projects/UAV/comprehensive/main.cpp
36838caddb94a01e66b0562a690db0e91848c875
[]
no_license
thinkinchaos/Tools
ff0030494996493aa75b355880961a5d6b511ba6
f0571d101c7003ded516b036ce2d6552d38b443f
refs/heads/master
2023-06-10T01:30:29.285972
2021-07-01T02:09:51
2021-07-01T02:09:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
132
cpp
main.cpp
#include "detect.h" int iModel = 0; int main() { CDetect detect; detect.ChooseModel(iModel); system("pause"); return 0; }
8efa5f3ac9d30565f0870ac35304efaeca899ff9
8a61877a1c32c48c763f28bf3064feb9aba35b99
/178798/178798/Question1.cpp
7db316584bc38b3368f7870bbe48e9b73b134b1c
[]
no_license
fresh1000/visual_studio
cafae53dd8577a3241d3b8150ee2b28be9505da7
95ea0f8bc19b95606a07b0e6bcfcecffb65b026a
refs/heads/master
2021-01-19T22:10:22.487959
2017-10-27T20:24:17
2017-10-27T20:24:17
88,763,826
0
0
null
null
null
null
UTF-8
C++
false
false
2,559
cpp
Question1.cpp
#include <iostream> #include <string> using namespace std; struct WorkShop { string title; int capacity; double price; }; WorkShop myWorkShop[4]; void initialize(); void listWS(); void registerWS(string); void listSelectedWS(string); int main() { initialize(); int choice; do { cout << "******** Main Menu ***********" << endl; cout << "1. List all workshops" << endl; cout << "2. Register workshop" << endl; cout << "3. List details of selected workshop" << endl; cout << "4. Exit" << endl; cout << "Enter choice:"; cin >> choice; cin.clear(); string titleReg = ""; string titleList = ""; switch (choice) { case 1: listWS(); break; case 2: cout << "Enter title: "; cin.ignore(); getline(cin, titleReg); registerWS(titleReg); break; case 3: cout << "Enter title: "; cin.ignore(); getline(cin, titleList); listSelectedWS(titleList); break; default: break; } } while (choice != 4); system("pause"); return 0; } void initialize() { myWorkShop[0].title = "Interactive Python 1"; myWorkShop[0].capacity = 20; myWorkShop[0].price = 1000; myWorkShop[1].title = "Embedded C Programming"; myWorkShop[1].capacity = 15; myWorkShop[1].price = 2000, 5; myWorkShop[2].title = "Interactive Python 2"; myWorkShop[2].capacity = 20; myWorkShop[2].price = 1000; myWorkShop[3].title = "Python & Data Scientist"; myWorkShop[3].capacity = 10; myWorkShop[3].price = 2000; } void listWS() { for (int i = 0; i < 4; i++) { cout << "Title: " << myWorkShop[i].title << endl; cout << "Capacity: " << myWorkShop[i].capacity << endl; cout << "Price: " << myWorkShop[i].price << endl; } } void registerWS(string title) { bool found = false; for (int i = 0; i < 4; i++) { if (myWorkShop[i].title == title && myWorkShop[i].capacity == 0 && !found) { cout << "Unsuccessful registration, no more vacancy!!" << endl; found = true; } if (myWorkShop[i].title == title && myWorkShop[i].capacity > 0 && !found) { cout << "Successfull registration!" << endl; myWorkShop[i].capacity--; found = true; } } if (!found) { cout << "Record not found!" << endl; } } void listSelectedWS(string title) { bool found = false; for (int i = 0; i < 4; i++) { if (myWorkShop[i].title == title) { cout << "Title: " << myWorkShop[i].title << endl; cout << "Capacity: " << myWorkShop[i].capacity << endl; cout << "Price: " << myWorkShop[i].price << endl; found = true; } } if (!found) { cout << "Record not found!" << endl; } }
d673c6458f341ee5764e01d65c425a85aabecd88
9f363e01f2c8f02d7409753669c757d1532b44a3
/rush01/display/GuiDisplay.hpp
dddfbd03e036562812a93e3af962cc9a65372023
[]
no_license
LastSymbol0/cpp_piscine
18d546b76b5003c878343996843ac7ab126c320d
c32fac08e101e565367ff536f30036a412b76a51
refs/heads/master
2020-08-15T03:11:38.333888
2019-10-15T10:32:07
2019-10-15T10:32:07
215,271,451
1
0
null
null
null
null
UTF-8
C++
false
false
1,539
hpp
GuiDisplay.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* GuiDisplay.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aillia <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/13 15:41:03 by aillia #+# #+# */ /* Updated: 2019/10/13 15:41:04 by aillia ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef GUIDISPLAY_HPP # define GUIDISPLAY_HPP # include "IMonitorDisplay.hpp" # include "ft_gkrellm.hpp" # define G_W_WIDTH 640 # define G_W_HEIGHT 440 class GuiDisplay : public IMonitorDisplay { private: SDL_Window *win; SDL_GLContext gl_context; struct nk_context *ctx; struct nk_colorf bg; GuiDisplay(GuiDisplay const & arg); GuiDisplay & operator=(GuiDisplay const & arg); public: GuiDisplay(/* args */); ~GuiDisplay(); void draw(); void draw_os(); void draw_hostname(); void draw_date(); void draw_cpu(); void draw_ram(); void draw_net(); void evt(); void nk_exit(); }; #endif /* GUIDISPLAY_HPP */
6d52f574b74e97ac69c17d22cf1185cc2dc898ab
46e1aeefa494780545a844f4f77e9d81bdf047dd
/2.server/CROServer/manager/classinfomanager.cpp
998a8298835a735a809e247c947a101f75b572ff
[]
no_license
luonglh90/classroomonline
7f90489edc331fe1ecbe4e426fc361bbb6ac3796
6220ad5411f9099303743d0c04fbf0d073d1f676
refs/heads/master
2021-01-10T07:41:58.617338
2016-04-10T03:47:26
2016-04-10T03:47:26
55,824,018
0
0
null
null
null
null
UTF-8
C++
false
false
2,699
cpp
classinfomanager.cpp
#include <QDebug> #include "../../msg/cpp/ClassroomInfoOfCategory.pb.h" #include "pgdao/classcategorydao.h" #include "pgdao/classinfodao.h" #include "utils/messagesender.h" #include "utils/stringutils.h" #include "usermanager.h" #include "classinfomanager.h" ClassInfoManager *ClassInfoManager::mInstance = nullptr; ClassInfoManager::ClassInfoManager(QObject *parent) : QObject(parent) { } ClassInfoManager *ClassInfoManager::instance() { if(!mInstance) { mInstance = new ClassInfoManager(); } return mInstance; } void ClassInfoManager::loadAllCategory() { ClassCategoryDAO categoryDAO; QList<ClassCategory> list; bool isOk; QString errMsg; categoryDAO.getAllClassCategory(list, isOk, errMsg); if(isOk) { qDebug() << "get class category: " << list.size(); foreach (const ClassCategory &category, list) { mHashClassCategory.insert(StringUtils::stringToInt(category.u_id()), category); } } else { qDebug() << "error: " << errMsg; } } void ClassInfoManager::loadAllClassroomInfo() { ClassInfoDAO classDAO; QList<ClassroomInfo> list; bool isOk; QString errMsg; classDAO.getAllClassInfo(list, isOk, errMsg); if(isOk) { qDebug() << "get class: " << list.size(); foreach (const ClassroomInfo &classInfo, list) { mHashClassroomInfo.insert(StringUtils::stringToInt(classInfo.uid()), classInfo); } } else { qDebug() << "error: " << errMsg; } } QList<ClassroomInfo> ClassInfoManager::getOwnerClasses(QString username) { QList<ClassroomInfo> result; for(const ClassroomInfo &info : mHashClassroomInfo.values()) { if(QString::fromStdString(info.teacher()).compare(username) == 0) { result.append(info); } } return result; } ClassroomInfo ClassInfoManager::getClassById(int classId) { ClassroomInfo info; if(mHashClassroomInfo.contains(classId)) { info = mHashClassroomInfo.value(classId); } return info; } void ClassInfoManager::sendClassroomOfCategory(int socketuid, int cate_id) { QList<ClassroomInfo> listOfClasses; for(ClassroomInfo &info : mHashClassroomInfo.values()) { if(StringUtils::stringToInt(info.cateid()) == cate_id) { listOfClasses.append(info); } } ClassroomInfoOfCategory msg; msg.set_cateid(std::to_string(cate_id)); for(ClassroomInfo &info : listOfClasses) { ClassroomInfo *data = msg.add_listofclasses(); (*data) = info; } MessageSender::instance()->sendIpcMessage(socketuid, &msg); }
432808e11a7050936765a237d6310c5e1627983d
a8880d5cbd16bb0c8c1a871370b22d46ca821bd7
/filters/GaussianFilter.cpp
3e8510a1deece76b6f75990c1247cfd740afe52c
[]
no_license
Totktonada/ImageProcessor
53c7f9692360cdd9573a40758a85462dbf6c1ea0
ab94496d44be6f5f156c61a96c703b93e9e385b6
refs/heads/master
2021-01-19T17:11:39.662338
2012-10-07T17:31:07
2012-10-07T17:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,778
cpp
GaussianFilter.cpp
#include <string.h> #include <QImage> #include <QtGlobal> #include <QtCore/qmath.h> #include "GaussianFilter.hpp" #include "../Utils.hpp" #include "../Constants.hpp" GaussianFilter::GaussianFilter(double aSigma) : sigma(aSigma) { wRadius = (uint) (sigma * 3 + 1.0); double * kernel = new double[wRadius + 1]; double sum = 0.0; kernel[0] = 1.0; for (uint w = 1; w <= wRadius; ++w) { kernel[w] = qExp(- ((int) (w * w)) / (2.0 * sigma * sigma)); sum += kernel[w]; } sum = sum * 2 + 1.0; /* Normalization */ kernel[0] /= sum; for (uint w = 1; w <= wRadius; ++w) { kernel[w] /= sum; } setColorCache(kernel); } GaussianFilter::~GaussianFilter() { delete[] colorCache; } QImage * GaussianFilter::filter(const QImage & source) const { uint w = source.width(); uint h = source.height(); QImage * dest = new QImage(source); QRgb * to = reinterpret_cast<QRgb *>(dest->bits()); const QRgb * rgb = reinterpret_cast<const QRgb *>(source.constBits()); QImage * mediumImage = new QImage(source); QRgb * medium = reinterpret_cast<QRgb *>(mediumImage->bits()); for (int y = area.y(); y < area.y() + area.height(); ++y) { for (int x = area.x(); x < area.x() + area.width(); ++x) { medium[y * w + x] = processRow(rgb, x, y, w, h); } } for (int y = area.y(); y < area.y() + area.height(); ++y) { for (int x = area.x(); x < area.x() + area.width(); ++x) { to[y * w + x] = processColumn(medium, x, y, w, h); } } delete mediumImage; return dest; } uint GaussianFilter::getWindowRadius() const { return wRadius; } QRgb GaussianFilter::processRow(const QRgb * rgb, uint x, uint y, uint w, uint h) const { QRgb pixel1 = rgb[Utils::coordinate(x, y, w, h)]; QRgb pixel2; double resR = colorCache[qRed(pixel1)]; double resG = colorCache[qGreen(pixel1)]; double resB = colorCache[qBlue(pixel1)]; uint base = COLORS; for (uint wx = 1; wx <= wRadius; ++wx) { pixel1 = rgb[Utils::coordinate(x - wx, y, w, h)]; pixel2 = rgb[Utils::coordinate(x + wx, y, w, h)]; resR += colorCache[base + qRed(pixel1)] + colorCache[base + qRed(pixel2)]; resG += colorCache[base + qGreen(pixel1)] + colorCache[base + qGreen(pixel2)]; resB += colorCache[base + qBlue(pixel1)] + colorCache[base + qBlue(pixel2)]; base += COLORS; } return qRgb(resR, resG, resB); } QRgb GaussianFilter::processColumn(const QRgb * rgb, uint x, uint y, uint w, uint h) const { QRgb pixel1 = rgb[Utils::coordinate(x, y, w, h)]; QRgb pixel2; double resR = colorCache[qRed(pixel1)]; double resG = colorCache[qGreen(pixel1)]; double resB = colorCache[qBlue(pixel1)]; uint base = COLORS; for (uint wy = 1; wy <= wRadius; ++wy) { pixel1 = rgb[Utils::coordinate(x, y - wy, w, h)]; pixel2 = rgb[Utils::coordinate(x, y + wy, w, h)]; resR += colorCache[base + qRed(pixel1)] + colorCache[base + qRed(pixel2)]; resG += colorCache[base + qGreen(pixel1)] + colorCache[base + qGreen(pixel2)]; resB += colorCache[base + qBlue(pixel1)] + colorCache[base + qBlue(pixel2)]; base += COLORS; } return qRgb(resR, resG, resB); } void GaussianFilter::setColorCache(double * kernel) { colorCache = new double[(wRadius + 1) * COLORS]; uint j = 0; /* (j == w * wSize + i) */ for (uint w = 0; w <= wRadius; ++w) { for (uint i = 0; i < COLORS; ++i) { colorCache[j] = kernel[w] * i; ++j; } } }
0c583639c4152ea69043391a7ad946e851f789e8
83163f5c7ef993433af5c39817cee1d7991e95d4
/GameDoD.cpp
259a342a5f06c842a7c28092ff8648e8ca8ea2ed
[]
no_license
sukwoo22/DataOrientedDesign
efdfcb78611a805c5c3c7c1e29e4473491c85e69
d93e28ebedbfc556653e8c1dbbc86aa7a346225b
refs/heads/master
2020-06-30T18:00:47.381234
2016-11-21T11:25:25
2016-11-21T11:25:25
74,356,037
0
0
null
null
null
null
UHC
C++
false
false
3,552
cpp
GameDoD.cpp
// DoD를 적용한 Entity System #include <vector> enum ComponentType { AI, PHYSICS, RENDERING }; class Component { public: virtual ~Component() {} virtual void Update() = 0; private: int cId; }; class UnitAI :public Component { public: virtual ~UnitAI() {} virtual void Update(); }; class UnitPhysics :public Component { public: virtual ~UnitPhysics() {} virtual void Update(); }; class UnitRendering :public Component { public: virtual ~UnitRendering() {} virtual void Update(); void Render(); bool IsAcitve(); }; class Entity { public: Component *GetComponent(int id); void AddComponent(Component *comp); void RemoveComponent(int id); bool HasComponent(int id); std::vector<Component*> GetComponents() { return mComponents; } private: std::vector<Component *> mComponents; int eId; }; class AISystem { public: UnitAI GetAIComponent(int id); void AddAIComponent(UnitAI ai); void RemoveAIComponent(int id); bool HasAIComponent(int id); void Update() { for (auto i = 0; i < AIComponents.size(); ++i) { AIComponents[i].Update(); } } private: std::vector<UnitAI> AIComponents; }; class PhysicsSystem { public: UnitPhysics GetPhysicsComponent(int id); void AddPhysicsComponent(UnitPhysics phy); void RemovePhysicsComponent(int id); bool HasPhysicsComponent(int id); void Update() { for (auto i = 0; i < PhysicsComponents.size(); ++i) { PhysicsComponents[i].Update(); } } private: std::vector<UnitPhysics> PhysicsComponents; }; // 더티 플래그가 있는 렌더링 시스템 class RenderingSystem { public: UnitRendering GetRenderingComponent(int id); void AddRenderingComponent(UnitRendering phy); void RemoveRenderingComponent(int id); bool HasRenderingComponent(int id); void Update() { for (auto i = 0; i < RenderingComponents.size(); ++i) { RenderingComponents[i].Update(); } } void Render() { for (auto i = 0; i < RenderingComponents.size(); ++i) { if (RenderingComponents[i].IsActive()) // 더티 플래그 RenderingComponents[i].Render(); } } private: std::vector<UnitRendering> RenderingComponents; }; // 더티 플래그를 없앤 렌더링 시스템 class RenderingSystem { public: UnitRendering GetRenderingComponent(int id); void AddRenderingComponent(UnitRendering phy); void RemoveRenderingComponent(int id); bool HasRenderingComponent(int id); void Update() { for (auto i = 0; i < RenderingComponents.size(); ++i) { AllRenderingComponents[i].Update(); } } void Render() { for (auto i = 0; i < ActiveRenderingComponents.size(); ++i) { ActiveRenderingComponents[i].Render(); } } private: std::vector<UnitRendering> AllRenderingComponents; std::vector<UnitRendering> ActiveRenderingComponents; }; class Engine { public: void Init(); void Update(float dt) { AIComponents.Update(); PhysicsComponents.Update(); RenderComponents.Update(); } void Render() { RenderComponents.Render(); } void MainLoop() { Update(timer.GetDeltaTime()); Render(); } private: AISystem AIComponents; PhysicsSystem PhysicsComponents; RenderingSystem RenderComponents; Timer timer; }; class Timer { public: float GetDeltaTime(); }; class Animation{}; class Vector{}; class LootType {}; // 한산한 코드와 빈번한 코드 나누기 class AIComponent { public: void Update(); private: Animation* animation; double evergy_; Vector goalPos; LootDrop* Loot; }; class LootDrop { friend class AIComponent; LootType drop; int minDrops; int maxDrops; double changeOfDrop; };
c071c9ca44c3a81cdbd5f8233706e33728822856
a19c26c5497442d1b73bc2081f5194105a713fd5
/src/mycobot_hw_interface_node.cc
1a6607656816d592c948df773c7b39dfa63b4962
[ "BSD-3-Clause", "MIT", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mertcookimg/mycobot_controller
b76fd41b144e66d8586fc03b67d520118b470569
36f72659df65613aeeee3623f62cbdfcfd231d9d
refs/heads/main
2023-04-26T20:38:37.291979
2021-02-11T09:58:58
2021-02-11T09:58:58
334,960,675
3
1
MIT
2021-02-13T15:25:53
2021-02-01T13:35:34
C++
UTF-8
C++
false
false
603
cc
mycobot_hw_interface_node.cc
#include "mycobot_robot.hh" #include <ros/ros.h> #include <controller_manager/controller_manager.h> using namespace mycobot_controller; int main(int argc, char* argv[]) { ros::init(argc, argv, "mycobot_controller"); MycobotHW robot = MycobotHW(); controller_manager::ControllerManager manager(&robot); ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner(1); spinner.start(); while (ros::ok()) { robot.read(); manager.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } return 0; }
761be0898302bcfb6a824d9509506d8315577d98
c445eef5728bdbec0c5dda137c0e05bf6ced8209
/cinemaengcomp_servidor/PROGRAMA_ARDUINO_FINALIZADO/PROGRAMA_ARDUINO_FINALIZADO.ino
e18f5ae28c58af5762252a80696846a0972eea46
[]
no_license
CinemaEngComp/cinemaengcomp
315ae14a9bb6cf5ae97131c55b04b0b811386713
a9c1bfb210a7edbb4286cb09370d4005aa05ffff
refs/heads/master
2021-08-27T23:48:23.506845
2017-12-10T19:57:59
2017-12-10T19:57:59
110,857,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,536
ino
PROGRAMA_ARDUINO_FINALIZADO.ino
char letra; char numero; char lig_des; #include <SoftwareSerial.h> SoftwareSerial mySerial(10, 11); // RX flutuante, TX + resistor void setup() { pinMode(12, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); digitalWrite(12, 0); digitalWrite(8, 1); digitalWrite(9, 0); mySerial.begin(9600); Serial.begin(9600); } void loop() { if (mySerial.available() > 20) { while (mySerial.available() > 0) { letra = mySerial.read(); if (letra == 'v') { letra = mySerial.read(); Serial.print(letra); if (letra == 'v') { letra = mySerial.read(); Serial.print(letra); if (letra == 'v') { letra = mySerial.read(); Serial.print(letra); for(int h = 0 ; h < 1; h++){ if (letra == 'a') { Serial.print("Poltrona A1"); numero = mySerial.read(); lig_des = mySerial.read(); if (numero == '1') { if (lig_des == 'x') { digitalWrite(12, 0); digitalWrite(9, LOW ); digitalWrite(8, HIGH); } else { digitalWrite(12, 1); digitalWrite(9,HIGH); digitalWrite(8, LOW); } } else {} } } } } } } } }
ae268e3b790223a536c4c81ff8ec5fe78f286ac2
b056d0fe999effc1f0a4b20a0f64aaf10567457a
/extension/qiniu/src/gwjQiniu/gwjQiniu.cpp
8852bd80dfc49e8d12706ccee5274be66216cdd3
[]
no_license
gerrykwok/gwjtest_defold
fa5a9b2327bd30fd5d15701ffa23abdf74454660
1f403e8cf5013bc7faf5e68dda0dd07852c6564e
refs/heads/master
2020-03-17T13:08:36.621496
2019-05-31T11:08:34
2019-05-31T11:08:34
133,618,873
1
0
null
null
null
null
UTF-8
C++
false
false
2,089
cpp
gwjQiniu.cpp
////////////////////////////////////////////////////////////////////////// #if defined(DM_PLATFORM_WINDOWS) || defined(DM_PLATFORM_OSX) #include <thread> #include "../qiniu.h" #include "gwjQiniu.h" extern "C" int Qiniu_win32_upload(const char *token, const char *name, const char *localPath, char *message); extern "C" void Qiniu_mac_upload(const char *sToken, const char *sName, const char *sLocalPath, const std::function<void(int, const char*)> &callback); gwjQiniu::gwjQiniu() { m_luaCallback = 0; m_idSchedule = 0; } gwjQiniu* gwjQiniu::startNewUpload(const char *token, const char *localPath, const char *name, int luaCallback) { gwjQiniu *qiniu = new gwjQiniu(); qiniu->init(token, localPath, name, luaCallback); qiniu->startUpload(); return qiniu; } void gwjQiniu::init(const char *token, const char *localPath, const char *name, int luaCallback) { m_token = token; m_localPath = localPath; m_name = name; m_luaCallback = luaCallback; } void gwjQiniu::startUpload() { #if defined(DM_PLATFORM_WINDOWS) std::thread thr([=]() { int code; char message[2048]; message[0] = 0; code = Qiniu_win32_upload(m_token.c_str(), m_name.c_str(), m_localPath.c_str(), message); onUploadEnd(code, message); }); thr.detach(); #else Qiniu_mac_upload(m_token.c_str(), m_name.c_str(), m_localPath.c_str(), [=](int code, const char *message) { onUploadEnd(code, message); }); #endif } void gwjQiniu::onUploadEnd(int code, const char *message) { // dmLogInfo("upload end,code=%d,message=%s", code, message); int uploadResult = 0; if(code == 200) { uploadResult = 0; } else if(code == 614)//目标资源已存在 { uploadResult = 1; } else { uploadResult = 2; } int callback = m_luaCallback; if(callback > 0) { char *pMsg = new char[strlen(message) + 4]; strcpy(pMsg, message); ext_performInUpdateThread([=](){ char str[256]; sprintf(str, "{\"result\":%d,\"errMsg\":\"%s\"}", uploadResult, pMsg); delete[] pMsg; ext_invokeLuaCallbackWithString(callback, str); ext_unregisterLuaCallback(callback); }); } delete this; } #endif
e5e4c5e2a629a19c578b6ff19745f272c13eb966
55b0bdd0e33f0d30562e118b51a2fd3a81bda542
/lolv1.0/GameDll/MonsterBase.h
3c54f9e563076704b81ae135e73c74dd677d3dfc
[]
no_license
0xhellord/pabbs
fdead699f7cb91966a826d4f051b8649a416eb08
d4dd01ac1b357b1663eb1236362f378777a900e9
refs/heads/master
2022-05-27T14:34:57.362770
2017-06-13T03:05:37
2017-06-13T03:05:37
null
0
0
null
null
null
null
GB18030
C++
false
false
1,005
h
MonsterBase.h
#pragma once #include "base.h" /* 怪物对象基类(派生类有:炮塔,小兵,龙,野怪,人物) */ //坐标 typedef struct EM_POINT_3D { float x; float z; float y; }EM_POINT_3D, *PEM_POINT_3D; //阵营 enum EM_CAMP { CAM_UNKNOW = 0, CAMP_BULE =100, CAMP_RED = 200, CAM_NEUTRAL = 300, }; //类型 enum EM_TYPE { CAMP_EM1, }; class MonsterBase : public base { public: MonsterBase(DWORD dwNodeBase); ~MonsterBase(); //获取名字 virtual char* GetName()const; //接口 float GetCurHp()const; float GetMaxHp()const; float GetCurMp()const; float GetMaxMp()const; //获取坐标 EM_POINT_3D GetPoint()const; EM_CAMP GetCamp()const; DWORD GetType()const; //是否在战争迷雾中 (true 表示在) virtual bool BVisableSee()const; //是否死亡 bool BDead()const; //获取距离 float GetDistance(EM_POINT_3D* mon); //获取朝向 返回值为 坐标 EM_POINT_3D GetMonsterOrientation()const; //获取玩家是否移动 bool GetBMoving()const; };
82c1c7a06a40af73c31f159c49c3b2a3f93cb978
70418d8faa76b41715c707c54a8b0cddfb393fb3
/1533.cpp
6bba74bbce2fb01de871485e5997fb46372359d9
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
2,336
cpp
1533.cpp
#include <bits/stdc++.h> using namespace std; #define PB push_back #define MP make_pair #define INF 0x5fffffff #define rep(i, x, y) for (i = x; i <= y; i++) #define reps(i, x, y) for (i = x; i >= y; i--) #define sqr(x) ((x) * (x)) typedef long long LL; typedef double DB; typedef vector<int> VI; struct node { int val, pre, from, to; }; vector<node> L; const int dir[6][16] = { 0, 0, 0, 1, 0, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 10, //NW 1 0, 0, 1, 0, 2, 3, 0, 4, 5, 6, 0, 7, 8, 9, 10, 0, //NE 2 0, 0, 0, 2, 0, 4, 5, 0, 7, 8, 9, 0, 11, 12, 13, 14, //W 0 0, 0, 3, 0, 5, 6, 0, 8, 9, 10, 0, 12, 13, 14, 15, 0,//E 3 0, 2, 4, 5, 7, 8, 9, 11, 12, 13, 14, 0, 0, 0, 0, 0, //SW 5 0, 3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 0, 0, 0, 0, 0 //SE 4 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 }; int cnt = 0; int hash_(bool *a) { int val = 0, i; rep(i, 1, 15) val = val * 2 + a[i]; assert(0 <= val && val <= 33000); return val; } void get(int val, bool *a) { int i; reps(i, 15, 1) a[i] = val & 1, val >>= 1; } int mark[40000]; bool bo[20]; void Print(node t) { VI ans; while (t.pre != -1) { ans.PB(t.to); ans.PB(t.from); t = L[t.pre]; } printf("%d\n", ans.size() >> 1); for (int i = ans.size() - 1; i >= 1; i--) { printf("%d ", ans[i]); } printf("%d\n", ans[0]); } void solve() { int i, j, k, l, q; cnt++; scanf("%d", &k); node t; t.pre = -1; memset(bo, 1, sizeof(bo)); bo[k] = bo[0] = 0; t.val = hash_(bo); rep(i, 1, 15) bo[i] ^= 1; int mval = hash_(bo); L.clear(); L.PB(t); for (l = 0; l < L.size(); l++) { t = L[l]; get(t.val, bo); rep(i, 1, 15) { if (bo[i]) { rep(k, 0, 5) { j = 0; int x = i; while (bo[x]) { bo[x] = 0; j++; x = dir[k][x]; } if (j >= 2 && x) { bo[x] = 1; t.val = hash_(bo); if (mark[t.val] != cnt) { t.from = i; t.to = x; t.pre = l; if (t.val == mval) { Print(t); return; } mark[t.val] = cnt; L.PB(t); } bo[x] = 0; } x = i; while (j--) { bo[x] = 1; x = dir[k][x]; } } } } } puts("IMPOSSIBLE"); } int main() { int Case; scanf("%d", &Case); while (Case--) { solve(); } return 0; }
7e359120d56961020d9f29aebc66f3bb3252717d
8c9250f3d436a2ecc6849766eebf51fdf6ddbc6a
/OnvifSDK/source/ReceiverServiceImpl.cpp
d334d95efad3ca6bb000f2108f7afd89a4af617f
[ "MIT-0" ]
permissive
aleksandrm8/OpenONVIF
8e2efece1be5feabfdd75d7b9f1eb16d38fcbf90
e14776c05dd97aa3d19160d47426044c8c1b8e3a
refs/heads/master
2021-01-15T19:27:24.973415
2019-11-29T05:45:22
2019-11-29T05:45:42
22,468,441
0
0
null
2015-02-25T14:58:45
2014-07-31T12:24:57
C++
UTF-8
C++
false
false
1,341
cpp
ReceiverServiceImpl.cpp
#include "OnvifSDK.h" #ifdef RECV_S #include "sigrlog.h" #include "ReceiverServiceImpl.h" #include "BaseServer.h" #warning TODO for while not supporting copy ReceiverBindingService* ReceiverServiceImpl::copy() { return NULL; } int ReceiverServiceImpl::GetReceivers(_trv__GetReceivers *trv__GetReceivers, _trv__GetReceiversResponse *trv__GetReceiversResponse) { RecvGetReceiversResponse resp( trv__GetReceiversResponse ); int nRes = handler_->GetReceivers(resp); CHECKRETURN(nRes, "ReceiverServiceImpl::GetReceivers"); } int ReceiverServiceImpl::CreateReceiver(_trv__CreateReceiver *trv__CreateReceiver, _trv__CreateReceiverResponse *trv__CreateReceiverResponse) { RecvCreateReceiver req(trv__CreateReceiver); RecvCreateReceiverResponse resp(trv__CreateReceiverResponse); std::string recvToken; int nRes = handler_->CreateReceiver( req.getUri(), recvToken ); resp.setToken(recvToken); CHECKRETURN(nRes, "ReceiverServiceImpl::CreateReceiver"); } int ReceiverServiceImpl::SetReceiverMode(_trv__SetReceiverMode *trv__SetReceiverMode, _trv__SetReceiverModeResponse *trv__SetReceiverModeResponse) { RecvSetReceiverMode req(trv__SetReceiverMode); int nRes = handler_->SetReceiverMode( req.getToken(), req.getMode() ); CHECKRETURN(nRes, "ReceiverServiceImpl::SetReceiverMode"); } #endif // RECV_S
31e1e5afeab9a23d82987d2dfc2906d03a22bf16
e3bcff37752d2c295a36a5ad0d433c5f592efa36
/problemas/divisibles.cpp
ef1b04b2fac1c94cc4e5d61053ca778283361f6d
[]
no_license
JeG99/Proyectos-finales-Algoritmos
916d7d2f76f4d5004f75c9229ddce6a485b1a82c
77bf5f7cf445e47bc59652d4a53f26f5537037c3
refs/heads/master
2023-01-22T22:25:57.240919
2020-12-06T23:17:19
2020-12-06T23:17:19
265,995,099
1
1
null
null
null
null
UTF-8
C++
false
false
829
cpp
divisibles.cpp
#include <iostream> int divisibles1(int inf, int sup){ int divisibles = 0; for(int i = inf; i <= sup; i++){ if (i % 3 == 0 && i % 5 == 0){ divisibles++; } } return divisibles; } int divisibles2(int inf, int sup){ int divisibles = 0; for(int i = inf; i <= sup; i++){ if (i % 15 == 0){ divisibles++; } } return divisibles; } int divisibles3(int inf, int sup){ int divisibles = 0; int arranque = inf + (inf % 15 == 0 ? 0 : 15 - inf % 15); for(int i = arranque; i <= sup; i += 15){ divisibles++; } return divisibles; } int divisibles4(int inf, int sup){ return sup/15 + inf/15 + (inf % 15 == 0 ? 1 : 0); } int main(){ std::cout << divisibles1(0, 30) << '\n'; std::cout << divisibles2(0, 30) << '\n'; std::cout << divisibles3(0, 30) << '\n'; std::cout << divisibles4(0, 30) << '\n'; return 0; }
7a40eb3441dac79c3b08a98f8a31c33702de9d30
0ee3df7d77ae8d7d91444add503ea37b43fdef74
/Proiect 3 POO Pascu Cristian Vlad.cpp
52c3b6138415730c4817ce7197464b9fe6f506ea
[]
no_license
cristivlad9913/Projects
5bc18e04b1d03247774880fe1cc3b05dc5d8f77e
57a2a71e873654083203c5f03f4988b79d26f9bb
refs/heads/main
2023-03-29T23:31:33.113056
2021-03-23T17:12:20
2021-03-23T17:12:20
350,791,844
0
0
null
null
null
null
UTF-8
C++
false
false
11,176
cpp
Proiect 3 POO Pascu Cristian Vlad.cpp
#include <iostream> #include <vector> using namespace std; class Car { protected: int nr; public: virtual void read(istream &in)=0; virtual void write(ostream &out)=0; friend istream & operator>>(istream &in,Car &p) { p.read(in); return in; } friend ostream & operator<<(ostream &out,Car &p) { p.write(out); return out; } }; class Coupe:public Car { private: string carName; string description; int horsePower; public: Coupe(string,string,int); virtual ~Coupe(); Coupe& operator=(Coupe &p); virtual void read(istream &in); virtual void write(ostream &out); friend istream& operator>>(istream&,Coupe&); friend ostream& operator<<(ostream&,Coupe&); }; Coupe::Coupe(string a="",string b="",int c=0) { carName=a; description=b; horsePower=c; } void Coupe::read(istream &in) { string a,b; int hp; cin.get(); cout<<"Coupe name: "; getline(in,b); carName=b; cout<<"Description of the Coupe car: "; getline(in,a); description=a; cout<<"Horsepower: "; cin>>hp; horsePower=hp; } void Coupe::write(ostream &out) { out<<"Name: "<<carName<<endl; out<<"Description: "<<description<<endl; out<<"Horsepower: "<<horsePower<<endl; } Coupe& Coupe :: operator=(Coupe &p) { if(this!=&p) { carName=p.carName; description=p.description; horsePower=p.horsePower; } return *this; } Coupe::~Coupe() { } istream& operator>>(istream&in,Coupe&p) { p.read(in); return in; } ostream& operator<<(ostream&out,Coupe&p) { p.write(out); return out; } class HH:public Car { private: string carName; string description; int horsePower; public: HH(string,string,int); virtual ~HH(); HH& operator=(HH &p); virtual void read(istream &in); virtual void write(ostream &out); friend istream& operator>>(istream&,HH&); friend ostream& operator<<(ostream&,HH&); }; HH::HH(string a="",string b="",int c=0) { carName=a; description=b; horsePower=c; } void HH::read(istream &in) { string a; int hp; cin.get(); cout<<"HH name: ";getline(in,a); carName=a; cout<<"Description of the HH car: "; getline(in,a); description=a; cout<<"Horsepower: "; in>>hp; horsePower=hp; } void HH::write(ostream &out) { out<<"Name: "<<carName<<endl; out<<"Description: "<<description<<endl; out<<"Horsepower: "<<horsePower<<endl; } HH& HH :: operator=(HH &p) { if(this!=&p) { carName=p.carName; description=p.description; horsePower=p.horsePower; } return *this; } HH::~HH() { } istream& operator>>(istream&in,HH&p) { p.read(in); return in; } ostream& operator<<(ostream&out,HH&p) { p.write(out); return out; } class Cabrio:public Car { private: string carName; string description; int horsePower; public: Cabrio(string,string,int); virtual ~Cabrio(); Cabrio& operator=(Cabrio &p); virtual void read(istream &in); virtual void write(ostream &out); friend istream& operator>>(istream&,Cabrio&); friend ostream& operator<<(ostream&,Cabrio&); }; Cabrio::Cabrio(string a="",string b="",int c=0) { carName=a; description=b; horsePower=c; } void Cabrio::read(istream &in) { string a; int hp; cin.get(); cout<<"Cabrio name: "; getline(in,a); carName=a; cout<<"Description of the Cabrio car: "; getline(in,a); description=a; cout<<"Horsepower: "; cin>>hp; horsePower=hp; } void Cabrio::write(ostream &out) { out<<"Name: "<<carName<<endl; out<<"Description: "<<description<<endl; out<<"Horsepower: "<<horsePower<<endl; } Cabrio& Cabrio :: operator=(Cabrio &p) { if(this!=&p) { carName=p.carName; description=p.description; horsePower=p.horsePower; } return *this; } Cabrio::~Cabrio() { } istream& operator>>(istream&in,Cabrio&p) { p.read(in); return in; } ostream& operator<<(ostream&out,Cabrio&p) { p.write(out); return out; } template <class t> class superSport { private: t cars_number; string carName; string description; t cars_sold; public: superSport() { cars_number=0; carName=""; description=""; cars_sold=0; } superSport(const superSport &p ) { cars_number=p.cars_number; carName=p.carName; description=p.description; cars_sold=p.cars_sold; } t set_cars_number(t x) { cars_number+=x; } t get_cars_number() { return cars_number; } t set_cars_sold(t x) { cars_sold=x; } t get_cars_sold() { return cars_sold; } void write(ostream &out) { out<<"There are "<<cars_number<<" supersport cars"<<endl; out<<"There are "<<cars_sold<<" supersport cars sold"<<endl; } friend ostream &operator<<(ostream &out,superSport &p) { p.write(out); return out; } }; template <> class superSport<int> { private: int cars_number; string carName; string description; int cars_sold; public: superSport() { cars_number=0; carName=""; description=""; cars_sold=0; } superSport(const superSport &p) { cars_number=p.cars_number; } void set_cars_number(int a) { cars_number+=a; } void set_cars_sold(int a) { cars_sold=a; } int get_cars_number() const { return cars_number; } int get_cars_sold() const { return cars_sold; } void write(ostream &out) { out<<"There are "<<cars_number<<" supersport cars left"<<endl; out<<"There are "<<cars_sold<<" supersport cars sold"<<endl; } friend ostream &operator<<(ostream &out,superSport &p) { p.write(out); return out; } }; template <class t> class Exposition { private: superSport < int > p; static int nr_cars; int n; t **v; vector<pair<string,int>> dataCar; public: Exposition(int n=0) { n=n; v=new t*[n]; } Exposition(Exposition &a) { delete[] v; n=a.n; v=a.v; } Exposition(const Exposition &p) { delete v; n=p.n; v=new Car*[n]; for(int i=0;i<n;i++) v[i]=p.v[i]; } ~Exposition() { delete[] v; n=0; } void add_car(int i) { static int cs=0; string type; prob4: try { cout<<"Type of the car: coupe/hh/cabrio/supersport "<<i+1<<": ";cin>>type; if(type=="coupe") { v[i]=new Coupe; cin>>*v[i]; } else if(type=="hh") { v[i]=new HH; cin>>*v[i]; } else if(type=="cabrio") { v[i]=new Cabrio; cin>>*v[i]; } else if(type=="supersport") { v[i]=NULL; string name; int price; int sold; cin.get(); cout<<"Supersport name: ";getline(cin,name); cout<<"Supersport price: ";cin>>price; prob1: try{ cout<<"You want to buy this car? (1=yes, 0=no): ";cin>>sold; if(sold==1) { dataCar.push_back(make_pair(name,-1)); cs++; cout<<"This car has been sold!"<<endl; } else if(sold==0) { dataCar.push_back(make_pair(name,price)); p.set_cars_number(1); cout<<"This car hasn't been sold!"<<endl; } else throw sold; } catch(int sold) { cout<<"Sold must be 1/0!"<<endl; goto prob1; } } else throw type; } catch (string type) { cout<<endl; cout<<"Please write coupe/hh/cabrio/supersport with small caps!"<<endl; goto prob4; } if(i==n-1) { p.set_cars_sold(cs); } } void read(istream &in) { prob2: try { cout<<"Write numbers of cars you want to read: ";cin>>n; if(n<=0) throw n; } catch(int n) { cout<<"Number of cars must be positive!"<<endl; goto prob2; } delete[] v; v=new t*[n]; for(int i=0;i<n;i++) { add_car(i); nr_cars++; } } void write(ostream &out) { vector<pair<string,int>>:: iterator iter=dataCar.begin(); //doar de frumusete for(int i=0;i<n;i++) { if(dynamic_cast<Coupe*> (v[i])!=NULL) { cout<<"Car "<<i+1<<" type: Coupe"<<endl<<*v[i]<<endl; cout<<"------------"<<endl; } else if(dynamic_cast<HH*> (v[i])!=NULL) { cout<<"Car "<<i+1<<" type: HH"<<endl<<*v[i]<<endl; cout<<"------------"<<endl; } else if(dynamic_cast<Cabrio *>(v[i])!=NULL) {cout<<"Car "<<i+1<<" type: Cabrio"<<endl<<*v[i]<<endl; cout<<"------------"<<endl; } else { cout<<"Car number: "<<i+1<<" type: supersport"<<endl; cout<<"Name:" <<dataCar[i].first<<endl; cout<<"Price:" <<dataCar[i].second<<endl; cout<<"------------"<<endl; } } cout<<"Cars that have been bought:"<<endl; for(int j=0; j<dataCar.size()+1; j++) if(dataCar[j].second==-1) cout<<"->"<<dataCar[j].first<<endl; cout<<p; } friend istream& operator>>(istream& in,Exposition &a) { a.read(in); return in; } friend ostream& operator<<(ostream &out,Exposition &a) { a.write(out); return out; } }; template <class t> int Exposition<t>::nr_cars=0; void menu_output() { cout<<"\t\t Pascu Cristian Vlad grupa 211 proiect 3 tema 5"<<endl<<endl<<endl; cout<<"Please write car type with low caps"<<endl<<endl; Exposition<Car> *p=new Exposition <Car>; cin>>*p; cout<<endl<<endl; cout<<"All cars: "<<endl<<endl; cout<<*p; } int main() { menu_output(); return 0; }
fcb97c1a5959b51279da82cc30b2d73d4b49022d
902f6cec24ade6905bc421b3e922e0ae7affc79b
/Instruments/WFSynth.cpp
03c84b7bc768b2d690a27d59c975a3e5f8a88ab0
[]
no_license
muaem/basicsynth-src
ec20ac648c03ffcfbeb7d4e219c12da31f8f465d
f41a840ba885e0ab52e9fed058d8c22c0e78fbba
refs/heads/master
2021-01-12T06:25:14.288458
2012-03-09T07:45:00
2012-03-09T07:45:00
77,357,814
0
0
null
null
null
null
UTF-8
C++
false
false
7,143
cpp
WFSynth.cpp
////////////////////////////////////////////////////////////////////// /// @file WFSynth.cpp Implementation of the WFSynth instrument. // // BasicSynth WaveFile playback instrument // // See _BasicSynth_ Chapter 23 for a full explanation // // This instrument plays a wave file. The sound is loaded into // a cache and can be shared by multiple instrument instances. // The sound can be played once or looped, and a simple AR // envelope can be applied to fade in/out. // // Copyright 2008, Daniel R. Mitchell // License: Creative Commons/GNU-GPL // (http://creativecommons.org/licenses/GPL/2.0/) // (http://www.gnu.org/licenses/gpl.html) ////////////////////////////////////////////////////////////////////// #include "Includes.h" #include "WFSynth.h" static WaveFileIn wfCache[WFSYNTH_MAX_WAVEFILES]; static int wfCacheCount = 0; static AmpValue dummy; int WFSynth::GetCacheCount() { return wfCacheCount; } WaveFileIn *WFSynth::GetCacheEntry(int n) { return &wfCache[n]; } void WFSynth::ClearCache() { int n; for (n = 0; n < wfCacheCount; n++) wfCache[n].Clear(); wfCacheCount = 0; } int WFSynth::AddToCache(const char *filename, bsInt16 id) { int n; for (n = 0; n < wfCacheCount; n++) { const char *wfname = wfCache[n].GetFilename(); if (wfname && strcmp(filename, wfname) == 0 && wfCache[n].GetFileID() == id) { return n; } } if (wfCacheCount >= WFSYNTH_MAX_WAVEFILES) return -1; if (wfCache[n].LoadWaveFile(filename, id) != 0) return -1; wfCacheCount++; return n; } Instrument *WFSynth::WFSynthFactory(InstrManager *m, Opaque tmplt) { WFSynth *ip = new WFSynth; ip->im = m; if (tmplt) ip->Copy((WFSynth *) tmplt); return ip; } SeqEvent *WFSynth::WFSynthEventFactory(Opaque tmplt) { VarParamEvent *evt = new VarParamEvent; evt->maxParam = 20; return (SeqEvent*)evt; } VarParamEvent *WFSynth::AllocParams() { return (VarParamEvent *)WFSynthEventFactory(0); } static InstrParamMap wfsynthParams[] = { {"envar", 19}, {"envrr", 20}, {"wvfid", 16}, {"wvflp", 17}, {"wvfpa", 18}, }; bsInt16 WFSynth::MapParamID(const char *name, Opaque tmplt) { return InstrParamMap::SearchParamID(name, wfsynthParams, sizeof(wfsynthParams)/sizeof(InstrParamMap)); } const char *WFSynth::MapParamName(bsInt16 id, Opaque tmplt) { return InstrParamMap::SearchParamName(id, wfsynthParams, sizeof(wfsynthParams)/sizeof(InstrParamMap)); } WFSynth::WFSynth() { im = NULL; samples = &dummy; sampleNumber = 0; sampleTotal = 0; sampleIncr = 1.0; sampleRel = 0; looping = 0; playAll = 0; fileID = -1; eg.SetAtkRt(0.0); eg.SetRelRt(0.0); eg.SetSus(1.0); eg.SetSusOn(1); memset(wfUsed, 0, sizeof(wfUsed)); } WFSynth::~WFSynth() { } void WFSynth::Copy(WFSynth *tp) { fileID = tp->fileID; sampleTotal = tp->sampleTotal; sampleNumber = tp->sampleNumber; sampleIncr = tp->sampleIncr; sampleRel = tp->sampleRel; samples = tp->samples; looping = tp->looping; playAll = tp->playAll; eg.Copy(&tp->eg); } void WFSynth::Start(SeqEvent *evt) { SetParams((VarParamEvent*)evt); samples = &dummy; sampleNumber = 0; sampleIncr = 1; sampleTotal = 0; WaveFileIn *wfp = &wfCache[0]; WaveFileIn *wfe = &wfCache[WFSYNTH_MAX_WAVEFILES]; while (wfp < wfe) { if (wfp->GetFileID() == fileID) { samples = wfp->GetSampleBuffer(); sampleTotal = wfp->GetInputLength(); sampleIncr = (PhsAccum) wfp->GetSampleRate() / (PhsAccum) synthParams.sampleRate; break; } wfp++; } if (sampleTotal > 0) sampleRel = sampleTotal - PhsAccum(eg.GetRelRt() * synthParams.sampleRate); eg.Reset(0); } void WFSynth::Param(SeqEvent *evt) { SetParams((VarParamEvent*)evt); } int WFSynth::SetParams(VarParamEvent *params) { int err = 0; chnl = params->chnl; eg.SetSus(params->vol); bsInt16 *id = params->idParam; float *valp = params->valParam; int n = params->numParam; while (n-- > 0) err += SetParam(*id++, *valp++); return err; } int WFSynth::SetParam(bsInt16 id, float v) { switch (id) { case 16: fileID = (bsInt16) v; break; case 17: looping = (bsInt16) v; break; case 18: playAll = (bsInt16) v; break; case 19: eg.SetAtkRt(FrqValue(v)); break; case 20: eg.SetRelRt(FrqValue(v)); break; default: return 1; } return 0; } int WFSynth::GetParams(VarParamEvent *params) { params->SetParam(P_VOLUME, (float)eg.GetSus()); params->SetParam(16, (float) fileID); params->SetParam(17, (float) looping); params->SetParam(18, (float) playAll); params->SetParam(19, (float) eg.GetAtkRt()); params->SetParam(20, (float) eg.GetRelRt()); return 0; } int WFSynth::GetParam(bsInt16 id, float *val) { switch (id) { case 16: *val = (float) fileID; break; case 17: *val = (float) looping; break; case 18: *val = (float) playAll; break; case 19: *val = (float) eg.GetAtkRt(); break; case 20: *val = (float) eg.GetRelRt(); break; default: return 1; } return 0; } void WFSynth::Stop() { if (looping || !playAll) eg.Release(); } void WFSynth::Tick() { if (sampleNumber >= sampleTotal) { if (!looping) return; sampleNumber -= sampleTotal; } im->Output(chnl, samples[(int)sampleNumber] * eg.Gen()); sampleNumber += sampleIncr; if (!looping && playAll && sampleNumber > sampleRel) eg.Release(); } int WFSynth::IsFinished() { if (!looping && sampleNumber >= sampleTotal) return 1; return eg.IsFinished(); } void WFSynth::Destroy() { delete this; } int WFSynth::Load(XmlSynthElem *parent) { float atk; float rel; short ival; memset(wfUsed, 0, sizeof(wfUsed)); XmlSynthElem *elem; XmlSynthElem *next = parent->FirstChild(); while ((elem = next) != NULL) { if (elem->TagMatch("wvf")) { if (elem->GetAttribute("fn", ival) == 0) fileID = (bsInt16) ival; if (elem->GetAttribute("lp", ival) == 0) looping = (bsInt16) ival; if (elem->GetAttribute("pa", ival) == 0) playAll = (bsInt16) ival; } else if (elem->TagMatch("env")) { elem->GetAttribute("ar", atk); elem->GetAttribute("rr", rel); eg.InitAR(atk, 1.0, rel, 1, linSeg); } else if (elem->TagMatch("file")) { char *filename = 0; if (elem->GetAttribute("name", &filename) == 0) { if (elem->GetAttribute("id", ival) == 0) { ival = AddToCache(filename, (bsInt16) ival); if (ival >= 0) wfUsed[ival] = 1; } delete filename; } } next = elem->NextSibling(); delete elem; } return 0; } int WFSynth::Save(XmlSynthElem *parent) { XmlSynthElem *elem; elem = parent->AddChild("wvf"); if (elem == NULL) return -1; elem->SetAttribute("fn", (long) fileID); elem->SetAttribute("lp", (short) looping); elem->SetAttribute("pa", (short) playAll); delete elem; elem = parent->AddChild("env"); if (elem == NULL) return -1; elem->SetAttribute("ar", eg.GetAtkRt()); elem->SetAttribute("rr", eg.GetRelRt()); delete elem; for (int n = 0; n < WFSYNTH_MAX_WAVEFILES; n++) { short id = (short) wfCache[n].GetFileID(); if (id >= 0 && wfUsed[n]) { elem = parent->AddChild("file"); if (elem == NULL) return -1; elem->SetAttribute("name", wfCache[n].GetFilename()); elem->SetAttribute("id", id); delete elem; } } return 0; }
1e570427b51424e036f0ef3a9235b4d6d9ef5f1b
8a7d37191c4f7c0444f6779ea3092c98c14bd1d7
/04_one_axis_sine/render.cpp
e4b769787e8df7c2929c63bfcd181136c5caaa82
[]
no_license
disastrid/kth_bela
259053cbd6dfa1c5eaa02836098716017d7e208c
a8a2138e46a07d1f79bcd377402491ae652893d5
refs/heads/master
2020-09-12T20:46:08.161672
2019-11-18T22:15:46
2019-11-18T22:15:46
222,550,616
1
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
render.cpp
#include <Bela.h> #include <libraries/Scope/Scope.h> Scope scope; float dcIn = 0; float dcOut = 0; float gInverseSampleRate; float gCalcFreq = 50.0; float gPhase; bool setup(BelaContext *context, void *userData) { scope.setup(5, context->audioSampleRate); gInverseSampleRate = 1 / context->audioSampleRate; gPhase = 0.0; return true; } void render(BelaContext *context, void *userData) { float accelOut = 0; for (int n = 0; n < context->audioFrames; n++) { if (!(n % 2)) { float in = analogRead(context, n/2, 0); accelOut = (in - dcIn + 0.9998 * dcOut); dcIn = in; dcOut = accelOut; gCalcFreq = map(accelOut, 0, 0.05, 50, 800); } float out = 0.8f * sinf(gPhase); gPhase += 2.0f * (float)M_PI * gCalcFreq * gInverseSampleRate; if(gPhase > M_PI) gPhase -= 2.0f * (float)M_PI; for(unsigned int channel = 0; channel < context->audioOutChannels; channel++) { audioWrite(context, n, channel, out); } scope.log(accelOut, out); } } void cleanup(BelaContext *context, void *userData) { }
243173d11040a425938377fc9c9ea7ff6430951e
2b60d3054c6c1ee01f5628b7745ef51f5cd3f07a
/Deformation/cubica/cubica-1.0/src/geometry/PARTITIONED_SKINNED_SUBSPACE_TET_MESH.cpp
6eefd643106a073944be846c648422412e643ef7
[]
no_license
LUOFQ5/NumericalProjectsCollections
01aa40e61747d0a38e9b3a3e05d8e6857f0e9b89
6e177a07d9f76b11beb0974c7b720cd9c521b47e
refs/heads/master
2023-08-17T09:28:45.415221
2021-10-04T15:32:48
2021-10-04T15:32:48
414,977,957
1
0
null
null
null
null
UTF-8
C++
false
false
24,039
cpp
PARTITIONED_SKINNED_SUBSPACE_TET_MESH.cpp
/* This file is part of Cubica. Cubica 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. Cubica 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 Cubica. If not, see <http://www.gnu.org/licenses/>. */ // SUBSPACE_TET_MESH.h: interface for the SUBSPACE_TET_MESH class. // ////////////////////////////////////////////////////////////////////// #include "PARTITIONED_SKINNED_SUBSPACE_TET_MESH.h" #if !USING_OSX #include <GL/glut.h> #endif ////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////////// PARTITIONED_SKINNED_SUBSPACE_TET_MESH::PARTITIONED_SKINNED_SUBSPACE_TET_MESH(SKELETON* skeleton, const char* filename, MATERIAL** materials, int totalMaterials, int partitions, Real springConst, bool simulate, bool loadOriginal, string partitionPath) : _skeleton(skeleton) { _partitions = partitions; _filename = string(filename); _partitionPath = partitionPath; // allocate per-interface spring consts _interfaceSpringConst.resizeAndWipe(_partitions, _partitions); _springConst = springConst; for (int y = 0; y < _partitions; y++) for (int x = 0; x < _partitions; x++) _interfaceSpringConst(x,y) = _springConst; // read in the original mesh if (loadOriginal) _originalMesh = new SUBSPACE_TET_MESH(filename, materials, totalMaterials); else _originalMesh = new SUBSPACE_TET_MESH(filename, materials, totalMaterials, false, "dontReadAnything", "dontReadAnything"); // read in each separate partition _meshes = new TET_MESH*[_partitions]; _ranks = new int[_partitions]; _superRank = 0; _superRankPlusRigids = 0; for (int x = 0; x < _partitions; x++) { cout << " ==============================" << endl; cout << " Loading partition " << x << endl; cout << " ==============================" << endl; char buffer[256]; sprintf(buffer, "%i", x); string partitionFilename = partitionPath; if (partitionFilename.length() == 0) partitionFilename = string(filename); partitionFilename += string(".partition."); partitionFilename += string(buffer); // if we are simulating, attach frames. Otherwise, we are training, // and extra translation modes should *not* be added to the basis // probe the file to see if it is unconstrained FILE* probe = fopen(partitionFilename.c_str(), "rb"); if (probe == NULL) printf("Filename %s not found!\n", partitionFilename.c_str()); int unconstrainedSize, constrainedSize; fread((void*)&unconstrainedSize, sizeof(int), 1, probe); fread((void*)&constrainedSize, sizeof(int), 1, probe); fclose(probe); if (constrainedSize == 0) cout << " Partition " << x << " is unconstrained." << endl; // force everything to unconstrained -- this is the main deviation from // the PARTITIONED_SUBSPACE_TET_MESH constructor cout << " Reading partition file: " << partitionFilename.c_str() << endl; bool simulateFullspace = true; if (simulate) simulateFullspace = false; _meshes[x] = new UNCONSTRAINED_SUBSPACE_TET_MESH(partitionFilename.c_str(), materials, totalMaterials, simulateFullspace, NULL, NULL, false); _unconstrainedPartition.push_back(true); if (simulate) ((UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x])->cacheSubspaceCenterOfMass(); cout << endl; // recompute the mass matrix to make the mesh matrix unity, not just each submesh if (simulate) { Real trueMass = _originalMesh->mass(0); ((SUBSPACE_TET_MESH*)_meshes[x])->resetMasses(trueMass); // recompute center of mass matrix with new masses if (constrainedSize == 0) ((UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x])->cacheSubspaceCenterOfMass(); // recompute the inertia tensor accordingly _meshes[x]->refreshInertiaTensor(); } int rank = ((SUBSPACE_TET_MESH*)_meshes[x])->rank(); cout << " Submesh rank: " << rank << endl; _ranks[x] = rank; _superRank += rank; _superRankPlusRigids += rank; if (constrainedSize == 0) _superRankPlusRigids += 6; } cout << " ==============================" << endl; cout << " Done loading all partitions." << endl; cout << " Super rank: " << _superRank << endl; cout << " Super rank with rigids: " << _superRankPlusRigids << endl; cout << " ==============================" << endl; // read in the correspondences cout << " Reading in correspondences ... "; _originalIDs = new vector<int>[_partitions]; for (int x = 0; x < _partitions; x++) { char buffer[256]; sprintf(buffer, "%i", x); string partitionFilename = partitionPath; if (partitionFilename.length() == 0) partitionFilename = string(filename); partitionFilename += string(".partition."); partitionFilename += string(buffer); partitionFilename += string(".correspondence"); FILE* file = fopen(partitionFilename.c_str(), "rb"); for (int y = 0; y < _meshes[x]->totalNodes(); y++) { int oldID; fread((void*)&oldID, sizeof(int), 1, file); _originalIDs[x].push_back(oldID); } fclose(file); } cout << " done. " << endl; // build inverse correspondences cout << " Building inverse correspondences ... "; flush(cout); for (int x = 0; x < _partitions; x++) for (unsigned int y = 0; y < _originalIDs[x].size(); y++) { int oldID = _originalIDs[x][y]; _partitionIDs.insert(pair<int, pair<int, int> >(oldID, pair<int, int>(x,y))); } cout << " done." << endl; cout << " Inverse correspondence size: " << _partitionIDs.size() << endl; cout << " Tet mesh size: " << _originalMesh->totalNodes() << endl; // allocate the clone table _clonedVertices = new vector<pair<int, int> >*[_partitions]; for (int x = 0; x < _partitions; x++) _clonedVertices[x] = new vector<pair<int, int> >[_partitions]; // read in the cloned vertices string cloneFilename = partitionPath; if (cloneFilename.length() == 0) cloneFilename = string(filename); cloneFilename += string(".clones"); cout << " Reading clone table: " << cloneFilename.c_str() << endl; FILE* file = fopen(cloneFilename.c_str(), "rb"); for (int x = 0; x < _partitions; x++) { for (int y = 0; y < _partitions; y++) { // read in how many interactions there are int totalClones; fread((void*)&totalClones, sizeof(int), 1, file); // read in the pairs for (int z = 0; z < totalClones; z++) { int first, second; fread((void*)&first, sizeof(int), 1, file); fread((void*)&second, sizeof(int), 1, file); pair<int, int> clone(first, second); // only store the clone if it is unconstrained, otherwise // it will just screw up the indexing of the interface nodes if (first < _meshes[x]->unconstrainedNodes()) _clonedVertices[x][y].push_back(clone); } } } fclose(file); // sanity check cout << " Sanity checking clone table ... "; flush(cout); for (int x = 0; x < _partitions; x++) for (int y = 0; y < _partitions; y++) assert(_clonedVertices[x][y].size() == _clonedVertices[y][x].size()); cout << " done. " << endl; // compute the surface vertices computeClonedSurfaceVertices(); // populate the explicit vertex version computeClonedVertexMap(); // compute the center of mass so we can draw the exploded view computeCenterOfMass(); // compute the Us for just the nodes between partitions cout << " Computing interface bases ... "; flush(cout); computeInterfaceUs(); cout << "done." << endl; // compute the cloned triangles cout << " Computing cloned triangles ..."; flush(cout); if (!readClonedTriangles()) { cout << " no cache found! ... "; flush(cout); computeClonedTriangles(); writeClonedTriangles(); } else cout << " cache found! ... "; flush(cout); computeInterfaceAreas(); computeBlendedSurfaceMesh(); cout << "done." << endl; // if we are simulating, compute a bunch of stuff if (simulate) { // compute the Us for just the nodes between partitions cout << " Computing interface rest pose differences ... "; flush(cout); computeRestDiffs(); cout << "done." << endl; // compute the sandwiches between all the interfaces cout << " Computing interface sandwiches ... "; flush(cout); computeSandwiches(); cout << "done." << endl; // compute projected interface rest poses cout << " Computing projected rest interfaces ... "; flush(cout); computeProjectedRestInterfaces(); cout << "done." << endl; } // allocate the array of graph colors; _graphColors = new int[_partitions]; // read in the graph coloring, and if there isn't one, compute one string dimacs = partitionPath; if (dimacs.length() == 0) dimacs = string(filename); dimacs += string(".dimacs.res"); cout << " Reading in graph coloring ... "; if (!readDIMACS(dimacs.c_str())) { cout << " No graph coloring found, computing one ... " << endl; computeGraphColoring(partitionPath); // try reading in again readDIMACS(dimacs.c_str()); } cout << "done." << endl; // compute the total number of interfaces _totalInterfaces = 0; for (int x = 0; x < _partitions; x++) for (int y = 0; y < x; y++) if (_interfaceU[x][y].rows() != 0) _totalInterfaces++; // recompute inertial variables due to mass adjustments cout << " Renormalizing masses ... "; flush(cout); for (int x = 0; x < _partitions; x++) { string cacheName = _meshes[x]->filename(); cacheName = cacheName + string(".normalized.inertia"); SUBSPACE_TET_MESH* mesh = (SUBSPACE_TET_MESH*)_meshes[x]; if (!mesh->readInertiaCache(cacheName)) { cout << " No cache found for partition " << x << " ... "; flush(cout); ((SUBSPACE_TET_MESH*)_meshes[x])->cacheMassMatrixVars(); mesh->writeInertiaCache(cacheName); } else cout << " Cache found for partition " << x << "! ... "; flush(cout); } cout << " done." << endl; // cache the colors _colors[0][0] = 1.0f; _colors[0][1] = 0.5f; _colors[0][2] = 0.5f; _colors[0][3] = 1.0f; _colors[1][0] = 0.5f; _colors[1][1] = 1.0f; _colors[1][2] = 0.5f; _colors[1][3] = 1.0f; _colors[2][0] = 0.5f; _colors[2][1] = 0.5f; _colors[2][2] = 1.0f; _colors[2][3] = 1.0f; _colors[3][0] = 1.0f; _colors[3][1] = 0.5f; _colors[3][2] = 1.0f; _colors[3][3] = 1.0f; _colors[4][0] = 0.5f; _colors[4][1] = 1.0f; _colors[4][2] = 1.0f; _colors[4][3] = 1.0f; _colors[5][0] = 1.0f; _colors[5][1] = 1.0f; _colors[5][2] = 0.5f; _colors[5][3] = 1.0f; _colors[6][0] = 1.0f; _colors[6][1] = 1.0f; _colors[6][2] = 1.0f; _colors[6][3] = 1.0f; _colors[7][0] = 0.5f; _colors[7][1] = 0.5f; _colors[7][2] = 0.5f; _colors[7][3] = 1.0f; } PARTITIONED_SKINNED_SUBSPACE_TET_MESH::~PARTITIONED_SKINNED_SUBSPACE_TET_MESH() { } ////////////////////////////////////////////////////////////////////// // load a mocap frame into the skeleton, and propagate the bone transforms // to the partitions ////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadInterpolatedMocapFrame(float frame) { _skeleton->loadInterpolatedMocapFrame(frame); scatterBoneTransforms(); } ////////////////////////////////////////////////////////////////////// // load a mocap frame into the skeleton, and propagate the bone transforms // to the partitions ////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadMocapFrame(int frame) { _skeleton->loadMocapFrame(frame); scatterBoneTransforms(); } ////////////////////////////////////////////////////////////////////// // propagate bone transforms to partitions ////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::scatterBoneTransforms() { vector<BONE*> bones = _skeleton->bones(); for (unsigned int x = 0; x < bones.size() - 1; x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; int whichBone = x + 1; QUATERNION quaternion = bones[whichBone]->quaternion(); MATRIX3 rotation = quaternion.toExplicitMatrix3x3(); VEC3F translation = bones[whichBone]->translation(); VEC3F& centerOfMass = mesh->originalCenterOfMass(); VEC3F domainTranslation = rotation * centerOfMass + translation; mesh->rigidTranslation() = domainTranslation; mesh->rotationQuaternion() = quaternion; } } ////////////////////////////////////////////////////////////////////// // scatter the constrained node positions to the submeshes -- in the case of a skinned // animation, these positions will actually change along with the skeleton ////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::scatterConstrainedNodes() { vector<VEC3F>& originalVertices = _originalMesh->vertices(); for (int x = 0; x < _partitions; x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; // get the rigid components to undo VEC3F translation = mesh->rigidTranslation(); VEC3F centerOfMass = mesh->originalCenterOfMass(); MATRIX3 rotation = mesh->rotationQuaternion().toExplicitMatrix3x3(); MATRIX3 RT = rotation.transpose(); int start = mesh->unconstrainedNodes(); vector<VEC3F>& vertices = mesh->vertices(); for (unsigned int y = start; y < vertices.size(); y++) { int originalID = this->originalID(x,y); vertices[y] = RT * (originalVertices[originalID] - translation); } } } ////////////////////////////////////////////////////////////////////////////// // load skinned simulation data snapshot, including the mocap data ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadInterpolatedSkeletonFrame(string dataPath, float frame) { // scatters bone transforms to the partitions as well loadInterpolatedMocapFrame(frame); // load up just the skinning _skeleton->updatePinocchioSkinning(true); // does it scatter the cubature points only? scatterConstrainedNodes(); } ////////////////////////////////////////////////////////////////////////////// // scatter the current skeleton bone transforms to the meshes ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::scatterSkeletonTransforms() { // scatter the bone transform data to the meshes -- don't call scatterBoneTransforms(), // as that uses Pinocchio's offset indices vector<BONE*> bones = _skeleton->bones(); for (unsigned int x = 0; x < bones.size(); x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; QUATERNION quaternion = bones[x]->quaternion(); MATRIX3 rotation = quaternion.toExplicitMatrix3x3(); VEC3F translation = bones[x]->translation(); VEC3F& centerOfMass = mesh->originalCenterOfMass(); mesh->rigidTranslation() = translation; mesh->rotationQuaternion() = quaternion; } } ////////////////////////////////////////////////////////////////////////////// // load skinned simulation data snapshot, including the mocap data ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadOdeSkeletonFrame(string dataPath, int frame) { // if this is the first frame, cache the rigids static bool called = false; if (frame == 0 && !called) { setOdeRestRigids(dataPath); called = true; } // update the frame char buffer[256]; sprintf(buffer, "%04i", frame); string skeletonFile = dataPath + string("ode.motion.") + string(buffer) + string(".skeleton"); _skeleton->loadOdeFrame(skeletonFile.c_str()); scatterSkeletonTransforms(); // Don't need to update the constrained nodes because of the way ODE handles // the rigid components //scatterConstrainedNodes(); } ////////////////////////////////////////////////////////////////////////////// // load skinned simulation data snapshot, including the mocap data ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadSkeletonFrame(string dataPath, int frame) { // scatters bone transforms to the partitions as well loadMocapFrame(frame); // load up just the skinning _skeleton->updatePinocchioSkinning(true); // does it scatter the cubature points only? scatterConstrainedNodes(); } ////////////////////////////////////////////////////////////////////////////// // load skinned simulation data snapshot, including the mocap data ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadOdeFrame(string dataPath, int frame, VECTOR& position) { // if this is the first frame, cache the rigids if (frame == 0) { vector<BONE*> bones = _skeleton->bones(); for (unsigned int x = 0; x < bones.size(); x++) { bones[x]->translationOriginal() = bones[x]->translation(); bones[x]->quaternionOriginal() = bones[x]->quaternion(); } } TET_MESH* originalMesh = _originalMesh; originalMesh->x() = position; originalMesh->TET_MESH::updateFullMesh(); originalMesh->readDeformedMesh(frame, dataPath, false); // update defo nodes vector<BONE*> bones = _skeleton->bones(); for (int x = 0; x < _partitions; x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* subMesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; // retrieve the rigid component from the skeleton QUATERNION quaternion = bones[x]->quaternion(); VEC3F translation = bones[x]->translation(); subMesh->rigidTranslation() = translation; subMesh->rotationQuaternion() = quaternion; VECTOR restVector = subMesh->restVector(); VECTOR subPosition = getSubvector(x, position); subPosition += restVector; subtractTranslation(x, subPosition); subtractRotation(x, subPosition); subPosition -= restVector; subMesh->x() = subPosition; subMesh->TET_MESH::updateFullMesh(); } // apply the transform to the constrained nodes as well for (int x = 0; x < _partitions; x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* subMesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; QUATERNION quaternion = bones[x]->quaternion(); QUATERNION quaternionOriginal = bones[x]->quaternionOriginal(); VEC3F translation = bones[x]->translation(); VEC3F translationOriginal = bones[x]->translationOriginal(); MATRIX3 rotationOriginal = quaternionOriginal.toExplicitMatrix3x3(); vector<VEC3F>& restPose = subMesh->restPose(); vector<VEC3F>& vertices = subMesh->vertices(); int unconstrainedNodes = subMesh->unconstrainedNodes(); MATRIX3 R = quaternion.toExplicitMatrix3x3(); MATRIX3 RT = R.transpose(); VEC3F centerOfMass = subMesh->originalCenterOfMass(); for (unsigned int y = unconstrainedNodes; y < restPose.size(); y++) { int original = originalID(x, y); vertices[y] = _originalMesh->vertices()[original]; // subtracting off to local frame would then be vertices[y] = (vertices[y] - translation); vertices[y] = RT * vertices[y]; } subMesh->TET_MESH::updateFullMesh(); } } ////////////////////////////////////////////////////////////////////////////// // load skinned simulation data snapshot, including the mocap data ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::loadSimulationFrame(string dataPath, int frame, VECTOR& position) { loadMocapFrame(frame); TET_MESH* originalMesh = _originalMesh; originalMesh->x() = position; originalMesh->TET_MESH::updateFullMesh(); originalMesh->readDeformedMesh(frame, dataPath, false); for (int x = 0; x < _partitions; x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* subMesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; VECTOR restVector = subMesh->restVector(); VECTOR subPosition = getSubvector(x, position); subPosition += restVector; subtractTranslation(x, subPosition); subtractRotation(x, subPosition); subPosition -= restVector; subMesh->x() = subPosition; subMesh->TET_MESH::updateFullMesh(); } scatterConstrainedNodes(); } ////////////////////////////////////////////////////////////////////////////// // undo the translation in a snapshot for a given partition ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::subtractTranslation(int partition, VECTOR& snapshot) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[partition]; VEC3F translation = mesh->rigidTranslation(); VEC3F centerOfMass = mesh->originalCenterOfMass(); translation -= centerOfMass; // subtract out the translation for (int x = 0; x < snapshot.size() / 3; x++) { snapshot[3 * x] -= translation[0]; snapshot[3 * x + 1] -= translation[1]; snapshot[3 * x + 2] -= translation[2]; } } ////////////////////////////////////////////////////////////////////////////// // undo the rotation in a snapshot for a given partition ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::subtractRotation(int partition, VECTOR& snapshot) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[partition]; MATRIX3 rotation = mesh->rotationQuaternion().toExplicitMatrix3x3(); MATRIX3 transpose = rotation.transpose(); for (int x = 0; x < snapshot.size() / 3; x++) { // copy into VEC3s VEC3F position3; position3[0] = snapshot[3 * x]; position3[1] = snapshot[3 * x + 1]; position3[2] = snapshot[3 * x + 2]; // perform the undo position3 = transpose * position3; // copy back into the bigger vector snapshot[3 * x] = position3[0]; snapshot[3 * x + 1] = position3[1]; snapshot[3 * x + 2] = position3[2]; } } ////////////////////////////////////////////////////////////////////////////// // set the rest poses of the meshes according to the first ODE frame ////////////////////////////////////////////////////////////////////////////// void PARTITIONED_SKINNED_SUBSPACE_TET_MESH::setOdeRestRigids(string dataPath) { string skeletonFile = dataPath + string("ode.motion.0000.skeleton"); _skeleton->loadOdeFrame(skeletonFile.c_str()); vector<BONE*> bones = _skeleton->bones(); for (unsigned int x = 0; x < bones.size(); x++) { UNCONSTRAINED_SUBSPACE_TET_MESH* mesh = (UNCONSTRAINED_SUBSPACE_TET_MESH*)_meshes[x]; vector<VEC3F>& restPose = mesh->restPose(); vector<VEC3F>& vertices = mesh->vertices(); QUATERNION quaternion = bones[x]->quaternion(); MATRIX3 rotation = quaternion.toExplicitMatrix3x3(); VEC3F translation = bones[x]->translation(); VEC3F& centerOfMass = mesh->originalCenterOfMass(); MATRIX3 RT = rotation.transpose(); for (unsigned int y = 0; y < restPose.size(); y++) { restPose[y] = RT * ((restPose[y] + centerOfMass) - translation); vertices[y] = RT * ((vertices[y] + centerOfMass) - translation); } mesh->rigidTranslation() = translation; mesh->rotationQuaternion() = quaternion; mesh->originalCenterOfMass() = translation; bones[x]->quaternionOriginal() = quaternion; bones[x]->translationOriginal() = translation; } updateFullMeshes(); }
3b49bf15dd7f1ab04635c04d0adc2784e891dd40
61c2b59619958dfd0be6abdb48df66749c335428
/lib3DUI/UIManager.cpp
6aa29864ab3de8c5046c63ce58d2de599eb2b12f
[]
no_license
ivlab/lib3DUI
e260b6362bf2c4e98790a3378aa0cd010c9f625a
d3f9245f62c4c42d931c6cf6794e1d565712b660
refs/heads/master
2021-01-23T05:24:53.312557
2017-03-27T13:46:17
2017-03-27T13:46:17
86,305,320
0
0
null
null
null
null
UTF-8
C++
false
false
6,357
cpp
UIManager.cpp
#include "UIManager.h" #include "QuickShapes.h" #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <iostream> UIManager::UIManager(BentoBoxWidget *bento) : _lhandCursorType(CURSOR_CUBE), _rhandCursorType(CURSOR_LASER), _lhandDown(false), _rhandDown(false), _lhandMat(glm::mat4(1.0)), _rhandMat(glm::mat4(1.0)) { _bothOutsideVol = new BothOutsideVol(this, bento); _dhInsideVol = new DHInsideVol(this, bento); _ndhInsideVol = new NDHInsideVol(this, bento); _bothInsideVol = new BothInsideVol(this, bento); _currentState = _bothOutsideVol; _currentStateID = UIState::STATE_BOTHOUTSIDE; resetVOISphere(); } UIManager::~UIManager() { delete _bothOutsideVol; delete _dhInsideVol; delete _ndhInsideVol; delete _bothInsideVol; } void UIManager::setState(UIState::STATE_ID newState) { if (newState == UIState::STATE_BOTHOUTSIDE) { UIState *prev = _currentState; UIState::STATE_ID prevID = _currentStateID; prev->exitState(); _currentStateID = UIState::STATE_BOTHOUTSIDE; _currentState = _bothOutsideVol; _currentState->enterState(prevID); } else if (newState == UIState::STATE_DHINSIDE) { UIState *prev = _currentState; UIState::STATE_ID prevID = _currentStateID; prev->exitState(); _currentStateID = UIState::STATE_DHINSIDE; _currentState = _dhInsideVol; _currentState->enterState(prevID); } else if (newState == UIState::STATE_NDHINSIDE) { UIState *prev = _currentState; UIState::STATE_ID prevID = _currentStateID; prev->exitState(); _currentStateID = UIState::STATE_NDHINSIDE; _currentState = _ndhInsideVol; _currentState->enterState(prevID); } else if (newState == UIState::STATE_BOTHINSIDE) { UIState *prev = _currentState; UIState::STATE_ID prevID = _currentStateID; prev->exitState(); _currentStateID = UIState::STATE_BOTHINSIDE; _currentState = _bothInsideVol; _currentState->enterState(prevID); } else { std::cerr << "UIManager: unknown state " << (int)newState << std::endl; exit(1); } } void UIManager::rhandTrackerMove(glm::mat4 transform) { if (_rhandDown) { _currentState->rhandTrackerDrag(transform); } else { _currentState->rhandTrackerMove(transform); } _rhandMat = transform; if (!_voiSphereLocked) { _voiSphereMat = _rhandMat; } } void UIManager::rhandBtnDown() { _currentState->rhandBtnDown(); _rhandDown = true; } void UIManager::rhandBtnUp() { _currentState->rhandBtnUp(); _rhandDown = false; } void UIManager::lhandTrackerMove(glm::mat4 transform) { if (_lhandDown) { _currentState->lhandTrackerDrag(transform); } else { _currentState->lhandTrackerMove(transform); } _lhandMat = transform; } void UIManager::lhandBtnDown() { _currentState->lhandBtnDown(); _lhandDown = true; } void UIManager::lhandBtnUp() { _currentState->lhandBtnUp(); _lhandDown = false; } // --------------------- Friend Renderer Class ---------------------- UIManagerRenderer::UIManagerRenderer(UIManager *mgr) : _mgr(mgr) { _quickShapes = new QuickShapes(); } UIManagerRenderer::~UIManagerRenderer() { delete _quickShapes; } void UIManagerRenderer::draw(glm::mat4 viewMatrix, glm::mat4 projMatrix) { float lcol[3] = {0.7, 0.2, 0.2}; float rcol[3] = {0.2, 0.2, 0.7}; if (_mgr->_lhandCursorType == _mgr->CURSOR_CUBE) { glm::mat4 S = glm::mat4(1.0); S[0].x = 0.1; S[1].y = 0.1; S[2].z = 0.1; glm::mat4 lM = _mgr->_lhandMat * S; _quickShapes->drawCube(glm::value_ptr(lM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), lcol); } else if (_mgr->_lhandCursorType == _mgr->CURSOR_LASER) { glm::mat4 S = glm::mat4(1.0); S[0].x = 0.03; S[1].y = 0.2; S[2].z = 0.03; glm::mat4 lM = _mgr->_lhandMat * glm::rotate(glm::mat4(1.0), -1.57f, glm::vec3(1,0,0)) * S; _quickShapes->drawCylinder(glm::value_ptr(lM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), lcol); S[0].x = 0.005; S[1].y = 1.5; S[2].z = 0.005; float lasercol[3] = {0.7, 0.7, 0.2}; lM = _mgr->_lhandMat * glm::rotate(glm::mat4(1.0), -1.57f, glm::vec3(1,0,0)) * S * glm::translate(glm::mat4(1.0), glm::vec3(0.0f, 1.0f, 0.0f)); _quickShapes->drawCylinder(glm::value_ptr(lM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), lasercol); } if (_mgr->_rhandCursorType == _mgr->CURSOR_CUBE) { glm::mat4 S = glm::mat4(1.0); S[0].x = 0.1; S[1].y = 0.1; S[2].z = 0.1; glm::mat4 rM = _mgr->_rhandMat * S; _quickShapes->drawCube(glm::value_ptr(rM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), rcol); } else if (_mgr->_rhandCursorType == _mgr->CURSOR_VOISPHERE) { // don't draw the cursor after it is locked in place and we are scaling it if (!_mgr->_voiSphereLocked) { glm::mat4 S = glm::mat4(1.0); S[0].x = _mgr->_voiSphereRad/2.0; S[1].y = _mgr->_voiSphereRad/2.0; S[2].z = _mgr->_voiSphereRad/2.0; glm::mat4 rM = _mgr->_voiSphereMat * S; _quickShapes->drawSphere(glm::value_ptr(rM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), rcol); } } else if (_mgr->_rhandCursorType == _mgr->CURSOR_LASER) { glm::mat4 S = glm::mat4(1.0); S[0].x = 0.03; S[1].y = 0.2; S[2].z = 0.03; glm::mat4 rM = _mgr->_rhandMat * glm::rotate(glm::mat4(1.0), -1.57f, glm::vec3(1,0,0)) * S; _quickShapes->drawCylinder(glm::value_ptr(rM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), rcol); S[0].x = 0.005; S[1].y = 1.5; S[2].z = 0.005; float lasercol[3] = {0.7, 0.7, 0.2}; rM = _mgr->_rhandMat * glm::rotate(glm::mat4(1.0), -1.57f, glm::vec3(1,0,0)) * S * glm::translate(glm::mat4(1.0), glm::vec3(0.0f, 1.0f, 0.0f)); _quickShapes->drawCylinder(glm::value_ptr(rM), glm::value_ptr(viewMatrix), glm::value_ptr(projMatrix), lasercol); } }
899968a9e84ca07dd435ea406be895889737295a
bdfd7bbad70c710bdf1da6092f0d8571bce8d938
/PA4/Part3/extent_client.h
5f8615605ab3c62604f0f35fefa824533a0eefb8
[]
no_license
ktk1012/EE324
6271f87be2ea0c098f1f544a439c09363cfbe6a2
9e8e828f71528331dd567d0477b9876dee4b1350
refs/heads/master
2021-01-18T22:45:39.816513
2016-03-09T05:49:41
2016-03-09T05:49:41
41,788,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
h
extent_client.h
// extent client interface. #ifndef extent_client_h #define extent_client_h #include <string> #include "extent_protocol.h" #include "rpc.h" class extent_client { private: rpcc *cl; public: extent_client(std::string dst); extent_protocol::status get(extent_protocol::extentid_t eid, std::string &buf); extent_protocol::status getattr(extent_protocol::extentid_t eid, extent_protocol::attr &a); extent_protocol::status put(extent_protocol::extentid_t eid, std::string buf); extent_protocol::status remove(extent_protocol::extentid_t eid); extent_protocol::status update(extent_protocol::extentid_t eid, const char *name, std::string &buf); extent_protocol::status read(extent_protocol::extentid_t eid, unsigned long offset, size_t size, std::string &buf); extent_protocol::status write(extent_protocol::extentid_t eid, unsigned long offset, std::string buf, int &nwritten); extent_protocol::status set_size(extent_protocol::extentid_t eid, size_t size); }; #endif
88e7776d3959272232f21cbc0fb9d63de938b25a
914156e9ff65e2449ee75dd0216ef2e78c91e56c
/RadReview/RAD/PLOT_LIB/Pl_prt.cpp
26a17087b3800196e159c3baa48eea7bab6a5188
[ "BSD-2-Clause" ]
permissive
radtek/Radiation-Review
0db454921eab3b9c4132a4169c799d619f9c0919
37bca0eabe75429a794b0d81eba552afed68d2ff
refs/heads/master
2020-06-23T01:12:39.303595
2019-01-31T22:23:33
2019-01-31T22:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,266
cpp
Pl_prt.cpp
/* This work was supported by the United States Member State Support Program to IAEA Safeguards; the U.S. Department of Energy, Office of Nonproliferation and National Security, International Safeguards Division; and the U.S. Department of Energy, Office of Safeguards and Security. LA-CC-14-040. This software was exported from the United States in accordance with the Export Administration Regulations. Diversion contrary to U.S. law prohibited. Copyright 2015, Los Alamos National Security, LLC. This software application and associated material ("The Software") was prepared by the Los Alamos National Security, LLC. (LANS), under Contract DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the software application and associated material are reserved by DOE on behalf of the Government and LANS pursuant to the contract. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the "Los Alamos National Security, LLC." 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 CONTRAT, 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. */ /* ======================================================================= */ /* ============================== pl_prt.cpp ============================= */ /* ======================================================================= */ /*--------------------------------------------------------------------------- * SPECIAL NOTE TO DEVELOPERS * * Information from this file is extracted to create portions of * PL_UM.DOC. Because of this, the appearance of that document * is highly dependent on the formatting of information in this file. * Thus, it is recommended to remain consistent with existing format * conventions in this file. Please observe the following: * o keep the use of tabs and spaces consistent with existing usage * in this file * o set tab width to 4 * o use "preserve tabs" * o keep extracted lines shorter than 80 characters * *--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- * pl_prt.cpp - PlPrtXxx routines * * Purpose: * The PlPrtXxx functions are focused on the printer. They include * functions to get a DC to the default printer, to start and end * documents, etc. * * Notes: * 1. The routines in this module do relatively little checking of * input arguments. It is assumed that the calling routine is * well tested and that it has already done the appropriate checking * on the input arguments. * * Date Author Revision * -------- ------------ -------- * 06-08-95 R. Cole created * *--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- * Copyright 1995-97, The Regents Of the University of California. This * program was prepared by the Regents of the University of California at * Los Alamos National Laboratory (the University) under Contract No. W-7405- * ENG-36 with the U.S. Department of Energy (DOE). The University has * certain rights in the program pursuant to the contract and the program * should not be copied or distributed outside your organization. All rights * in the program are reserved by the DOE and the University. Neither the * U.S. Government nor the University makes any warranty express or implied, * or assumes any liability or responsibility for the use of this software. * * This software was produced by the Safeguards Science and Technology * Group (NIS-5). *--------------------------------------------------------------------------*/ #include <malloc.h> #include <stdio.h> #include <string.h> #include <windows.h> #include <commdlg.h> #include "pl.h" #include "pl_pvt.h" #include "wu.h" #define IDC_PLPRT_CANCEL 100 #if !defined WIN32 #define FAR16 _far #define EXPORT16 __export #define EXPORT32 #else #define FAR16 #define EXPORT16 #define EXPORT32 __declspec(dllexport) #endif /*+/csubr/TOC---------------------------------------------------------------- * PlPrtClose - close a print job for a Windows printer * * Purpose: * Closes a print job for a Windows printer. "end page" and "end * document" commands are sent to the printer. * * After closing the print job, this routine wraps up operations * for the PL_CTX for the printout. * * Return Value: * PL_OK, or * PL_PRT_CANCEL if bAbort is 1 or if PlPrtStatusWindow has been * called and the operator clicks Cancel, or * other codes for other errors * * Notes: * 1. If bAbort is 1 (or if pPlot->bPrintCancel is 1), then the printout * is aborted, so that nothing is sent to the printer. * 2. This routine automatically calls PlotWrapup. * * See Also: * PlPrtOpenDefault, PlPrtOpenDialog, PlPrtStatusWindow * *-Date Author Revision * -------- ------------ -------- * 06-08-95 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtClose( PL_CTX *pPlot, // IO pointer to plot context struct for printing int bAbort) // I 1 to abort the printout { int retStat=PL_OK; int stat; PRINTDLG *pPd=NULL; if (pPlot->hDC != 0) { if (bAbort || pPlot->bPrintCancel) stat = AbortDoc(pPlot->hDC); else { stat = EndPage(pPlot->hDC); stat = EndDoc(pPlot->hDC); } } if (pPlot->pPd != NULL) { pPd = (PRINTDLG *)pPlot->pPd; if (pPd->hDevMode != 0) GlobalFree(pPd->hDevMode); if (pPd->hDevNames != 0) GlobalFree(pPd->hDevNames); GlobalUnlock(pPlot->hPD); } if (pPlot->hPD != 0) GlobalFree(pPlot->hPD); if (pPlot->hDC != 0) DeleteDC(pPlot->hDC); pPlot->hDC = 0; pPlot->hPD = 0; pPlot->pPd = NULL; retStat = PlPlotWrapup(pPlot); strcpy(pPlot->szPrintOpen, "cls"); return retStat; } /*+/csubr/TOC---------------------------------------------------------------- * PlPrtNewPage - finish a page and start a new one * * Purpose: * Creates a page break, finishing the current page and starting * a new one. * * Return Value: * PL_OK, or * other codes for other errors * *-Date Author Revision * -------- ------------ -------- * 01-25-96 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtNewPage( PL_CTX *pPlot) // IO pointer to plot context struct for printing { int retStat=PL_OK; int stat; if (pPlot->bPrintCancel) { retStat = PL_PRT_CANCEL; goto done; } if (pPlot->hDC == 0) goto done; stat = EndPage(pPlot->hDC); if (stat < 0) goto gdi_error; stat = StartPage(pPlot->hDC); if (stat <= 0) goto gdi_error; done: return retStat; gdi_error: retStat = PL_GDI_FAIL; goto done; } /*+/csubr/TOC/internal------------------------------------------------------- * PlPrtOpen - open a print job for a Windows printer * * Purpose: * Opens a print job for a Windows printer, and issues "start * document" and "start page" commands. * * Return Value: * PL_OK, or * other codes for other errors * *-Date Author Revision * -------- ------------ -------- * 01-19-96 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtOpen( PL_CTX *pPlot, // IO pointer to plot context struct for printing HDC hDC, // I handle for device context HGLOBAL hPD, // I handle for PRINTDLG, or 0 void *pPd, // I pointer to PRINTDLG, or NULL const char *szPrtName, // I printer name, or "" or NULL const char *szPrtPort, // I printer port, or "" or NULL const char *szPrtJob, // I name of print job, or "" or NULL const char *szPrtFile) // I path for print file, or "" or NULL { int retStat=PL_OK; DOCINFO docInfo; int stat; if (szPrtName == NULL) szPrtName = ""; if (szPrtPort == NULL) szPrtPort = ""; if (szPrtJob == NULL) szPrtJob = ""; if (szPrtFile == NULL) szPrtFile = ""; pPlot->hDC = hDC; pPlot->hPD = hPD; pPlot->pPd = pPd; pPlot->szPrtName = pPlot->szPrtPort = pPlot->szPrtFile = pPlot->szPrtJob = NULL; docInfo.cbSize = sizeof(docInfo); docInfo.lpszDocName = szPrtJob; if (szPrtFile[0] != '\0') docInfo.lpszOutput = szPrtFile; else docInfo.lpszOutput = NULL; docInfo.lpszDatatype = NULL; docInfo.fwType = 0; char printer_string[256]; strcpy (printer_string, szPrtPort); stat = StartDoc(hDC, &docInfo); if (stat <= 0) goto gdi_error; stat = StartPage(hDC); if (stat <= 0) goto gdi_error; #define STORE_IT(psz, sz) \ psz = (char *)malloc((strlen(sz) + 1) * sizeof(char)); \ if (psz == NULL) goto malloc_fail; \ strcpy(psz, sz); STORE_IT(pPlot->szPrtName, szPrtName) STORE_IT(pPlot->szPrtPort, szPrtPort) STORE_IT(pPlot->szPrtFile, szPrtFile) STORE_IT(pPlot->szPrtJob, szPrtJob) #undef STORE_IT pPlot->bPrintCancel = 0; pPlot->hwPrintCancel = NULL; // szPrintOpen is the basis for PlPlotInit_prt deciding whether // to preserve hDC, hPD, and pPd. The casual caller will be using // an unitialized PL_CTX for printing, and the odds of having this // member accidentally be "prt" are small. strcpy(pPlot->szPrintOpen, "prt"); retStat = PlPlotInit_prt(pPlot, NULL, 0.F, 1.F, 1.F, 1.F, 1.F); if (retStat != PL_OK) goto done; done: //if (retStat != PL_OK) { #define FREE_IT(psz) if (psz != NULL) { free(psz); psz = NULL; } FREE_IT(pPlot->szPrtName) FREE_IT(pPlot->szPrtPort) FREE_IT(pPlot->szPrtFile) FREE_IT(pPlot->szPrtJob) #undef FREE_IT //} return retStat; gdi_error: retStat = PL_GDI_FAIL; goto done; malloc_fail: retStat = PL_MALLOC_FAIL; goto done; } /*+/csubr/TOC---------------------------------------------------------------- * PlPrtOpenDefault - open a print job to Windows default printer * * Purpose: * Opens a print job to the Windows default printer, and issues "start * document" and "start page" commands. * * If szPrtJob is "" and szPrtFile is not "", then the output is * formatted for the default printer but written to szPrtFile. * * The print job is started with default margins of 1 inch on * each side. Call PlPlotInit_prt to change the margins. * * PlPlotInit_prt can also be used to set up an area on the paper * as a facsimile of a plot window on the screen. * * Return Value: * PL_OK, or * other codes for other errors * * Notes: * 1. When printing is complete, PlPrtClose must be called to wrap up * printing (and to releasee print-related resources). * 2. If both szPrtJob and szPrtFile are "" or both are not "", then * the printout is directed to the default printer. The user can * print the file at a later time by copying it to the printer's port. * * See Also: * PlPrtOpenDialog, PlPrtClose, PlPrtStatusWindow * *-Date Author Revision * -------- ------------ -------- * 06-08-95 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtOpenDefault( PL_CTX *pPlot, // IO pointer to plot context struct for printing const char *szPrtJob, // I name of print job, or "" or NULL const char *szPrtFile) // I path for print file, or "" or NULL { int retStat=PL_OK; int stat; HDC hDC=0; char szPrt[64], *szDrv, *szDev, *szPort; HCURSOR hCurOld=0; if (szPrtJob == NULL) szPrtJob = ""; if (szPrtFile == NULL) szPrtFile = ""; // Get the default printer from the [windows] section, device= record. // It will be something like: // device=HP LaserJet IIID,hppcl5a,LPT1: stat = GetProfileString("windows", "device", "", szPrt, 64); if (stat < 1) goto gdi_error; szDev = strtok(szPrt, ","); // HP LaserJet IIID szDrv = strtok(NULL, ","); // hppcl5a szPort = strtok(NULL, ","); // LPT1: hDC = CreateDC(szDrv, szDev, szPort, NULL); if (hDC == 0) goto gdi_error; retStat = PlPrtOpen(pPlot, hDC, 0, NULL, szDev, szPort, szPrtJob, ""); if (retStat != PL_OK) goto bail_out; done: return retStat; gdi_error: retStat = PL_GDI_FAIL; bail_out: if (hDC != 0) DeleteDC(hDC); pPlot->hDC = 0; pPlot->hPD = 0; pPlot->pPd = NULL; goto done; } /*+/csubr/TOC---------------------------------------------------------------- * PlPrtOpenDialog - open a print job to operator-selected printer * * Purpose: * Opens a print job to the operator-selected printer. * * A 'Print' dialog box is displayed to the operator, to allow * choosing the printer to be used. "start document" and "start * page" commands are issued to the printer. * * If the operator clicks Cancel, this routine will return * PL_PRT_CANCEL. In this case, the calling program must not proceed * with printing, and PlPrtClose must not be called. * * The print job is started with default margins of 1 inch on * each side. Call PlPlotInit_prt to change the margins. * * PlPlotInit_prt can also be used to set up an area on the paper * as a facsimile of a plot window on the screen. * * When printing operations are complete, PlPrtClose must be called * to complete the print job and to wrap up interactions with the * plotting library. * * Return Value: * PL_OK, or * PL_PRT_CANCEL if the operator clicks Cancel in the dialog box, or * PL_FILE if the operator checks the 'Print to file' box, * other codes for other errors * * Notes: * 1. When printing is complete, PlPrtClose must be called to wrap up * printing (and to releasee print-related resources). * 2. If szPrtFile isn't "", then the 'Print' dialog will display a * 'Print to file' checkbox. If the user checks the box, then the * printout will be formatted for the selected printer, but written * to the file specified by szPrtFile. The user can print the file * at a later time by copying it to the printer's port. * * See Also: * PlPrtOpenDefault, PlPrtClose, PlPrtStatusWindow * *-Date Author Revision * -------- ------------ -------- * 01-19-96 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtOpenDialog( PL_CTX *pPlot, // IO pointer to plot context struct for printing const char *szPrtJob, // I name of print job, or "" or NULL const char *szPrtFile) // I path for print file, or "" or NULL { int retStat=PL_OK; int stat; HDC hDC=0; HGLOBAL hPD=0; PRINTDLG *pPd=NULL; DEVNAMES *pDevNames=NULL; HCURSOR hCurOld=0; if (szPrtJob == NULL) szPrtJob = ""; if (szPrtFile == NULL) szPrtFile = ""; hPD = GlobalAlloc(GPTR, sizeof(PRINTDLG)); if (hPD == 0) goto gdi_error; pPd = (PRINTDLG *)GlobalLock(hPD); if (pPd == NULL) goto gdi_error; pPd->lStructSize = sizeof(PRINTDLG); pPd->hwndOwner = NULL; pPd->Flags = PD_RETURNDC | PD_ALLPAGES | PD_NOPAGENUMS | PD_NOSELECTION; if (szPrtFile[0] == '\0') pPd->Flags |= PD_HIDEPRINTTOFILE; hCurOld = SetCursor(LoadCursor(NULL, IDC_ARROW)); stat = PrintDlg(pPd); if (hCurOld != 0) SetCursor(hCurOld); if (stat == 0) goto cancel; pDevNames = (DEVNAMES *)GlobalLock(pPd->hDevNames); if (pDevNames == NULL) goto gdi_error; hDC = pPd->hDC; if (hDC == 0) goto gdi_error; if ((pPd->Flags & PD_PRINTTOFILE) == 0) szPrtFile = ""; retStat = PlPrtOpen(pPlot, hDC, hPD, pPd, (char *)pDevNames + pDevNames->wDeviceOffset, (char *)pDevNames + pDevNames->wOutputOffset, szPrtJob, szPrtFile); if (retStat != PL_OK) goto bail_out; if (pPd->Flags & PD_PRINTTOFILE) retStat = PL_FILE; done: return retStat; cancel: retStat = PL_PRT_CANCEL; goto bail_out; gdi_error: retStat = PL_GDI_FAIL; bail_out: if (pDevNames != NULL) GlobalUnlock(pPd->hDevNames); if (pPd != NULL) { if (pPd->hDevMode != 0) GlobalFree(pPd->hDevMode); if (pPd->hDevNames != 0) GlobalFree(pPd->hDevNames); GlobalUnlock(hPD); } if (hPD != 0) GlobalFree(hPD); if (hDC != 0) DeleteDC(hDC); pPlot->hDC = 0; pPlot->hPD = 0; pPlot->pPd = NULL; goto done; } /*+/csubr/TOC---------------------------------------------------------------- * PlPrtPrintSimple - print the plot as it appears on the screen * * Purpose: * Prints the plot that is currently on the screen, with the current * zoom factors and scroll positions. * * The margin arguments control the size and position of the plot on * the printed page. Note that this provides independence from the * paper orientation that is currently in effect. * * Return Value: * PL_OK, or * PL_BAD_INPUT if one of the input checks fails, or * other codes for other errors * * Notes: * 1. A dialog box is presented to the operator to allow choosing the * printer to be used. * 2. When this routine begins sending the plot to the printer, a dialog * box is presented to the operator to allow canceling the print job. * 3. If fBorderPts is 0, no border is drawn around the plot on the page. * * See Also: * PlPrtOpenDefault, PlPrtOpenDialog, PlPlotInit_prt * *-Date Author Revision * -------- ------------ -------- * 12-29-96 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtPrintSimple( PL_CTX *pPlot, // I pointer to plot context struct for screen const char *szJobName, // I name for print job in Windows Print Manager float fBorderPts, // I thickness of border to be drawn, or 0.F float fLMarg_in, // I margin left of plot area, in inches float fRMarg_in, // I margin right of plot area, in inches float fTMarg_in, // I margin above plot area, in inches float fBMarg_in) // I margin below plot area, in inches { int retStat=PL_OK, inpErr=0; HCURSOR hCurOld=0; PL_CTX plPrtCtx; /*+-------------------------------------------------------------------------- * * Input Checks: * 1 pPlot must not be NULL *--------------------------------------------------------------------------*/ PL_INP_CHK(1, pPlot == NULL, done) if (szJobName == NULL) szJobName = "plot"; hCurOld = SetCursor(LoadCursor(NULL, IDC_WAIT)); retStat = PlPrtOpenDialog(&plPrtCtx, szJobName, ""); if (retStat != PL_OK) goto done; retStat = PlPlotInit_prt(&plPrtCtx, pPlot, fBorderPts, fLMarg_in, fRMarg_in, fTMarg_in, fBMarg_in); if (retStat != PL_OK) goto print_error; PlPrtStatusWindow(&plPrtCtx, pPlot->hwPlot, 0); PlWinRepaint(&plPrtCtx); PlPrtStatusWindow(&plPrtCtx, pPlot->hwPlot, 1); retStat = PlPrtClose(&plPrtCtx, 0); done: if (hCurOld != 0) SetCursor(hCurOld); PL_IF_INP_ERR("PlPrtPrintSimple") return retStat; print_error: PlPrtClose(&plPrtCtx, 1); goto done; } /*+/csubr/TOC/internal------------------------------------------------------- * PlPrtStatusPaint - paint the information in the status window * * Purpose: * Paints the information in the status window. * * Return Value: * void * *-Date Author Revision * -------- ------------ -------- * 11-02-96 R. Cole created *--------------------------------------------------------------------------*/ void PlPrtStatusPaint( PL_CTX *pPlot, // IO pointer to plot context struct for printing int bPaint, // I 1 to print, 0 to lay out window RECT *prWin, // I pointer to window's rect HDC hDC, // IO handle to DC for status window int *piYpx) // IO pointer to Y position { RECT rectLine; char szLine[PL_MSG_DIM]; UINT uiFlags=DT_CENTER | DT_WORDBREAK; if (!bPaint) uiFlags |= DT_CALCRECT; rectLine.left = 5; rectLine.right = prWin->right - prWin->left - 9; rectLine.top = *piYpx; rectLine.bottom = *piYpx + 50; *piYpx += DrawText(hDC, "Printing", -1, &rectLine, uiFlags); *piYpx += 5; if (pPlot->szPrtJob != NULL && *pPlot->szPrtJob != '\0') { rectLine.right = prWin->right - prWin->left - 9; rectLine.top = *piYpx; rectLine.bottom = *piYpx + 50; *piYpx += DrawText(hDC, pPlot->szPrtJob, -1, &rectLine, uiFlags); *piYpx += 5; } if (pPlot->szPrtName != NULL && pPlot->szPrtPort != NULL) { rectLine.right = prWin->right - prWin->left - 9; rectLine.top = *piYpx; rectLine.bottom = *piYpx + 50; _snprintf(szLine, PL_MSG_DIM-1, "to '%s' on '%s'", pPlot->szPrtName, pPlot->szPrtPort); *piYpx += DrawText(hDC, szLine, -1, &rectLine, uiFlags); *piYpx += 5; } } /*+/csubr/TOC/internal------------------------------------------------------- * PlPrtProc - handle events for a status window * * Purpose: * Handles events for a status window. * * Return Value: * * *-Date Author Revision * -------- ------------ -------- * 10-25-96 R. Cole created *--------------------------------------------------------------------------*/ LRESULT EXPORT16 CALLBACK PlPrtProc( HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { PL_CTX *pPlot; pPlot = (PL_CTX *)GetWindowLong(hWnd, 0); if (iMsg == WM_COMMAND) { if (wParam == IDC_PLPRT_CANCEL) goto cancel_exit; else goto default_proc; } else if (iMsg == WM_PAINT) { PAINTSTRUCT ps; HDC hDC; RECT rectWin; int iYpx=5; hDC = BeginPaint(hWnd, &ps); GetWindowRect(hWnd, &rectWin); PlPrtStatusPaint(pPlot, 1, &rectWin, hDC, &iYpx); EndPaint(hWnd, &ps); } else if (iMsg == WM_KEYDOWN) { if (wParam == VK_RETURN) goto cancel_exit; else { MessageBeep(0); goto default_proc; } } else if (iMsg == WM_SYSCOMMAND) { if (wParam == SC_CLOSE) DestroyWindow(hWnd); else goto default_proc; } else goto default_proc; default_proc: return DefWindowProc(hWnd, iMsg, wParam, lParam); cancel_exit: pPlot->bPrintCancel = 1; DestroyWindow(pPlot->hwPrintCancel); pPlot->hwPrintCancel = 0; return 0; } /*+/csubr/TOC/internal------------------------------------------------------- * PlPrtWin - create a status window * * Purpose: * Creates a status window. * * Return Value: * HWND, or * NULL if error occurs * *-Date Author Revision * -------- ------------ -------- * 10-25-96 R. Cole created *--------------------------------------------------------------------------*/ HWND PASCAL PlPrtWin( HINSTANCE hInst, // I handle to this instance HWND hwParent, // I parent window handle PL_CTX *pPlot) // IO pointer to plot context struct for printing { HWND hwStatus=0; char *szClass="PLPRTST"; WNDCLASS statusClass; ATOM atom; int stat; stat = GetClassInfo(hInst, szClass, &statusClass); if (stat == 0) { // the class hasn't been registered yet statusClass.style = CS_OWNDC; statusClass.lpfnWndProc = PlPrtProc; statusClass.cbClsExtra = 0; statusClass.cbWndExtra = 1 * sizeof(void *); statusClass.hInstance = hInst; statusClass.hIcon = NULL; statusClass.hCursor = NULL; statusClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); statusClass.lpszMenuName = NULL; statusClass.lpszClassName = szClass; atom = RegisterClass(&statusClass); if (atom == 0) goto done; } hwStatus = CreateWindow(szClass, "", WS_POPUPWINDOW | WS_CAPTION, 50, 50, 300, 100, hwParent, 0, hInst, NULL); if (hwStatus == 0) goto done; SetWindowLong(hwStatus, 0, (DWORD)pPlot); done: return hwStatus; } /*+/csubr/TOC---------------------------------------------------------------- * PlPrtStatusWindow - show or dismiss the printing status window * * Purpose: * Shows or dismisses the printing status window. * * This routine can be called before printing begins to display * a status window to the operator. If the operator clicks the * CANCEL button, then the program is notified (via PL.LIB * return status codes) to cancel the printout. * * After printing is complete, this routine is called to dismiss * the status window. * * Return Value: * PL_OK, or * other codes for other errors * * Notes: * 1. If this routine is used, it must be called after PlPrtOpen is * called. * 2. To dismiss the printing status window, call this routine prior * to the call to PlPrtClose. * 3. Typically, hwParent will be the handle for the program's main * window or a dialog box. * *-Date Author Revision * -------- ------------ -------- * 10-25-96 R. Cole created *--------------------------------------------------------------------------*/ int PASCAL PlPrtStatusWindow( PL_CTX *pPlot, // IO pointer to plot context struct for printing HWND hwParent, // I handle for parent window int bDismiss) // I 0 (or 1) to show (or dismiss) the window { int retStat=PL_OK; HINSTANCE hInst; HWND hwStatus, hwBtn; RECT rectWin; HDC hDC=0; int iYpx=5; if (!bDismiss && pPlot->bPrintCancel) goto done; if (bDismiss) { WuDoEvents(); // allow possible "Cancel" click to take effect if (pPlot->hwPrintCancel != 0) DestroyWindow(pPlot->hwPrintCancel); pPlot->hwPrintCancel = 0; } else { hInst = WuGetHInstance(hwParent); hwStatus = PlPrtWin(hInst, hwParent, pPlot); if (hwStatus == 0) goto gdi_error; pPlot->hwPrintCancel = hwStatus; hDC = GetDC(hwStatus); if (hDC == 0) goto gdi_error; GetWindowRect(hwStatus, &rectWin); SetWindowText(hwStatus, "Printing"); PlPrtStatusPaint(pPlot, 0, &rectWin, hDC, &iYpx); iYpx += 5; hwBtn = WuButton_dflt(hwStatus, IDC_PLPRT_CANCEL, "Cancel", (rectWin.right - rectWin.left) / 2 - 50, iYpx, 100, 22); if (hwBtn == 0) goto gdi_error; iYpx += 27; rectWin.bottom = rectWin.top + iYpx + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CYBORDER); MoveWindow(hwStatus, rectWin.left, rectWin.top, rectWin.right - rectWin.left + 1, rectWin.bottom - rectWin.top + 1, FALSE); ShowWindow(hwStatus, SW_SHOW); WuDoEvents(); } done: if (hDC != 0) ReleaseDC(hwStatus, hDC); return retStat; gdi_error: retStat = PL_GDI_FAIL; goto done; }
24cfbbeaaf1865584fa41324467c2ce89d9c1254
f0eeb6724147908e6903a07cd524472938d5cdba
/Baekjoon/13161_분단의 슬픔.cpp
184e22a136dc0b3d9b1e4696e0ee64048845dca1
[]
no_license
paperfrog1228/Algorithm
bb338e51169d2b9257116f8e9c23afc147e65e27
14b0da325f317d36537a1254bc178bed32337829
refs/heads/master
2022-09-22T23:58:28.824408
2022-09-09T07:01:41
2022-09-09T07:01:41
152,889,184
3
0
null
2019-03-24T14:49:13
2018-10-13T16:04:45
C++
UTF-8
C++
false
false
1,813
cpp
13161_분단의 슬픔.cpp
#include<stdio.h> #include<vector> #include<queue> #define INF 987654321 using namespace std; int s,t,n,res[505][505],level[505],work[505],total; vector<int> adj[505]; bool bfs(){ fill_n(level,n+2,-1); level[t]=-1; level[s]=0; queue<int> q; q.push(s); while(!q.empty()){ int cur=q.front(); q.pop(); for(int i=0;i<adj[cur].size();i++) if(level[adj[cur][i]]==-1&&res[cur][adj[cur][i]]>0) level[adj[cur][i]]=level[cur]+1,q.push(adj[cur][i]); } return level[t]!=-1; } int dfs(int a,int b,int flow){ if(a==b) return flow; for(int &i=work[a];i<adj[a].size();i++){ int next=adj[a][i]; if(level[next]==level[a]+1&&res[a][next]>0){ int df=dfs(next,b,min(res[a][next],flow)); if(df>0){ res[a][next]-=df,res[next][a]+=df; return df; } } } return 0; } void add(int x,int y,int w){ res[x][y]=w; adj[x].push_back(y); adj[y].push_back(x); } int main(){ s=0,t=501; int a; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a); if(a==1) add(s,i,INF); if(a==2) add(i,t,INF); } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ scanf("%d",&a); add(i,j,a); } while(bfs()){ fill(work, work+n+2, 0); work[t]=0; while(1){ int flow=dfs(s,t,INF); if(flow==0) break; total+=flow; } } printf("%d\n",total); for(int i=1;i<=n;i++) if(level[i]!=-1) printf("%d ",i); printf("\n"); for(int i=1;i<=n;i++) if(level[i]==-1) printf("%d ",i); printf("\n"); }
b8fcc895fe30af8be26cab7a130880af491859c9
440f814f122cfec91152f7889f1f72e2865686ce
/src/game_server/server/extension/playing/playing_message_handler.h
f9e1cfef3b301842327a478be3839d94c2b063c2
[]
no_license
hackerlank/buzz-server
af329efc839634d19686be2fbeb700b6562493b9
f76de1d9718b31c95c0627fd728aba89c641eb1c
refs/heads/master
2020-06-12T11:56:06.469620
2015-12-05T08:03:25
2015-12-05T08:03:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,415
h
playing_message_handler.h
// // Summary: buzz source code. // // Author: Tony. // Email: tonyjobmails@gmail.com. // Last modify: 2013-09-16 14:38:15. // File name: actor_message_handler.h // // Description: // Define class PlayingMessageHandler. // #ifndef __GAME__SERVER__PLAYING__PLAYING__MESSAGE__HANDLER__H #define __GAME__SERVER__PLAYING__PLAYING__MESSAGE__HANDLER__H #include <stddef.h> #include "core/base/noncopyable.h" #include "core/base/types.h" namespace game { namespace server { namespace playing { class PlayingMessageHandler : public core::Noncopyable { public: PlayingMessageHandler(); ~PlayingMessageHandler(); bool Initialize(); void Finalize(); private: void OnMessagePlayingCreateRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingCompleteRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingLeaveRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingAwardRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingAutoRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingAutoFinishRequest(core::uint64 id, const char *data, size_t size); void OnMessagePlayingPaidAwardRequest(core::uint64 id, const char *data, size_t size); }; } // namespace playing } // namespace server } // namespace game #endif // __GAME__SERVER__PLAYING__PLAYING__MESSAGE__HANDLER__H
3eaa8090ddf9460b4b8f44ec6136a864b101435d
92c5a8e79405fb198524596d44e201dc38ce345f
/src/vm/vm.cpp
5ab593bcab6357c23f04cb20d7b9c9afcfa1110d
[]
no_license
Vandise/mark-sweep
7d9446fdea0d0acccc2dcc7230fcbed6093f7a0d
5a5e889ebcd52a90daa4b2925db22c0bde6dc304
refs/heads/master
2021-01-20T05:19:03.540663
2017-04-29T07:02:06
2017-04-29T07:02:06
89,769,507
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
vm.cpp
#include "vm/vm.h" VM::VM(int stackSize, int numObjects, int maxObjects) { this->stackSize = stackSize; this->numObjects = numObjects; this->maxObjects = maxObjects; this->firstObject = nullptr; } void VM::push(Object* value) { this->stack[this->stackSize++] = value; } Object* VM::pop() { return this->stack[--this->stackSize]; } VM::~VM() { }
d8421bafcf4050cfcd19a18ebc30674a3b5c1114
05a31be52351aa6e05f0d13803bac4c510944cdf
/src/libdbcppp/DBC_Grammar.h
eb4b5ac1b2237d0fe2b84d8c8441b6a56ed8203d
[ "MIT" ]
permissive
mf01/dbcppp
0ff98855a35de1b26a3a47536d3d2e24e47deb34
93c3cbf7ed148da74662a4da312004c244a0a584
refs/heads/master
2023-04-05T21:05:25.723264
2021-04-27T08:56:50
2021-04-27T08:56:50
357,893,204
0
0
MIT
2021-04-14T12:29:45
2021-04-14T12:13:13
null
UTF-8
C++
false
false
40,405
h
DBC_Grammar.h
#pragma once #include <map> #include <string> #include <vector> #include <istream> #include <cstdint> #include <ostream> #include <fstream> #include <iterator> #include <boost/variant.hpp> #include <boost/optional.hpp> #include <boost/phoenix.hpp> #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_lit.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/fusion/include/vector.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/io.hpp> #include <boost/fusion/include/std_tuple.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/fusion/adapted.hpp> #include <boost/spirit/include/qi_hold.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_object.hpp> #include <boost/spirit/repository/include/qi_iter_pos.hpp> #include "DBC_Grammar.h" namespace dbcppp { using variant_attr_value_t = boost::variant<int64_t, double, std::string>; struct G_Version { std::string::iterator position; std::string version; }; struct G_NewSymbols { std::string::iterator position; std::vector<std::string> new_symbols; }; struct G_BitTiming { std::string::iterator position; uint64_t baudrate; uint64_t BTR1; uint64_t BTR2; }; struct G_Node { std::string::iterator position; std::string name; }; struct G_ValueTable { std::string::iterator position; std::string name; std::map<int64_t, std::string> value_encoding_descriptions; }; struct G_Signal { std::string::iterator position; std::string name; boost::optional<std::string> multiplexer_indicator; uint64_t start_bit; uint64_t signal_size; char byte_order; char value_type; double factor; double offset; double minimum; double maximum; std::string unit; std::vector<std::string> receivers; }; struct G_Message { std::string::iterator position; uint64_t id; std::string name; uint64_t size; std::string transmitter; std::vector<G_Signal> signals; }; struct G_MessageTransmitter { std::string::iterator position; uint64_t id; std::vector<std::string> transmitters; }; struct G_EnvironmentVariable { std::string::iterator position; std::string name; uint64_t var_type; double minimum; double maximum; std::string unit; double initial_value; uint64_t id; std::string access_type; std::vector<std::string> access_nodes; }; struct G_EnvironmentVariableData { std::string::iterator position; std::string name; uint64_t size; }; struct G_SignalType { std::string::iterator position; std::string name; uint64_t size; char byte_order; char value_type; double factor; double offset; double minimum; double maximum; std::string unit; double default_value; std::string value_table_name; }; struct G_CommentNetwork { std::string::iterator position; std::string comment; }; struct G_CommentNode { std::string::iterator position; std::string node_name; std::string comment; }; struct G_CommentMessage { std::string::iterator position; uint64_t message_id; std::string comment; }; struct G_CommentSignal { std::string::iterator position; uint64_t message_id; std::string signal_name; std::string comment; }; struct G_CommentEnvVar { std::string::iterator position; std::string env_var_name; std::string comment; }; using variant_comment_t = boost::variant<G_CommentNetwork, G_CommentNode, G_CommentMessage, G_CommentSignal, G_CommentEnvVar>; struct G_Comment { std::string::iterator position; variant_comment_t comment; }; struct G_AttributeValueTypeInt { std::string::iterator position; int64_t minimum; int64_t maximum; }; struct G_AttributeValueTypeHex { std::string::iterator position; int64_t minimum; int64_t maximum; }; struct G_AttributeValueTypeFloat { std::string::iterator position; double minimum; double maximum; }; struct G_AttributeValueTypeString { std::string::iterator position; }; struct G_AttributeValueTypeEnum { std::string::iterator position; std::vector<std::string> values; }; using variant_attribute_value_t = boost::variant< G_AttributeValueTypeInt, G_AttributeValueTypeHex, G_AttributeValueTypeFloat, G_AttributeValueTypeString, G_AttributeValueTypeEnum>; struct G_AttributeValue { std::string::iterator position; variant_attribute_value_t value; }; struct G_AttributeDefinition { std::string::iterator position; boost::optional<std::string> object_type; std::string name; G_AttributeValue value_type; }; struct G_Attribute { std::string::iterator position; std::string name; variant_attr_value_t value; }; struct G_AttributeNetwork { std::string::iterator position; std::string attribute_name; variant_attr_value_t value; }; struct G_AttributeNode { std::string::iterator position; std::string attribute_name; std::string node_name; variant_attr_value_t value; }; struct G_AttributeMessage { std::string::iterator position; std::string attribute_name; uint64_t message_id; variant_attr_value_t value; }; struct G_AttributeSignal { std::string::iterator position; std::string attribute_name; uint64_t message_id; std::string signal_name; variant_attr_value_t value; }; struct G_AttributeEnvVar { std::string::iterator position; std::string attribute_name; std::string env_var_name; variant_attr_value_t value; }; using variant_attribute_t = boost::variant<G_AttributeNetwork, G_AttributeNode, G_AttributeMessage, G_AttributeSignal, G_AttributeEnvVar>; struct G_ValueDescriptionSignal { std::string::iterator position; uint64_t message_id; std::string signal_name; std::map<int64_t, std::string> value_descriptions; }; struct G_ValueDescriptionEnvVar { std::string::iterator position; std::string env_var_name; std::map<int64_t, std::string> value_descriptions; }; struct G_ValueDescription { std::string::iterator position; boost::variant<G_ValueDescriptionSignal, G_ValueDescriptionEnvVar> description; }; struct G_SignalExtendedValueType { std::string::iterator position; uint64_t message_id; std::string signal_name; uint64_t value; }; struct G_Network { std::string::iterator position; G_Version version; std::vector<std::string> new_symbols; boost::optional<G_BitTiming> bit_timing; std::vector<G_Node> nodes; std::vector<G_ValueTable> value_tables; std::vector<G_Message> messages; std::vector<G_MessageTransmitter> message_transmitters; std::vector<G_EnvironmentVariable> environment_variables; std::vector<G_EnvironmentVariableData> environment_variable_datas; std::vector<G_SignalType> signal_types; std::vector<variant_comment_t> comments; std::vector<G_AttributeDefinition> attribute_definitions; std::vector<G_Attribute> attribute_defaults; std::vector<variant_attribute_t> attribute_values; std::vector<G_ValueDescription> value_descriptions; std::vector<G_SignalExtendedValueType> signal_extended_value_types; }; } BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Version, position, version ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_NewSymbols, position, new_symbols ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_BitTiming, position, baudrate, BTR1, BTR2 ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Node, position, name ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_ValueTable, position, name, value_encoding_descriptions ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Signal, position, name, multiplexer_indicator, start_bit, signal_size, byte_order, value_type, factor, offset, minimum, maximum, unit, receivers ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Message, position, id, name, size, transmitter, signals ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_MessageTransmitter, position, id, transmitters ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_EnvironmentVariable, position, name, var_type, minimum, maximum, unit, initial_value, id, access_type, access_nodes ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_EnvironmentVariableData, position, name, size ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_SignalType, position, name, size, byte_order, value_type, factor, offset, minimum, maximum, unit, default_value, value_table_name ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_CommentNetwork, position, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_CommentNode, position, node_name, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_CommentMessage, position, message_id, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_CommentSignal, position, message_id, signal_name, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_CommentEnvVar, position, env_var_name, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Comment, position, comment ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValueTypeInt, position, minimum, maximum ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValueTypeHex, position, minimum, maximum ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValueTypeFloat, position, minimum, maximum ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValueTypeString, position ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValueTypeEnum, position, values ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeValue, position, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeDefinition, position, object_type, name, value_type ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Attribute, position, name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeNetwork, position, attribute_name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeNode, position, attribute_name, node_name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeMessage, position, attribute_name, message_id, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeSignal, position, attribute_name, message_id, signal_name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_AttributeEnvVar, position, attribute_name, env_var_name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_ValueDescriptionSignal, position, message_id, signal_name, value_descriptions ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_ValueDescriptionEnvVar, position, env_var_name, value_descriptions ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_ValueDescription, position, description ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_SignalExtendedValueType, position, message_id, signal_name, value ) BOOST_FUSION_ADAPT_STRUCT( dbcppp::G_Network, position, version, new_symbols, bit_timing, nodes, value_tables, messages, message_transmitters, environment_variables, environment_variable_datas, signal_types, comments, attribute_definitions, attribute_defaults, attribute_values, value_descriptions, signal_extended_value_types ) namespace dbcppp { template <class Iter> std::tuple<std::size_t, std::size_t> getErrPos(Iter iter, Iter cur) { std::size_t line = 1; std::size_t column = 1; while (iter != cur) { if (*iter == '\n') { line++; column = 1; } else { column++; } iter++; } return {line, column}; } template <class Iter> struct DBCSkipper : boost::spirit::qi::grammar<Iter> { DBCSkipper() : boost::spirit::qi::grammar<Iter>(skipper) { using namespace boost::spirit::qi; single_line_comment = "//" >> *(char_ - eol) >> (eol | eoi); block_comment = ("/*" >> *(block_comment | char_ - "*/")) > "*/"; skipper = space | single_line_comment | block_comment; } boost::spirit::qi::rule<Iter> block_comment, single_line_comment, skipper; }; template <class Iter> class NetworkGrammar : public boost::spirit::qi::grammar<Iter, G_Network(), DBCSkipper<Iter>> { public: using Skipper = DBCSkipper<Iter>; static auto parse(Iter begin, Iter end, G_Network& gnet) { bool result = true; DBCSkipper<Iter> skipper; NetworkGrammar<Iter> grammar(begin); auto pp_begin = begin; bool succeeded = phrase_parse(pp_begin, end, grammar, skipper, gnet); if (!succeeded || (pp_begin != end)) { result = false; } return result; } NetworkGrammar(Iter begin) : NetworkGrammar::base_type(_network, "DBC_Network") { namespace fu = boost::fusion; namespace ph = boost::phoenix; namespace qi = boost::spirit::qi; namespace sp = boost::spirit::labels; namespace ascii = boost::spirit::ascii; _unsigned_integer.name("uint"); _signed_integer.name("int"); _double.name("double"); _char_string.name("QuotedString"); _C_identifier.name("Identifier"); _C_identifier_.name("Identifier"); _version.name("Version"); _new_symbol.name("NewSymbol"); _new_symbols.name("NS_"); _bit_timing.name("BitTiming"); _baudrate.name("Baudrate"); _BTR1.name("BTR1"); _BTR2.name("BTR2"); _nodes.name("Nodes"); _node_.name("Node"); _node_name.name("NodeName"); _node_name.name("NodeName"); _value_tables.name("ValueTables"); _value_table.name("ValueTable"); _value_table_name.name("ValueTableName"); _value_encoding_descriptions.name("VAlueEncodingDescriptions"); _value_encoding_description.name("VAlueEncodingDescription"); _messages.name("Messages"); _message.name("Message"); _message_id.name("MessageId"); _message_name.name("MessageName"); _message_size.name("MessageSize"); _transmitter.name("NodeName"); _transmitter_.name("NodeName"); _signals.name("Signals"); _signal.name("Signal"); _signal_name.name("SignalName"); _multiplexer_indicator.name("SignalMultiplexerIndicator"); _attribute_value_type_string.name("AttributeValueTypeString"); _start_bit.name("SignalStartBit"); _signal_size.name("SignalSize"); _byte_order.name("ByteOrder"); _value_type.name("ValueType"); _factor.name("Factor"); _offset.name("Offset"); _minimum.name("Minimum"); _maximum.name("Maximum"); _unit.name("Unit"); _receivers.name("NodeNames"); _receiver_.name("NodeName"); _receivers_.name("NodeNames"); _message_transmitters.name("MessageTransmitters"); _message_transmitter.name("MessageTransmitter"); _transmitters.name("NodeNames"); _environment_variables.name("EnvironmentVariables"); _environment_variable.name("EnvironmentVariable"); _env_var_name.name("EnvVarName"); _env_var_type.name("EnvVarType"); _initial_value.name("InitialValue"); _ev_id.name("EvId"); _access_type.name("AccessType"); _access_nodes.name("NodeNames"); _environment_variable_datas.name("EnvironmentVariableDatas"); _environment_variable_data.name("EnvironmentVariableData"); _data_size.name("DataSize"); _signal_types.name("SignalTypes"); _signal_type.name("SignalType"); _signal_type_name.name("SignalTypeName"); _default_value.name("DefaultValue"); _comments.name("Comments"); _comment.name("Comment"); _comment_network.name("CommentNetwork"); _comment_node.name("CommentNode"); _comment_message.name("CommentMessage"); _comment_signal.name("CommentSignal"); _comment_env_var.name("CommentEnvVar"); _attribute_definitions.name("AttributeDefinitions"); _attribute_definition.name("AttributeDefinition"); _object_type.name("ObjectType"); _attribute_name.name("AttributeName"); _attribute_value_type.name("AttributeValueType"); _attribute_value_type_int.name("AttributeValueTypeInt"); _attribute_value_type_hex.name("AttributeValueTypeHex"); _attribute_value_type_float.name("AttributeValueTypeFloat"); _attribute_value_type_enum.name("AttributeValueTypeEnum"); _attribute_defaults.name("AttributeDefaults"); _attribute_default.name("AttributeDefault"); _attribute_value.name("AttributeValue"); _attribute_values.name("AttributeValues"); _attribute_value_ent.name("AttributeValueEnt"); _attribute_value_ent_network.name("AttributeValueEntNetwork"); _attribute_value_ent_node.name("AttributeValueEntNode"); _attribute_value_ent_message.name("AttributeValueEntMessage"); _attribute_value_ent_signal.name("AttributeValueEntSignal"); _attribute_value_ent_env_var.name("AttributeValueEntEnvVar"); _value_descriptions.name("ValueDescriptions"); _value_description_sig_env_var.name("ValueDescriptionsSigEnvVar"); _value_description_signal.name("ValueDescriptionsSignal"); _value_description_env_var.name("ValueDescriptionsEnvVar"); _signal_extended_value_types.name("SignalExtendedValueTypes"); _signal_extended_value_type.name("SignalExtendedValueType"); using boost::spirit::repository::qi::iter_pos; _network.name("Network"); _network %= iter_pos > _version > _new_symbols > _bit_timing > _nodes > _value_tables > _messages > _message_transmitters > _environment_variables > _environment_variable_datas > _signal_types > _comments > _attribute_definitions > _attribute_defaults > _attribute_values > _value_descriptions > _signal_extended_value_types ; _unsigned_integer %= qi::uint_; _signed_integer %= qi::int_; _double %= qi::double_; _char_string %= qi::lexeme['"' >> *(('\\' >> qi::char_("\\\"")) | ~qi::char_('"')) >> '"']; _C_identifier %= qi::lexeme[qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9")]; _C_identifier_ %= qi::lexeme[qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9")]; _start_bit %= _unsigned_integer; _signal_size %= _unsigned_integer; _factor %= _double; _offset %= _double; _minimum %= _double; _byte_order = qi::lexeme[qi::char_('0') | qi::char_('1')]; _value_type = qi::lexeme[qi::char_('-') | qi::char_('+')]; _version %= iter_pos >> qi::lit("VERSION") > _char_string; _new_symbol %= qi::lexeme[ qi::string("SIGTYPE_VALTYPE_") | qi::string("BA_DEF_DEF_REL_") | qi::string("BA_DEF_SGTYPE_") | qi::string("SIG_TYPE_REF_") | qi::string("ENVVAR_DATA_") | qi::string("SIG_VALTYPE_") | qi::string("SG_MUL_VAL_") | qi::string("BA_DEF_DEF_") | qi::string("ENVVAR_DTA_") | qi::string("BA_DEF_REL_") | qi::string("SGTYPE_VAL_") | qi::string("VAL_TABLE_") | qi::string("BA_SGTYPE_") | qi::string("SIG_GROUP_") | qi::string("BU_SG_REL_") | qi::string("BU_EV_REL_") | qi::string("BU_BO_REL_") | qi::string("BO_TX_BU_") | qi::string("NS_DESC_") | qi::string("CAT_DEF_") | qi::string("EV_DATA_") | qi::string("BA_REL_") | qi::string("SGTYPE_") | qi::string("BA_DEF_") | qi::string("FILTER") | qi::string("DEF_") | qi::string("VAL_") | qi::string("CAT_") | qi::string("BA_") | qi::string("CM_") ]; _new_symbols %= qi::lit("NS_") > ':' > *_new_symbol; _bit_timing %= qi::lit("BS_") > ':' >> -_bit_timing_inner; _bit_timing_inner %= iter_pos >> _baudrate >> ':' >> _BTR1 >> ',' >> _BTR2; _baudrate %= _unsigned_integer; _BTR1 %= _unsigned_integer; _BTR2 %= _unsigned_integer; _nodes %= qi::lit("BU_") > ':' > qi::skip(ascii::blank)[*_node_ > qi::eol]; _node_ %= iter_pos >> _node_name_; _node_name %= _C_identifier; _node_name_ %= _C_identifier_; _value_tables %= *_value_table; _value_table %= iter_pos >> qi::lit("VAL_TABLE_") > _value_table_name > _value_encoding_descriptions > ';'; _value_table_name %= _C_identifier; _value_encoding_descriptions %= *_value_encoding_description; _value_encoding_description %= _signed_integer > _char_string; _messages %= *_message; _message %= iter_pos >> qi::lit("BO_ ") > _message_id > _message_name > ':' > _message_size > qi::skip(ascii::blank)[_transmitter_ > qi::eol] > _signals; _message_id %= _unsigned_integer; _message_name %= _C_identifier; _message_size %= _unsigned_integer; _transmitter %= _node_name; _transmitter_ %= _node_name_; _signals %= *_signal; _signal %= iter_pos >> qi::lexeme[qi::lit("SG_") >> qi::omit[qi::space]] > _signal_name > _multiplexer_indicator > ':' > _start_bit > '|' > _signal_size > '@' > _byte_order > _value_type > '(' > _factor > ',' > _offset > ')' > '[' > _minimum > '|' > _maximum > ']' > _unit > qi::skip(ascii::blank)[_receivers_ > qi::eol]; _signal_name %= _C_identifier; _multiplexer_indicator %= -_C_identifier; _maximum %= _double; _unit %= _char_string; _receivers %= qi::skip(ascii::blank)[*_receiver_ > qi::eol]; _receiver_ %= _node_name_; _receivers_ %= _receiver_ % ','; _message_transmitters %= *_message_transmitter; _message_transmitter %= iter_pos >> qi::lexeme[qi::lit("BO_TX_BU_") >> qi::omit[qi::space]] > _message_id > ':' > _transmitters > ';'; _transmitters %= _transmitter % ','; _environment_variables %= *_environment_variable; _environment_variable %= iter_pos >> qi::lexeme[qi::lit("EV_") >> qi::omit[qi::space]] > _env_var_name > ':' > _env_var_type > '[' > _minimum > '|' > _maximum > ']' > _unit > _initial_value > _ev_id > _access_type > _access_nodes > ';'; _env_var_name %= _C_identifier; _env_var_type %= _unsigned_integer; _initial_value %= _double; _ev_id %= _unsigned_integer; _access_type %= _C_identifier; _access_nodes %= _node_name % ','; _environment_variable_datas %= *_environment_variable_data; _environment_variable_data %= iter_pos >> qi::lexeme[qi::lit("ENVVAR_DATA_") >> qi::omit[qi::space]] > _env_var_name > ':' > _data_size > ';'; _data_size %= _unsigned_integer; _signal_types %= *_signal_type; _signal_type %= iter_pos >> qi::lexeme[qi::lit("SGTYPE_") >> qi::omit[qi::space]] > _signal_type_name > ':' > _signal_size > '@' > _byte_order > _value_type > '(' > _factor > ',' > _offset > ')' > '[' > _minimum > '|' >> _maximum > ']' > _unit > _default_value > ',' > _value_table_name > ';'; _signal_type_name %= _C_identifier; _default_value %= _double; _comments %= *_comment; _comment %= qi::lexeme[qi::lit("CM_") >> qi::omit[qi::space]] > (_comment_node | _comment_message | _comment_signal | _comment_env_var | _comment_network); _comment_network %= iter_pos >> _char_string > ';'; _comment_node %= iter_pos >> qi::lit("BU_") > _node_name > _char_string > ';'; _comment_message %= iter_pos >> qi::lit("BO_") > _message_id > _char_string > ';'; _comment_signal %= iter_pos >> qi::lit("SG_") > _message_id > _signal_name > _char_string > ';'; _comment_env_var %= iter_pos >> qi::lit("EV_") > _env_var_name > _char_string > ';'; _attribute_definitions %= *_attribute_definition; _attribute_definition %= iter_pos >> qi::lexeme[qi::lit("BA_DEF_") >> qi::omit[qi::space]] > _object_type > _attribute_name > _attribute_value_type > ';'; _object_type %= -(qi::string("BU_") | qi::string("BO_") | qi::string("SG_") | qi::string("EV_")); _attribute_name %= _char_string; _attribute_value_type %= iter_pos >> (_attribute_value_type_int | _attribute_value_type_hex | _attribute_value_type_float | _attribute_value_type_string | _attribute_value_type_enum); _attribute_value_type_int %= iter_pos >> qi::lit("INT") > _signed_integer > _signed_integer; _attribute_value_type_hex %= iter_pos >> qi::lit("HEX") > _signed_integer > _signed_integer; _attribute_value_type_float %= iter_pos >> qi::lit("FLOAT") > _double > _double; _attribute_value_type_string %= iter_pos >> qi::lit("STRING"); _attribute_value_type_enum %= iter_pos >> qi::lit("ENUM") > (_char_string % ','); _attribute_defaults %= *_attribute_default; _attribute_default %= iter_pos >> (qi::lexeme[(qi::lit("BA_DEF_DEF_REL_") | qi::lit("BA_DEF_DEF_")) >> qi::omit[qi::space]]) > _attribute_name > _attribute_value > ';'; _attribute_value %= _double | _signed_integer | _char_string; _attribute_values %= *_attribute_value_ent; _attribute_value_ent %= qi::lexeme[qi::lit("BA_") >> qi::omit[qi::space]] >> (_attribute_value_ent_network | _attribute_value_ent_node | _attribute_value_ent_message | _attribute_value_ent_signal | _attribute_value_ent_env_var) > ';'; _attribute_value_ent_network %= iter_pos >> _attribute_name >> _attribute_value; _attribute_value_ent_node %= iter_pos >> _attribute_name >> qi::lit("BU_") >> _node_name >> _attribute_value; _attribute_value_ent_message %= iter_pos >> _attribute_name >> qi::lit("BO_") >> _message_id >> _attribute_value; _attribute_value_ent_signal %= iter_pos >> _attribute_name >> qi::lit("SG_") >> _message_id >> _signal_name >> _attribute_value; _attribute_value_ent_env_var %= iter_pos >> _attribute_name >> qi::lit("EV_") >> _env_var_name >> _attribute_value; _value_descriptions %= *_value_description_sig_env_var; _value_description_sig_env_var %= iter_pos >> (_value_description_signal | _value_description_env_var); _value_description_signal %= iter_pos >> qi::lexeme[qi::lit("VAL_") >> qi::omit[qi::space]] >> _message_id >> _signal_name >> _value_encoding_descriptions > ';'; _value_description_env_var %= iter_pos >> qi::lexeme[qi::lit("VAL_") >> qi::omit[qi::space]] >> _env_var_name >> _value_encoding_descriptions > ';'; _signal_extended_value_types %= *_signal_extended_value_type; _signal_extended_value_type %= iter_pos >> qi::lexeme[qi::lit("SIG_VALTYPE_") >> qi::omit[qi::space]] > _message_id > _signal_name > ':' > _unsigned_integer > ';'; auto error_handler = [begin](const auto& args, const auto& context, const auto& error) { const auto& first = fu::at_c<0>(args); const auto& last = fu::at_c<1>(args); const auto& err = fu::at_c<2>(args); const auto& what = fu::at_c<3>(args); auto[line, column] = getErrPos(begin, err); std::cout << line << ":" << column << " Error! Expecting " << what << std::endl; }; qi::on_error<qi::fail>(_network, error_handler); } private: boost::spirit::qi::rule<Iter, G_Network(), Skipper> _network; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _unsigned_integer; boost::spirit::qi::rule<Iter, int64_t(), Skipper> _signed_integer; boost::spirit::qi::rule<Iter, double(), Skipper> _double; boost::spirit::qi::rule<Iter, std::string(), Skipper> _char_string; boost::spirit::qi::rule<Iter, std::string(), Skipper> _C_identifier; boost::spirit::qi::rule<Iter, std::string(), boost::spirit::ascii::blank_type> _C_identifier_; boost::spirit::qi::rule<Iter, G_Version, Skipper> _version; boost::spirit::qi::rule<Iter, std::string(), Skipper> _new_symbol; boost::spirit::qi::rule<Iter, std::vector<std::string>(), Skipper> _new_symbols; boost::spirit::qi::rule<Iter, boost::optional<G_BitTiming>, Skipper> _bit_timing; boost::spirit::qi::rule<Iter, G_BitTiming, Skipper> _bit_timing_inner; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _baudrate; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _BTR1; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _BTR2; boost::spirit::qi::rule<Iter, std::vector<G_Node>(), Skipper> _nodes; boost::spirit::qi::rule<Iter, std::string(), Skipper> _node_name; boost::spirit::qi::rule<Iter, G_Node(), boost::spirit::ascii::blank_type> _node_; boost::spirit::qi::rule<Iter, std::vector<std::string>(), boost::spirit::ascii::blank_type> _node_names; boost::spirit::qi::rule<Iter, std::string(), boost::spirit::ascii::blank_type> _node_name_; boost::spirit::qi::rule<Iter, std::vector<G_ValueTable>(), Skipper> _value_tables; boost::spirit::qi::rule<Iter, G_ValueTable(), Skipper> _value_table; boost::spirit::qi::rule<Iter, std::string(), Skipper> _value_table_name; boost::spirit::qi::rule<Iter, std::map<int64_t, std::string>(), Skipper> _value_encoding_descriptions; boost::spirit::qi::rule<Iter, std::pair<int64_t, std::string>(), Skipper> _value_encoding_description; boost::spirit::qi::rule<Iter, std::vector<G_Message>(), Skipper> _messages; boost::spirit::qi::rule<Iter, G_Message(), Skipper> _message; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _message_id; boost::spirit::qi::rule<Iter, std::string(), Skipper> _message_name; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _message_size; boost::spirit::qi::rule<Iter, std::string(), Skipper> _transmitter; boost::spirit::qi::rule<Iter, std::string(), boost::spirit::ascii::blank_type> _transmitter_; boost::spirit::qi::rule<Iter, std::vector<G_Signal>(), Skipper> _signals; boost::spirit::qi::rule<Iter, G_Signal(), Skipper> _signal; boost::spirit::qi::rule<Iter, std::string(), Skipper> _signal_name; boost::spirit::qi::rule<Iter, boost::optional<std::string>(), Skipper> _multiplexer_indicator; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _start_bit; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _signal_size; boost::spirit::qi::rule<Iter, char(), Skipper> _byte_order; boost::spirit::qi::rule<Iter, char(), Skipper> _value_type; boost::spirit::qi::rule<Iter, double(), Skipper> _factor; boost::spirit::qi::rule<Iter, double(), Skipper> _offset; boost::spirit::qi::rule<Iter, double(), Skipper> _maximum; boost::spirit::qi::rule<Iter, double(), Skipper> _minimum; boost::spirit::qi::rule<Iter, std::string(), Skipper> _unit; boost::spirit::qi::rule<Iter, std::vector<std::string>(), Skipper> _receivers; boost::spirit::qi::rule<Iter, std::vector<std::string>(), boost::spirit::ascii::blank_type> _receivers_; boost::spirit::qi::rule<Iter, std::string(), boost::spirit::ascii::blank_type> _receiver_; boost::spirit::qi::rule<Iter, std::vector<G_MessageTransmitter>(), Skipper> _message_transmitters; boost::spirit::qi::rule<Iter, G_MessageTransmitter(), Skipper> _message_transmitter; boost::spirit::qi::rule<Iter, std::vector<std::string>(), Skipper> _transmitters; boost::spirit::qi::rule<Iter, std::vector<G_EnvironmentVariable>(), Skipper> _environment_variables; boost::spirit::qi::rule<Iter, G_EnvironmentVariable(), Skipper> _environment_variable; boost::spirit::qi::rule<Iter, std::string(), Skipper> _env_var_name; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _env_var_type; boost::spirit::qi::rule<Iter, double(), Skipper> _initial_value; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _ev_id; boost::spirit::qi::rule<Iter, std::string(), Skipper> _access_type; boost::spirit::qi::rule<Iter, std::vector<std::string>(), Skipper> _access_nodes; boost::spirit::qi::rule<Iter, std::vector<G_EnvironmentVariableData>(), Skipper> _environment_variable_datas; boost::spirit::qi::rule<Iter, G_EnvironmentVariableData(), Skipper> _environment_variable_data; boost::spirit::qi::rule<Iter, uint64_t(), Skipper> _data_size; boost::spirit::qi::rule<Iter, std::vector<G_SignalType>(), Skipper> _signal_types; boost::spirit::qi::rule<Iter, G_SignalType(), Skipper> _signal_type; boost::spirit::qi::rule<Iter, std::string(), Skipper> _signal_type_name; boost::spirit::qi::rule<Iter, double(), Skipper> _default_value; boost::spirit::qi::rule<Iter, std::vector<variant_comment_t>(), Skipper> _comments; boost::spirit::qi::rule<Iter, variant_comment_t(), Skipper> _comment; boost::spirit::qi::rule<Iter, G_CommentNetwork(), Skipper> _comment_network; boost::spirit::qi::rule<Iter, G_CommentNode(), Skipper> _comment_node; boost::spirit::qi::rule<Iter, G_CommentMessage(), Skipper> _comment_message; boost::spirit::qi::rule<Iter, G_CommentSignal(), Skipper> _comment_signal; boost::spirit::qi::rule<Iter, G_CommentEnvVar(), Skipper> _comment_env_var; boost::spirit::qi::rule<Iter, std::vector<G_AttributeDefinition>(), Skipper> _attribute_definitions; boost::spirit::qi::rule<Iter, G_AttributeDefinition(), Skipper> _attribute_definition; boost::spirit::qi::rule<Iter, boost::optional<std::string>(), Skipper> _object_type; boost::spirit::qi::rule<Iter, std::string(), Skipper> _attribute_name; boost::spirit::qi::rule<Iter, G_AttributeValue(), Skipper> _attribute_value_type; boost::spirit::qi::rule<Iter, G_AttributeValueTypeInt(), Skipper> _attribute_value_type_int; boost::spirit::qi::rule<Iter, G_AttributeValueTypeHex(), Skipper> _attribute_value_type_hex; boost::spirit::qi::rule<Iter, G_AttributeValueTypeFloat(), Skipper> _attribute_value_type_float; boost::spirit::qi::rule<Iter, G_AttributeValueTypeString(), Skipper> _attribute_value_type_string; boost::spirit::qi::rule<Iter, G_AttributeValueTypeEnum(), Skipper> _attribute_value_type_enum; boost::spirit::qi::rule<Iter, std::vector<G_Attribute>(), Skipper> _attribute_defaults; boost::spirit::qi::rule<Iter, G_Attribute(), Skipper> _attribute_default; boost::spirit::qi::rule<Iter, variant_attr_value_t(), Skipper> _attribute_value; boost::spirit::qi::rule<Iter, std::vector<variant_attribute_t>(), Skipper> _attribute_values; boost::spirit::qi::rule<Iter, variant_attribute_t(), Skipper> _attribute_value_ent; boost::spirit::qi::rule<Iter, G_AttributeNetwork(), Skipper> _attribute_value_ent_network; boost::spirit::qi::rule<Iter, G_AttributeNode(), Skipper> _attribute_value_ent_node; boost::spirit::qi::rule<Iter, G_AttributeMessage(), Skipper> _attribute_value_ent_message; boost::spirit::qi::rule<Iter, G_AttributeMessage(), Skipper> _attribute_value_ent_message2; boost::spirit::qi::rule<Iter, G_AttributeSignal(), Skipper> _attribute_value_ent_signal; boost::spirit::qi::rule<Iter, G_AttributeEnvVar(), Skipper> _attribute_value_ent_env_var; boost::spirit::qi::rule<Iter, std::vector<G_ValueDescription>(), Skipper> _value_descriptions; boost::spirit::qi::rule<Iter, G_ValueDescription(), Skipper> _value_description_sig_env_var; boost::spirit::qi::rule<Iter, G_ValueDescriptionSignal(), Skipper> _value_description_signal; boost::spirit::qi::rule<Iter, G_ValueDescriptionEnvVar(), Skipper> _value_description_env_var; boost::spirit::qi::rule<Iter, std::vector<G_SignalExtendedValueType>(), Skipper> _signal_extended_value_types; boost::spirit::qi::rule<Iter, G_SignalExtendedValueType(), Skipper> _signal_extended_value_type; }; }
0398e23512c7d7895ea17acb4a68262f9f3d53f8
27bada7a4ed0cd54169dc2a8d945dd2a95cf75ef
/Production/OilRigMonitor/OilRigMonitor/SimulationMain.cpp
374d6e0ce5c3055a890633b762c592ebb325b8e4
[]
no_license
timFinn/Assignment-1
0ccf1856533e7698696513b0fef4ad9f6f3465b0
1e9ef1fcba6e3a72ad2680f36625773244cd0393
refs/heads/master
2020-05-22T17:29:56.161532
2018-07-13T18:11:12
2018-07-13T18:11:12
39,195,634
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
SimulationMain.cpp
/******************************************************************* * SimulationMain.cpp * Timothy Finnegan * Programming Assignment 1: Oil Rig Monitor * * This program is entirely my own work *******************************************************************/ #include "Simulation.h" void main() { Simulation *sim = new Simulation(); sim->initSim(sim); sim->run(); }
433170a7ac771e3d2e521765d3a8e2a566458d94
a69e2cffbbe4e959a0f7535c84503546ed56df00
/2_1D_Modell/2_8_STM32F4_SW_Backup/Eclipse_Workspace/CuBa_1D_JumpUpControl/include/IHardware.h
761714d1fbe2d4dd27a1975f91b72af104ec0046
[]
no_license
HSKA-CuBa/CuBa_git
2316e543de6f5cd2e48f54ae226370bb48fc00e2
343ae1a4c9e1cfad27a4528a0c87ff6c0f16b053
refs/heads/master
2020-05-21T23:57:51.906152
2016-10-17T04:33:54
2016-10-17T04:33:54
64,459,989
0
1
null
null
null
null
UTF-8
C++
false
false
756
h
IHardware.h
//27.8.2016, Michael Meindl //Interface to seperate the Hardware #ifndef IHARDWARE_H #define IHARDWARE_H #include "Global.h" class IHardware { public: virtual UInt16 getX1__dd_raw() = 0; virtual UInt16 getX2__dd_raw() = 0; virtual UInt16 getY1__dd_raw() = 0; virtual UInt16 getY2__dd_raw() = 0; virtual UInt16 getPhi1__d_raw() = 0; virtual UInt16 getPhi2__d_raw() = 0; virtual Int16 getPsi__d_raw() = 0; virtual void openBrake() = 0; virtual void closeBrake() = 0; virtual void enableMotor() = 0; virtual void disableMotor() = 0; virtual void setTorque(const float torque) = 0; public: IHardware() = default; IHardware(const IHardware&) = delete; IHardware& operator=(const IHardware&) = delete; virtual ~IHardware() = default; }; #endif
c337b089fc8072fd0e1629d41075be0d5570930c
a40ac37ee0803aa96afe8708e2bbe185c436a515
/163/Assignment_6/Deliverables/ch7_ex9_main.cpp
3f1f3ae681aba52a438de79dd8e12812f164d3ec
[]
no_license
life8899/Computer_Science
f0c224ea8a0bd6148c9592616201d64b94a74309
a88960b8f31bf982c0d47566120aeb35f49d48eb
refs/heads/master
2021-01-19T13:44:00.786884
2015-10-27T02:17:41
2015-10-27T02:17:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
cpp
ch7_ex9_main.cpp
/* Chapter 7. Exercise 9. main.cpp Reads a series of names from a file with the format lastName, firstName middleName The reads the file and reverses the order of the names to the new formet: firstName middleName lastName NOTE: CHANGE FILE PATH CONSTANT TO PROPER FILE PATH @author Nick Alexander @version 6/20/2015 */ #include <iostream> #include <fstream> #include <string> using namespace std; //const string FILE_PATH = "C:\\Users\\Nick\\Developer\\Computer_Science\\163\\Assignment 6\\Ch7Ex9V2\\names.txt"; const string FILE_PATH = "/home/nalexander/Desktop/Computer_Science/163/Assignment 6/Ch7Ex9/names.txt"; /* Given a line from the source file reverses the names into the target format @param Source string @return String in the target format */ string reverseName(string fullName) { string firstName = "", middleName = "", lastName = ""; int comma_index = fullName.find(',', 0); lastName = fullName.substr(0, comma_index); fullName = fullName.substr(comma_index + 2); int space_index = fullName.find(' ', 0); firstName = fullName.substr(0, space_index); if (space_index != -1) { middleName = fullName.substr(space_index + 1); } string reversedName = firstName + " "; if (!middleName.empty()) { reversedName += middleName + " "; } reversedName += lastName; return reversedName; } /* Main Insertion Point */ int main() { ifstream namesFile; namesFile.open(FILE_PATH.c_str()); while (namesFile.good()) { string fullName; getline(namesFile, fullName); string name = reverseName(fullName); cout << name << endl; } getchar(); }
04817b664c2a01823e4038c62d16a92c64a4dd6d
ae6dbcfd6a333bf598b871e15a7741fef81f964f
/Projects/Fcs/src/Workshare.FCS.Lite.BinaryReader/PptReaderImpl.h
14298993d8372bb587598b54038b7afb6209434a
[]
no_license
xeon2007/WSProf
7d431ec6a23071dde25226437583141f68ff6f85
d02c386118bbd45237f6defa14106be8fd989cd0
refs/heads/master
2016-11-03T17:25:02.997045
2015-12-08T22:04:14
2015-12-08T22:04:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,548
h
PptReaderImpl.h
// PptReaderImpl.h : Declaration of the PptReaderImpl #pragma once #include "SlideInfo.h" #include "StateBasedStrategy.h" #include "PowerPointState.h" #include "AbstractReader.h" #include "CleanableDocType.h" #include "CleanException.h" #include "PowerPointCustomPropertiesReader.h" #include "PowerPointMacrosReader.h" #include "Exclusion.h" class PptBinaryReader; namespace Workshare { namespace FCS { namespace Lite { namespace BinaryReader { class CustomPropertiesReader; class WORKSHAREFCSLITE_BINARY_READER PptReaderImpl : public AbstractReader, public StateBasedStrategy,public CleanableDocType { friend class TestSlides; typedef std::map<long, SlideInfo*> slideInfoMap; public: PptReaderImpl(ChBYTE* memoryfile, unsigned int memoryfileSize,bool bOpenForReadWrite = false); virtual ~PptReaderImpl(); void Init(); void Cleanup(); virtual void Execute(); virtual void Accept(DocumentText::ptr_type pVisitor); virtual void Clean(const std::vector<AbstractTextType::ContentType>& vecContentTypes, std::vector<CleanException>& vecCleanExceptions, std::vector<AbstractTextType::ContentType>& vecContentTypesToSave); virtual void Clean(const std::vector<AbstractTextType::ContentType>& vecContentTypes, std::vector<CleanException>& vecCleanExceptions, std::vector<AbstractTextType::ContentType>& vecContentTypesToSave, std::vector<Workshare::FCS::Lite::BinaryReader::CExclusion> vectExclusions); PptBinaryReader* GetReader(); ChSINT2 GetTextLength() { return m_TextLength; } void SetTextLength(ChSINT2 length) { m_TextLength = length; } long GetCurrentSlideReference() { return m_currentSlideReference; } void SetCurrentSlideReference(long slideReference) { m_currentSlideReference = slideReference;} long GetCurrentSlideNumber() { return m_currentSlideNumber; } void IncrementSlideNumber() { ++m_currentSlideNumber; } long GetCurrentSlideId() { return m_currentSlideId; } void SetCurrentSlideId(long slideId) { m_currentSlideId = slideId;} ChUINT4 GetNumberOfChildren() { return m_numberOfChildren; } bool GetCurrentTextIsTitle() { return m_bCurrentTextIsTitle; } void SetCurrentTextIsTitle(bool currentTextIsTitle) { m_bCurrentTextIsTitle = currentTextIsTitle;} long GetCurrentShapeID() { return m_currentShapeID; } void SetCurrentShapeID(long currentShapeID) { m_currentShapeID = currentShapeID;} DocumentText::ptr_type GetVisitor() { return m_pVisitor; } SlideInfo* AddSlide(long referenceId, const std::wcstring& title); SlideInfo* GetSlideByReferenceId(long referenceId); SlideInfo* GetSlideBySlideId(long slideId); void DeleteFastSaveSlideInfoBySlideId(long slideId); bool IsHiddenSlide(long referenceId); long NextUniqueID() { return m_uniqueID++; } OcMark* GetBeginingMark() { return m_beginingMark; } bool IsHiddenSlidePlusOtherTypeToClean() {return m_bHiddenSlidePlusOtherTypeToClean;} void SetWriteable(bool newValue); bool GetCleanHeaders(); bool GetCleanFooters(); std::vector<CExclusion> GetExclusionList(); private: PptReaderImpl(const PptReaderImpl&); PptReaderImpl& operator=(const PptReaderImpl&); void Execute(EshObject& in_parent); void ProcessRootObject(EshObject& eshObject); void ProcessSemanticEscher(EshObject& eshObject); void ProcessContainer(EshObject& eshObject); void ProcessHiddenSlides(); void ReadSummary(); void ReadCustomProperties(); void ReadMacros(); private: PptObjectFactory* m_pObjectFactory; PptBinaryReader* m_pReader; DocumentText::ptr_type m_pVisitor; PowerPointCustomPropertiesReader m_pptCustomPropertiesReader; PowerPointMacrosReader m_MacReader; slideInfoMap* m_pslideInfo; ChSINT2 m_TextLength; long m_currentSlideReference; long m_currentSlideNumber; long m_currentSlideId; long m_currentShapeID; bool m_bCurrentTextIsTitle; ChUINT4 m_numberOfChildren; long m_uniqueID; OcMark* m_beginingMark; ChBYTE* m_memoryfile; unsigned int m_memoryfileSize; bool m_bOpenForReadWrite; bool m_bHiddenSlidePlusOtherTypeToClean; std::vector<CExclusion> m_vectExclusions; typedef std::vector<CExclusion>::iterator exclusionsIter; bool m_bCleanHeaders; bool m_bCleanFooters; }; } // namespace BinaryReader } // namespace Lite } // namespace FCS } // namespace Workshare
8d45c6aafc7e5ca434437c50d61c814bf289be01
46e1aeefa494780545a844f4f77e9d81bdf047dd
/msg/cpp/User.pb.cc
feed530930f518850d7d13b250849f3d8db1c26e
[]
no_license
luonglh90/classroomonline
7f90489edc331fe1ecbe4e426fc361bbb6ac3796
6220ad5411f9099303743d0c04fbf0d073d1f676
refs/heads/master
2021-01-10T07:41:58.617338
2016-04-10T03:47:26
2016-04-10T03:47:26
55,824,018
0
0
null
null
null
null
UTF-8
C++
false
true
21,387
cc
User.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: User.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "User.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace METRO { namespace CRO { namespace MESSAGES { namespace { const ::google::protobuf::Descriptor* User_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* User_reflection_ = NULL; } // namespace void protobuf_AssignDesc_User_2eproto() { protobuf_AddDesc_User_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "User.proto"); GOOGLE_CHECK(file != NULL); User_descriptor_ = file->message_type(0); static const int User_offsets_[6] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, username_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, email_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, fullname_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, yearofborn_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, imgurl_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, password_), }; User_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( User_descriptor_, User::default_instance_, User_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(User, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(User)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_User_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( User_descriptor_, &User::default_instance()); } } // namespace void protobuf_ShutdownFile_User_2eproto() { delete User::default_instance_; delete User_reflection_; } void protobuf_AddDesc_User_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\nUser.proto\022\022METRO.CRO.MESSAGES\"o\n\004User" "\022\020\n\010username\030\001 \002(\t\022\r\n\005email\030\002 \002(\t\022\020\n\010ful" "lname\030\003 \001(\t\022\022\n\nyearofborn\030\004 \002(\t\022\016\n\006imgur" "l\030\005 \001(\t\022\020\n\010password\030\006 \001(\t", 145); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "User.proto", &protobuf_RegisterTypes); User::default_instance_ = new User(); User::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_User_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_User_2eproto { StaticDescriptorInitializer_User_2eproto() { protobuf_AddDesc_User_2eproto(); } } static_descriptor_initializer_User_2eproto_; // =================================================================== #ifndef _MSC_VER const int User::kUsernameFieldNumber; const int User::kEmailFieldNumber; const int User::kFullnameFieldNumber; const int User::kYearofbornFieldNumber; const int User::kImgurlFieldNumber; const int User::kPasswordFieldNumber; #endif // !_MSC_VER User::User() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:METRO.CRO.MESSAGES.User) } void User::InitAsDefaultInstance() { } User::User(const User& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:METRO.CRO.MESSAGES.User) } void User::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; username_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); email_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); fullname_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); yearofborn_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); imgurl_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); password_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } User::~User() { // @@protoc_insertion_point(destructor:METRO.CRO.MESSAGES.User) SharedDtor(); } void User::SharedDtor() { if (username_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete username_; } if (email_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete email_; } if (fullname_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete fullname_; } if (yearofborn_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete yearofborn_; } if (imgurl_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete imgurl_; } if (password_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete password_; } if (this != default_instance_) { } } void User::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* User::descriptor() { protobuf_AssignDescriptorsOnce(); return User_descriptor_; } const User& User::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_User_2eproto(); return *default_instance_; } User* User::default_instance_ = NULL; User* User::New() const { return new User; } void User::Clear() { if (_has_bits_[0 / 32] & 63) { if (has_username()) { if (username_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { username_->clear(); } } if (has_email()) { if (email_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { email_->clear(); } } if (has_fullname()) { if (fullname_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { fullname_->clear(); } } if (has_yearofborn()) { if (yearofborn_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { yearofborn_->clear(); } } if (has_imgurl()) { if (imgurl_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { imgurl_->clear(); } } if (has_password()) { if (password_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { password_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool User::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:METRO.CRO.MESSAGES.User) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required string username = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_username())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->username().data(), this->username().length(), ::google::protobuf::internal::WireFormat::PARSE, "username"); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_email; break; } // required string email = 2; case 2: { if (tag == 18) { parse_email: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_email())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->email().data(), this->email().length(), ::google::protobuf::internal::WireFormat::PARSE, "email"); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_fullname; break; } // optional string fullname = 3; case 3: { if (tag == 26) { parse_fullname: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_fullname())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->fullname().data(), this->fullname().length(), ::google::protobuf::internal::WireFormat::PARSE, "fullname"); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_yearofborn; break; } // required string yearofborn = 4; case 4: { if (tag == 34) { parse_yearofborn: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_yearofborn())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->yearofborn().data(), this->yearofborn().length(), ::google::protobuf::internal::WireFormat::PARSE, "yearofborn"); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_imgurl; break; } // optional string imgurl = 5; case 5: { if (tag == 42) { parse_imgurl: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_imgurl())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->imgurl().data(), this->imgurl().length(), ::google::protobuf::internal::WireFormat::PARSE, "imgurl"); } else { goto handle_unusual; } if (input->ExpectTag(50)) goto parse_password; break; } // optional string password = 6; case 6: { if (tag == 50) { parse_password: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_password())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->password().data(), this->password().length(), ::google::protobuf::internal::WireFormat::PARSE, "password"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:METRO.CRO.MESSAGES.User) return true; failure: // @@protoc_insertion_point(parse_failure:METRO.CRO.MESSAGES.User) return false; #undef DO_ } void User::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:METRO.CRO.MESSAGES.User) // required string username = 1; if (has_username()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->username().data(), this->username().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "username"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->username(), output); } // required string email = 2; if (has_email()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->email().data(), this->email().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "email"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->email(), output); } // optional string fullname = 3; if (has_fullname()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->fullname().data(), this->fullname().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "fullname"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->fullname(), output); } // required string yearofborn = 4; if (has_yearofborn()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->yearofborn().data(), this->yearofborn().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "yearofborn"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->yearofborn(), output); } // optional string imgurl = 5; if (has_imgurl()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->imgurl().data(), this->imgurl().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "imgurl"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 5, this->imgurl(), output); } // optional string password = 6; if (has_password()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->password().data(), this->password().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "password"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 6, this->password(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:METRO.CRO.MESSAGES.User) } ::google::protobuf::uint8* User::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:METRO.CRO.MESSAGES.User) // required string username = 1; if (has_username()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->username().data(), this->username().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "username"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->username(), target); } // required string email = 2; if (has_email()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->email().data(), this->email().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "email"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->email(), target); } // optional string fullname = 3; if (has_fullname()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->fullname().data(), this->fullname().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "fullname"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->fullname(), target); } // required string yearofborn = 4; if (has_yearofborn()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->yearofborn().data(), this->yearofborn().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "yearofborn"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->yearofborn(), target); } // optional string imgurl = 5; if (has_imgurl()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->imgurl().data(), this->imgurl().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "imgurl"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->imgurl(), target); } // optional string password = 6; if (has_password()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->password().data(), this->password().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "password"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 6, this->password(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:METRO.CRO.MESSAGES.User) return target; } int User::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required string username = 1; if (has_username()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->username()); } // required string email = 2; if (has_email()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->email()); } // optional string fullname = 3; if (has_fullname()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->fullname()); } // required string yearofborn = 4; if (has_yearofborn()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->yearofborn()); } // optional string imgurl = 5; if (has_imgurl()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->imgurl()); } // optional string password = 6; if (has_password()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->password()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void User::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const User* source = ::google::protobuf::internal::dynamic_cast_if_available<const User*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void User::MergeFrom(const User& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_username()) { set_username(from.username()); } if (from.has_email()) { set_email(from.email()); } if (from.has_fullname()) { set_fullname(from.fullname()); } if (from.has_yearofborn()) { set_yearofborn(from.yearofborn()); } if (from.has_imgurl()) { set_imgurl(from.imgurl()); } if (from.has_password()) { set_password(from.password()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void User::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void User::CopyFrom(const User& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool User::IsInitialized() const { if ((_has_bits_[0] & 0x0000000b) != 0x0000000b) return false; return true; } void User::Swap(User* other) { if (other != this) { std::swap(username_, other->username_); std::swap(email_, other->email_); std::swap(fullname_, other->fullname_); std::swap(yearofborn_, other->yearofborn_); std::swap(imgurl_, other->imgurl_); std::swap(password_, other->password_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata User::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = User_descriptor_; metadata.reflection = User_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace MESSAGES } // namespace CRO } // namespace METRO // @@protoc_insertion_point(global_scope)
72dbf94a3c56a70650815b2c51ad831b270373df
ce07b3248965713ba8b0c2b8b6c80cdbd8a44f12
/node_modules/opencv/src/Contours.cc
2193c235d132fa5fba3bcb7f85dee595780d36d4
[ "MIT" ]
permissive
liquidg3/cascadetrainer
b72a6632028ca7b4b69ee50a875c579ac0b9f466
e55064559a6353baca1d8748c1dca254ca9fdd5d
refs/heads/master
2020-03-28T19:42:50.752761
2014-03-12T05:03:36
2014-03-12T05:03:36
17,655,370
4
0
null
null
null
null
UTF-8
C++
false
false
6,881
cc
Contours.cc
#include "Contours.h" #include "OpenCV.h" #include <iostream> v8::Persistent<FunctionTemplate> Contour::constructor; void Contour::Init(Handle<Object> target) { HandleScope scope; //Class v8::Local<v8::FunctionTemplate> m = v8::FunctionTemplate::New(New); m->SetClassName(v8::String::NewSymbol("Contours")); // Constructor constructor = Persistent<FunctionTemplate>::New(m); constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(String::NewSymbol("Contours")); // Prototype //Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); NODE_SET_PROTOTYPE_METHOD(constructor, "point", Point); NODE_SET_PROTOTYPE_METHOD(constructor, "size", Size); NODE_SET_PROTOTYPE_METHOD(constructor, "cornerCount", CornerCount); NODE_SET_PROTOTYPE_METHOD(constructor, "area", Area); NODE_SET_PROTOTYPE_METHOD(constructor, "arcLength", ArcLength); NODE_SET_PROTOTYPE_METHOD(constructor, "approxPolyDP", ApproxPolyDP); NODE_SET_PROTOTYPE_METHOD(constructor, "convexHull", ConvexHull); NODE_SET_PROTOTYPE_METHOD(constructor, "boundingRect", BoundingRect); NODE_SET_PROTOTYPE_METHOD(constructor, "minAreaRect", BoundingRect); NODE_SET_PROTOTYPE_METHOD(constructor, "isConvex", IsConvex); NODE_SET_PROTOTYPE_METHOD(constructor, "moments", Moments); target->Set(String::NewSymbol("Contours"), m->GetFunction()); }; Handle<Value> Contour::New(const Arguments &args) { HandleScope scope; if (args.This()->InternalFieldCount() == 0) return v8::ThrowException(v8::Exception::TypeError(v8::String::New("Cannot instantiate without new"))); Contour *contours; contours = new Contour; contours->Wrap(args.Holder()); return scope.Close(args.Holder()); } Contour::Contour(): ObjectWrap() { } Handle<Value> Contour::Point(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); int index = args[1]->NumberValue(); cv::Point point = self->contours[pos][index]; Local<Object> data = Object::New(); data->Set(String::NewSymbol("x"), Number::New(point.x)); data->Set(String::NewSymbol("y"), Number::New(point.y)); return scope.Close(data); } // FIXME: this sould better be called "Length" as ``Contours`` is an Array like structure // also, this would allow to use ``Size`` for the function returning the number of corners // in the contour for better consistency with OpenCV. Handle<Value> Contour::Size(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); return scope.Close(Number::New(self->contours.size())); } Handle<Value> Contour::CornerCount(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); return scope.Close(Number::New(self->contours[pos].size())); } Handle<Value> Contour::Area(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); //return scope.Close(Number::New(contourArea(self->contours))); return scope.Close(Number::New(contourArea(cv::Mat(self->contours[pos])))); } Handle<Value> Contour::ArcLength(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); bool isClosed = args[1]->BooleanValue(); return scope.Close(Number::New(arcLength(cv::Mat(self->contours[pos]), isClosed))); } Handle<Value> Contour::ApproxPolyDP(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); double epsilon = args[1]->NumberValue(); bool isClosed = args[2]->BooleanValue(); cv::Mat approxed; approxPolyDP(cv::Mat(self->contours[pos]), approxed, epsilon, isClosed); approxed.copyTo(self->contours[pos]); return scope.Close(v8::Null()); } Handle<Value> Contour::ConvexHull(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); bool clockwise = args[1]->BooleanValue(); cv::Mat hull; cv::convexHull(cv::Mat(self->contours[pos]), hull, clockwise); hull.copyTo(self->contours[pos]); return scope.Close(v8::Null()); } Handle<Value> Contour::BoundingRect(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); cv::Rect bounding = cv::boundingRect(cv::Mat(self->contours[pos])); Local<Object> rect = Object::New(); rect->Set(String::NewSymbol("x"), Number::New(bounding.x)); rect->Set(String::NewSymbol("y"), Number::New(bounding.y)); rect->Set(String::NewSymbol("width"), Number::New(bounding.width)); rect->Set(String::NewSymbol("height"), Number::New(bounding.height)); return scope.Close(rect); } Handle<Value> Contour::MinAreaRect(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); cv::RotatedRect minimum = cv::minAreaRect(cv::Mat(self->contours[pos])); Local<Object> rect = Object::New(); rect->Set(String::NewSymbol("angle"), Number::New(minimum.angle)); Local<Object> size = Object::New(); size->Set(String::NewSymbol("height"), Number::New(minimum.size.height)); size->Set(String::NewSymbol("width"), Number::New(minimum.size.width)); rect->Set(String::NewSymbol("size"), size); Local<Object> center = Object::New(); center->Set(String::NewSymbol("x"), Number::New(minimum.center.x)); center->Set(String::NewSymbol("y"), Number::New(minimum.center.y)); v8::Local<v8::Array> points = v8::Array::New(4); cv::Point2f rect_points[4]; minimum.points(rect_points); for (unsigned int i=0; i<4; i++){ Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(rect_points[i].x)); point->Set(String::NewSymbol("y"), Number::New(rect_points[i].y)); points->Set(i, point); } rect->Set(String::NewSymbol("points"), points); return scope.Close(rect); } Handle<Value> Contour::IsConvex(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); return scope.Close(Boolean::New(isContourConvex(cv::Mat(self->contours[pos])))); } Handle<Value> Contour::Moments(const Arguments &args) { HandleScope scope; Contour *self = ObjectWrap::Unwrap<Contour>(args.This()); int pos = args[0]->NumberValue(); /// Get the moments cv::Moments mu = moments( self->contours[pos], false ); Local<Object> res = Object::New(); res->Set(String::NewSymbol("m00"), Number::New(mu.m00)); res->Set(String::NewSymbol("m10"), Number::New(mu.m10)); res->Set(String::NewSymbol("m01"), Number::New(mu.m01)); res->Set(String::NewSymbol("m11"), Number::New(mu.m11)); return scope.Close(res); }
4519f166416095a4820003a404ea357c9432ffc5
83f2f2c4f0d3881551ae82f41eb9171c74cdd440
/A1078 注意平方探测发.cpp
916df4eb05ab04b8f621e2c91a5de645c6b63d9d
[]
no_license
DoyouhaveJJ/myPAT
eb10d668d4b8e9dbf9908490e49a031a8a25f94d
fd82687c3cc7d6488ad48cac5c05fa46f8945a9f
refs/heads/master
2022-11-23T00:23:12.579795
2020-07-24T03:33:24
2020-07-24T03:33:24
275,576,200
1
0
null
null
null
null
UTF-8
C++
false
false
1,375
cpp
A1078 注意平方探测发.cpp
#include <string.h> #include <cstdio> #include <algorithm> #include <map> #include <queue> #include <stack> #include <math.h> using namespace std; const int maxN = 10010; bool flag[maxN]{false}; bool visited[maxN]={false}; void init(){ flag[1] = true; for(int i = 2;i<maxN;++i){ if(!flag[i]){ for(int j = 2*i; j < maxN ; j+=i){ flag[j] = true;//true = 不是素数 } } } } int findMax(int i){ int j = 0; for(j = i ; j < maxN ; ++j){ if(!flag[j]){ break; } } return j; } int main(){ init(); int M,N,num[maxN]; scanf("%d %d",&M,&N); M = findMax(M); for(int i = 0 ; i < N ; ++i){ scanf("%d",&num[i]); } for(int i = 0 ; i < N ; ++i){ if(!visited[num[i]%M]){ printf("%d",num[i]%M); visited[num[i]%M]=true; }else{ //发生冲突 int step = 1; for(step = 1 ; step < M ; step++){ if(!visited[(step*step+num[i])%M]) { printf("%d", (step*step+num[i])%M); visited[(step*step+num[i])%M] = true; break; } } if(step == M){ printf("-"); } } if(i != N -1){ printf(" "); } } }
2cfb028ea52557747a67b20eff39568771a6e937
45463579dc5ac1f1bee0fd4df39d7660574523b6
/src/tempe/varTable.h
1a015965c9c87e06f36abd7ea1b3ef648bb82a0c
[ "MIT" ]
permissive
ondra-novak/tempe
b8ef5244d430714960763b1018c6e6e3daa17e4f
faaae56c186597a090ece9afa66ad0388ee69a88
refs/heads/master
2016-09-16T07:06:52.774260
2016-03-18T18:15:02
2016-03-18T18:15:02
42,603,240
0
0
null
null
null
null
UTF-8
C++
false
false
3,393
h
varTable.h
/* * VarTable.h * * Created on: 6.7.2012 * Author: ondra */ #ifndef AEXPRESS_VARTABLE_H_ #define AEXPRESS_VARTABLE_H_ #include "lightspeed/base/containers/set.h" #include "lightspeed/base/memory/rtAlloc.h" #include "interfaces.h" #include "objects.h" namespace Tempe { class IncludeMap { public: }; class AbstractEnv: public IExprEnvironment { public: bool checkIncludeProcessed(const FilePath &) const; void markIncludeProcessed(const FilePath &); virtual void clear(); protected: Set<FilePath> includeMap; }; class VarTable: public AbstractEnv { public: virtual Value getVar(VarNameRef name) const; virtual void setVar(VarNameRef name, const Value val); virtual void unset(VarNameRef name); virtual bool varExists(VarNameRef name) const; virtual JSON::IFactory &getFactory() const; virtual IExprEnvironment &getGlobalEnv() ; virtual const IExprEnvironment *getParentScope() const; virtual IExprEnvironment &getInternalGlobalEnv() ; virtual const IExprEnvironment &getGlobalEnv() const ; virtual const IExprEnvironment &getInternalGlobalEnv() const; //construct global variable table VarTable(); //construct global variable table with custom allocator (will be used to allocate variables) explicit VarTable(IRuntimeAlloc &alloc); ~VarTable(); void setStaticVar(VarNameRef name, const Value val); void clear(); void clearStatic(); typedef Set<VarName,std::less<VarName> > Tags; void setCycleTimeout(natural tmInMs); virtual natural getCycleTimeout() const ; virtual IVtWriteIterator<char> *getTempeOutput() { return 0; } protected: void initFunctions(); class Factory_t; IRuntimeAlloc &alloc; GCRegRoot gcreg; JSON::PFactory factory; JSON::PNode table; JSON::PNode staticTable; natural cycleTm; JSON::PNode regToGc(const JSON::PNode &obj); }; class LocalScope: public AbstractEnv { public: LocalScope(IExprEnvironment &parent); LocalScope(IExprEnvironment &parent, JSON::PNode import); virtual Value getVar(VarNameRef name) const; virtual void setVar(VarNameRef name, const Value val); virtual void unset(VarNameRef name); virtual bool varExists(VarNameRef name) const; virtual JSON::IFactory &getFactory() const; virtual IExprEnvironment &getGlobalEnv() ; virtual IExprEnvironment &getInternalGlobalEnv() ; virtual const IExprEnvironment *getParentScope() const; virtual const IExprEnvironment &getInternalGlobalEnv() const; virtual const IExprEnvironment &getGlobalEnv() const ; void clear(); JSON::PNode getObject() const {return table;} void setCycleTimeout(natural tmInMs); virtual natural getCycleTimeout() const; virtual IVtWriteIterator<char> *getTempeOutput() { return parent.getTempeOutput(); } protected: IExprEnvironment &parent; IExprEnvironment &global; IExprEnvironment &internalGlobal; JSON::PFactory factory; JSON::PNode table; natural cycleTm; private: LocalScope(const LocalScope &parent); LocalScope &operator=(const LocalScope &parent); }; class FakeGlobalScope : public LocalScope { public: FakeGlobalScope(IExprEnvironment &parent); FakeGlobalScope(IExprEnvironment &parent, JSON::PNode import); virtual Value getVar(VarNameRef name) const; virtual bool varExists(VarNameRef name) const; virtual IExprEnvironment &getGlobalEnv(); virtual const IExprEnvironment *getParentScope() const; }; } /* namespace Tempe */ #endif /* AEXPRESS_VARTABLE_H_ */
03638b7d7c71f271abb70d173e0de7dac21a26c0
6ce194eba1c0c9654246e0f2a8bcd93c2c951cbd
/Data Structures and Algorithms (3rd semester)/Homework1/WaterSupplies/WaterSupplies.cpp
413042076ebae6123b28231c673fc1cbd6e0d645
[]
no_license
georgidemirev/University-Programming
63bad031c55ef2ec1cba0f67b9d8557f0c0a11ed
59b240b6b3e75c4fd562f4ba7c4253f039b69c7f
refs/heads/master
2020-08-11T16:16:12.904335
2020-05-24T13:59:09
2020-05-24T13:59:09
214,593,687
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
WaterSupplies.cpp
// WaterSupplies.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include <vector> #include <iostream> using namespace std; int main() { int n; cin >> n; if (n <= 0 || n> 100000) { return 0; } vector<int> arr; for (int i = 0; i < n; i++) { int p; cin >> p; arr.push_back(p); } int s = 0; for (int i = 0; i < n-1; i++) { int wall = arr.at(i); for (int t = i+1; t < n; t++) { int area = 0; if (wall <= arr.at(t)) { area = wall*(t-i); } else { area = arr.at(t) * (t-i); } if (area > s) { s = area; } } } cout << s << endl; return 0; }
5157d6f91f302ec751db5380bedd37cfc3d38170
9683e36d7f2a266302f0eb8e06ca75a013ee5185
/include/multival.h
8a6d0468ba9cd97d1c1b6dca56cceddd0a7a5630
[]
no_license
bi-ran/history
7430a9106af6a06af47f927d328239d60999175d
f9b72153b395b1c9745597027eb03454635c07ab
refs/heads/master
2021-09-10T04:55:23.669141
2021-08-26T23:23:41
2021-08-26T23:23:46
193,162,687
0
0
null
null
null
null
UTF-8
C++
false
false
2,746
h
multival.h
#ifndef MULTIVAL_H #define MULTIVAL_H #include <iterator> #include <numeric> #include <type_traits> #include <vector> #include "interval.h" class multival { public: template <typename... T> multival(T const&... intervals) : _dims(sizeof...(T)) { extract(intervals...); _size = std::accumulate(std::begin(_shape), std::end(_shape), 1, std::multiplies<int64_t>()); } multival(multival const& other) = default; multival& operator=(multival const& other) = default; ~multival() = default; std::vector<int64_t> indices_for(int64_t index) const; template <template <typename...> class T> std::vector<int64_t> indices_for(T<double> const& values) const { std::vector<int64_t> indices; auto append = [&](interval const& axis, double val) -> int32_t { indices.push_back(axis.index_for(val)); return 0; }; std::inner_product(std::begin(_intervals), std::end(_intervals), std::begin(values), 0, std::plus<>(), append); return indices; } template <template <typename...> class T, typename U> typename std::enable_if<std::is_integral<U>::value, int64_t>::type index_for(T<U> const& indices) const { int64_t block = 1; auto size = [&](int64_t x, int64_t axis) -> int64_t { auto index = block * x; block = block * axis; return index; }; return std::inner_product(std::begin(indices), std::end(indices), std::begin(_shape), 0, std::plus<>(), size); } template <template <typename...> class T, typename U> typename std::enable_if<std::is_floating_point<U>::value, int64_t>::type index_for(T<U> const& values) const { return index_for(indices_for(values)); } template <typename T> T* book(int64_t, std::string const&, std::string const&) const; template <typename T, int64_t N> T* book(int64_t, std::string const&, std::string const&, std::array<int64_t, N> const&) const; std::vector<int64_t> const& shape() const { return _shape; } int64_t dims() const { return _dims; } int64_t size() const { return _size; } interval const& axis(int64_t i) const { return _intervals[i]; } std::vector<interval> const& axes() const { return _intervals; } private: template <typename... T> void extract(T const&... args) { (void) (int [sizeof...(T)]) { (_intervals.emplace_back(args), 0)... }; for (auto const& axis : _intervals) { _shape.push_back(axis.size()); } } std::vector<int64_t> _shape; int64_t _dims; int64_t _size; std::vector<interval> _intervals; }; #endif /* MULTIVAL_H */
71a68068db1e4980d36e0c7530b31c4e06e729dc
ca97444b0a8f8aafb2f97fa332507a5102480f1b
/src/graph/mst/prim.cpp
b76b396803390e01fd3d387f6c6af02866fd4180
[ "MIT" ]
permissive
houzaj/ACM-CheatSheet
5bedf470f93a7f0adeffefbb4b47a75f79f40f17
d35695acedc9744486257109ce4ec1fd65fcc6f4
refs/heads/master
2020-09-01T17:56:07.399740
2019-12-04T05:54:06
2019-12-04T05:54:06
219,021,015
1
0
MIT
2019-11-01T16:18:51
2019-11-01T16:18:50
null
UTF-8
C++
false
false
564
cpp
prim.cpp
int prim(int n){ int ans = 0; mincost[1] = 0; que.push(node(0, 1)); while(!que.empty()){ int u = que.top().u; int cost = que.top().cost; que.pop(); if(used[u] || mincost[u] < cost) continue; used[u] = true; mincost[u] = cost; ans += cost; for(int v = 1; v <= n; v++){ if(u == v) continue; if(!used[v] && mincost[v] > G[u][v]){ mincost[v] = G[u][v]; que.push(node(G[u][v], v)); } } } return ans; }
a70606b2d1accfbbd3d71f5b66deaf8442edd6f0
8425574e87365bba72bc45ab9eab9f29b9f3568d
/src/win/dockConfDialog.cpp
66e5a9a5de0baefdcaaa4c7e4c98fa71b98d37e2
[]
no_license
melisaadin/modedock
92dd3714928f18f70c621de4760facb43f05b376
28fc1398ea8022b85883979a2da6d6451a0a7472
refs/heads/master
2023-03-15T15:28:47.042591
2019-02-19T07:06:18
2019-02-19T07:06:18
522,142,100
1
0
null
2022-08-07T07:10:36
2022-08-07T07:10:36
null
UTF-8
C++
false
false
17,377
cpp
dockConfDialog.cpp
/* * dockConfDialog.cpp * * Created on: Jan 18, 2015 * Author: stan */ #include"dockConfDialog.h" #include<fstream> ProteinPage::ProteinPage(QWidget *parent) : QWidget(parent) { QGroupBox *configGroup = new QGroupBox(tr("Protein configuration")); QLabel *proteinLabel = new QLabel(tr("Protein:")); proteinEdit = new QLineEdit; QPushButton *proteinLoad = new QPushButton(tr("Load")); connect( proteinLoad, SIGNAL(clicked()), this, SLOT(loadFile()) ); QHBoxLayout *serverLayout = new QHBoxLayout; serverLayout->addWidget(proteinLabel); serverLayout->addWidget(proteinEdit); serverLayout->addWidget(proteinLoad); QVBoxLayout *configLayout = new QVBoxLayout; configLayout->addLayout(serverLayout); configGroup->setLayout(configLayout); QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QPushButton *nextButton = new QPushButton(tr("Next")); connect(nextButton, SIGNAL(clicked()), this, SLOT(sNext())); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); // buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(configGroup); mainLayout->addStretch(120); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } void ProteinPage::loadFile(){ QString file = QFileDialog::getOpenFileName(this, tr("Open Molecular File"), ".", tr("molecular files (*.pdb *.mol2 *.pdbqt)")); if (!file.isEmpty()){ proteinEdit->insert( file ); fileName = file.toStdString(); emit loadProtein( file ); } } //------------------------------------------------------------- BindingSitePage::BindingSitePage(QWidget *parent) : QWidget(parent) { QGroupBox *packageGroup = new QGroupBox(tr("Binding Site")); QLabel *xLabel=new QLabel( tr("center x:") ); xEdit=new QLineEdit; QLabel *yLabel=new QLabel( tr("y:") ); yEdit=new QLineEdit; QLabel *zLabel=new QLabel( tr("z:") ); zEdit=new QLineEdit; QHBoxLayout *centerLayout = new QHBoxLayout; centerLayout->addWidget(xLabel); centerLayout->addWidget(xEdit); centerLayout->addWidget(yLabel); centerLayout->addWidget(yEdit); centerLayout->addWidget(zLabel); centerLayout->addWidget(zEdit); QLabel *rLabel=new QLabel(tr("radius:")); rEdit=new QLineEdit; QHBoxLayout *rLayout = new QHBoxLayout; rLayout->addWidget(rLabel); rLayout->addWidget(rEdit); QPushButton *updateButton = new QPushButton(tr("view binding site")); connect(updateButton, SIGNAL(clicked()), this, SLOT(getData()) ); QVBoxLayout *packageLayout = new QVBoxLayout; packageLayout->addLayout(centerLayout); packageLayout->addLayout(rLayout); packageGroup->setLayout(packageLayout); QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QPushButton *nextButton = new QPushButton(tr("Next")); connect(nextButton, SIGNAL(clicked()), this, SLOT(sNext())); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(packageGroup); mainLayout->addWidget(updateButton); mainLayout->addStretch(12); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } void BindingSitePage::getData(){ x=xEdit->text().toFloat(); y=yEdit->text().toFloat(); z=zEdit->text().toFloat(); r=rEdit->text().toFloat(); vector<float> d; d.push_back(x); d.push_back(y); d.push_back(z); d.push_back(r); emit bindingSite(d); } //------------------------------------------------------------------------------- LigandPage::LigandPage(QWidget *parent) : QWidget(parent) { QGroupBox *configGroup = new QGroupBox(tr("Ligand configuration")); QLabel *ligandLabel = new QLabel(tr("Init Ligand:")); ligandEdit = new QLineEdit; QPushButton *ligandLoad = new QPushButton(tr("Load")); connect( ligandLoad, SIGNAL(clicked()), this, SLOT(loadFile()) ); QLabel *ligandLabelRef=new QLabel( tr("Reference Ligand:") ); refLigandEdit=new QLineEdit; QPushButton *refLigandLoad = new QPushButton(tr("Load")); connect( refLigandLoad, SIGNAL(clicked()), this, SLOT(loadRefFile()) ); QHBoxLayout *serverLayout = new QHBoxLayout; serverLayout->addWidget(ligandLabel); serverLayout->addWidget(ligandEdit); serverLayout->addWidget(ligandLoad); QHBoxLayout *refLayout = new QHBoxLayout; refLayout->addWidget(ligandLabelRef); refLayout->addWidget(refLigandEdit); refLayout->addWidget(refLigandLoad); QVBoxLayout *configLayout = new QVBoxLayout; configLayout->addLayout(serverLayout); configLayout->addLayout(refLayout); configGroup->setLayout(configLayout); QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QPushButton *nextButton = new QPushButton(tr("Next")); connect(nextButton, SIGNAL(clicked()), this, SLOT(sNext())); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(configGroup); mainLayout->addStretch(12); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } void LigandPage::loadFile(){ QString file = QFileDialog::getOpenFileName(this, tr("Open Molecular File"), ".", tr("molecular files (*.pdb *.mol2 *.pdbqt)")); if (!file.isEmpty()){ ligandEdit->insert( file ); fileName = file.toStdString(); emit loadLigand( file ); } } void LigandPage::loadRefFile(){ QString file = QFileDialog::getOpenFileName(this, tr("Open Molecular File"), ".", tr("molecular files (*.pdb *.mol2 *.pdbqt)")); if (!file.isEmpty()){ refLigandEdit->insert( file ); refFileName = file.toStdString(); emit loadRefLigand( file ); } } //-------------------------------------------------------------------------------- ScorePage::ScorePage(QWidget *parent) : QWidget(parent) { QGroupBox *packagesGroup = new QGroupBox(tr("Scoring function")); QLabel *ffLabel=new QLabel(tr("Force field:")); QComboBox *ffCombo=new QComboBox; // ffCombo->addItem( tr("Amber") ); // ffCombo->addItem( tr("Charmm") ); ffCombo->addItem( tr("Sybyl") ); QHBoxLayout *ffLayout=new QHBoxLayout; ffLayout->addWidget(ffLabel); ffLayout->addWidget(ffCombo); // QPushButton *startQueryButton = new QPushButton(tr("Set")); QGridLayout *packagesLayout = new QGridLayout; // packagesLayout->addLayout(ffLayout); packagesGroup->setLayout(packagesLayout); QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QPushButton *nextButton = new QPushButton(tr("Next")); connect(nextButton, SIGNAL(clicked()), this, SLOT(sNext())); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(packagesGroup); mainLayout->addLayout(ffLayout); mainLayout->addSpacing(12); // mainLayout->addWidget(startQueryButton); mainLayout->addStretch(12); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } AlgorithmPage::AlgorithmPage(QWidget *parent) : QWidget(parent) { QGroupBox *configGroup = new QGroupBox(tr("Algorithm configuration")); QLabel *popLabel = new QLabel(tr("Population size:")); popEdit = new QLineEdit(tr("25")); QLabel *genLabel = new QLabel( tr("Maximum generation:") ); genEdit = new QLineEdit(tr("100")); QLabel *croLabel = new QLabel(tr("Crossover rate:")); croEdit = new QLineEdit(tr("0.5")); QGridLayout *packagesLayout = new QGridLayout; packagesLayout->addWidget(popLabel,0,0); packagesLayout->addWidget(popEdit,0,1); packagesLayout->addWidget(genLabel,1,0); packagesLayout->addWidget(genEdit,1,1); packagesLayout->addWidget(croLabel,2,0); packagesLayout->addWidget(croEdit,2,1); configGroup->setLayout(packagesLayout); QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QPushButton *nextButton = new QPushButton(tr("Next")); connect(nextButton, SIGNAL(clicked()), this, SLOT(sNext())); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(configGroup); mainLayout->addStretch(12); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } void AlgorithmPage::sPrevious(){ popSize = popEdit->text().toInt(); genSize = genEdit->text().toInt(); crossRate = croEdit->text().toFloat(); emit previous(); } void AlgorithmPage::sNext(){ popSize = popEdit->text().toInt(); genSize = genEdit->text().toInt(); crossRate = croEdit->text().toFloat(); emit next(); } //--------------------------------------------------------------------------- RunPage::RunPage(QWidget *parent) : QWidget(parent) { QGroupBox *packagesGroup = new QGroupBox(tr("Finished configuration")); QGridLayout *packagesLayout = new QGridLayout; packagesGroup->setLayout(packagesLayout); QPushButton *runButton = new QPushButton(tr("Start docking")); connect( runButton, SIGNAL(clicked()), this, SLOT(dock())); QVBoxLayout *mainLayout = new QVBoxLayout; QPushButton *previousButton = new QPushButton(tr("Previous")); connect(previousButton, SIGNAL(clicked()), this, SLOT(sPrevious())); QLabel *popLabel = new QLabel(tr(" ")); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); // buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(popLabel); mainLayout->addSpacing(12); mainLayout->addWidget(packagesGroup); mainLayout->addWidget(runButton); mainLayout->addStretch(1); mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); } //--------------------------------------------------------------------- ConfigDialog::ConfigDialog() { contentsWidget = new QListWidget; contentsWidget->setViewMode(QListView::IconMode); contentsWidget->setIconSize(QSize(96, 84)); contentsWidget->setMovement(QListView::Static); contentsWidget->setMaximumWidth(128); contentsWidget->setSpacing(12); pagesWidget = new QStackedWidget; proteinPage = new ProteinPage; pagesWidget->addWidget( proteinPage); connect( proteinPage, SIGNAL(loadProtein(QString)), this, SLOT(getProteinFile(QString)) ); connect( proteinPage, SIGNAL(previous()), this, SLOT(previous()) ); connect( proteinPage, SIGNAL(next()), this, SLOT(next()) ); bindingSitePage = new BindingSitePage; pagesWidget->addWidget( bindingSitePage); connect( bindingSitePage, SIGNAL(bindingSite(vector<float>)), this, SLOT(getBindingSite(vector<float>))); connect( bindingSitePage, SIGNAL(previous()), this, SLOT(previous()) ); connect( bindingSitePage, SIGNAL(next()), this, SLOT(next()) ); ligandPage = new LigandPage; pagesWidget->addWidget( ligandPage ); connect( ligandPage, SIGNAL(loadLigand(QString)), this, SLOT(getLigandFile(QString)) ); connect( ligandPage, SIGNAL(previous()), this, SLOT(previous()) ); connect( ligandPage, SIGNAL(next()), this, SLOT(next()) ); scorePage = new ScorePage; pagesWidget->addWidget(scorePage); connect( scorePage, SIGNAL(previous()), this, SLOT(previous()) ); connect( scorePage, SIGNAL(next()), this, SLOT(next()) ); algorithmPage = new AlgorithmPage; pagesWidget->addWidget( algorithmPage); connect( algorithmPage, SIGNAL(previous()), this, SLOT(previous()) ); connect( algorithmPage, SIGNAL(next()), this, SLOT(next()) ); runPage = new RunPage; pagesWidget->addWidget(runPage); connect( runPage, SIGNAL(run()), this, SLOT(dock())); connect( runPage, SIGNAL(previous()), this, SLOT(previous()) ); createIcons(); contentsWidget->setCurrentRow(0); QPushButton *previousButton = new QPushButton(tr("Previous")); connect( previousButton, SIGNAL(clicked()), this, SLOT(previous()) ); QPushButton *nextButton = new QPushButton(tr("Next")); connect( nextButton, SIGNAL(clicked()), this, SLOT( next() ) ); QPushButton *runButton = new QPushButton(tr("Run")); connect( runButton, SIGNAL(clicked()), this, SLOT( run()) ); QPushButton *closeButton = new QPushButton(tr("Close")); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); QHBoxLayout *horizontalLayout = new QHBoxLayout; horizontalLayout->addWidget(contentsWidget); horizontalLayout->addWidget(pagesWidget, 1); QHBoxLayout *buttonsLayout = new QHBoxLayout; buttonsLayout->addStretch(1); buttonsLayout->addWidget(previousButton); buttonsLayout->addWidget(nextButton); buttonsLayout->addWidget(runButton); buttonsLayout->addWidget(closeButton); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addLayout(horizontalLayout); mainLayout->addStretch(1); mainLayout->addSpacing(12); // mainLayout->addLayout(buttonsLayout); setLayout(mainLayout); setWindowTitle(tr("Config Dialog")); } void ConfigDialog::createIcons() { QListWidgetItem *proteinButton = new QListWidgetItem(contentsWidget); proteinButton->setIcon(QIcon("images/protein.png1")); proteinButton->setText(tr("protein")); proteinButton->setTextAlignment(Qt::AlignHCenter); proteinButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QListWidgetItem *bindingSiteButton = new QListWidgetItem(contentsWidget); bindingSiteButton->setIcon(QIcon("images/bindingSite.png1")); bindingSiteButton->setText(tr("bindingSite")); bindingSiteButton->setTextAlignment(Qt::AlignHCenter); bindingSiteButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QListWidgetItem *ligandButton = new QListWidgetItem(contentsWidget); ligandButton->setIcon(QIcon("images/ligand.png1")); ligandButton->setText(tr("lignd")); ligandButton->setTextAlignment(Qt::AlignHCenter); ligandButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QListWidgetItem *scoreButton = new QListWidgetItem(contentsWidget); scoreButton->setIcon(QIcon("images/score.png1")); scoreButton->setText(tr("score")); scoreButton->setTextAlignment(Qt::AlignHCenter); scoreButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QListWidgetItem *algorithmButton = new QListWidgetItem(contentsWidget); algorithmButton->setIcon(QIcon("images/algorithm.png1")); algorithmButton->setText(tr("algorithm")); algorithmButton->setTextAlignment(Qt::AlignHCenter); algorithmButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QListWidgetItem *runButton = new QListWidgetItem(contentsWidget); runButton->setIcon(QIcon("images/run.png1")); runButton->setText(tr("run")); runButton->setTextAlignment(Qt::AlignHCenter); runButton->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); connect(contentsWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this, SLOT(changePage(QListWidgetItem*,QListWidgetItem*))); } void ConfigDialog::changePage(QListWidgetItem *current, QListWidgetItem *previous) { if (!current) current = previous; pagesWidget->setCurrentIndex(contentsWidget->row(current)); } void ConfigDialog::previous( ){ int ind = contentsWidget->currentRow() - 1; if( ind <=0 ){ ind = 0; } contentsWidget->setCurrentRow( ind ); } void ConfigDialog::next(){ int ind = contentsWidget->currentRow() + 1; if( ind >5 ){ ind = 5; } contentsWidget->setCurrentRow( ind ); } void ConfigDialog::run(){ emit dockRun(); } void ConfigDialog::dock(){ ofstream off("dock.par"); off.width(15); off<<left<<"MolFile"<<(proteinPage->getFileName())<<endl; off.width(15); off<<left<<"InitLig"<<ligandPage->getInitLigandName()<<endl; off.width(15); off<<left<<"ReferLig"<<ligandPage->getRefLigandName()<<endl; off.width(15); off<<left<<"ForceField"<<"ff.dat"<<endl;; off.width(15); off<<left<<"BindCenter"<<bindingSitePage->getX()<<" "<<bindingSitePage->getY()<<" "<<bindingSitePage->getZ()<<endl; off.width(15); off<<left<<"BindRadius"<<bindingSitePage->getR()<<endl; off.width(15); off<<left<<"PopSize"<<algorithmPage->getPop()<<endl; off.width(15); off<<left<<"Generation"<<algorithmPage->getGen()<<endl; off.width(15); off<<left<<"CountMax"<<20<<endl; off.width(15); off<<left<<"CR"<<algorithmPage->getCro()<<endl; off.close(); close(); emit dockRun(); }
9795e18ccbb21c44e8cb86c35bbd8bc5d22b7349
1e9fbdb90fa4fd3d2c97fc8a45541461ce8ec67f
/src/2016.XO/Solyna_Andriana/XO/HighScoresView.cpp
041e487eed37ca9141e49b9913aa598161c87caf
[]
no_license
vnobis-univ/sonarcube-test
715168684fdd3547240db032d8ccc4d9680fff6f
f917ef2722144107cb12435021dd02574d149e39
refs/heads/master
2020-03-29T11:49:25.879413
2018-09-24T12:29:56
2018-09-24T12:29:56
149,872,507
0
0
null
null
null
null
UTF-8
C++
false
false
1,487
cpp
HighScoresView.cpp
#include "HighScoresView.h" #include "StartView.h" #include <fstream> HighScoresView:: HighScoresView() { ifstream in("Scores.txt"); for(size_t i = 0; i < 5; ++i) { in >> arr[i]; } } void HighScoresView::draw() { clean(); HANDLE hConsole; hConsole = GetStdHandle(STD_OUTPUT_HANDLE); COORD position; position.X = 11; position.Y = 3; COORD position1; position1.X = 23; position1.Y = 3; SetConsoleCursorPosition(hConsole, position); SetConsoleTextAttribute(hConsole, 14); cout << "Player: "; position.Y = position.Y + 2; SetConsoleCursorPosition(hConsole, position1); SetConsoleTextAttribute(hConsole, 9); cout << "Score:" << endl << endl; position1.Y = position1.Y + 2; for (size_t i = 0; i < 5; ++i) { SetConsoleCursorPosition(hConsole, position); SetConsoleTextAttribute(hConsole, 9); cout << arr[i].name; position.Y = position.Y + 2; SetConsoleCursorPosition(hConsole, position1); SetConsoleTextAttribute(hConsole, 14); cout << arr[i].score << endl << endl; position1.Y = position1.Y + 2; } SetConsoleTextAttribute(hConsole, 14); printInTheCentre("Press ENTER to return to main menu", 17, 40); SetConsoleTextAttribute(hConsole, 9); printInTheCentre("Press ESCAPE to exit", 19, 40); } View * HighScoresView:: handle() { View * nextV = NULL; int key = _getch(); if(key == 13) { nextV = new StartView; return nextV; } else if(key == 27) { return nextV; } }
4c3ac7f69a78916ed708c8fea1f5d42297fc1bc6
f1bc129debaca67dd206d20bddf3cbac2aff235a
/UVa_Online_Judge_Problem_Solutions/diff.cpp
e1c1c6370f64f85002fd8080251ad813f2e41486
[]
no_license
ovis96/coding-practice
a848b0b869b8001a69770464c46e4cfe1ba69164
7214383be1e3a2030aa05ff99666b9ee038ae207
refs/heads/master
2022-05-28T14:13:17.517562
2022-05-21T14:16:04
2022-05-21T14:16:04
70,779,713
3
2
null
null
null
null
UTF-8
C++
false
false
277
cpp
diff.cpp
#include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<queue> using namespace std; int main() { string line; while(getline(line)) { } return 0; }
9a347b448a1fd00c5fe8fc36a0251e1cbae85d9f
fd16215cc466dd1d2aa924f6c495520ed3a5f374
/10.1.cpp
acf3b218f6a07b2e4719cfc4913e96bcdcc6a23f
[]
no_license
alvyC/ctci
4aa02408a90107c5c4e8f43f7535aa934d358585
2fd6796f9dd019a6b2a2ef72d974dd56efb38e6b
refs/heads/master
2021-06-18T10:22:54.994747
2017-06-07T21:41:28
2017-06-07T21:41:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
10.1.cpp
#include <stdio.h> #include <stdlib.h> #include <initializer_list> #include <algorithm> #include <stack> #include <queue> #include <string> #include <memory> #include <limits> #include <list> #include <map> #include <iostream> #include <array> #include <set> using namespace std; void merge_sorted(int* a, int a_len, int* b, int b_len) { int a_pos = a_len - 1; int b_pos = b_len - 1; int end_pos = a_len + b_len - 1; while (b_pos >= 0) { if (a_pos >= 0 && a[a_pos] > b[b_pos]) { a[end_pos--] = a[a_pos]; a_pos--; } else { a[end_pos--] = b[b_pos]; b_pos--; } } } int main(int argc, char** argv) { int a[] = { 0, 2, 4, 8, 16, 32, 100, 1000, 10001, 0, 0, 0, 0, 0, 0, 0 }; int a_len = sizeof(a) / sizeof(*a); int b[] = { 1, 3, 7, 8, 16, 70, 81 }; int b_len = sizeof(b) / sizeof(*b); a_len -= b_len; // account for extra space at the end of a merge_sorted(a, a_len, b, b_len); for (int a_val : a) { cout << a_val << " "; } cout << endl; }
4870e7c1300cba8c918b8018644ce7a75c4c2f31
1056e62e6e2bb1c3ba17d46dbb808eac4427cc78
/socket1/server2.cpp
1e2075c80f901c869ae74f9173fc83e9a61d2712
[]
no_license
vanesantillana/CCR
cf79ca4cecb685e6d0ddb1aea92fd04243921668
88463f7c809dc4241687a26504b27a9429e1eeb0
refs/heads/master
2020-03-07T01:35:09.465669
2018-05-02T16:29:10
2018-05-02T16:29:10
127,187,132
0
0
null
2018-05-02T16:29:03
2018-03-28T19:18:07
C++
UTF-8
C++
false
false
4,183
cpp
server2.cpp
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <iostream> #include <bits/stdc++.h> #include <thread> #include "f.h" using namespace std; StringMap Users; thread t[1000]; string printMap(){ StringMap::iterator pos; string lista="+++++++++++++++++++++++++++\nLISTA DE USUARIOS\n"; StringMap::iterator it = Users.begin(); int cont=1; while(it != Users.end()){ lista=lista+to_string(cont)+"- "; lista=lista+it->first+"\n"; it++; cont++; } lista=lista+"+++++++++++++++++++++++++++"; return lista; } void nuevoUsuario( int ConnectFD){ string menu="\n----------------------------\nMENU\n 1. [Action P] Print list of user on the chat\n 2. [Action L] Login to the chat\n 3. [Action C] Send a msg to an user on the chat\n 4. [Action F] Send File \n 6. [Action E] End chat or logout from chat \n----------------------------"; string mensaje; menu=write_protocol_R(menu); while(true){ my_writeSimple(ConnectFD,menu); int sizef; char tipo=getTypeProtocol(ConnectFD,sizef); if (tipo == 'P'){ string nv= write_protocol_R(printMap()); my_writeSimple(ConnectFD,nv); } else if (tipo == 'L'){ string nick=read_protocol_L(ConnectFD,sizef); Users[nick]=ConnectFD; string nv= write_protocol_R(printMap()); my_writeSimple(ConnectFD,nv); } else if (tipo == 'C'){ string nick,msj; msj=read_protocol_C(ConnectFD,sizef,nick); if(Users[nick]){ string newNick=findInMap(Users,ConnectFD); msj=newNick+" dice: "+msj; string nv= write_protocol_R(msj); my_writeSimple(Users[nick],nv); } else{ string nv= write_protocol_R("No existe el usuario"); my_writeSimple(ConnectFD,nv); } } else if (tipo == 'E'){ //shutdown(ConnectFD, SHUT_RDWR); my_writeSimple(ConnectFD,write_protocol_E()); string key=findInMap(Users,ConnectFD); Users.erase(key); close(ConnectFD); break; } else if (tipo == 'F'){ string nick,msj; string newNick=findInMap(Users,ConnectFD); msj=read_protocol_D(ConnectFD,sizef,nick,newNick); //cout<<"msj:"<<msj<<endl; if(Users[nick]){ //msj=newNick+" dice: "+msj; my_writeSimple(Users[nick],msj); } else{ string nv= write_protocol_R("No existe el usuario"); my_writeSimple(ConnectFD,nv); } //cout<<"lego aqui"<<endl; //msj=read_protocol_D(buffer,nick,newNick); // my_write2(Users[nick],msj); } /* else if (buffer[4] == 'F'){ string nick,msj; //cout<<"lego aqui"<<endl; string newNick=findInMap(Users,ConnectFD); msj=read_protocol_D(buffer,nick,newNick); my_write2(Users[nick],msj); } else if (buffer[4] == 'E'){ //shutdown(ConnectFD, SHUT_RDWR); my_write2(ConnectFD,"E"); string key=findInMap(Users,ConnectFD); Users.erase(key); close(ConnectFD); break; }*/ } } //g++ client.cpp -o cli -std=c++11 -pthread int main(void){ struct sockaddr_in stSockAddr; int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); int n; string msg=""; if(-1 == SocketFD) { perror("can not create socket"); exit(EXIT_FAILURE); } memset(&stSockAddr, 0, sizeof(struct sockaddr_in)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(344); stSockAddr.sin_addr.s_addr = INADDR_ANY; if(-1 == bind(SocketFD,(const struct sockaddr *)&stSockAddr, sizeof(struct sockaddr_in))) { perror("error bind failed"); close(SocketFD); exit(EXIT_FAILURE); } if(-1 == listen(SocketFD, 10)) { perror("error listen failed"); close(SocketFD); exit(EXIT_FAILURE); } int cont=0; for(;;){ int ConnectFD = accept(SocketFD, NULL, NULL); t[cont]=thread(nuevoUsuario,ConnectFD); cont++; } for(int h=0;h<cont;h++) t[h].join(); //shutdown(ConnectFD, SHUT_RDWR); //close(ConnectFD); //close(SocketFD); return 0; }
3be1962c3e2deef7f59b4945cc72543bdab0c8b5
e465fec4e499f4253cb3c24c17ea04f99291cadc
/GameEngine/Src/Manager/Network.cpp
b6c2bdf3f5e1c099120c34f8d4643df66a72e810
[]
no_license
ola-tunde/R-Type
6eb645c41db7aa1dca9982093889f280baa9db2c
d0bc717ae98b227c8e73031dbb0026075db740b0
refs/heads/master
2022-04-15T10:09:08.345689
2019-12-01T22:29:58
2019-12-01T22:29:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,048
cpp
Network.cpp
/* ** EPITECH PROJECT, 2019 ** CPP_rtype_2019 ** File description: ** Manager/Network.cpp */ #include <iostream> #include <cstring> #include "Error.hpp" #include "Manager/Network.hpp" #include "Player.hpp" Manager::Network::Network() { } void Manager::Network::setSocket(std::shared_ptr<sf::UdpSocket> _socket) { this->socket = _socket; this->socket->setBlocking(false); } void Manager::Network::setIpTarget(const std::string &ipTarget) { this->ipTarget = ipTarget; } void Manager::Network::setPortTarget(unsigned short portTarget) { this->portTarget = portTarget; } const std::vector <Client> &Manager::Network::getClients() const { return this->clients; } EntityFactory &Manager::Network::getEntityFactory() { return this->entityFactory; } /** * @brief onPlayerJoin generate Player entity at the default position * and add it in the list * @param core * @param senderIp * @param senderPort */ void Manager::Network::onPlayerJoin(ACore &core, const sf::IpAddress &senderIp, unsigned short senderPort) { std::cout << "Network::onPlayerJoin" << std::endl; sf::Vector2f newClientPosition(-90, 0); std::size_t playerNbr = this->clients.size(); this->addNewClient(senderIp, senderPort); core.feedEntity( std::make_shared<Player>(core, newClientPosition, playerNbr)); } void Manager::Network::sendPacket(sf::Packet packet, sf::IpAddress ip, unsigned short port) { this->socket->send(packet, ip, port); } void Manager::Network::readSocket(ACore &core) { sf::Packet packet; sf::IpAddress sender; unsigned short senderPort; int opCode; int entityID; sf::Uint64 id; this->resetClientsKeyMap(); auto state = this->socket->receive(packet, sender, senderPort); if (state == sf::Socket::NotReady) return; while (state == sf::Socket::Done) { packet >> opCode; auto networkCode = static_cast<enum network::PacketType>(opCode); if (networkCode == network::PT_PLAYER_JOIN && this->clients.size() < 4) { std::cout << "RECEIVE PLAYER_JOIN: " << sender << ":" << senderPort << std::endl; this->onPlayerJoin(core, sender, senderPort); } if (networkCode == network::PT_PORT_REDIRECTION) { packet >> this->portTarget; std::cout << "RECEIVE PORT_REDIRECTION: " << this->portTarget << std::endl; sf::Packet answer; answer << network::PT_PLAYER_JOIN; this->sendPacket(answer, sender, this->portTarget); } if (networkCode == network::PT_ENTITY_CREATION) { packet >> entityID; std::cout << "RECEIVE ENTITY_CREATION: " << entityID << std::endl; core.feedEntity( this->entityFactory.buildEntity((enum EntityID) entityID, core, packet)); } if (networkCode == network::PT_ENTITY_UPDATE) { packet >> entityID; id = bswap_64(*((size_t *) packet.getData() + 1)); std::cout << "RECEIVE ENTITY_UPDATE: " << std::endl << "\t" << "entityID: " << entityID << std::endl << "\t" << "id: " << id << std::endl; // If you miss the CREATION event, recreate it AEntityPtr target = core.getEntityFromId(id); if (!target) { std::cout << "id: " << id << " not found so recreate it" << std::endl; core.feedEntity(this->entityFactory.buildEntity( (enum EntityID) entityID, core, packet)); } else { target->updateFromPacket(packet); } } if (networkCode == network::PT_ENTITY_DESTRUCTION) { packet >> entityID; packet >> id; std::cout << "RECEIVE ENTITY_DESTRUCTION: " << id << std::endl; core.addToDeletionQueue(id); } // We received an input from a client. if (networkCode == network::PT_INPUT) { int key; packet >> key; for (auto &it: this->clients) { if (sender == it.ip && senderPort == it.port && key < sf::Keyboard::KeyCount) { it.keyMap[key]++; } } } // Stream end, process should stop, although exit is the lazy way. if (networkCode == network::PT_STREAM_END) exit(0); state = this->socket->receive(packet, sender, senderPort); } } void Manager::Network::streamInput(std::shared_ptr <Action> actionManager) { auto pressedKey = actionManager->getKeyPressed(); if (!pressedKey.size()) return; std::cout << "Network::streamInput" << std::endl; for (const auto &keyCode : pressedKey) { sf::Packet packet; packet << network::PT_INPUT; packet << keyCode; std::cout << "\t" << "key: " << keyCode << std::endl; this->sendPacket(packet, this->ipTarget, this->portTarget); } } bool Manager::Network::isClientKeyPressed(std::size_t clientId, sf::Keyboard::Key key) { if (clientId >= this->clients.size()) return false; return this->clients[clientId].keyMap[key % sf::Keyboard::KeyCount] != 0; } void Manager::Network::execEntityAction(AEntityPtr entity, network::PacketType packetType) { std::cout << "Network::execEntityAction entity: " << entity->getEntityType() << " ; packetType " << packetType << std::endl; sf::Packet packet = entity->buildMyAsAPacket(packetType); for (auto &client : this->clients) this->socket->send(packet, client.ip, client.port); } void Manager::Network::endOfStream() { sf::Packet packet; packet << network::PT_STREAM_END; for (auto &it : this->clients) this->socket->send(packet, it.ip, it.port); } /** * @brief addNewClient check if the player isn't already playing and put a * well-initialize Client in the list * @param ip * @param port */ void Manager::Network::addNewClient(const sf::IpAddress &ip, unsigned short port) { Client newClient; for (const auto &value : this->getClients()) if (value.ip == ip && value.port == port) throw Error("Client from " + ip.toString() + " on port " + std::to_string(port) + " is already playing", __FILE__, __func__, __LINE__); newClient.ip = ip; newClient.port = port; for (size_t i = 0 ; i < sf::Keyboard::KeyCount ; i++) newClient.keyMap[i] = 0; this->clients.push_back(newClient); } void Manager::Network::resetClientsKeyMap() { for (auto &client : this->clients) std::memset(client.keyMap, 0, sizeof(client.keyMap)); }
301a9ffa9c21ae28a5ae792230e01ac1af4cf082
ee2cf8613bce6a4615245d21533628834f64f535
/benchmark/benchmarklocalclient.h
1dfcad0ddc71817b038dbca6c4067d1f0e3d5a57
[]
no_license
nemomobile-graveyard/mthemedaemon
7443bee0e2559982760cb6f88807db3da8c30e48
8de0b0f8888dbd1f77241309868106a2d2fbf65a
refs/heads/master
2020-05-16T21:49:43.375499
2013-07-08T10:44:35
2013-07-08T10:44:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
796
h
benchmarklocalclient.h
/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #ifndef BENCHMARKLOCALCLIENT_H #define BENCHMARKLOCALCLIENT_H #include <QObject> class BenchmarkLocalClient : public QObject { Q_OBJECT public: BenchmarkLocalClient(); signals: void finished(); public slots: void run(); }; #endif // BENCHMARKLOCALCLIENT_H
ae61d04b98bce52332c7842725ad109de269655f
db21b28ec9e64c33cf8f2a725d56cd8585720a91
/leetcode_1381.cpp
beede414596eadd06eb725677904d7976ae48310
[]
no_license
2018hsridhar/Leetcode_Solutions
afb6a88f2b1075af3f6339956e499f228cde0ba3
f6b356ff5393113d0a6cc29118e6ef6c45a4f0ee
refs/heads/master
2023-08-30T22:43:23.308370
2023-08-29T04:15:31
2023-08-29T04:15:31
78,995,027
4
0
null
null
null
null
UTF-8
C++
false
false
958
cpp
leetcode_1381.cpp
/* 1381. Design a Stack With Increment Operation URL = https://leetcode.com/problems/design-a-stack-with-increment-operation/ */ class CustomStack { private: std::vector<int> stk; int sp; int n; public: CustomStack(int maxSize) { // stk = vector<int>(maxSize,0); sp = 0; n = maxSize; stk.resize(maxSize,0); } void push(int x) { if(sp < n){ stk[sp++] = x; } } int pop() { if(sp <= 0){ return -1; } else { int res= stk[sp-1]; sp--; return res; } } void increment(int k, int val) { for(int a = 0; a < std::min(k,sp); a++){ stk[a] += val; } } }; /** * Your CustomStack object will be instantiated and called as such: * CustomStack* obj = new CustomStack(maxSize); * obj->push(x); * int param_2 = obj->pop(); * obj->increment(k,val); */
d514ad95dca4757c55fb27be65d1404c814d3c6a
4da5677dff2ede6954736b0cc0f11922be64f512
/GameEngineBase/src/Graphics/Layer/Layer3D.h
97dc70aaaf2a0e080f374f6fbf3f8662843efe37
[]
no_license
Mark-Diedericks/Game-Engine
7fe5377789b5e8b39e610506f6804527b6992caf
dd0b7f885b17d165f7b53f0093d3691b7d193acb
refs/heads/master
2021-01-05T15:27:57.780743
2018-04-01T11:02:58
2018-04-01T11:02:58
241,060,199
0
0
null
null
null
null
UTF-8
C++
false
false
738
h
Layer3D.h
#pragma once #include "Common.h" #include "Layer.h" #include "Graphics/Scene.h" #include "Graphics/Renderer/Renderer3D.h" #include "Graphics/Renderer/ForwardRenderer.h" namespace gebase { namespace graphics { class GE_API Layer3D : public Layer { protected: Scene* m_Scene; Renderer3D* m_Renderer; virtual bool OnResize(uint width, uint height) override; public: Layer3D(Scene* scene, Renderer3D* renderer = genew ForwardRenderer()); ~Layer3D(); virtual void Init(); virtual void OnInit(Renderer3D& renderer, Scene& scene); virtual void OnRender(Renderer3D& renderer); inline Scene* getScene() const { return m_Scene; } void OnUpdateInternal(const float delta) override; void OnRender() override; }; } }
d19a142a509173c27b16168d70c50463d29c9069
4e5bf0492ae2f328190b2ed1c3e2c72464bba08b
/module1.h
9ba66124711a4388e421a349790e1894a106ff36
[ "Apache-2.0" ]
permissive
HeyyyyyyG/SJTU-EE228
264aeaa2842e6c0f25d5f4c2875224b4380933c5
f9c37d13f7aa747357baf465db64228efa00799a
refs/heads/master
2020-06-09T21:14:39.799678
2019-06-24T13:18:23
2019-06-24T13:18:23
193,507,110
2
1
null
null
null
null
UTF-8
C++
false
false
802
h
module1.h
// // Created by hp on 2018/11/17. // #ifndef II_BSOFT_MODULE1_H #define II_BSOFT_MODULE1_H #include <iostream> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui.hpp> //#include <opencv/cxcore.h> #include <opencv2/imgproc/imgproc.hpp> #include "mouse_callback.h" #include "draw.h" using namespace std; using namespace cv; void testVideo() { VideoCapture camera(0); if (!camera.isOpened()) { cout << "Open camera failed\n"; return; } cout << "Open camera successfully\n"; Mat img; while (1) { camera >> img; imshow("module1", img); if (waitKey(5) == 13) break; } } #endif //II_BSOFT_MODULE1_H
d4fda5fbdc458eff9d307c39fd170e10e8fe883a
52404f13d6ab052ed1382d249707adddf1257baa
/Game2D/entity.h
62cd65cbd89915a897ed5ad131d4456efb862309
[]
no_license
dkssud421/galage-game
2a9624e9365b38ae233ed7e0c9f2ddb64ac0e99e
15edc7c5aecf2a48c409b36cf39fff7d2f4ecde1
refs/heads/master
2020-09-20T21:57:17.441618
2019-11-28T08:13:50
2019-11-28T08:13:50
215,313,698
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
h
entity.h
class entity { protected: short x, y; short l, r, t, b; bool tf = false; public: entity(short x, short y) { this->x = x; this->y = y; } short show_x(); short show_y(); short show_l(); short show_r(); short show_t(); short show_b(); bool drow(); void die(); virtual void move_x(short); virtual void move_y(short); ~entity() { x = 0; y = 0; l = 0; r = 0; t = 0; b = 0; tf = false; } }; class plane :public entity { private: short hp = 0; public: plane(short fx, short fy) :entity(fx, fy) { l = 0; t = 0; r = 88; b = 109; tf = true; hp = 3; } short show_hp(); void damege(); void move_x(short); void move_y(short); ~plane() { tf = false; hp = 0; x = 0; y = 0; } }; class bleat :public entity { private: public: bleat(short fx, short fy) :entity(fx, fy) { l = 0; t = 0; r = 30; b = 30; tf = false; } void move_bleat(); void bleat_shot(); void bleat_crach(); virtual void bmove_y(); ~bleat() { x = -70; y = -70; tf = false; } }; class bleat2 : public bleat { public: bleat2(short fx, short fy) :bleat(fx, fy) { l = 0; t = 0; r = 30; b = 30; tf = false; } void bmove_y(); ~bleat2() { x = -70; y = -70; tf = false; } }; class meteor :public entity { protected: short hp; public: meteor(short fx, short fy) :entity(fx, fy) { l = 0; t = 0; r = 70; b = 70; tf = true; hp = 0; } ~meteor() { x = 0; y = 0; tf = false; } virtual void move_meteor(); virtual void meteor_crach1(); virtual void meteor_crach2(); void lie_meteor(); }; class meteor1 :public meteor { public: meteor1(short fx, short fy) :meteor(fx, fy) { l = 0; t = 0; r = 70; b = 70; tf = false; hp = 1; } void move_meteor(); }; class meteor2 :public meteor { public: meteor2(short fx, short fy) :meteor(fx, fy) { l = 0; t = 0; r = 70; b = 70; tf = false; hp = 2; } void move_meteor(); }; class meteor3 :public meteor { public: meteor3(short fx, short fy) :meteor(fx, fy) { l = 0; t = 0; r = 70; b = 70; tf = false; hp = 3; } void move_meteor(); }; class meteor_boss :public meteor { public: meteor_boss(short fx, short fy) :meteor(fx, fy) { hp = 8; tf = false; } void move_meteor(); void meteor_true(); };
1d320843c964ebf1db58684c7bf7e1163d433545
9e280e9ad789f3ef6159faea66596195d07f8c64
/orchagent/crmorch.cpp
e7e89eac836281ea48438377c6f157c83f0bc1e7
[ "Apache-2.0" ]
permissive
barefootnetworks/sonic-swss
0069e26f8277420d0358ca4088660e53304fa18d
db12ef4b9f8b4116b34aab34c90dcc640136464e
refs/heads/bf-master
2023-01-05T20:08:48.763249
2023-01-03T16:16:14
2023-01-03T16:16:14
104,252,143
2
0
NOASSERTION
2018-11-23T13:57:52
2017-09-20T18:18:38
C++
UTF-8
C++
false
false
23,043
cpp
crmorch.cpp
#include <sstream> #include "crmorch.h" #include "converter.h" #include "timer.h" #define CRM_POLLING_INTERVAL "polling_interval" #define CRM_COUNTERS_TABLE_KEY "STATS" #define CRM_POLLING_INTERVAL_DEFAULT (5 * 60) #define CRM_THRESHOLD_TYPE_DEFAULT CrmThresholdType::CRM_PERCENTAGE #define CRM_THRESHOLD_LOW_DEFAULT 70 #define CRM_THRESHOLD_HIGH_DEFAULT 85 #define CRM_EXCEEDED_MSG_MAX 10 #define CRM_ACL_RESOURCE_COUNT 256 extern sai_object_id_t gSwitchId; extern sai_switch_api_t *sai_switch_api; extern sai_acl_api_t *sai_acl_api; using namespace std; const map<CrmResourceType, string> crmResTypeNameMap = { { CrmResourceType::CRM_IPV4_ROUTE, "IPV4_ROUTE" }, { CrmResourceType::CRM_IPV6_ROUTE, "IPV6_ROUTE" }, { CrmResourceType::CRM_IPV4_NEXTHOP, "IPV4_NEXTHOP" }, { CrmResourceType::CRM_IPV6_NEXTHOP, "IPV6_NEXTHOP" }, { CrmResourceType::CRM_IPV4_NEIGHBOR, "IPV4_NEIGHBOR" }, { CrmResourceType::CRM_IPV6_NEIGHBOR, "IPV6_Neighbor" }, { CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER, "NEXTHOP_GROUP_MEMBER" }, { CrmResourceType::CRM_NEXTHOP_GROUP, "NEXTHOP_GROUP" }, { CrmResourceType::CRM_ACL_TABLE, "ACL_TABLE" }, { CrmResourceType::CRM_ACL_GROUP, "ACL_GROUP" }, { CrmResourceType::CRM_ACL_ENTRY, "ACL_ENTRY" }, { CrmResourceType::CRM_ACL_COUNTER, "ACL_COUNTER" }, { CrmResourceType::CRM_FDB_ENTRY, "FDB_ENTRY" } }; const map<CrmResourceType, uint32_t> crmResSaiAvailAttrMap = { { CrmResourceType::CRM_IPV4_ROUTE, SAI_SWITCH_ATTR_AVAILABLE_IPV4_ROUTE_ENTRY }, { CrmResourceType::CRM_IPV6_ROUTE, SAI_SWITCH_ATTR_AVAILABLE_IPV6_ROUTE_ENTRY }, { CrmResourceType::CRM_IPV4_NEXTHOP, SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEXTHOP_ENTRY }, { CrmResourceType::CRM_IPV6_NEXTHOP, SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEXTHOP_ENTRY }, { CrmResourceType::CRM_IPV4_NEIGHBOR, SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEIGHBOR_ENTRY }, { CrmResourceType::CRM_IPV6_NEIGHBOR, SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEIGHBOR_ENTRY }, { CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER, SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_MEMBER_ENTRY }, { CrmResourceType::CRM_NEXTHOP_GROUP, SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_ENTRY }, { CrmResourceType::CRM_ACL_TABLE, SAI_SWITCH_ATTR_AVAILABLE_ACL_TABLE }, { CrmResourceType::CRM_ACL_GROUP, SAI_SWITCH_ATTR_AVAILABLE_ACL_TABLE_GROUP }, { CrmResourceType::CRM_ACL_ENTRY, SAI_ACL_TABLE_ATTR_AVAILABLE_ACL_ENTRY }, { CrmResourceType::CRM_ACL_COUNTER, SAI_ACL_TABLE_ATTR_AVAILABLE_ACL_COUNTER }, { CrmResourceType::CRM_FDB_ENTRY, SAI_SWITCH_ATTR_AVAILABLE_FDB_ENTRY } }; const map<string, CrmResourceType> crmThreshTypeResMap = { { "ipv4_route_threshold_type", CrmResourceType::CRM_IPV4_ROUTE }, { "ipv6_route_threshold_type", CrmResourceType::CRM_IPV6_ROUTE }, { "ipv4_nexthop_threshold_type", CrmResourceType::CRM_IPV4_NEXTHOP }, { "ipv6_nexthop_threshold_type", CrmResourceType::CRM_IPV6_NEXTHOP }, { "ipv4_neighbor_threshold_type", CrmResourceType::CRM_IPV4_NEIGHBOR }, { "ipv6_neighbor_threshold_type", CrmResourceType::CRM_IPV6_NEIGHBOR }, { "nexthop_group_member_threshold_type", CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER }, { "nexthop_group_threshold_type", CrmResourceType::CRM_NEXTHOP_GROUP }, { "acl_table_threshold_type", CrmResourceType::CRM_ACL_TABLE }, { "acl_group_threshold_type", CrmResourceType::CRM_ACL_GROUP }, { "acl_entry_threshold_type", CrmResourceType::CRM_ACL_ENTRY }, { "acl_counter_threshold_type", CrmResourceType::CRM_ACL_COUNTER }, { "fdb_entry_threshold_type", CrmResourceType::CRM_FDB_ENTRY } }; const map<string, CrmResourceType> crmThreshLowResMap = { {"ipv4_route_low_threshold", CrmResourceType::CRM_IPV4_ROUTE }, {"ipv6_route_low_threshold", CrmResourceType::CRM_IPV6_ROUTE }, {"ipv4_nexthop_low_threshold", CrmResourceType::CRM_IPV4_NEXTHOP }, {"ipv6_nexthop_low_threshold", CrmResourceType::CRM_IPV6_NEXTHOP }, {"ipv4_neighbor_low_threshold", CrmResourceType::CRM_IPV4_NEIGHBOR }, {"ipv6_neighbor_low_threshold", CrmResourceType::CRM_IPV6_NEIGHBOR }, {"nexthop_group_member_low_threshold", CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER }, {"nexthop_group_low_threshold", CrmResourceType::CRM_NEXTHOP_GROUP }, {"acl_table_low_threshold", CrmResourceType::CRM_ACL_TABLE }, {"acl_group_low_threshold", CrmResourceType::CRM_ACL_GROUP }, {"acl_entry_low_threshold", CrmResourceType::CRM_ACL_ENTRY }, {"acl_counter_low_threshold", CrmResourceType::CRM_ACL_COUNTER }, {"fdb_entry_low_threshold", CrmResourceType::CRM_FDB_ENTRY }, }; const map<string, CrmResourceType> crmThreshHighResMap = { {"ipv4_route_high_threshold", CrmResourceType::CRM_IPV4_ROUTE }, {"ipv6_route_high_threshold", CrmResourceType::CRM_IPV6_ROUTE }, {"ipv4_nexthop_high_threshold", CrmResourceType::CRM_IPV4_NEXTHOP }, {"ipv6_nexthop_high_threshold", CrmResourceType::CRM_IPV6_NEXTHOP }, {"ipv4_neighbor_high_threshold", CrmResourceType::CRM_IPV4_NEIGHBOR }, {"ipv6_neighbor_high_threshold", CrmResourceType::CRM_IPV6_NEIGHBOR }, {"nexthop_group_member_high_threshold", CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER }, {"nexthop_group_high_threshold", CrmResourceType::CRM_NEXTHOP_GROUP }, {"acl_table_high_threshold", CrmResourceType::CRM_ACL_TABLE }, {"acl_group_high_threshold", CrmResourceType::CRM_ACL_GROUP }, {"acl_entry_high_threshold", CrmResourceType::CRM_ACL_ENTRY }, {"acl_counter_high_threshold", CrmResourceType::CRM_ACL_COUNTER }, {"fdb_entry_high_threshold", CrmResourceType::CRM_FDB_ENTRY } }; const map<string, CrmThresholdType> crmThreshTypeMap = { { "percentage", CrmThresholdType::CRM_PERCENTAGE }, { "used", CrmThresholdType::CRM_USED }, { "free", CrmThresholdType::CRM_FREE } }; const map<string, CrmResourceType> crmAvailCntsTableMap = { { "crm_stats_ipv4_route_available", CrmResourceType::CRM_IPV4_ROUTE }, { "crm_stats_ipv6_route_available", CrmResourceType::CRM_IPV6_ROUTE }, { "crm_stats_ipv4_nexthop_available", CrmResourceType::CRM_IPV4_NEXTHOP }, { "crm_stats_ipv6_nexthop_available", CrmResourceType::CRM_IPV6_NEXTHOP }, { "crm_stats_ipv4_neighbor_available", CrmResourceType::CRM_IPV4_NEIGHBOR }, { "crm_stats_ipv6_neighbor_available", CrmResourceType::CRM_IPV6_NEIGHBOR }, { "crm_stats_nexthop_group_member_available", CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER }, { "crm_stats_nexthop_group_available", CrmResourceType::CRM_NEXTHOP_GROUP }, { "crm_stats_acl_table_available", CrmResourceType::CRM_ACL_TABLE }, { "crm_stats_acl_group_available", CrmResourceType::CRM_ACL_GROUP }, { "crm_stats_acl_entry_available", CrmResourceType::CRM_ACL_ENTRY }, { "crm_stats_acl_counter_available", CrmResourceType::CRM_ACL_COUNTER }, { "crm_stats_fdb_entry_available", CrmResourceType::CRM_FDB_ENTRY } }; const map<string, CrmResourceType> crmUsedCntsTableMap = { { "crm_stats_ipv4_route_used", CrmResourceType::CRM_IPV4_ROUTE }, { "crm_stats_ipv6_route_used", CrmResourceType::CRM_IPV6_ROUTE }, { "crm_stats_ipv4_nexthop_used", CrmResourceType::CRM_IPV4_NEXTHOP }, { "crm_stats_ipv6_nexthop_used", CrmResourceType::CRM_IPV6_NEXTHOP }, { "crm_stats_ipv4_neighbor_used", CrmResourceType::CRM_IPV4_NEIGHBOR }, { "crm_stats_ipv6_neighbor_used", CrmResourceType::CRM_IPV6_NEIGHBOR }, { "crm_stats_nexthop_group_member_used", CrmResourceType::CRM_NEXTHOP_GROUP_MEMBER }, { "crm_stats_nexthop_group_used", CrmResourceType::CRM_NEXTHOP_GROUP }, { "crm_stats_acl_table_used", CrmResourceType::CRM_ACL_TABLE }, { "crm_stats_acl_group_used", CrmResourceType::CRM_ACL_GROUP }, { "crm_stats_acl_entry_used", CrmResourceType::CRM_ACL_ENTRY }, { "crm_stats_acl_counter_used", CrmResourceType::CRM_ACL_COUNTER }, { "crm_stats_fdb_entry_used", CrmResourceType::CRM_FDB_ENTRY } }; CrmOrch::CrmOrch(DBConnector *db, string tableName): Orch(db, tableName), m_countersDb(new DBConnector(COUNTERS_DB, DBConnector::DEFAULT_UNIXSOCKET, 0)), m_countersCrmTable(new Table(m_countersDb.get(), COUNTERS_CRM_TABLE)), m_timer(new SelectableTimer(timespec { .tv_sec = CRM_POLLING_INTERVAL_DEFAULT, .tv_nsec = 0 })) { SWSS_LOG_ENTER(); m_pollingInterval = chrono::seconds(CRM_POLLING_INTERVAL_DEFAULT); for (const auto &res : crmResTypeNameMap) { m_resourcesMap.emplace(res.first, CrmResourceEntry(res.second, CRM_THRESHOLD_TYPE_DEFAULT, CRM_THRESHOLD_LOW_DEFAULT, CRM_THRESHOLD_HIGH_DEFAULT)); } auto executor = new ExecutableTimer(m_timer.get(), this); Orch::addExecutor("CRM_COUNTERS_POLL", executor); m_timer->start(); } CrmOrch::CrmResourceEntry::CrmResourceEntry(string name, CrmThresholdType thresholdType, uint32_t lowThreshold, uint32_t highThreshold): name(name), thresholdType(thresholdType), lowThreshold(lowThreshold), highThreshold(highThreshold) { if ((thresholdType == CrmThresholdType::CRM_PERCENTAGE) && ((lowThreshold > 100) || (highThreshold > 100))) { throw runtime_error("CRM percentage threshold value must be <= 100%%"); } if (!(lowThreshold < highThreshold)) { throw runtime_error("CRM low threshold must be less then high threshold"); } } void CrmOrch::doTask(Consumer &consumer) { SWSS_LOG_ENTER(); string table_name = consumer.getTableName(); if (table_name != CFG_CRM_TABLE_NAME) { SWSS_LOG_ERROR("Invalid table %s", table_name.c_str()); } auto it = consumer.m_toSync.begin(); while (it != consumer.m_toSync.end()) { KeyOpFieldsValuesTuple t = it->second; string key = kfvKey(t); string op = kfvOp(t); if (op == SET_COMMAND) { handleSetCommand(key, kfvFieldsValues(t)); } else if (op == DEL_COMMAND) { SWSS_LOG_ERROR("Unsupported operation type %s\n", op.c_str()); it = consumer.m_toSync.erase(it); } else { SWSS_LOG_ERROR("Unknown operation type %s\n", op.c_str()); } consumer.m_toSync.erase(it++); } } void CrmOrch::handleSetCommand(const string& key, const vector<FieldValueTuple>& data) { SWSS_LOG_ENTER(); for (auto i : data) { const auto &field = fvField(i); const auto &value = fvValue(i); try { if (field == CRM_POLLING_INTERVAL) { m_pollingInterval = chrono::seconds(to_uint<uint32_t>(value)); auto interv = timespec { .tv_sec = m_pollingInterval.count(), .tv_nsec = 0 }; m_timer->setInterval(interv); m_timer->reset(); } else if (crmThreshTypeResMap.find(field) != crmThreshTypeResMap.end()) { auto resourceType = crmThreshTypeResMap.at(field); auto thresholdType = crmThreshTypeMap.at(value); m_resourcesMap.at(resourceType).thresholdType = thresholdType; } else if (crmThreshLowResMap.find(field) != crmThreshLowResMap.end()) { auto resourceType = crmThreshLowResMap.at(field); auto thresholdValue = to_uint<uint32_t>(value); m_resourcesMap.at(resourceType).lowThreshold = thresholdValue; } else if (crmThreshHighResMap.find(field) != crmThreshHighResMap.end()) { auto resourceType = crmThreshHighResMap.at(field); auto thresholdValue = to_uint<uint32_t>(value); m_resourcesMap.at(resourceType).highThreshold = thresholdValue; } else { SWSS_LOG_ERROR("Failed to parse CRM %s configuration. Unknown attribute %s.\n", key.c_str(), field.c_str()); return; } } catch (const exception& e) { SWSS_LOG_ERROR("Failed to parse CRM %s attribute %s error: %s.", key.c_str(), field.c_str(), e.what()); return; } catch (...) { SWSS_LOG_ERROR("Failed to parse CRM %s attribute %s. Unknown error has been occurred", key.c_str(), field.c_str()); return; } } } void CrmOrch::incCrmResUsedCounter(CrmResourceType resource) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[CRM_COUNTERS_TABLE_KEY].usedCounter++; } catch (...) { SWSS_LOG_ERROR("Failed to increment \"used\" counter for the %s CRM resource.", crmResTypeNameMap.at(resource).c_str()); return; } } void CrmOrch::decCrmResUsedCounter(CrmResourceType resource) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[CRM_COUNTERS_TABLE_KEY].usedCounter--; } catch (...) { SWSS_LOG_ERROR("Failed to decrement \"used\" counter for the %s CRM resource.", crmResTypeNameMap.at(resource).c_str()); return; } } void CrmOrch::incCrmAclUsedCounter(CrmResourceType resource, sai_acl_stage_t stage, sai_acl_bind_point_type_t point) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[getCrmAclKey(stage, point)].usedCounter++; } catch (...) { SWSS_LOG_ERROR("Failed to increment \"used\" counter for the %s CRM resource.", crmResTypeNameMap.at(resource).c_str()); return; } } void CrmOrch::decCrmAclUsedCounter(CrmResourceType resource, sai_acl_stage_t stage, sai_acl_bind_point_type_t point, sai_object_id_t oid) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[getCrmAclKey(stage, point)].usedCounter--; // Remove ACL table related counters if (resource == CrmResourceType::CRM_ACL_TABLE) { auto & cntMap = m_resourcesMap.at(CrmResourceType::CRM_ACL_TABLE).countersMap; for (auto it = cntMap.begin(); it != cntMap.end();) { if (it->second.id == oid) { it = cntMap.erase(it); } else { ++it; } } } } catch (...) { SWSS_LOG_ERROR("Failed to decrement \"used\" counter for the %s CRM resource.", crmResTypeNameMap.at(resource).c_str()); return; } } void CrmOrch::incCrmAclTableUsedCounter(CrmResourceType resource, sai_object_id_t tableId) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[getCrmAclTableKey(tableId)].usedCounter++; m_resourcesMap.at(resource).countersMap[getCrmAclTableKey(tableId)].id = tableId; } catch (...) { SWSS_LOG_ERROR("Failed to increment \"used\" counter for the %s CRM resource (tableId:%lx).", crmResTypeNameMap.at(resource).c_str(), tableId); return; } } void CrmOrch::decCrmAclTableUsedCounter(CrmResourceType resource, sai_object_id_t tableId) { SWSS_LOG_ENTER(); try { m_resourcesMap.at(resource).countersMap[getCrmAclTableKey(tableId)].usedCounter--; } catch (...) { SWSS_LOG_ERROR("Failed to decrement \"used\" counter for the %s CRM resource (tableId:%lx).", crmResTypeNameMap.at(resource).c_str(), tableId); return; } } void CrmOrch::doTask(SelectableTimer &timer) { SWSS_LOG_ENTER(); getResAvailableCounters(); updateCrmCountersTable(); checkCrmThresholds(); auto interv = timespec { .tv_sec = m_pollingInterval.count(), .tv_nsec = 0 }; timer.setInterval(interv); timer.reset(); } void CrmOrch::getResAvailableCounters() { SWSS_LOG_ENTER(); for (auto &res : m_resourcesMap) { sai_attribute_t attr; attr.id = crmResSaiAvailAttrMap.at(res.first); switch (attr.id) { case SAI_SWITCH_ATTR_AVAILABLE_IPV4_ROUTE_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_IPV6_ROUTE_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEXTHOP_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEXTHOP_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_IPV4_NEIGHBOR_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_IPV6_NEIGHBOR_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_MEMBER_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_NEXT_HOP_GROUP_ENTRY: case SAI_SWITCH_ATTR_AVAILABLE_FDB_ENTRY: { sai_status_t status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to get switch attribute %u , rv:%d", attr.id, status); break; } res.second.countersMap[CRM_COUNTERS_TABLE_KEY].availableCounter = attr.value.u32; break; } case SAI_SWITCH_ATTR_AVAILABLE_ACL_TABLE: case SAI_SWITCH_ATTR_AVAILABLE_ACL_TABLE_GROUP: { vector<sai_acl_resource_t> resources(CRM_ACL_RESOURCE_COUNT); attr.value.aclresource.count = CRM_ACL_RESOURCE_COUNT; attr.value.aclresource.list = resources.data(); sai_status_t status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr); if (status == SAI_STATUS_BUFFER_OVERFLOW) { resources.resize(attr.value.aclresource.count); attr.value.aclresource.list = resources.data(); status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr); } if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to get switch attribute %u , rv:%d", attr.id, status); break; } for (uint32_t i = 0; i < attr.value.aclresource.count; i++) { string key = getCrmAclKey(attr.value.aclresource.list[i].stage, attr.value.aclresource.list[i].bind_point); res.second.countersMap[key].availableCounter = attr.value.aclresource.list[i].avail_num; } break; } case SAI_ACL_TABLE_ATTR_AVAILABLE_ACL_ENTRY: case SAI_ACL_TABLE_ATTR_AVAILABLE_ACL_COUNTER: { for (auto &cnt : res.second.countersMap) { sai_status_t status = sai_acl_api->get_acl_table_attribute(cnt.second.id, 1, &attr); if (status != SAI_STATUS_SUCCESS) { SWSS_LOG_ERROR("Failed to get ACL table attribute %u , rv:%d", attr.id, status); break; } cnt.second.availableCounter = attr.value.u32; } break; } default: SWSS_LOG_ERROR("Failed to get CRM attribute %u. Unknown attribute.\n", attr.id); return; } } } void CrmOrch::updateCrmCountersTable() { SWSS_LOG_ENTER(); // Update CRM used counters in COUNTERS_DB for (const auto &i : crmUsedCntsTableMap) { for (const auto &cnt : m_resourcesMap.at(i.second).countersMap) { FieldValueTuple attr(i.first, to_string(cnt.second.usedCounter)); vector<FieldValueTuple> attrs = { attr }; m_countersCrmTable->set(cnt.first, attrs); } } // Update CRM available counters in COUNTERS_DB for (const auto &i : crmAvailCntsTableMap) { for (const auto &cnt : m_resourcesMap.at(i.second).countersMap) { FieldValueTuple attr(i.first, to_string(cnt.second.availableCounter)); vector<FieldValueTuple> attrs = { attr }; m_countersCrmTable->set(cnt.first, attrs); } } } void CrmOrch::checkCrmThresholds() { SWSS_LOG_ENTER(); for (auto &i : m_resourcesMap) { auto &res = i.second; for (const auto &j : i.second.countersMap) { auto &cnt = j.second; uint64_t utilization = 0; uint32_t percentageUtil = 0; string threshType = ""; if (cnt.usedCounter != 0) { percentageUtil = (cnt.usedCounter * 100) / (cnt.usedCounter + cnt.availableCounter); } switch (res.thresholdType) { case CrmThresholdType::CRM_PERCENTAGE: utilization = percentageUtil; threshType = "TH_PERCENTAGE"; break; case CrmThresholdType::CRM_USED: utilization = cnt.usedCounter; threshType = "TH_USED"; break; case CrmThresholdType::CRM_FREE: utilization = cnt.availableCounter; threshType = "TH_FREE"; break; default: throw runtime_error("Unknown threshold type for CRM resource"); } if ((utilization >= res.highThreshold) && (res.exceededLogCounter < CRM_EXCEEDED_MSG_MAX)) { SWSS_LOG_WARN("%s THRESHOLD_EXCEEDED for %s %u%% Used count %u free count %u", res.name.c_str(), threshType.c_str(), percentageUtil, cnt.usedCounter, cnt.availableCounter); res.exceededLogCounter++; } else if ((utilization <= res.lowThreshold) && (res.exceededLogCounter > 0)) { SWSS_LOG_WARN("%s THRESHOLD_CLEAR for %s %u%% Used count %u free count %u", res.name.c_str(), threshType.c_str(), percentageUtil, cnt.usedCounter, cnt.availableCounter); res.exceededLogCounter = 0; } } // end of counters loop } // end of resources loop } string CrmOrch::getCrmAclKey(sai_acl_stage_t stage, sai_acl_bind_point_type_t bindPoint) { string key = "ACL_STATS"; switch(stage) { case SAI_ACL_STAGE_INGRESS: key += ":INGRESS"; break; case SAI_ACL_STAGE_EGRESS: key += ":EGRESS"; break; default: return ""; } switch(bindPoint) { case SAI_ACL_BIND_POINT_TYPE_PORT: key += ":PORT"; break; case SAI_ACL_BIND_POINT_TYPE_LAG: key += ":LAG"; break; case SAI_ACL_BIND_POINT_TYPE_VLAN: key += ":VLAN"; break; case SAI_ACL_BIND_POINT_TYPE_ROUTER_INTERFACE: key += ":RIF"; break; case SAI_ACL_BIND_POINT_TYPE_SWITCH: key += ":SWITCH"; break; default: return ""; } return key; } string CrmOrch::getCrmAclTableKey(sai_object_id_t id) { std::stringstream ss; ss << "ACL_TABLE_STATS:" << "0x" << std::hex << id; return ss.str(); }
3debf0ea1359ff21b025c4e23df57db26dcc6e8c
0ab12d582e94d4d9390751beb6c94b6821c7d95c
/virtual.cpp
bf4ae64fcb5ab82648233f981820c6c0a88a77a1
[]
no_license
coding520/test
09ef147a8c7100bb0280726cfb3b8edb8ed149da
37f1dbc8913d40ada3883df142414083b9ddbd35
refs/heads/master
2020-08-21T14:38:10.507441
2019-10-20T01:34:01
2019-10-20T01:34:01
216,181,287
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
virtual.cpp
#include<iostream> using namespace std; class Animal { public: virtual void speak() { cout << "animal language!" << endl; } }; class Cat :public Animal { public: void speak() { cout << "cat miaomiao" << endl; } }; int main() { Cat c; Animal* p = &c; p->speak(); c.Animal::speak(); Animal* a = new Cat; a->speak(); c.speak(); Animal animal; animal.speak(); return 0; }
79f6e45e83b84405b38b69f1f02324291778a430
a3eab08a8ecb69fb2ada99ec26a359825dc1a1a5
/05. Scope/localScope.cpp
b06442e4c76214a97d4f3cbba60d011e9704e51b
[]
no_license
zonayedpca/learnCpp
09c2b0c2bdcfb8a5af5ff2f5c6747d43fe0f2f27
ac28cb0559a182ef97d16a418b9317863880e358
refs/heads/master
2020-04-24T15:02:22.253861
2019-04-03T12:38:39
2019-04-03T12:38:39
172,049,237
1
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
localScope.cpp
#include <iostream> void aFunc(int x) { std::cout << "Function paramaters and variables are local scoped" << '\n'; std::cout << "Paramaters can be accessed here: " << x << '\n'; int y = 20; std::cout << "Variables defined here also can be accessed from here: " << y << '\n'; } int main() { aFunc(10); return 0; }
32448e93458ed006a080a7e07873b130774465a1
426aee581a4e4285471dfc28dde22a7ecb4ab80c
/Source/MessageProtocols/Private/Threads/ProtocolsReceiverThread.h
a8ba124adb2d350f2036b54c522783b0ca9c508e
[ "MIT" ]
permissive
jeslaspravin/MessageProtocols
e1b42e94a6789fe6d49e0564c95770dfbffa13d9
6d26092640fdf977a2e7d7b1df16e4fb83f2fc4a
refs/heads/master
2022-02-13T01:42:23.216235
2019-07-18T14:36:37
2019-07-18T14:36:37
195,392,723
1
0
null
null
null
null
UTF-8
C++
false
false
325
h
ProtocolsReceiverThread.h
#pragma once #include "Threads/ProtocolsThreadBase.h" class FProtocolsReceiverThread : public FProtocolsThreadBase { protected: virtual void processConnections(const TArray<UWeakConnectionsPtr>& connectionsToProcess) override; public: FProtocolsReceiverThread(FString tName) :FProtocolsThreadBase(tName) { } };
8459951ac9f5966f9e4c98a7ed5b237eaa5874a9
6e8d1bc47b1d293d2cb0ffe917b2e4afdb676c50
/TestCode/TestCode/Core/Math/TCVector2f.h
eab7941b915dcdc3b6cc8ef0444376af1cdde46c
[]
no_license
wlgys8/TestCode
03b4184c9327230e5da903a5b6c3bef77f8920e0
5ce57346bd40fcd41ad6b020709a75994bc8b67a
refs/heads/master
2021-01-01T19:07:42.928205
2013-04-13T15:40:31
2013-04-13T15:40:31
8,627,580
1
0
null
2013-04-12T13:30:40
2013-03-07T13:12:55
C
UTF-8
C++
false
false
2,135
h
TCVector2f.h
#ifndef __TC_VECTOR2_H__ #define __TC_VECTOR2_H__ #include "TCCommon.h" NS_TC_BEGIN class Vector2{ public: int x; int y; Vector2():x(0),y(0){ } Vector2(int x,int y){ this->x=x; this->y=y; } const Vector2 operator+(const Vector2& v2) const{ return Vector2(x+v2.x,y+v2.y); } const Vector2 operator-(const Vector2& v2) const{ return Vector2(x-v2.x,y-v2.y); } const Vector2 operator*(const Vector2& v2) const { return Vector2(x*v2.x,y*v2.y); } const Vector2 operator*(const int& cons) const{ return Vector2(x*cons,y*cons); } void operator+=(const Vector2& v){ x+=v.x; y+=v.y; } void operator-=(const Vector2& v){ x-=v.x; y-=v.y; } void operator*=(const Vector2& v){ x*=v.x; y*=v.y; } void operator*=(const int& cons){ x*=cons; y*=cons; } friend bool operator==(const Vector2& v1,const Vector2& v2){ return v1.x==v2.x&&v1.y==v2.y; } friend bool operator!=(const Vector2& v1,const Vector2& v2){ return !(v1==v2); } public: static Vector2 zero(){ return Vector2(0,0); } static Vector2 one(){ return Vector2(1,1); } }; class Vector2f{ public: float x; float y; Vector2f():x(0),y(0){ } Vector2f(float x,float y){ this->x=x; this->y=y; } const Vector2f operator+(const Vector2f& v2) const{ return Vector2f(x+v2.x,y+v2.y); } const Vector2f operator-(const Vector2f& v2) const{ return Vector2f(x-v2.x,y-v2.y); } const Vector2f operator*(const Vector2f& v2) const { return Vector2f(x*v2.x,y*v2.y); } const Vector2f operator*(const float& cons) const{ return Vector2f(x*cons,y*cons); } void operator+=(const Vector2f& v){ x+=v.x; y+=v.y; } void operator-=(const Vector2f& v){ x-=v.x; y-=v.y; } void operator*=(const Vector2f& v){ x*=v.x; y*=v.y; } void operator*=(const float& cons){ x*=cons; y*=cons; } friend bool operator==(const Vector2f& v1,const Vector2f& v2){ return v1.x==v2.x&&v1.y==v2.y; } friend bool operator!=(const Vector2f& v1,const Vector2f& v2){ return !(v1==v2); } public: static Vector2f zero(){ return Vector2f(0,0); } static Vector2f one(){ return Vector2f(1,1); } }; NS_TC_END #endif
520356f1ab254f8f18ab48a09cd4db2b6826948b
7a876d5e6d055491d06b65e3f8ffb7626e0aef99
/2020-week1/c++/2020-week1_14.cpp
1e9ed75a4518daeba59b45c2b00618326184c4e3
[]
no_license
sewonkimm/AlgorithmStudy
3f172c453b9bf149dd89bdb2678bca17a5534c95
1478b696ea7b9bd2b63f930817a656976af00ae5
refs/heads/master
2021-07-17T19:42:46.915886
2020-09-02T06:59:09
2020-09-02T06:59:09
205,660,994
6
2
null
null
null
null
UTF-8
C++
false
false
1,795
cpp
2020-week1_14.cpp
#include <iostream> #include <vector> using namespace std; // Max heap vector<int> heap(1, 0); void insertheap(int num) { heap.push_back(num); int i = heap.size() - 1; while (i != 1) { if (heap[i] > heap[i / 2]) { int temp = heap[i]; heap[i] = heap[i / 2]; heap[i / 2] = temp; i /= 2; } else { break; } } } void deleteheap() { if (heap.size() == 2) { heap.erase(heap.begin() + 1, heap.begin() + 2); } else { heap[1] = heap[heap.size() - 1]; heap.erase(heap.begin() + heap.size() - 1, heap.begin() + heap.size()); } int parent = 1; int child = 2; int temp = heap[parent]; while (child < heap.size()) { if (heap[child] < heap[child + 1]) { child++; } if (temp >= heap[child]) { break; } else { heap[parent] = heap[child]; heap[child] = temp; parent = child; child = parent * 2; } temp = heap[parent]; } } int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { int x; scanf("%d", &x); if (x == 0) { // 루트 값 출력 후 삭제 if (heap.size() > 1) { printf("%d\n", heap[1]); deleteheap(); } else { printf("%d\n", 0); } } else { // 삽입 insertheap(x); } } return 0; }
337602e2103d297d68ba07c6f0c17ce1d7400be9
2e4898fc1dc5982bb004fd19bd2848d60e3e3611
/src/display/Menu.cpp
d9310f210d7df8b887200e700dd28203084b4f3d
[]
no_license
NotHawthorne/Hunters-Online-Client
174deeb00a289c6c10366c6acf7049b3eedde6dd
8d4be8706875732e5f7b9aded057f58b42d9dabb
refs/heads/master
2022-06-22T08:59:07.040474
2020-05-06T07:10:42
2020-05-06T07:10:42
260,990,622
0
0
null
null
null
null
UTF-8
C++
false
false
3,541
cpp
Menu.cpp
#include "../../includes/display.h" Menu::Menu(WINDOW *sub) { win = sub; } Menu::Menu() { win = NULL; } Menu::~Menu() { } static char *unpad(char *s) { int last = 0; for (int i = 0; s[i]; i++) if (s[i] != ' ' && (s[i] + 1)) last = i + 1; if (last > 0) s[last] = 0; return (s); } int Menu::handleInput(int c) { switch (c) { case KEY_DOWN: menu_driver(menu, REQ_DOWN_ITEM); break ; case KEY_UP: menu_driver(menu, REQ_UP_ITEM); break ; default: break ; } return (1); } int LoginMenu::handleInput(int c) { std::hash<std::string> hasher; switch (c) { case KEY_DOWN: menu_driver(menu, REQ_DOWN_ITEM); break ; case KEY_UP: menu_driver(menu, REQ_UP_ITEM); break ; case KEY_F(1): return (0); break ; case KEY_BACKSPACE: form_driver(form, REQ_DEL_CHAR); if (pass_field && pass_str.size()) pass_str.erase(pass_str.size() - 1); break ; case '\t': form_driver(form, REQ_VALIDATION); form_driver(form, pass_field ? REQ_PREV_FIELD : REQ_NEXT_FIELD); pass_field = !pass_field; set_field_back(input[(int)pass_field], A_STANDOUT); set_field_back(input[(int)!pass_field], A_NORMAL); break ; case 10: form_driver(form, REQ_VALIDATION); if ((pass_field = !pass_field)) { form_driver(form, REQ_NEXT_FIELD); set_field_back(input[0], A_NORMAL); set_field_back(input[1], A_STANDOUT); } else { user_str = std::string(unpad(field_buffer(input[0], 0))); pass_str = std::to_string(hasher(pass_str)); return (2); } // login break ; case 127: form_driver(form, REQ_DEL_CHAR); if (pass_field && pass_str.size()) pass_str.erase(pass_str.size() - 1); break ; default: form_driver(form, pass_field ? '*' : c); if (pass_field) pass_str += c; break ; } return (1); } LoginMenu::LoginMenu(WINDOW *sub) { //containers for what seems to be scaling a form based //on a subwindow int r, c; //set up some class variables type = LOGIN; win = sub; pass_field = false; itemcount = 3; // create the fields to go in to the form input[0] = new_field(1, (COLS / 2) - 2, 3, 1, 0, 0); input[1] = new_field(1, (COLS / 2) - 2, 5, 1, 0, 0); input[2] = NULL; //set flags set_field_opts(input[0], O_VISIBLE | O_PUBLIC | O_EDIT | O_ACTIVE); set_field_opts(input[1], O_VISIBLE | O_EDIT | O_ACTIVE | O_PUBLIC); //create form form = new_form(input); scale_form(form, &r, &c); set_form_win(form, sub); set_form_sub(form, (usrbox = derwin(sub, r, c, 1, 1))); keypad(usrbox, true); box(usrbox, 0, 0); set_field_back(input[0], A_STANDOUT); post_form(form); //display some information about the forms mvwprintw(sub, 3, 2, "username:\n"); mvwprintw(sub, 5, 2, "password:\n"); mvwprintw(sub, 1, 2, notification_strings[WELCOME_MSG]); refresh(); //create the menu item array menu_items = new ITEM*[4]; menu_items[0] = new_item(menu_item_strings[0], ""); menu_items[1] = new_item(menu_item_strings[1], ""); menu_items[2] = new_item(menu_item_strings[2], ""); menu_items[3] = NULL; //create and style the menu menu = new_menu(menu_items); set_menu_win(menu, sub); set_menu_sub(menu, derwin(sub, 3, 15, 8, 1)); set_menu_mark(menu, ">"); post_menu(menu); //final refresh wrefresh(usrbox); wrefresh(sub); } LoginMenu::~LoginMenu() { unpost_form(form); free_form(form); free_field(input[0]); free_field(input[1]); for (int i = 0; i != itemcount; i++) free_item(menu_items[i]); free_menu(menu); } void LoginMenu::update() { wrefresh(win); wrefresh(usrbox); }
38bfddb21cb25229ca8f3e1d3f8d1d7caa6fa08f
64e618c56faece8b935ca0592ab96a37c94319aa
/src/core/impl/parser/parser.h
3298da0e9d4f0d3e99b57edfbb07dabfa3bd2fe8
[ "Apache-2.0" ]
permissive
dave-msk/CppND-Capstone-Calc
fb294400ee7e795ea6b6e47613ed4ef6ed53e0c0
a2f07c4c4ccecc7ecb326f5830155c49f06282e1
refs/heads/master
2020-06-29T13:09:12.037694
2019-08-24T18:53:47
2019-08-24T18:53:47
200,546,189
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
h
parser.h
/* Copyright 2019 Siu-Kei Muk (David). 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. ==============================================================================*/ #ifndef CPPND_CAPSTONE_CALC_CORE_IMPL_PARSER_PARSER_H_ #define CPPND_CAPSTONE_CALC_CORE_IMPL_PARSER_PARSER_H_ #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <variant> #include "core/expr.h" #include "core/fsm/graph.h" #include "core/impl/nodes/node.h" #include "core/lang/symbols.h" #include "core/lang/syntax.h" namespace calc { namespace impl { namespace parser { class GrammarGraphParser : public Parser { public: explicit GrammarGraphParser( std::unique_ptr< ::calc::fsm::Graph<::calc::lang::SyntaxType>> grammar_graph) : grammar_graph_(std::move(grammar_graph)) {} void AddSymbol(std::string symbol, ::calc::lang::SyntaxType syntax_type, ::calc::lang::SymbolType symbol_type); std::unique_ptr<Expression> Parse(const std::vector<std::string>&); private: struct SymbolMeta { SymbolMeta(::calc::lang::SyntaxType syntax_type, ::calc::lang::SymbolType symbol_type) : syntax_type(syntax_type), symbol_type(symbol_type) {} const ::calc::lang::SyntaxType syntax_type; const ::calc::lang::SymbolType symbol_type; }; std::unordered_map<std::string, SymbolMeta> symbol_metas_; std::unique_ptr<::calc::fsm::Graph<::calc::lang::SyntaxType>> grammar_graph_; std::mutex mtx_; }; } // namespace parser } // namespace impl } // namespace calc #endif // CPPND_CAPSTONE_CALC_CORE_IMPL_PARSER_PARSER_H_
eefe340163f855abe2c0cf84bf8d1b8ae8c756e4
69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96
/GPU Pro5/06_Compute/Object-order Ray Tracing for Fully Dynamic Scenes/beCore/header/beCore/beComponentObservation.h
42dba7bc970ec1c5820949b107572d6d591c8d77
[ "MIT", "BSD-3-Clause" ]
permissive
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
65c16710d1abb9207fd7e1116290336a64ddfc86
f442622273c6c18da36b61906ec9acff3366a790
refs/heads/master
2022-12-15T00:40:42.931271
2020-09-07T16:48:25
2020-09-07T16:48:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
h
beComponentObservation.h
/*****************************************************/ /* breeze Engine Core Module (c) Tobias Zirr 2011 */ /*****************************************************/ #pragma once #ifndef BE_CORE_COMPONENT_OBSERVATION #define BE_CORE_COMPONENT_OBSERVATION #include "beCore.h" namespace beCore { class Component; class PropertyProvider; class ReflectedComponent; /// Property listener. class LEAN_INTERFACE ComponentObserver { LEAN_INTERFACE_BEHAVIOR(ComponentObserver) public: /// Called when properties in the given provider might have changed. BE_CORE_API virtual void PropertyChanged(const PropertyProvider &provider) { } /// Called when child components in the given provider might have changed. BE_CORE_API virtual void ChildChanged(const ReflectedComponent &provider) { } /// Called when the structure of the given component has changed. BE_CORE_API virtual void StructureChanged(const Component &provider) { } /// Called when the given component has been replaced. BE_CORE_API virtual void ComponentReplaced(const Component &previous) { } }; } // namespace #endif
4c80c1a45a17adca0b10ac554a0d8537f514177c
1dfdadab321c3d5592f5807aaf11ea26b16ff2a9
/dev/CPP/DinrusVizWXC/src/wxdatetime.cpp
70b0d1677a772ecdd6b9c86da53893880e1d93c9
[]
no_license
dinrus/WX
dca328c474b9d6d243e22d01cac85b87643976d2
de192ea12c8b2e88405907203c57dde55741a968
refs/heads/master
2023-07-10T08:54:42.488305
2021-07-29T07:17:47
2021-07-29T07:17:47
116,132,166
0
0
null
null
null
null
UTF-8
C++
false
false
2,477
cpp
wxdatetime.cpp
//----------------------------------------------------------------------------- // wxD - wxdatetime.cpp // (C) 2005 bero <berobero.sourceforge.net> // based on // wx.NET - wxdatetime.cxx // // The wxDateTime proxy interface // // Written by Bryan Bulten (bryan@bulten.ca) // (C) 2003 by Bryan Bulten // Licensed under the wxWidgets license, see LICENSE.txt for details. // // $Id: wxdatetime.cpp,v 1.9 2006/11/17 15:21:06 afb Exp $ //----------------------------------------------------------------------------- /* #include <wx/wx.h> #include "common.h" #include <wx/datetime.h> */ #include "pch.h" extern "C" WXEXPORT const wxDateTime* wxDefaultDateTime_Get() { return &wxDefaultDateTime; } //----------------------------------------------------------------------------- extern "C" WXEXPORT wxDateTime* wxDateTime_ctor() { return new wxDateTime(); } extern "C" WXEXPORT void wxDateTime_dtor(wxDateTime* self) { if (self != NULL) delete self; } //----------------------------------------------------------------------------- extern "C" WXEXPORT wxDateTime* wxDateTime_Now() { return new wxDateTime(wxDateTime::Now()); } //----------------------------------------------------------------------------- extern "C" WXEXPORT void wxDateTime_Set(wxDateTime* self, unsigned short day, int month, int year, unsigned short hour, unsigned short minute, unsigned short second, unsigned short millisec) { self->Set(day, (wxDateTime::Month)month, year, hour, minute, second, millisec); } //----------------------------------------------------------------------------- extern "C" WXEXPORT unsigned short wxDateTime_GetYear(wxDateTime* self) { return self->GetYear(); } extern "C" WXEXPORT int wxDateTime_GetMonth(wxDateTime* self) { return (int)self->GetMonth(); } extern "C" WXEXPORT unsigned short wxDateTime_GetDay(wxDateTime* self) { return self->GetDay(); } extern "C" WXEXPORT unsigned short wxDateTime_GetHour(wxDateTime* self) { return self->GetHour(); } extern "C" WXEXPORT unsigned short wxDateTime_GetMinute(wxDateTime* self) { return self->GetMinute(); } extern "C" WXEXPORT unsigned short wxDateTime_GetSecond(wxDateTime* self) { return self->GetSecond(); } extern "C" WXEXPORT unsigned short wxDateTime_GetMillisecond(wxDateTime* self) { return self->GetMillisecond(); } //-----------------------------------------------------------------------------
410c86de33ec70d868e174312f7ebc75b12b19af
d6ed80fd02d17e6089de2157dcc09e8a8b8f7b08
/DataStructures/Graphs/adjList.cpp
a12df70f6ecb69e34305a2e2b84637eae8c03530
[]
no_license
iamakshatjain/Data-Structures-and-Algorithms
33362971d43a9325a695862af873cab7d88e5ff2
067351c7598e1bdafee962b846cfc26ae75286ff
refs/heads/master
2020-06-01T00:24:54.635113
2019-12-23T17:43:58
2019-12-23T17:43:58
190,557,396
0
0
null
null
null
null
UTF-8
C++
false
false
12,377
cpp
adjList.cpp
#include <bits/stdc++.h> #include <iostream> using namespace std; //the graph below is an unweighted graph //Node of the adjacency list struct ListNode{ int vertex; ListNode* next; }; //implementation using adjacency list struct graph{ int v; int e; ListNode *list;//this would be an array of linked lists }; graph* create_graph(int v,int e){ graph* g = (graph *)malloc(sizeof(graph)); if(!g){ cout<<"memory-error"<<endl; return g; } g->v = v; g->e = e; //creating the list g->list = (ListNode *)malloc(sizeof(ListNode)*v); //initializing the list for(int i=0;i<v;i++){ g->list[i].vertex = i; g->list[i].next = g->list+i;//the end of each list points back to the begining } return g; } //here u and v lies from 0 to g->v void add_edge(graph* g,int u,int v){ if(u == v){ cout<<"same vertex"<<endl; return; } //here the list is not made of pointers so we need ampersand ListNode* i = &(g->list[u]); // cout<<i->vertex<<endl; //because, the end of each list points back to the begining while(i->next->vertex!=g->list[u].vertex){ i = i->next; } ListNode *node = (ListNode *)malloc(sizeof(ListNode)); node->vertex = v; node->next = i->next; //attaching the node i->next = node; } void display_graph(graph* g){ cout<<"vertices : "<<g->v<<endl; cout<<"edges : "<<g->e<<endl; for(int u = 0;u<g->v;u++){ ListNode* i = &(g->list[u]); cout<<i->vertex<<' '; i = i->next; while(i->vertex!=g->list[u].vertex){ cout<<i->vertex<<' '; i = i->next; } cout<<endl; } } void DFS(graph *g,int i,int v[]){//this is actually the function to visit the nodes // if(v[i]!=0) // return; v[i] = 1;//this node is now visited cout<<g->list[i].vertex<<' '; ListNode *itr = &(g->list[i]);//this ith node is now visited itr = itr->next; while(itr->vertex != g->list[i].vertex){//traverse through all the adjacent nodes if(v[itr->vertex]==0)//if any adjacent node is not visited DFS(g,itr->vertex,v);//we visit the node itr = itr->next; } } void DFS_Traversal(graph *g){ cout<<endl; int visited[g->v] = {0};//all elements initialized to zero for(int i = 0;i<g->v;i++){//for each vertex apply dfs if(visited[i]==0)//this would actually be true once. It traverse all elements in one starting node. DFS(g,i,visited);//this loop comes into play when there are more than one connected component in the graph. } cout<<endl; } //we also need to implement a queue void BFS(graph *g,int v[],int w){ int u; int q[g->v]; int f = -1; int r = -1; // if(f<=r && r<g->v-1){ q[++r] = w; if(f==-1) f++; // } while(f<=r){//we dequeue when the queue is not empty u = q[f];//dequeue if(v[u] == 1){//very important condition f++; continue; } v[u] = 1; cout<<g->list[u].vertex<<' '; //this node is now visited ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex != g->list[u].vertex){ if (!v[itr->vertex]) { r++; q[r] = itr->vertex; } itr = itr->next; } f++; } } void BFS_Traversal(graph *g){ cout<<endl; int visited[g->v] = {0}; for(int i=0;i<g->v;i++){ if(!visited[i]){ BFS(g,visited,i); } } } //O(V+E) void Topological_sort(graph *g){ cout<<endl; //first step is to find the indegree int indcount = 0; int indegree[g->v] = {0}; for(int i=0;i<g->v;i++){ ListNode* itr = &(g->list[i]); itr = itr->next; while(itr->vertex!=g->list[i].vertex){ indegree[itr->vertex]++; indcount++; if(indcount>g->e){//#important cout<<"maybe undirected/cycle"<<endl; return; } itr = itr->next; } } int queue[2*g->v];//2*g->v because there may be a chance of cycle int f = -1; int r = -1; int counter = 0; for(int i = 0;i<g->v;i++){ if(indegree[i]==0){ queue[++r] = i; if(f==-1) f++; } } while(f<=r){ int u = queue[f];//dequeue cout<<u<<' '; ++counter; if(counter != g->v){ cout<<"maybe cycle present!"<<endl; break; } ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ indegree[itr->vertex]--; if(indegree[itr->vertex] == 0){ queue[++r] = itr->vertex;//enqueue } itr = itr->next; } f++; } cout<<endl; } void initialize(int distance[],int parent[],int l){ for(int i=0;i<l;i++){ if(i==0){ distance[i] = 0; } distance[i] = 100000; parent[i] = -1; } } void dijkastra_unweighted(graph *g,int source){ //unweighted graph dijkastra works with a queue, a distance array and a parent array int distance[g->v]; int parent[g->v]; initialize(distance,parent,g->v); int queue[g->v]; int f = -1; int r = -1; queue[++r] = source; f++; distance[source] = 0; while(f<=r){//O(V), since now the elements would arive only once int u = queue[f];//dequeue ListNode *itr = &(g->list[u]); itr=itr->next; while(itr->vertex!=g->list[u].vertex){//O(E) in total if(distance[itr->vertex] == 100000){ parent[itr->vertex] = u; distance[itr->vertex] = distance[u]+1; queue[++r] = itr->vertex;//enqueue only the elements with INFINITE distance, this way elements come only once } itr = itr->next; } f++; } cout<<"ele dist par"<<endl; for(int i=0;i<g->v;i++){ cout<<i<<'\t'<<distance[i]<<'\t'<<parent[i]<<endl; } } //Articulation points by tarjan's algorithm int tme = 0; void articulationUtil(int u,graph* g, int ap[],int visited[],int parent[],int disc[],int low[], int children[]){ visited[u] = 1;//the node is now visited disc[u] = low[u] = ++tme;//discovery time and low is initiated ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ int v = itr->vertex; if(!visited[v]){ parent[v] = u; children[u]++; articulationUtil(v,g,ap,visited,parent,disc,low,children); //after the return low[u] = min(low[v],low[u]); //case1 - if root if(parent[u] == -1 && children[u]>=2){ ap[u] = 1; } //case2 - if discovery time is less than low of adjacent vertex if(disc[u]<=low[v] && parent[u]!=-1){ ap[u] = 1; } } else if(v != parent[u]){//like B and C in tushar roy's video low[u] = min(disc[v],low[u]); } itr = itr->next; } } void articulation_points(graph *g){ int *ap = (int *)malloc(sizeof(int)*g->v); int visited[g->v]; int parent[g->v]; int disc[g->v]; int low[g->v]; int children[g->v]; for(int i=0;i<g->v;i++){ ap[i] = 0; visited[i] = 0; parent[i] = -1; disc[i] = -1; low[i] = -1; children[i] = 0; } for(int i=0;i<g->v;i++){ if(!visited[i]) articulationUtil(i,g,ap,visited,parent,disc,low,children); } //then here we print ap cout<<"Articulation Point : "; for(int i=0;i<g->v;i++){ if(ap[i]==1) cout<<i<<' '; } cout<<endl; } int t_bridge = 0; void bridge_util(int u,graph* g,int low[],int disc[],int parent[],int visited[]){ visited[u] = 1; disc[u] = low[u] = ++t_bridge; ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ int v = itr->vertex; if(!visited[v]){ parent[v] = u; bridge_util(v,g,low,disc,parent,visited); low[u] = min(low[u],low[v]); if(low[v] > disc[u]) cout<<"( "<<u<<" , "<<v<<" )"<<endl; } else if(v != parent[u]) low[u] = min(low[u],disc[v]); itr = itr->next; } } void bridge(graph* g){ int low[g->v]; int disc[g->v]; int visited[g->v]; int parent[g->v]; for(int i=0;i<g->v;i++){ visited[i] = 0; disc[i] = -1; low[i] = -1; parent[i] = -1; } cout<<"Bridges : "<<endl; for(int i=0;i<g->v;i++){ if(!visited[i]) bridge_util(i,g,low,disc,parent,visited); } } //Strongly connected components - TC: O(V+E) ; SC: O(V) int top = -1;//this is the top of the stackendl void post_order_traversal(graph* g,int u,int visited[],int postOrder[]){ visited[u] = 1; ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ int v = itr->vertex; if(!visited[v]) post_order_traversal(g,v,visited,postOrder); itr = itr->next; } postOrder[++top] = u; } void print_component(graph* g,int u, int visited[]){ cout<<u<<' '; visited[u]=1; ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ if(!visited[itr->vertex]) print_component(g,itr->vertex,visited); itr = itr->next; } return; } void ssc(graph *g){ //first perform dfs //get elements on the basis of post-order traversal int visited[g->v] = {0}; int postOrder[g->v] = {0};//rather than an array it is better to put to a stack otherwise we need to sort //we can also make the length of the postOrder one greater than g->v and we can use the first element as top for(int i=0;i<g->v;i++){ if(!visited[i]) post_order_traversal(g,i,visited,postOrder); } //reverse the graph : O(E) //we need to create a new graph graph*Gr = create_graph(g->v,g->e); //O(V+E) for(int i=0;i<g->v;i++){ ListNode* itr = &(g->list[i]); itr=itr->next; while(itr->vertex!=g->list[i].vertex){ add_edge(Gr,itr->vertex,i); itr = itr->next; } } //reversing is easier in adjacency matrix //pull element one by one out of the stack and peform dfs from them, all the reachable elements would get printed int visited2[Gr->v] = {0}; while(top>=0){ int u = postOrder[top]; if(!visited2[u]){ print_component(Gr,u,visited2); cout<<endl; } top--; } } int check_cycle_util(graph*g,int u,int visited[],int parent){ visited[u] = 1; ListNode*itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ int v = itr->vertex; if(!visited[v]) return check_cycle_util(g,v,visited,u); else if(v != parent){ return 1; } itr = itr->next; } return 0; } void detect_cycle_undirected(graph* g){ int visited[g->v] = {0}; for(int i=0;i<g->v;i++){//this would keep care for the disconnected components if(!visited[i]){ if(check_cycle_util(g,i,visited,-1)){ cout<<"cycle exists"<<endl; return; } } } cout<<"cycle doesn't exist"<<endl; return; } //Detecting a cycle in a directed graph //Time Complexity : O(V+E) //Space Complexity : O(V) bool flag = false; void check_cycle_util_directed(graph* g,int u,int grey[],int black[]){ if(!grey[u] && !black[u]){ grey[u] = 1; } else if(black[u] == 0){ cout<<"cycle exists"<<endl; flag = true; return; } ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ int v = itr->vertex; check_cycle_util_directed(g,v,grey,black); itr = itr->next; } black[u] = 1; grey[u] = 0; } void detect_cycle_directed(graph* g){ int black[g->v]={0}; int grey[g->v]={0}; for(int i=0;i<g->v;i++){ if(!grey[i]&&!black[i]){ check_cycle_util_directed(g,i,grey,black); } } if(!flag) cout<<"cycle doesn't exist"<<endl; } //Calculate depth of directed graph //O(V+E) int calculate_indegree(graph *g,int indegree[]){ int indegreeCount = 0; int v = g->v;//number of vertices in the graph for(int u=0;u<v;u++){ ListNode* itr = &(g->list[u]); itr = itr->next; while(itr->vertex!=g->list[u].vertex){ indegree[itr->vertex]++; indegreeCount++; if(indegreeCount > g->e){ cout<<"may be undirected graph/cycle"<<endl; return 1; } itr = itr->next; } } return 0; } int find_depth_directed(graph *g){ int depth = 0; int indegree[g->v] = {0}; int visited[g->v] = {0}; int noOfVertexProcessed = 0; if(calculate_indegree(g,indegree)){ return 0;//0 means error } int queue[2*g->v] = {0}; int rear = -1; int front = -1; for(int i=0;i<g->v;i++){ if(indegree[i] == 0){ queue[++rear] = i;//enqueue } } queue[++rear] = -1;//this marks the end of the level while(front!=rear && noOfVertexProcessed<g->v){ int val = queue[++front]; if(val == -1){ depth++; queue[++rear] = -1;//this marks the end of the level } else{ ListNode* itr = &(g->list[val]); itr = itr->next; while(itr->vertex!=g->list[val].vertex){ indegree[itr->vertex]--; if(indegree[itr->vertex] == 0){//only the vertex that makes it zero enqueues it. queue[++rear] = itr->vertex;//enqueue } itr=itr->next; } noOfVertexProcessed++; } } return depth; } int main(){ graph *g = create_graph(4,4); //this graph contains a cycle add_edge(g,0,1); add_edge(g,0,2); // add_edge(g,0,5); add_edge(g,1,3); add_edge(g,2,3); // add_edge(g,3,5); // add_edge(g,4,5); // add_edge(g,6,4); cout<<"depth : "<<find_depth_directed(g)<<endl; return 0; }
d6909810900d59270346d76d7617f9107bf3539e
2e9bcf4f49d45bdaab8338d9d719aba82e6f0ee8
/src/Task5/src/task5_4.cpp
6927d64a84f0bbc6ec1def1296aa4e12e3210188
[]
no_license
dlbuger/OOP_Practical
819432f365a549bdc72e382419efff5f62643507
2c30dcd4f4b3a4eaafb0d40831608adcddadc114
refs/heads/master
2020-07-16T17:58:09.680780
2019-09-10T15:05:02
2019-09-10T15:05:02
205,837,465
0
0
null
null
null
null
UTF-8
C++
false
false
931
cpp
task5_4.cpp
#include <iostream> using namespace std; class Student { private: string name; int numUnits; string *unitList; public : Student(string name, int numUnits) { this->name = name; this->numUnits = numUnits; unitList = new string[numUnits]; string input = ""; int counter = 0; do { input = getInput(); unitList[counter] = input; counter++; } while (counter != numUnits); } void display() { cout<<"The Student name --> "<< name<<endl; for (int i=0;i<numUnits;i++) cout<<unitList[i] << "\t"; } ~Student() { delete[] unitList; } private: string getInput() { cout << "Please enter the Units --> "; string tmp; cin >> tmp; return tmp; } }; int main() { Student s1("Jason", 4); s1.display(); }
0a4c7c7f58417035cf8367976703e5b05fc4485b
a7544dbcb7f8bfdfac6961466cea861aeb7392f5
/dp/atcoder dp/d.cpp
76685b53d1f5a0b1567dd055b8818d9dd88bac64
[]
no_license
rahulmala007/Compy
7359f2095a3d0c8d6188533fe86c3330cf700092
a7f248a26bb6462cf22d6a2766ca54b546e73097
refs/heads/master
2022-11-19T13:36:03.630329
2020-07-16T21:03:09
2020-07-16T21:03:09
276,660,657
1
0
null
null
null
null
UTF-8
C++
false
false
2,589
cpp
d.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define pf push_front #define fi first #define se second #define si size() #define bk back() #define popb pop_back() #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) #define endl "\n" #define lb lower_bound #define ub upper_bound #define emp empty() #define beg begin() #define en end() #define ump unordered_map #define forl(i,a,n) for(int i=a;i<n;i++) #define rfor(i,n,a) for(int i=n;i>=a;i--) #define fore(i,a,n) for(int i=a;i<=n;i++) #define len length() const int N=1e9+7; // dp[i][j] means we are at position i and total sum in knapsack is j // so aat position i we can take the element i or leave it // if we take it the transiotio nto dp[i][j]--->dp[i-1][j-weight[i]] other wise dp[i][j]-->dp[i-1][j] //iterative approach time-O(n*W) space-O(n*W) //Note at given (i,j) we only need to store the value in previous row i.e (i-1,j) //so storing info about all the rows is not required //with this observation we think we can reduce space //time-O(n*W) space-O(W) int main() { int n,w; cin>>n>>w; ll arr[n][2]; forl(i,0,n)forl(j,0,2)cin>>arr[i][j]; //O(N*W) space // ll dp[n+1][w+1]; // forl(i,0,w+1) dp[0][i]=0; // forl(i,0,n+1) dp[i][0]=0; // forl(i,1,n+1) // { // forl(j,0,w+1) // { // if(j>=arr[i-1][0])dp[i][j]=max(dp[i-1][j],dp[i-1][j-arr[i-1][0]]+arr[i-1][1]); // else dp[i][j]=dp[i-1][j]; // } // } //cout<<dp[n][w]<<endl; //Printing which elements are taken using the above dp // vector<int>v; // ll wt=w; // rfor(i,n,1) // { // if(dp[i][wt]==dp[i-1][wt-arr[i-1][0]]+arr[i-1][1]) // { // //this means if i have included the last object then value at (i,wt) must be equal to (i-1,wt-weight[i])+val[i] // //else it would e equal to (i-1,wt); // v.pb(1); // wt=wt-arr[i-1][0]; // } // else // { // v.pb(0); // } // } //print the reversed vecctor // rfor(i,v.si-1,0) // { // cout<<v[i]<<" "; // } // cout<<endl; //O(W) space soln ll dp[w+1]; forl(i,0,w+1)dp[i]=0; forl(i,0,n) { rfor(j,w,0) { if(j-arr[i][0]>=0) dp[j]=max(dp[j],dp[j-arr[i][0]]+arr[i][1]); } } //Note here we know for dp[j] we need dp[j-weight[i]] //so we traverse from back so that j-weight[i] does not get affected before j cout<<dp[w]<<endl; }
9b30a1572603147f822d00a7012c8b4a3ba8bd6b
9704fcf80f197d66365ff63b856892fa9b81e1a9
/HttpResponse.h
a0d758ee70a7a56c39f2af90aa8fa277da52fe56
[]
no_license
erkang26/-botsong
cf43fd9af72e777ac54f1058439d97568958f806
f9ac0e3c99af9c67adafa327ad79ef5b77875a1e
refs/heads/master
2020-05-09T20:07:15.321479
2019-05-15T05:50:52
2019-05-15T05:50:52
181,394,093
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
HttpResponse.h
// FileName:HttpResponse.h // // Desc: // // Created by token.tong at 2019-04-15 15:57:46 #ifndef _HTTP_RESPONSE_H_ #define _HTTP_RESPONSE_H_ #include "Utils.h" #include "sharelib.h" class HttpRequest; class Cookie; class HttpResponse { public: HttpResponse( HttpRequest* request ); ~HttpResponse(); bool parse( const string& data ); int getCode() const { return _code; } const string& getBody() const { return _body; } const vector<Cookie*>& getCookies() const { return _cookies; } HttpRequest* getRequest() { return _request; } bool hasHeader( const string& key ); const string& getHeader( const string& name ); private: bool parseHeader( const string& header ); bool parseBody( const string& body ); void parseFirstLine( const string& line ); private: HttpRequest *_request; map< string, string > _headers; string _body; string _ver; int _code; string _codeDesc; vector<Cookie*> _cookies; string _empty; }; #endif //_HTTP_RESPONSE_H_
7d648a98d4deef559593d22b1da4b90cefb48404
d97735ef39079b45f89e4381965cd1026c6ba2ec
/Fog/Src/Fog/Core/Kernel/EventLoopImpl.h
f7a0397e54af649b65de51bc1007b25797345f97
[ "BSD-3-Clause", "LicenseRef-scancode-boost-original", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
prepare/Graphics2DVariants
36d0bb503ecc00ae9b19a704830310597e272af6
0f59169b332e23b166adcad63e5427de2449bf70
refs/heads/master
2021-01-22T05:33:29.575665
2014-11-18T13:39:28
2014-11-18T13:39:28
22,535,508
1
1
null
null
null
null
UTF-8
C++
false
false
14,660
h
EventLoopImpl.h
// [Fog-Core] // // [License] // MIT, See COPYING file in package // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // [Guard] #ifndef _FOG_CORE_KERNEL_EVENTLOOPIMPL_H #define _FOG_CORE_KERNEL_EVENTLOOPIMPL_H // [Dependencies] #include <Fog/Core/Global/Global.h> #include <Fog/Core/Kernel/EventLoop.h> #include <Fog/Core/Kernel/EventLoopObserverList.h> #include <Fog/Core/Kernel/Task.h> #include <Fog/Core/Threading/Lock.h> #include <Fog/Core/Tools/List.h> #include <Fog/Core/Tools/String.h> #include <Fog/Core/Tools/Time.h> namespace Fog { //! @addtogroup Fog_Core_Kernel //! @{ // ============================================================================ // [Fog::EventLoopPendingTask] // ============================================================================ //! @brief Pending task used inside @c EventLoop. struct FOG_NO_EXPORT EventLoopPendingTask { FOG_INLINE EventLoopPendingTask(Task* task, bool nestable) { setTask(task, nestable); } // -------------------------------------------------------------------------- // [Accessors] // -------------------------------------------------------------------------- //! @brief Get the pending task. FOG_INLINE Task* getTask() const { #if FOG_ARCH_BITS >= 64 return (Task*)((size_t)_task & ~(size_t)1); #else return _task; #endif } //! @brief Get whether task is nestable. FOG_INLINE bool isNestable() const { #if FOG_ARCH_BITS >= 64 return ((size_t)_task & 1) == 1; #else return _isNestable != 0; #endif } //! @brief Set task and nestable flag. FOG_INLINE void setTask(Task* task, bool nestable) { #if FOG_ARCH_BITS >= 64 _task = (Task*)((size_t)task | (size_t)nestable); #else _task = task; _isNestable = nestable; #endif } //! @brief Get dispatch time (can be null if it's not delayed task). FOG_INLINE const Time& getTime() const { return _time; } //! @brief Set delayed time. FOG_INLINE void setTime(const Time& time) { _time = time; } // -------------------------------------------------------------------------- // [Members] // -------------------------------------------------------------------------- // Make the structure 16-bytes long. If compiled for 64-bit CPU then nestable // flag is stored together with the pointer, because last three bits are // always zero (alignment). If compiled for 32-bit then we have two 32-bit // values to use (pointer, and nestable value). #if FOG_ARCH_BITS >= 64 //! @brief Task combined with nestable flag (0x1 bit). Task* _task; #else //! @brief Task. Task* _task; //! @brief Nestable flag. uint32_t _isNestable; #endif // FOG_ARCH_BITS //! @brief Delayed time. Time _time; }; // ============================================================================ // [Fog::EventLoopImpl] // ============================================================================ struct FOG_API EventLoopImpl { // -------------------------------------------------------------------------- // [Construction / Destruction] // -------------------------------------------------------------------------- EventLoopImpl(const StringW& type); virtual ~EventLoopImpl(); // -------------------------------------------------------------------------- // [AddRef / Release] // -------------------------------------------------------------------------- virtual EventLoopImpl* addRef() const; virtual void release(); //! @brief Called by @c release(). virtual void destroy(); // -------------------------------------------------------------------------- // [Observable] // -------------------------------------------------------------------------- //! @brief Add an event observer @a obj to observe native event dispatching. //! //! @note Default implementation returns @c ERR_RT_NOT_IMPLEMENTED. virtual err_t addObserver(EventLoopObserver* obj); //! @brief Remove the event observer @a obj. //! //! @note Default implementation returns @c ERR_RT_NOT_IMPLEMENTED. virtual err_t removeObserver(EventLoopObserver* obj); // -------------------------------------------------------------------------- // [Run / Quit] // -------------------------------------------------------------------------- //! @brief The @c run() method is called to enter the event loop's run loop. //! //! Within the method, the event loop is responsible for processing native //! events as well as for giving cycles to the tasks periodically. The event //! loop should take care to mix own events with native event processing //! so neither type of event starves the other of cycles. //! //! The anatomy of a typical run loop: //! //! @verbatim //! for (;;) //! { //! didWork |= doWork(); //! if (quitting) \ //! break; //! //! didWork |= doDelayedWork(); //! if (quitting) \ //! break; //! //! if (didWork) //! continue; //! //! didWork = doIdleWork(); //! if (quitting) //! break; //! //! if (didWork) //! continue; //! //! waitForWork(); //! } //! @endverbatim //! //! Here, @c doInternalWork() is some private method of the event loop that is //! responsible for dispatching the next native event (this can be UI event, //! IO event, etc). @c waitForWork() is a protected method that simply blocks //! until there is more work of any type to do. //! //! Notice that the run loop cycles between calling @c doInternalWork(), //! @c doWork(), and @c doDelayedWork() methods. This helps ensure that //! neither work queue starves the other. This is important for event loops //! that are used to drive animations, for example. //! //! Notice also that after each callout to foreign code, the run loop checks //! to see if it should quit. The quit() method is responsible for setting //! this flag. No further work is done once the quit flag is set. //! //! @note Care must be taken to handle @c run() being called again from within //! any of the callouts to foreign code. Native event loops may also need to //! deal with other native event loops being run outside their control //! (e.g., the MessageBox API on Windows pumps UI messages!). To be specific, //! the callouts (@c scheduleWork() and @c scheduleDelayedWork()) MUST still //! be provided even in nested sub-loops that are "seemingly" outside the //! control of this event loop. @c doWork() in particular must never be //! starved for time slices unless it returns false (meaning it has run out //! of things to do). virtual err_t run(); //! Process all pending tasks, windows messages, etc., but don't wait/sleep. //! Return as soon as all items that can be run are taken care of. virtual err_t runAllPending(); //! A surrounding stack frame around the running of the event loop that //! supports all saving and restoring of state, as is needed for any/all (ugly) //! recursive calls. virtual err_t runInternal() = 0; //! @brief Quit immediately from the most recently entered run loop. //! //! Signals the @c run() method to return after it is done processing all //! pending events. This method may only be called on the same thread that //! called @c run(), and @c run() must still be on the call stack. //! //! Use @c QuitTask() if you need to quit another thread's @c EventLoop, but //! note that doing so is fairly dangerous if the target thread makes nested //! calls to @c run(). The problem being that you won't know which nested //! run loop you are quiting, so be careful! virtual err_t quit(); // -------------------------------------------------------------------------- // [Post] // -------------------------------------------------------------------------- //! The @c postTask() family of methods call the task's run() method //! asynchronously from within a event loop at some point in the future. //! //! With the @c postTask() variant, tasks are invoked in FIFO order, //! inter-mixed with normal UI or IO event processing. With the //! @c postTask() with delay larger than zero variant, tasks are called after //! at least approximately delay have elapsed. //! //! The EventLoop takes ownership of the @a task, and deletes it after it has //! been run. //! //! @note These methods may be called on any thread. The Task will be invoked //! on the thread that executes @c run() (event loop home thread). virtual err_t postTask(Task* task, bool nestable = true, uint32_t delay = 0); //! @brief Post a task to our incomming queue. void postTask_Helper(Task* task, uint32_t delay); // -------------------------------------------------------------------------- // [Helpers] // -------------------------------------------------------------------------- // Run a workQueue task or @a task, and delete it (if it was processed by // @c postTask()). If there are queued tasks, the oldest one is executed and // @a task is queued. @a task is optional and can be NULL. In this NULL case, // the method will run one pending task (if any exist). Returns true if it // executes a task. Queued tasks accumulate only when there is a non-nestable // task currently processing, in which case the @a task is appended to the // list workQueue. Such re-entrancy generally happens when an unrequested // event loop (typical of a native dialog) is executing in the context of a // task. // bool queueOrRunTask(Task* task); //! @brief Runs the specified task and deletes it. void runTask(Task* task); //! @brief Calls RunTask or queues the pendingTask on the deferred task list //! if it cannot be run right now. Returns true if the task was run. bool deferOrRunPendingTask(const EventLoopPendingTask& pendingTask); //! @brief Adds the pending task to delayedWorkQueue. //! //! This method will return @c true if it's needed to re-schedule internal //! timer. bool addToDelayedWorkQueue(const EventLoopPendingTask& pendingTask); //! @brief Load tasks from the incomingQueue into workQueue if the latter is //! empty. The former requires a lock to access, while the latter is directly //! accessible on this thread. void reloadWorkQueue(); //! @brief Delete tasks that haven't run yet without running them. Used in the //! destructor to make sure all the task's destructors get called. Returns //! true if some work was done. bool deletePendingTasks(); // -------------------------------------------------------------------------- // [DoWork] // -------------------------------------------------------------------------- //! @brief Called from within @c run() in response to @c scheduleWork() or when //! the event loop would otherwise call @c doDelayedWork(). Returns true //! to indicate that work was done. @c doDelayedWork() will not be called //! if @a doWork() returns true. //! //! This means that priority of timers is lower than priority of tasks. virtual bool doWork(); //! @brief Called from within @c run() in response to @c scheduleDelayedWork() //! or when the event loop would otherwise sleep waiting for more work. //! //! Returns true to indicate that delayed work was done. doIdleWork() will //! not be called if doDelayedWork() returns true. Upon return //! @a nextDelayedWorkTime indicates the time when doDelayedWork() should be //! called again. If @a nextDelayedWorkTime is null, see @c Time::isNull(), //! then the queue of future delayed work (timer events) is currently empty, //! and no additional calls to this function need to be scheduled. virtual bool doDelayedWork(Time* nextDelayedWorkTime); //! @brief Called from within run() just before the event loop goes to sleep. //! Returns true to indicate that idle work was done. virtual bool doIdleWork(); // -------------------------------------------------------------------------- // [ScheduleWork] // -------------------------------------------------------------------------- //! @brief Schedule a @c doWork() callback to happen reasonably soon. Does //! nothing if a @c doWork() callback is already scheduled. This method may //! be called from any thread. Once this call is made, @c doWork() should //! not be "starved" at least until it returns a value of false. virtual void scheduleWork() = 0; //! @brief Schedule a @c doDelayedWork() callback to happen at the specified //! time, cancelling any pending @c doDelayedWork() callback. This method may //! only be used on the thread that called @c run(). virtual void scheduleDelayedWork(const Time& delayedWorkTime) = 0; // -------------------------------------------------------------------------- // [Members] // -------------------------------------------------------------------------- //! @brief Reference count. mutable Atomic<size_t> _reference; //! @brief Event loop type. StringW _type; //! @brief Current event loop depth (nested @c run() calls). int _depth; //! @brief Whether this is a native event loop with observable event //! dispatching. uint8_t _isObservable; //! @brief destroy() method was called. There is assertion in ~EventLoop() //! so this must be set to true before EventLoop::~EventLoop() is called. uint8_t _isDestroyed; //! @brief Whether the event loop is at quitting stage (quit() was called). uint8_t _quitting; //! @brief Free to use for any @c EventLoopImpl implementation. uint8_t _flag_0; // These are accessed only by event loop's thread. //! @brief Current work queue (may also contain delayed tasks). List<EventLoopPendingTask> _workQueue; //! @brief Current delayed work queue (parsed originally from @c workQueue). List<EventLoopPendingTask> _delayedWorkQueue; //! @brief Current deferred work queue (tasks that will be called by //! non-nested event loop). List<EventLoopPendingTask> _deferredWorkQueue; //! @brief Protect access to incomingQueue and observerList. Lock lock; //! @brief List which creates an incomingQueue of tasks that are aquired under //! incomingLock for processing on this instance's thread. These tasks have not //! yet been sorted out into items for our workQueue vs items that will be //! handled by the timer manager. List<EventLoopPendingTask> _incomingQueue; //! @brief List of event observers. EventLoopObserverList<EventLoopObserver> _observerList; private: FOG_NO_COPY(EventLoopImpl) }; //! @} } // Fog namespace #endif // _FOG_CORE_KERNEL_EVENTLOOPIMPL_H
b6daecf0271b8c1b370f9bef484a08b43233e047
73f30c1a8248be5866c6127328e9f0034045659c
/Stack.h
632d22de3ab06bb241060f62be4f2ad82ba86ec2
[]
no_license
mkrooted256/uni-datastructures-elementary
7a139317a7868f4cb3ac138d27e03eda6c21c7b2
8643b77b2807f9a0ae7dd3f7a37987a18c4d6143
refs/heads/master
2021-05-17T16:08:06.800600
2020-03-30T10:50:27
2020-03-30T10:50:27
250,862,741
0
0
null
null
null
null
UTF-8
C++
false
false
1,616
h
Stack.h
#ifndef LAB3_REMASTERED_STACK_H #define LAB3_REMASTERED_STACK_H #include "Deque.h" #include "Dinorray.h" namespace Deque { template<class T> class Stack { Deque <T> deq; public: void push(const T &val) { deq.push_back(val); } T pop() { auto val = deq.back(); deq.pop_back(); return val; } typedef typename Deque<T>::iterator iterator; iterator begin() { return deq.begin(); } iterator end() { return deq.end(); } const Deque <T> &getDeq() const { return deq; } bool empty() { return deq.empty(); } friend std::ostream &operator<<(std::ostream &os, const Stack &stack) { os << stack.deq; return os; } }; } namespace Dinorray { template<class T> class Stack { Dinorray <T> deq; public: void push(const T &val) { deq.push_back(val); } T pop() { auto val = deq.back(); deq.pop_back(); return val; } typedef typename Dinorray<T>::iterator iterator; iterator begin() { return deq.begin(); } iterator end() { return deq.end(); } const Dinorray <T> &getDeq() const { return deq; } bool empty() { return deq.empty(); } friend std::ostream &operator<<(std::ostream &os, const Stack &stack) { os << stack.deq; return os; } }; } #endif //LAB3_REMASTERED_STACK_H
5bce80c11138811d54331249dbbc47106de55346
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2692487_0/C++/Saylars/main.cpp
f23294cba7e8a7eaf0d62e01ac3e577aacb1afe1
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,549
cpp
main.cpp
#include <iostream> #include <fstream> #include <vector> #include <algorithm> using namespace std; int main() { freopen("A-small-attempt2.in", "r", stdin); freopen("output.txt", "w", stdout); int t; cin >> t; for (int q = 0; q < t; q++) { int a, n; cin >> a >> n; vector <int> b; for (int i = 0; i < n; i++) { int temp; cin >> temp; b.push_back(temp); } sort(b.begin(), b.end()); int c[n + 1]; int ans; if (a != 1) { int tempa = a; for (int i = 0; i < n; i++) { if (tempa > b[i]) { tempa += b[i]; c[i] = 0; } else { int w =0; while (tempa <= b[i]) { w++; tempa = tempa + tempa - 1; } tempa += b[i]; c[i] = w; } } ans = n; int tmp = 0; for (int i = 0; i < n; i++) { tmp += c[i]; if (tmp + n - i - 1< ans) ans = tmp + n - i - 1; } } else { ans = n; } cout << "Case #"<<q + 1 << ": " << ans << endl; } return 0; }
310eb08bf611a9ffbab5dfff31b50f83514b7cc9
7851ceb1f9d87cad9ba8cb68061f11ca2ed61944
/src/hud/NewPercent.cpp
40d3f299259e132f9625a91fee8912b80e6507e5
[]
no_license
aspurgin/GoingNuts-
419de4b2cb3e96ada011fc3caabed2b4d4840e65
9415625647f826d382ee3c6c94bba6f56e37f540
refs/heads/master
2020-05-17T17:02:16.817086
2014-06-11T23:28:22
2014-06-11T23:28:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
NewPercent.cpp
#include "NewPercent.hpp" NewPercent::NewPercent() { model = Assets::getMesh(Assets::NEW_PERCENT_M); shaderType = FT_SHADE; scaleX = 0.12f; scaleY = 0.12f; scaleZ = 0.12f; colorTexture = Assets::getTexture(Assets::HUD_ELEMENTS_T); this->position = glm::vec3(11.6, -7.15, 0); this->modelTrans.useModelViewMatrix(); } void NewPercent::render() { Renderable::render(); }
9c1c16f2b6055af61d4301459a0e6979b4db99c6
dbf16ceabd85268618670f02e03e6838874b6d4c
/common/vector.cpp
101146a882512517647a1a344ac8f679b7d9e475
[]
no_license
capel/brazos
9bb72a0c25dd7afd65f3d4a10baa2b1beb575a61
759004a5e7c19f79590a28ef403b3ce7d4bc7bc9
refs/heads/master
2016-09-11T14:59:56.369866
2012-04-27T07:55:24
2012-04-27T07:55:24
4,156,239
1
0
null
null
null
null
UTF-8
C++
false
false
2,172
cpp
vector.cpp
// David Capel <capel@wisc.edu>, cs account: capel // Implementation of the auto-expanding array data structure. #include "stdlib.h" #include "vector.h" template<typename T> void vector::push(T t) { if (size() >= m_allocated-2) { m_allocated *= 2; m_data = new T[allocated]; } m_data[m_size++] = t; } template<typename T> T vector::pop() { T t = m_data[size()]; remove(size()); return t; } template<typename T> vector::vector(size_t size) : m_allocated(3), m_size(0), m_data(new T[m_allocated]) {} vector::~vector() { delete [] m_data; } void vector::remove(size_t idx) { if (idx >= size()) return; // copy stuff over for(size_t j = i+1; j < v->size; ++j) { m_data[j-1] = m_data[j]; } --size; } /* bool is_sep(const char c, const char* seps) { size_t len = strlen(seps); for (size_t i = 0; i < len; ++i) { if (c == seps[i]) return true; } return false; } vector* _split_to_vector(const char * str, const char* seps, const alloc_funcs* funcs) { if (!str || !seps) return 0; vector * v = _make_vector(sizeof(char*), __SPLIT_TO_VECTOR, funcs); size_t len = strlen(str); v->__source = v->__alloc_funcs->calloc(len+1, 1); strlcpy(v->__source, str, len+1); // for ease of use char* src = v->__source; size_t i = 0; size_t beginning; while (true) { // skip beginning stuff for(; i < len; ++i) { if (!is_sep(src[i], seps)) { break; } } if (i >= len) return v; beginning = i; for (; i < len; ++i) { if (is_sep(src[i], seps)) { src[i++] = '\0'; vector_push(v, src+beginning); break; } } if (i == len) { if (i != beginning) { src[++i] = '\0'; vector_push(v, src+beginning); } return v; } } } void* vector_best(vector* v, vector_better_func better) { if (v->size == 0) { return NULL; } void* best = NULL; for(size_t i = 0; i < v->size; i++) { if (!best) best = v->data[i]; if (better(v->data[i], best)) best = v->data[i]; } return best; } */
07b7634b3bae2dacbf2c2d80570b3cb743419cf4
cd9022acc362ba27e57f88cc87e5ec20b521b7f4
/Arrays/array func.cpp
a1ba492e1b0e3cdf8b405239e4387d751a7e8635
[]
no_license
ibadeeCodes/All-About-C-
ecea2d325265a8a0d57d751bf0612f8e56e45ebf
4b50226a567149fa8754685f0721c1c9dcdbeacd
refs/heads/master
2020-04-13T20:59:25.260782
2019-01-02T18:09:59
2019-01-02T18:09:59
163,445,280
1
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
array func.cpp
#include<stdio.h> void modify(void); int main() { int a[10]; modify(); } void modify(void) { int a[10]={1,2,3,4,5,6,7,8,9,10},i,j; for(i=0;i<10;i++) { printf("the value is:%d\n",(a[i]*3)); } }
9d673f9bcb948f4e3c2d2ef4176f70260ce0bdec
5620f1855048326dadf55f2619450b2ff1a6a0ac
/43/43A.cpp
94b93fd41a2964d61099d324313a8109c654c41c
[]
no_license
ranilakshmi/codeforces
29206d0cab1e890dc9a1993c80c85e14d6644f18
bf1b264d88ff1d7eb6d78e518e4a7ba1288f7127
refs/heads/master
2023-06-04T10:48:58.302029
2021-06-27T05:51:08
2021-06-27T05:51:08
287,335,922
0
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
43A.cpp
#include<iostream> #include<string> using namespace std; int main(){ int n; string x,y; int a=1; int b=0; cin >> n; cin >> x; string team; for (int i=1;i<n;i++){ cin >> team; if (team == x){ a = a+1; } else{ y=team; b=b+1; } } if(a>b){ cout << x; } else{ cout << y; } }
63244e8d4708f8d3fc7cc90f5349daaf3e49d69b
64ea51dc8798667c6854ec0ba6abaabff1baca94
/ConsoleApplication2/ConsoleApplication2/ConsoleApplication2.cpp
7a30c3638b98e4fa5804b44aa91b15e0d519e798
[]
no_license
Erik2901/Cross-Zero
9cd9c5b92555a0d2a781860acf34d2c6f3fd7d85
e17f9fd1381c33587d33365bcea92ee1ce5d6928
refs/heads/main
2023-06-19T11:25:58.342426
2021-07-20T03:01:48
2021-07-20T03:01:48
387,655,327
0
0
null
null
null
null
UTF-8
C++
false
false
6,382
cpp
ConsoleApplication2.cpp
 #include <iostream> #include <random> #include <stdlib.h> #include <chrono> using namespace std; enum Cell { CROSS = 'X', ZERO = '0', EMPTY = '_' }; struct Coord{ size_t y; size_t x; }; enum Progress { IN_PROGRESS, WON_HUMAN, WON_AI, DRAW }; struct Field { Cell** ppField = nullptr; const size_t SIZE = 3; size_t turn = 0; Progress progress = IN_PROGRESS; Cell ai; Cell human; }; //============================== Progress getWon(const Field& f); void clear() { system("cls"); } int32_t getRandomNum(int32_t min, int32_t max) { const static auto seed = chrono::system_clock::now().time_since_epoch().count(); static mt19937_64 generator(seed); uniform_int_distribution<int32_t> dis(min, max); return dis(generator); } void initField(Field & f) { f.ppField = new(nothrow) Cell * [f.SIZE]; for (size_t i = 0; i < f.SIZE; i++) { f.ppField[i] = new(nothrow) Cell [f.SIZE]; } for (size_t y = 0; y < f.SIZE; y++) { for (size_t x = 0; x < f.SIZE; x++) { f.ppField[y][x] = EMPTY; } } if (getRandomNum(0, 1000) > 500) { f.human = CROSS; f.ai = ZERO; f.turn = 0; } else { f.human = ZERO; f.ai = CROSS; f.turn = 1; } } void deinitField(Field& f) { for (size_t i = 0; i < f.SIZE; i++) { delete [] f.ppField[i]; } delete [] f.ppField; f.ppField = nullptr; } void printField(const Field& f) { cout << " "; for (size_t x = 0; x < f.SIZE; x++) cout << x + 1 << " "; cout << endl; for (size_t y = 0; y < f.SIZE; y++) { cout << " " << y + 1 << " | "; for (size_t x = 0; x < f.SIZE; x++) { cout << (char)f.ppField[y][x] << " | "; } cout << endl; } cout << " Human: " << (char)f.human << endl; cout << " Computer: " << (char)f.ai << endl << endl; } Coord getHumanCoord(const Field& f) { Coord c{0,0}; do { cout << "X coord: "; cin >> c.x; cout << "Y coord: "; cin >> c.y; } while (c.x == 0 || c.y == 0 || c.x > 3 || c.y > 3 || f.ppField[c.y - 1][c.x - 1] != EMPTY); c.x--; c.y--; return c; } Coord getAICoord(Field& f) { for (size_t y = 0; y < f.SIZE; y++) { for (size_t x = 0; x < f.SIZE; x++) { if (f.ppField[y][x] == EMPTY) { f.ppField[y][x] == f.ai; if (getWon(f) == WON_AI) { f.ppField[y][x] == EMPTY; return { y,x }; } f.ppField[y][x] == EMPTY; } } } for (size_t y = 0; y < f.SIZE; y++) { for (size_t x = 0; x < f.SIZE; x++) { if (f.ppField[y][x] == EMPTY) { f.ppField[y][x] == f.human; if (getWon(f) == WON_HUMAN) { f.ppField[y][x] == EMPTY; return { y,x }; } f.ppField[y][x] == EMPTY; } } } if (f.ppField [1][1] == EMPTY) { return { 1,1 }; } if (f.ppField[0][0] == EMPTY) { return { 0,0 }; } if (f.ppField[2][2] == EMPTY) { return { 2,2 }; } if (f.ppField[2][0] == EMPTY) { return { 2,0 }; } if (f.ppField[0][2] == EMPTY) { return { 0,2 }; } if (f.ppField[0][1] == EMPTY) { return { 0,1 }; } if (f.ppField[2][1] == EMPTY) { return { 2,1 }; } if (f.ppField[1][0] == EMPTY) { return { 1,0 }; } if (f.ppField[1][2] == EMPTY) { return { 1,2 }; } } Progress getWon(const Field& f) { for (size_t y = 0; y < f.SIZE; y++) { if (f.ppField[y][0] == f.ppField[y][1] && f.ppField[y][0] == f.ppField[y][2]) { if (f.ppField[y][0] == f.ai) { return WON_AI; } if (f.ppField[y][0] == f.human) { return WON_HUMAN; } } } for (size_t x = 0; x < f.SIZE; x++) { if (f.ppField[0][x] == f.ppField[1][x] && f.ppField[0][x] == f.ppField[2][x]) { if (f.ppField[0][x] == f.ai) { return WON_AI; } if (f.ppField[0][x] == f.human) { return WON_HUMAN; } } } if (f.ppField[0][0] == f.ppField[1][1] && f.ppField[0][0] == f.ppField[2][2]) { if (f.ppField[0][0] == f.ai) { return WON_AI; } if (f.ppField[0][0] == f.human) { return WON_HUMAN; } } if (f.ppField[0][2] == f.ppField[1][1] && f.ppField[2][0] == f.ppField[1][1]) { if (f.ppField[1][1] == f.ai) { return WON_AI; } if (f.ppField[1][1] == f.human) { return WON_HUMAN; } } bool draw = true; for (size_t y = 0; y < f.SIZE; y++) { for (size_t x = 0; x < f.SIZE; x++) { if (f.ppField[y][x] == EMPTY) { draw = false; break; } } if (!draw) { break; } } if (draw) { return DRAW; } return IN_PROGRESS; } //============================== int main() { Field f; clear(); initField(f); printField(f); do { if (f.turn % 2 == 0) { Coord c = getHumanCoord(f); f.ppField[c.y][c.x] = f.human; } else { Coord c = getAICoord(f); f.ppField[c.y][c.x] = f.ai; } clear(); printField(f); f.turn++; f.progress = getWon(f); } while (f.progress == IN_PROGRESS); if (f.progress == WON_HUMAN) { cout << "Human Won!" << endl; } else if (f.progress == WON_AI) { cout << "Computer Won!" << endl; } else if (f.progress == DRAW) { cout << "Draw!" << endl; } deinitField(f); system("pause"); return 0; } //==============================
2462c73ea3301135df821a04012a25f9a12485d0
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/flyem/zsynapseannotationanalyzer.h
9a1694f10c1f1b98b5e21a687c499f738960640c
[ "BSD-2-Clause", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
1,324
h
zsynapseannotationanalyzer.h
#ifndef ZSYNAPSEANNOTATIONANALYZER_H #define ZSYNAPSEANNOTATIONANALYZER_H #include "zsynapseannotationarray.h" #include "tz_swc_tree.h" #include <map> #include <string> #include <vector> namespace FlyEm { class ZSynapseAnnotationAnalyzer { public: ZSynapseAnnotationAnalyzer(); ~ZSynapseAnnotationAnalyzer(); public: void set(const std::vector<int> bodyIdList, const std::vector<std::string> swcFileList); void setStackSize(int width, int height, int depth); void setDownsampleRate(int ds1, int ds2); void setResolution(double xRes, double yRes, double zRes); void setOffset(int dx, int dy, int dz); void setUnit(std::string unit); void setStartNumber(int number); void identifySynapseLocation(ZSynapseAnnotationArray *synapseArray); inline SynapseAnnotationConfig& config() { return m_config; } public: void loadConfig(std::string filePath); void print(); private: SynapseAnnotationConfig m_config; std::map<int, int> m_bodyIdMap; std::vector<std::string> m_swcFileList; std::vector<Swc_Tree*> m_swcTreeList; //The distances are all in the unit of 'nm' double m_minTbarDistance; double m_minPsdDistance; double m_minTbarPsdDistance; double m_maxTbarPsdDistance; int m_minPartnerNumber; int m_maxPartnerNumber; }; } #endif // ZSYNAPSEANNOTATIONANALYZER_H
e936b605bc3eef8eadd57346c12231ba58575b61
8c396082f75956184f129aef1b5728a009612d48
/Source/AliveLib/ExportHooker.hpp
ab30aa649eb74a0f7c70352d58bc32a5ea407c11
[]
no_license
mlgthatsme/alive_reversing
16adb80f79acc2ff4563dd47e20df22a824f2af8
26054b0a63e7aa86aba1047610af2cafe8bc38fe
refs/heads/master
2023-05-01T20:41:59.218593
2020-04-13T02:06:11
2020-04-13T02:06:11
136,331,488
0
0
null
2018-06-06T13:18:38
2018-06-06T13:18:38
null
UTF-8
C++
false
false
1,119
hpp
ExportHooker.hpp
#pragma once #include <assert.h> #include <vector> #include <set> #include <sstream> #include "logger.hpp" #include "Function.hpp" class ExportHooker { public: explicit ExportHooker(HINSTANCE instance); void Apply(bool saveImplementedFuncs = false); void OnExport(PCHAR pszName, PVOID pCode); private: void LoadDisabledHooks(); void ProcessExports(); static bool IsHexDigit(char letter); struct ExportInformation { bool mIsImplemented; std::string mExportedFunctionName; std::string mUnMangledFunctioName; const std::string& Name(); }; static ExportInformation GetExportInformation(PVOID pExportedFunctionAddress, const std::string& exportedFunctionName); HINSTANCE mhInstance = nullptr; struct Export { std::string mName; LPVOID mCode; DWORD mGameFunctionAddr; DWORD mHookedGameFunctionAddr; bool mIsImplemented; }; std::vector<Export> mExports; std::map<DWORD, ExportInformation> mUsedAddrs; std::map<DWORD, DWORD> mRealStubs; std::set<DWORD> mDisabledImpls; };
1d9321883154706a5bdd41b41c0372dedb234872
39fe085377f3c7327e82d92dcb38083d039d8447
/core/sql/executor/ExUdrServer.h
d53bda74a19bca83bb3e93c9abb61fa692fb1ddc
[ "Apache-2.0" ]
permissive
naveenmahadevuni/incubator-trafodion
0da8d4c7d13a47d3247f260b4e67618c0fae1539
ed24b19436530b2c214e4bf73280bc8e3f419669
refs/heads/master
2021-01-22T04:40:52.402291
2015-07-16T00:02:50
2015-07-16T00:02:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,477
h
ExUdrServer.h
/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 1994-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #ifndef __EX_UDR_SERVER_H #define __EX_UDR_SERVER_H /* -*-C++-*- ***************************************************************************** * * File: ExUdrServer.h * Description: Client-side process management for UDR servers * * Created: 08/16/2000 * Language: C++ * * ***************************************************************************** */ #include "ComSmallDefs.h" #include "UdrExeIpc.h" #include "ExCollections.h" #include "NAUserId.h" // Default nowait depth of 3 is used for connections (except control // connection) to UDR Server #define DEFAULT_NOWAIT_DEPTH 3 // ----------------------------------------------------------------------- // Forward class references // ----------------------------------------------------------------------- class UdrControlMsg; class UdrClientControlStream; class ExUdrTcb; class IpcProcessId; // ----------------------------------------------------------------------- // Classes defined in this file // ----------------------------------------------------------------------- class ExUdrServer; class ExUdrServerManager; extern NABoolean ProcessIdIsNull(const IpcProcessId &); extern void InvalidateProcessId(IpcProcessId &); // ----------------------------------------------------------------------- // ExUdrServer // ----------------------------------------------------------------------- class ExUdrServer : public NABasicObject { public: enum ExUdrServerStatus { EX_UDR_SUCCESS = 0, EX_UDR_WARNING, EX_UDR_ERROR }; enum ExUdrServerState { EX_UDR_NOT_STARTED = 0, EX_UDR_READY, EX_UDR_BROKEN }; ExUdrServer(IpcEnvironment *env, const Int32 &userId, const char *options, const char *optionDelimiters, const char *userName, const char *userPassword, IpcServerClass *serverClass); ~ExUdrServer(); void setState(ExUdrServerState state) { state_ = state; } ExUdrServerState getState() const { return state_; } void setDedicated(NABoolean dedicated) { dedicated_ = dedicated; } NABoolean isDedicated(void) { return dedicated_;} void setInUse(NABoolean inUse) { inUse_ = inUse; } NABoolean inUse(void){ return inUse_;} ExUdrServerStatus start(ComDiagsArea **diags, CollHeap *diagsHeap, Int64 transId, IpcProcessId &newId, NABoolean usesTransactions); ExUdrServerStatus stop(); ExUdrServerStatus kill(ComDiagsArea *diags); const IpcProcessId getServerProcessId() const { return serverProcessId_; } const char *getOptions() const { return options_; } const char *getOptionDelimiters() const { return optionDelimiters_; } // Helper function to send down server-side runtime options. Must be // called only after successful startup of the server. void sendStartupOptions(ComDiagsArea **diags, CollHeap *diagsHeap, Int64 transId); // Matchmaking logic to determine if this server has the requested // attributes NABoolean match(const Int32 &userId, const char *options, const char *optionDelimiters) const; // // Functions to quiesce the UDR server // - isIOPending() returns TRUE if any replies are outstanding. // - completeUdrRequests(TRUE) polls for I/O completion until // isIOPending() returns FALSE. completeUdrRequests(FALSE) // waits for one I/O to complete then returns. // NABoolean isIOPending(IpcConnection *conn) const; void completeUdrRequests(IpcConnection *conn, NABoolean waitForAllIO) const; IpcConnection *getUdrControlConnection() const; IpcConnection *getAnIpcConnection() const; void releaseConnection(IpcConnection *conn); IpcEnvironment *myIpcEnv() const { return ipcEnvironment_; } CollHeap *myIpcHeap() const; void incrRefCount() { ++refCount_; } void decrRefCount() { --refCount_; } void setRefCount(ComUInt32 refCount) { refCount_ = refCount; } ComUInt32 getRefCount() const { return refCount_; } const Int32 &getUserId() const { return userId_; }; #ifdef UDR_DEBUG void setTraceFile(FILE *f) { traceFile_ = f; } #endif protected: inline NABoolean ready() const { return (state_ == EX_UDR_READY); } ExUdrServerState state_; IpcEnvironment *ipcEnvironment_; IpcServerClass *udrServerClass_; IpcServer *ipcServer_; IpcProcessId serverProcessId_; ULng32 startAttempts_; // The user identity for this UDR server Int32 userId_; char *userName_; char *userPassword_; // Server-side runtime options. Currently the options_ string stores // JVM startup options only. char *options_; char *optionDelimiters_; // A small summary of how reference count, dedicated and inUse flags // are used. Note that there are three layers of maintaining the // usage of mxudr servers. First layer being the top layer. // First layer: Server Manager is an instance in CliGlobals. Server // manager either creates a new server process or returns a existing // server in its pool for reuse. Server manager maintains a single // list of servers. // // Second layer: ContextCli obtains servers from server manager or // the first layer on a need basis. ContextCli reuses servers in its // pool to service requests from various statements in its scope. // contextCli can request a shared or a dedicated server from server // manager. A dedicated server request to server manager will always // return a server whose reference count is 1. // Note that server manager upon request from other contextCli requests for // a shared mode server will not hand over a server from its pool that has // been already obtained as dedicated by another contextCli. // Referece count of server is always incremented by one (by the server // manager) when ContextCli obtaines a server from server manager. Once // the server is in ContextCli scope, its reference count is not altered // in contextCli scope. Reference count is decremented once contectCli // returns the server back to server manager. Once the server is returned // back to server manager, it is free to be reassined to other contextCli // requests as a shared or dedicated server. // ContextCli uses the list of servers to complete Io or return back servers // when under certain scenarios. search for udrServerList_ in contextCli scope. // Third layer: ex_exe_statement_globals obtains servers from contextcli on // a demand basis. Multiple tcbs in a statment may use a server that is obtained // from contextcli in shared mode. For TMUDF tcbs, a dedicated server from // contextCli would be obtained in dedicated mode. ex_exe_statement_globals // maintains a single pointer to server that is obtained in shared mode and // a separate list of pointers to servers that have been obtained in dedicated mode. // Ex_exe_statement_global sets the inUse_ flag for dedicated servers so that // contextCli does not hand the same dedicated server to other statements. // Number of contexts and TCBs using this ExUdrServer object. A // refCount of 0 means no other objects are using this UDR server // and it can be returned to the pool of idle servers, or released. ComUInt32 refCount_; // This flag indicates that the server is obtained as dedicated and // cannot be shared with other contextCli requests. Usually this flag // is set dedicated by contextCli attempting to get this server in dedicated // mode, usuually to service a TMUDF client. A dedicated server is // usually used by one client and never shared until it is not in use. // see inUse_ flag. NABoolean dedicated_; // Ex_exe_statement_global sets the inUse_ flag for dedicated servers so that // contextCli does not hand the same dedicated server to other statements. // inUse_ flag is reset once a statement is deallocated. NABoolean inUse_; // Lists to maintain IPC Connections to the UDR Server process NAList<IpcConnection *> *inUseConns_; NAList<IpcConnection *> *freeConns_; #ifdef UDR_DEBUG FILE *traceFile_; #endif private: ExUdrServer(); // do not implement a default constructor }; // ----------------------------------------------------------------------- // ExUdrServerManager // ----------------------------------------------------------------------- class ExUdrServerManager : public NABasicObject { public: ExUdrServerManager( IpcEnvironment *env, ComUInt32 maxServersPerGroup = 1); ~ExUdrServerManager(); // This method provides access to a UDR server with the requested // attributes. Successful completion of this method does not // guarantee that the process is actually started. Currently the // options parameter is for JVM startup options only, and simple // string comparision is our test to determine if two option sets // are equivalent. ExUdrServer *acquireUdrServer(const Int32 &userId, const char *options, const char *optionDelimiters, const char *userName, const char *userPassword, NABoolean dedicated = FALSE); // Decrement the reference count for a given ExUdrServer instance void releaseUdrServer(ExUdrServer *udrServer); // This is the heap that will be used for all dynamic memory // allocations inline CollHeap *myIpcHeap() const { return ipcEnvironment_->getHeap(); } inline ComUInt32 getMaxServersPerGroup() const { return maxServersPerGroup_; } protected: // We need an IpcEnvironment pointer to create ExUdrServer objects. // That's why we store this here. All ExUdrServer objects share // this pointer. IpcEnvironment *ipcEnvironment_; // Server class used to create a server process. This pointer will // be copied to all ExUdrServer objects. IpcServerClass *udrServerClass_; // Pool of ExUdrServers LIST(ExUdrServer*) serverPool_; // Maximum number of servers an executor can create with a given set // of attributes. Currently this value is set to 1. In the future if // we want to manage multiple servers with the same attributes we // can set this value higher. ComUInt32 maxServersPerGroup_; // The following boolean helps us decide when it is OK to retain an // unused server in the pool for an application that only requires a // single server. NABoolean okToRetainOneServer_; #ifdef UDR_DEBUG FILE *traceFile_; #endif }; #endif // __EX_UDR_SERVER_H
ff788865ce10b07268c32c24d9b0506293e8ac56
431a3bfc60627c6f220d3238de5cb2e1819690f1
/src/Loader/MusicLoader.h
aeef7f2b590681aa4d0e9ab7c043a3565e156d18
[]
no_license
joka90/TDDC76-TowerDefence
f0845aefadb9172d6a74448b5031a5173cf7629d
1cf4a9dc4d8b028f3f7c0aa4af0b362375809daf
refs/heads/master
2021-03-12T20:42:01.696903
2012-12-13T19:27:00
2012-12-13T19:27:00
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,343
h
MusicLoader.h
/** * TDDC76 TowerDefence * * IDENTIFIERING * * Filnamn: MusicLoader.cc * Enhetsnamn: MusicLoader * Typ: implementering * Skriven av: I. Junaeus * * * BESKRIVNING * * Denna modul hanterar inladdning och lagring av musik för senare använding i programmet * */ #ifndef MUSICLOADER_H #define MUSICLOADER_H #include "Loader.h" #include <SFML/Audio.hpp> #include <map> #include <string> #include <iostream> class MusicLoader : public Loader { public: // Konstruktor. Behövs ej då denna klass är statisk MusicLoader(); // Tar bort en låt static void remove(const std::string& key); // Tar bort alla låtar static void clear(); // Returnerar om denna loader är tom static bool empty(); // Laddar in en ny låt med det givna filnamnet static void load(const std::string& filename); // Returnerar en inladdad SFML-låt med en given nyckel static sf::Music* getMusic(const std::string& key); // DEBUG static void print(); private: // Medlemsfunktioner. static std::string directory; static std::map<std::string, sf::Music*> songs; static bool find(const std::string& key); static void insert(const std::string& key, sf::Music* inMusic); }; #endif
d5c1dbe5ae0bdcaab808236b9adf45df02776c81
410d71ac1becd3c608ddda1db4c3b4fcfc41d1ae
/share_ptr/shared_ptr_test.cc
668a4f8ba3254f714b432d0e387f21685e194b92
[]
no_license
RenhanZhang/learning_cpp
3517563e0d52df3708835ed1aa34bad03c53bb07
8899c84a386d2fd698e89722b6f481000f160d66
refs/heads/master
2022-12-16T20:25:23.708707
2020-09-14T06:05:30
2020-09-14T06:05:30
283,911,703
0
0
null
null
null
null
UTF-8
C++
false
false
781
cc
shared_ptr_test.cc
#include "shared_ptr.h" #include <iostream> class A { public: A(int x) : v(x) {} void print() { std::cout << v << std::endl; } private: int v; }; class B { public: B(int i, int& j, A&& a) {} void print() { std::cout << "B printing." << std::endl; } }; void Test_ArrowOperator() { auto ptr = make_shared<A>(2); ptr->print(); } void Test_Dereference() { auto ptr = make_shared<A>(3); (*ptr).print(); } void Test_CopyConstruct() { auto ptr1 = make_shared<A>(4); shared_ptr<A> ptr2 = ptr1; shared_ptr<A> ptr3 = ptr2; ptr1->print(); ptr2->print(); ptr3->print(); } void Test_Construcor() { A a(5); int j = 2; auto ptr = make_shared<B>(0, j, std::move(a)); ptr->print(); } int main() { Test_ArrowOperator(); Test_Dereference(); Test_Construcor(); }
20338892806b8991e2f16e5cb4cae0d0868b1492
ec98c3ff6cf5638db5c590ea9390a04b674f8f99
/components/HaplotypeFrequencyComponent/test/test_haplotype_frequency_loglikelihood.cpp
bdeb3e5e881a36792aa46c6024ff003ca27730d8
[ "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
gavinband/qctool
37e1122d61555a39e1ae6504e4ca1c4d75f371e9
8d8adb45151c91f953fe4a9af00498073b1132ba
refs/heads/master
2023-06-22T07:16:36.897058
2021-11-13T00:12:26
2021-11-13T00:12:26
351,933,501
6
2
BSL-1.0
2023-06-12T14:13:57
2021-03-26T23:04:52
C++
UTF-8
C++
false
false
17,407
cpp
test_haplotype_frequency_loglikelihood.cpp
// Copyright Gavin Band 2008 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <Eigen/Core> #include "genfile/Error.hpp" #include "components/HaplotypeFrequencyComponent/HaplotypeFrequencyLogLikelihood.hpp" #include "config/config.hpp" #include "test_case.hpp" using std::log ; AUTO_TEST_CASE( test_haplotype_frequency_loglikelihood_value ) { typedef Eigen::MatrixXd Matrix ; typedef Eigen::VectorXd Vector ; double const tolerance = 0.0000000000001 ; Matrix table( 3, 3 ) ; { table << 1, 0, 0, 0, 0, 0, 0, 0, 0 ; HaplotypeFrequencyLogLikelihood ll( table ) ; Vector params( 3 ) ; params << 0.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -2.0 * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.2, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.0, 0.2, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.0, 0.0, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.8 * 0.8 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.2, 0.2, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.2, 0.0, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.0, 0.2, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -2.0 / 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -( 2.0 / ( 0.6 * 0.6 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ; params << 0.2, 0.2, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ; BOOST_CHECK_SMALL( ( ll.get_value_of_first_derivative() - Vector::Constant( 3, -2.0 / 0.4 ) ).array().abs().maxCoeff(), tolerance ) ; BOOST_CHECK_SMALL( ( ll.get_value_of_second_derivative() - ( -( 2.0 / ( 0.4 * 0.4 )) * Vector::Constant( 3, -1.0 ) * Vector::Constant( 3, -1.0 ).transpose() ) ).array().abs().maxCoeff(), tolerance ) ; params << 1.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -Matrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ; params << 0.0, 1.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -Matrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ; params << 0.0, 0.0, 1.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), - Matrix::Constant( 3, 3, std::numeric_limits< double >::infinity() ) ) ; } { table << 0, 0, 0, 0, 0, 0, 0, 0, 1 ; HaplotypeFrequencyLogLikelihood ll( table ) ; Vector params( 3 ) ; params << 0.0, 0.0, 1.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_second_derivative(), -2.0 * Vector::Unit( 3, 2 ) * Vector::Unit( 3, 2 ).transpose() ) ; params << 0.0, 0.0, 0.8 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ; params << 0.2, 0.0, 0.8 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ; params << 0.0, 0.2, 0.8 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.8 ) ; params << 0.2, 0.0, 0.6 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ; params << 0.0, 0.2, 0.6 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ; params << 0.2, 0.2, 0.6 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.6 ) ; params << 0.2, 0.2, 0.4 ; ll.evaluate_at( params ) ; BOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), 2.0 * Vector::Unit( 3, 2 ) / 0.4 ) ; params << 0.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; BOOST_CHECK_EQUAL( ll.get_value_of_first_derivative(), Vector::Constant( 3, -std::numeric_limits< double >::infinity() )) ; params << 1.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 0.0, 1.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; } { table << 0, 0, 1, 0, 0, 0, 0, 0, 0 ; HaplotypeFrequencyLogLikelihood ll( table ) ; Vector params( 3 ) ; params << 1.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ; params << 0.8, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.8, 0.2, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.8, 0.0, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.6, 0.2, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.6, 0.0, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.6, 0.2, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.4, 0.2, 0.4 ; ll.evaluate_at( params ) ; BOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ; params << 0.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 0.0, 1.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 0.0, 0.0, 1.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; } { table << 0, 0, 0, 0, 0, 0, 1, 0, 0 ; HaplotypeFrequencyLogLikelihood ll( table ) ; Vector params( 3 ) ; params << 0.0, 1.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ; params << 0.0, 0.8, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.2, 0.8, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.0, 0.8, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.2, 0.6, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.0, 0.6, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.2, 0.6, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.4, 0.4, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ; params << 0.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 1.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 0.0, 0.0, 1.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; } { table << 0, 0, 0, 0, 0, 0, 1, 0, 0 ; HaplotypeFrequencyLogLikelihood ll( table ) ; Vector params( 3 ) ; params << 0.0, 1.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), log( 1.0 ) ) ; params << 0.0, 0.8, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.2, 0.8, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.0, 0.8, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.8 ) ) ; params << 0.2, 0.6, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.0, 0.6, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.2, 0.6, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), 2.0 * log( 0.6 ) ) ; params << 0.4, 0.4, 0.2 ; ll.evaluate_at( params ) ; BOOST_CHECK_CLOSE( ll.get_value_of_function(), 2.0 * log( 0.4 ), tolerance ) ; params << 0.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 1.0, 0.0, 0.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; params << 0.0, 0.0, 1.0 ; ll.evaluate_at( params ) ; BOOST_CHECK_EQUAL( ll.get_value_of_function(), -std::numeric_limits< double >::infinity() ) ; } } namespace { void test_haplotype_frequency_estimation( Eigen::MatrixXd const& genotypes, Eigen::VectorXd const& expected ) { HaplotypeFrequencyLogLikelihood ll( genotypes ) ; std::cerr << "test_haplotype_frequency_estimation: genotypes: " << genotypes << "\nexpected: " << expected << "\n" ; std::cerr << " got: " << ll.get_MLE_by_EM() << ".\n" ; BOOST_CHECK_SMALL( ( ll.get_MLE_by_EM() - expected ).maxCoeff(), 0.000000000001 ) ; } } AUTO_TEST_CASE( test_haplotype_frequency_exceptions ) { { Eigen::MatrixXd genotypes = Eigen::MatrixXd::Zero( 3, 3 ) ; BOOST_CHECK_THROW( { HaplotypeFrequencyLogLikelihood ll( genotypes ) ; }, genfile::BadArgumentError ) ; } } AUTO_TEST_CASE( test_single_person_haplotype_frequency_estimation ) { Eigen::MatrixXd genotypes( 3, 3 ) ; Eigen::VectorXd params( 3 ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 0 ) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 1 ) = 1 ; params(0) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 2 ) = 1 ; params(0) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 0 ) = 1 ; params(1) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 1 ) = 1 ; // both SNPs heterozygores; half a chance of AB_ab and half of Ab_aB params(0) = 0.25 ; params(1) = 0.25 ; params(2) = 0.25 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 2 ) = 1 ; params(0) = 0.5 ; params(2) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 0 ) = 1 ; params(1) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 1 ) = 1 ; params(1) = 0.5 ; params(2) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 2 ) = 1 ; params(2) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; } AUTO_TEST_CASE( test_N_person_haplotype_frequency_estimation ) { Eigen::MatrixXd genotypes( 3, 3 ) ; Eigen::VectorXd params( 3 ) ; for( std::size_t N = 1; N < 10; ++N ) { genotypes.setZero() ; params.setZero() ; genotypes( 0, 0 ) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 1 )= N ; params(0) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 2 )= N ; params(0) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 0 )= N ; params(1) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 1 )= N ; // both SNPs heterozygores; half a chance of AB_ab and half of Ab_aB params(0) = 0.25 ; params(1) = 0.25 ; params(2) = 0.25 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 1, 2 )= N ; params(0) = 0.5 ; params(2) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 0 )= N ; params(1) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 1 )= N ; params(1) = 0.5 ; params(2) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 2 )= N ; params(2) = 1 ; test_haplotype_frequency_estimation( genotypes, params ) ; } } AUTO_TEST_CASE( test_2_person_haplotype_frequency_estimation ) { Eigen::MatrixXd genotypes( 3, 3 ) ; Eigen::VectorXd params( 3 ) ; genotypes.setZero() ; params.setZero() ; genotypes( 0, 0 ) = 1 ; genotypes( 2, 1 ) = 1 ; params(1) = 0.25 ; params(2) = 0.25 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 2 ) = 1 ; genotypes( 2, 1 ) = 1 ; params(1) = 0.25 ; params(2) = 0.75 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 2 ) = 1 ; genotypes( 1, 0 ) = 1 ; params(1) = 0.25 ; params(2) = 0.5 ; test_haplotype_frequency_estimation( genotypes, params ) ; genotypes.setZero() ; params.setZero() ; genotypes( 2, 2 ) = 1 ; genotypes( 1, 1 ) = 1 ; params(0) = 0.125 ; params(1) = 0.125 ; params(2) = 0.5 + ( 0.25 * 0.5 ); test_haplotype_frequency_estimation( genotypes, params ) ; }
95f796e2f1c59b83721a53c59625e7eed8ada744
e2204858df42b6328e8fd2546b8b017d84f66d70
/lib/mlib/inc/Simulator.h
491bc0626b723632d55b5128434636fb43227dd7
[]
no_license
jbeare/midas
4b1da9135a24ebef39b721470039a18735e2477a
d2ee60c874acb94b86774ef4679e26d929e4422c
refs/heads/master
2021-08-23T19:14:57.989533
2017-12-05T22:11:44
2017-12-05T22:11:44
106,354,740
0
0
null
null
null
null
UTF-8
C++
false
false
4,262
h
Simulator.h
#pragma once #include <memory> #include <Strategy.h> #include <DataBrowser.h> #include <map> #include <Classifier.h> #include <FeatureStream.h> #include <LabelStream.h> #include <Analyzer.h> #include <LabelFinder.h> template<class F = DefaultFeatureSet> class Simulator { public: Simulator(std::shared_ptr<DataBrowser> dataBrowser, std::shared_ptr<Strategy> strategy) : m_dataBrowser(dataBrowser), m_strategy(strategy) { } void Run(std::time_t start, std::time_t end) { ExtractDataBrowserBars(start, end); TrainClassifier(); Simulate(); } private: void ExtractDataBrowserBars(std::time_t start, std::time_t end) { for (auto const& symbol : m_dataBrowser->GetSymbols()) { m_barMap[symbol].first = {m_dataBrowser->GetBars(symbol, BarResolution::Minute, start, end)}; m_barMap[symbol].second = m_barMap[symbol].first.begin(); } } void TrainClassifier() { for (auto const& bars : m_barMap) { LabelFinder labelFinder; auto configs = labelFinder.FindLabelConfig(bars.second.first, bars.second.first, 5, 2); FeatureStream<F> fs; std::vector<FeatureSet> f; fs << bars.second.first; fs >> f; LabelStream ls(configs[0].Config); std::vector<BarLabel> l; ls << bars.second.first; ls >> l; auto data = AlignTimestamps(bars.second.first, f, l); auto raw = SimpleMatrixFromBarVector(std::get<0>(data)); auto features = SimpleMatrixFromFeatureSetVector(std::get<1>(data)); auto labels = VectorFromLabelVector(std::get<2>(data)); m_classifierMap[bars.first] = Classifier::MakeShared(ls.LabelCount(), m_strategy->Dimensions()); m_classifierMap[bars.first]->Train(features, labels, true); std::vector<uint32_t> results = m_classifierMap[bars.first]->Classify(features); std::cout << bars.first << std::endl; Analyzer::Analyze2(raw, labels, results).Print2(); } } std::time_t GetLeastTimestamp() { std::time_t timestamp{INT32_MAX}; for (auto const& bars : m_barMap) { if ((bars.second.second != bars.second.first.end()) && (bars.second.second->Timestamp < timestamp)) { timestamp = bars.second.second->Timestamp; } } return timestamp; } std::map<std::string, Bar> GetNextTimeslice() { auto timestamp = GetLeastTimestamp(); std::map<std::string, Bar> timeslice; for (auto& bars : m_barMap) { if ((bars.second.second != bars.second.first.end()) && (bars.second.second->Timestamp == timestamp)) { timeslice[bars.first] = *bars.second.second; bars.second.second++; } } return timeslice; } void Simulate() { std::map<std::string, FeatureStream<F>> streamMap; auto timeslice = GetNextTimeslice(); while (!timeslice.empty()) { bool tradeExecuted{false}; for (auto& bar : timeslice) { streamMap[bar.first] << std::vector<Bar>{bar.second}; } for (auto& stream : streamMap) { std::vector<FeatureSet> featureSet; stream.second >> featureSet; if (!featureSet.empty()) { auto c = m_classifierMap[stream.first]->Classify(featureSet.back().Features); if (c) { tradeExecuted = true; } printf("%4s:%2u ", stream.first.c_str(), c); } } printf("****:%2d\n", tradeExecuted ? 1 : 0); timeslice = GetNextTimeslice(); } } std::shared_ptr<DataBrowser> m_dataBrowser; std::shared_ptr<Strategy> m_strategy; std::map<std::string, std::pair<std::vector<Bar>, std::vector<Bar>::iterator>> m_barMap; std::map<std::string, std::shared_ptr<Classifier>> m_classifierMap; };
1ffbc5969a77c886e27f8c5371367c91eb747296
a7d87d78402278ca88186e0066530d9f003cb90b
/CBProjects/11.10 - 3/main.cpp
47ec52bf0e2c505dac0f0f373fa7925b947d7ef3
[]
no_license
BlackHenry/Freshman
33e51e017d4105494592f8b59b508caf9232faab
f88c8d0c05314d4f62060325b324d6d0e7d150f0
refs/heads/master
2020-03-28T13:11:34.651393
2018-09-11T20:01:33
2018-09-11T20:01:33
148,373,512
0
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
main.cpp
#include <iostream> using namespace std; int arr[100][100], brr[100][100]; int main() { int n; cin >> n; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> arr[i][j]; } } for(int i = 0; i < n; i++){ for(int j = 0; j < n - i; j++){ if(!i){ brr[j][j] = arr[j][j]; }else brr[i + j][j] == min(brr[i + j - 1][j], min(brr[i + j][j + 1], arr[i + j][j])); } for(int j = i + 1; j < n; j++){ if(i) brr[i + j][j] == min(brr[i + j + 1][j], min(brr[i + j][j - 1], arr[i + j][j])); } } return 0; }
447b63e785e98c0e3dd110d14e319e4819470503
f800495fa981a2b5d6657323b8b78c687e0d59ca
/lib/Target/PIC16/PIC16TargetAsmInfo.h
e464e36f7887e4ed2dc5e67e3c3e3f4054e466e2
[ "NCSA" ]
permissive
blickly/llvm-clang-PRETC
6169f3727f44dc35ee90d44c32a55ecbe92c5eea
0e4ac5636a3be17ba69ce239c15c73bb08223216
refs/heads/master
2021-01-06T20:38:13.628008
2009-06-04T02:13:29
2009-06-04T02:13:29
99,533
1
0
null
null
null
null
UTF-8
C++
false
false
2,842
h
PIC16TargetAsmInfo.h
//=====-- PIC16TargetAsmInfo.h - PIC16 asm properties ---------*- C++ -*--====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the declaration of the PIC16TargetAsmInfo class. // //===----------------------------------------------------------------------===// #ifndef PIC16TARGETASMINFO_H #define PIC16TARGETASMINFO_H #include "PIC16.h" #include "llvm/Target/TargetAsmInfo.h" #include <vector> #include "llvm/Module.h" #define DataBankSize 80 namespace llvm { // Forward declaration. class PIC16TargetMachine; class GlobalVariable; // PIC16 Splits the global data into mulitple udata and idata sections. // Each udata and idata section needs to contain a list of globals that // they contain, in order to avoid scanning over all the global values // again and printing only those that match the current section. // Keeping values inside the sections make printing a section much easier. struct PIC16Section { const Section *S_; // Connection to actual Section. unsigned Size; // Total size of the objects contained. std::vector<const GlobalVariable*> Items; PIC16Section (const Section *s) { S_ = s; Size = 0; } }; struct PIC16TargetAsmInfo : public TargetAsmInfo { std::string getSectionNameForSym(const std::string &Sym) const; PIC16TargetAsmInfo(const PIC16TargetMachine &TM); mutable std::vector<PIC16Section *> BSSSections; mutable std::vector<PIC16Section *> IDATASections; mutable std::vector<PIC16Section *> AutosSections; mutable PIC16Section *ROSection; mutable PIC16Section *ExternalVarDecls; mutable PIC16Section *ExternalVarDefs; virtual ~PIC16TargetAsmInfo(); private: const char *RomData8bitsDirective; const char *RomData16bitsDirective; const char *RomData32bitsDirective; const char *getRomDirective(unsigned size) const; virtual const char *getASDirective(unsigned size, unsigned AS) const; const Section *getBSSSectionForGlobal(const GlobalVariable *GV) const; const Section *getIDATASectionForGlobal(const GlobalVariable *GV) const; const Section *getSectionForAuto(const GlobalVariable *GV) const; virtual const Section *SelectSectionForGlobal(const GlobalValue *GV) const; public: void SetSectionForGVs(Module &M); std::vector<PIC16Section *> getBSSSections() const { return BSSSections; } std::vector<PIC16Section *> getIDATASections() const { return IDATASections; } std::vector<PIC16Section *> getAutosSections() const { return AutosSections; } }; } // namespace llvm #endif
a36b1193952d7a7aa0cc99aa0e8d4153542069f6
13e1e38318d6c832347b75cd76f1d342dfec3f64
/arangod/Utils/V8ResolverGuard.h
55232f7336fb8a1857652c31db1f8d2959870a46
[ "Apache-2.0", "GPL-1.0-or-later", "ICU", "BSD-3-Clause", "MIT" ]
permissive
msand/arangodb
f1e2c2208258261e6a081897746c247a0aec6bdf
7c43164bb989e185f9c68a5275cebdf15548c2d6
refs/heads/devel
2023-04-07T00:35:40.506103
2015-07-20T08:59:22
2015-07-20T08:59:22
39,376,414
0
0
Apache-2.0
2023-04-04T00:08:22
2015-07-20T09:58:42
C++
UTF-8
C++
false
false
4,963
h
V8ResolverGuard.h
//////////////////////////////////////////////////////////////////////////////// /// @brief V8 collection name resolver guard /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #ifndef ARANGODB_UTILS_V8RESOLVER_GUARD_H #define ARANGODB_UTILS_V8RESOLVER_GUARD_H 1 #include "Basics/Common.h" #include "Utils/CollectionNameResolver.h" #include "Utils/V8TransactionContext.h" #include "VocBase/vocbase.h" #include "V8/v8-globals.h" #include <v8.h> namespace triagens { namespace arango { class V8ResolverGuard { // ----------------------------------------------------------------------------- // --SECTION-- class V8ResolverGuard // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- public: //////////////////////////////////////////////////////////////////////////////// /// @brief create the guard //////////////////////////////////////////////////////////////////////////////// V8ResolverGuard (TRI_vocbase_t* vocbase) : _v8g(static_cast<TRI_v8_global_t*>(v8::Isolate::GetCurrent()->GetData(V8DataSlot))), _ownResolver(false) { if (! static_cast<V8TransactionContext*>(_v8g->_transactionContext)->hasResolver()) { static_cast<V8TransactionContext*>(_v8g->_transactionContext)->setResolver(new CollectionNameResolver(vocbase)); _ownResolver = true; } } //////////////////////////////////////////////////////////////////////////////// /// @brief destroy the guard //////////////////////////////////////////////////////////////////////////////// ~V8ResolverGuard () { if (_ownResolver && static_cast<V8TransactionContext*>(_v8g->_transactionContext)->hasResolver()) { static_cast<V8TransactionContext*>(_v8g->_transactionContext)->deleteResolver(); } } // ----------------------------------------------------------------------------- // --SECTION-- public functions // ----------------------------------------------------------------------------- public: //////////////////////////////////////////////////////////////////////////////// /// @brief return the resolver //////////////////////////////////////////////////////////////////////////////// inline CollectionNameResolver const* getResolver () const { TRI_ASSERT_EXPENSIVE(static_cast<V8TransactionContext*>(_v8g->_transactionContext)->hasResolver()); return static_cast<V8TransactionContext*>(_v8g->_transactionContext)->getResolver(); } // ----------------------------------------------------------------------------- // --SECTION-- private variables // ----------------------------------------------------------------------------- private: //////////////////////////////////////////////////////////////////////////////// /// @brief v8 global context //////////////////////////////////////////////////////////////////////////////// TRI_v8_global_t* _v8g; //////////////////////////////////////////////////////////////////////////////// /// @brief whether or not we are responsible for the resolver //////////////////////////////////////////////////////////////////////////////// bool _ownResolver; }; } } #endif // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End:
f3d09c5891a08e8a26f2f7f396009ea56a909e58
3c53d57793ed7f416cbe57d3be02e4670ee1742a
/Graph/OpenGL/glut/glut-project/visual studio 模板-地图视图-管网视图-数据交换/DialogControlBoard.h
9f45fabfeb559a9e14cc6f8b26625c1974666a64
[ "WTFPL" ]
permissive
znvmk/Study
a6f0edd61e7c7befc2b63ed7fa31e0ad9cd747cf
9af11d2addad51c1b806411b876920ea95482b1b
refs/heads/master
2022-09-14T01:34:54.792597
2022-08-26T20:12:53
2022-08-26T20:12:53
248,516,565
3
1
null
null
null
null
UTF-8
C++
false
false
868
h
DialogControlBoard.h
#pragma once #include "afxwin.h" #include"resource.h" // CDialogControl 对话框 class CDialogControlBoard : public CDialogEx { DECLARE_DYNAMIC(CDialogControlBoard) public: CDialogControlBoard(CWnd* pParent = NULL); // 标准构造函数 virtual ~CDialogControlBoard(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_CONTROL }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() protected: CStatic m_StaticDrawMessage; protected: void ShowDrawMessage(); public: int m_nNumber; CString m_sNubmer; CEdit m_EditNumber; bool m_bShow; public: public: //afx_msg void OnBnClickedAdd(); //afx_msg void OnBnClickedMinus(); afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); };
5a37e1c6629c6806c7ad3b272cabc6b50f0c61a9
33e130dd992f25233ee80032b583928b2e303e5d
/minimum-operations-to-reduce-x-to-zero.cpp
09a1366ee43ed27d08177c06983e4038f9e948ad
[]
no_license
ChrisAshton84/LeetCode
66a06d45b6b37e44ca2f1358c92c8177093ab989
b343fa8db63951cc2b416a7cc233eb34f543bf1c
refs/heads/main
2023-02-02T18:04:09.568414
2020-12-12T22:03:16
2020-12-12T22:03:16
315,500,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,440
cpp
minimum-operations-to-reduce-x-to-zero.cpp
class Solution { public:    int minOperations(vector<int>& nums, int x) {        if (nums.size() == 0)            return -1; // If no elements, return failure                if (nums[0] == x)            return 1; // Shortcut                int ret = nums.size() + 1;                int curSum = 0;        unordered_map<int, int> lhs_sum(nums.size() + 1);        lhs_sum[0] = 0; // Map <num of lhs> to sum at that point        for (int i = 0; i < nums.size(); i++) {            curSum += nums[i];                        if (curSum > x) // Once we've reached beyond target val don't need to continue                break;                        lhs_sum[curSum] = i + 1;       }                curSum = 0;        for (int i = nums.size() - 1; i >= 0; i--) {            curSum += nums[i];                        if (curSum > x)                break; ​            int complement = x - curSum;                        if (lhs_sum.count(complement) > 0) { // If some series of LHS sums to the complement                int size = lhs_sum[complement] + (nums.size() - i);                ret = min(ret, size);           }       }        if (ret == nums.size() + 1)            ret = -1; ​        return ret;   } };